Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(style): retain incremental document style worlds
ldm079a1bca1200c
diff --git a/README.md b/README.mdindex 8d21f7820..fea8a2ffc 100644--- a/README.md+++ b/README.md@@ -261,14 +261,25 @@ Rust, has its own ownership and lifecycle rules, and relies on:- AnyRender/Vello CPU, `usvg`, and the Rust image ecosystem — software renderingDocument and style have a single source of truth: the native DOM and its Stylo-integration. Every real refresh builds a temporary working tree from that-source, optionally produces and consumes one fresh paint snapshot, freezes the+integration. Each connected `Document` owns one persistent Stylo style world:+an incrementally updated `Stylist`, an ordered active-sheet collection,+per-`ShadowRoot` author state (including empty scopes), and canonical computed+values in Stylo's per-element data. DOM and CSSOM mutations only mark affected+scopes, elements, or subtrees dirty; the next style observation flushes those+changes and recomputes demanded elements. This retained semantic style state is+not a retained layout or paint tree. Live CSSOM rule edits are journaled and+forwarded through Stylo's rule-change API when representable; stylesheet+resource dependencies are published from a typed manifest rather than found by+serializing CSS during layout.++Every real refresh builds a temporary working layout tree from that source,+optionally produces and consumes one fresh paint snapshot, freezes thecanonical box/fragment geometry into a compact `FrozenLayoutTree`, and discards-the working tree, style borrows, layout caches, diagnostics, and paint state.-Screencast tokens contain generation metadata, never layout or paint data.-Source lookup and hit-test candidates are derived from the frozen tree when-queried. The system has no incrementally maintained layout tree, damage graph,-retained display list, GPU compositor, or persistent window.+the working tree, temporary style borrows, layout caches, diagnostics, and+paint state. Screencast tokens contain generation metadata, never layout or+paint data. Source lookup and hit-test candidates are derived from the frozen+tree when queried. The system has no incrementally maintained layout tree,+damage graph, retained display list, GPU compositor, or persistent window.## Benchmarkdiff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.mdindex e3897d323..7a2d5d93b 100644--- a/docs/README.zh-CN.md+++ b/docs/README.zh-CN.md@@ -207,7 +207,9 @@ Moli 是一个独立的浏览器内核,而不是对 Chromium 的封装。它- Taffy + Parley——盒模型与文本布局- AnyRender/Vello CPU、`usvg` 以及 Rust 图像生态——软件渲染-文档和样式只有一个事实来源:原生 DOM 与 Stylo 的集成。每次真正的刷新,都会据此构建临时工作树,按需生成并消费一份新的绘制快照,把最终的盒与文字分片几何冻结成紧凑的 `FrozenLayoutTree`,随后丢弃工作树、样式借用、布局缓存、诊断和绘制状态。屏幕串流 token 只包含 generation 元数据,不包含布局或绘制数据。来源查询表和命中测试候选仍在查询时从冻结树派生。整个系统没有增量维护的布局树、损伤区域图、保留式显示列表、GPU 合成器或持久化窗口。+文档和样式只有一个事实来源:原生 DOM 与 Stylo 的集成。每个 connected `Document` 持有一套持久的 Stylo 样式世界,其中包括原地增量更新的 `Stylist`、有序的 active stylesheet 集合、每个 `ShadowRoot`(包括空作用域)的 author state,以及 Stylo 元素数据中的规范 computed values。DOM/CSSOM mutation 只把受影响的 scope、元素或子树标脏;下一次样式 observation 才 flush 这些变化,并按需重算被读取的元素。可以精确表达的 live CSSOM rule mutation 会通过 journal 转发到 Stylo 的 rule-change API;stylesheet 资源依赖则来自 typed manifest,不再由布局阶段序列化 CSS 后重新扫描。这些是持久的语义样式状态,不是持久的布局树或绘制树。++每次真正的刷新,都会据此构建临时工作布局树,按需生成并消费一份新的绘制快照,把最终的盒与文字分片几何冻结成紧凑的 `FrozenLayoutTree`,随后丢弃工作树、临时样式借用、布局缓存、诊断和绘制状态。屏幕串流 token 只包含 generation 元数据,不包含布局或绘制数据。来源查询表和命中测试候选仍在查询时从冻结树派生。整个系统没有增量维护的布局树、损伤区域图、保留式显示列表、GPU 合成器或持久化窗口。## 测试数据diff --git a/moli-core/tests/fetch_behaviors.rs b/moli-core/tests/fetch_behaviors.rsindex 99096c55d..96af14008 100644--- a/moli-core/tests/fetch_behaviors.rs+++ b/moli-core/tests/fetch_behaviors.rs@@ -48,8 +48,9 @@ async fn wait_for_parser_image_fetch_policy_asset_requests(return Ok(());}if Instant::now() >= deadline {+ let actual_count = support::parser_image_fetch_policy_asset_request_count(token);return Err(anyhow!(- "timed out waiting for {expected_count} parser image fixture request(s) token `{token}`"+ "timed out waiting for {expected_count} parser image fixture request(s) token `{token}`; observed {actual_count}"));}tokio::time::sleep(Duration::from_millis(10)).await;@@ -1181,19 +1182,23 @@ async fn fetch_with_load_skips_parser_image_fetch_by_default() -> Result<()> {}#[tokio::test]-async fn fetch_with_load_observes_dom_and_css_images_when_enabled() -> Result<()> {+async fn fetch_with_load_defers_css_images_until_a_paint_layout() -> Result<()> {let server = FixtureServer::spawn().await?;let token = support::next_parser_image_fetch_policy_token();- let browser = Browser::new(AppConfig::default().with_image_fetch_enabled(true))?;+ let browser = Browser::new(+ AppConfig::default()+ .with_layout_policy(moli_page_types::LayoutPolicy::OnDemand)+ .with_image_fetch_enabled(true),+ )?;- let page = browser+ let mut page = browser.fetch_with_wait_until(&server.url(&format!("/compat/parser-image-fetch-policy?token={token}")),RenderedDomWaitUntil::Load,Duration::from_secs(5),).await?;- wait_for_parser_image_fetch_policy_asset_requests(&token, 2).await?;+ wait_for_parser_image_fetch_policy_asset_requests(&token, 1).await?;assert!(page_started_image_request(@@ -1205,6 +1210,16 @@ async fn fetch_with_load_observes_dom_and_css_images_when_enabled() -> Result<()"parser-discovered HTML image requests must preserve their parser initiator; network output: {:#?}",page.script_execution().network_output_items());+ assert!(+ !page_started_image_request(&page, &token, "css", SubresourceRequestInitiatorType::Css),+ "a load-only observation must not scan CSS text or start an unrendered CSS image"+ );++ let pending = page.start_capture_screenshot()?;+ let completion = pending.wait().await?;+ let _ = page.finish_capture_screenshot(completion)?;+ wait_for_parser_image_fetch_policy_asset_requests(&token, 2).await?;+assert!(page_started_image_request(&page,&token,diff --git a/moli-dom/src/native/host/document.rs b/moli-dom/src/native/host/document.rsindex 3fdfd80bf..4121aebde 100644--- a/moli-dom/src/native/host/document.rs+++ b/moli-dom/src/native/host/document.rs@@ -55,6 +55,7 @@ impl DomHost {query_version: Cell::new(0),shadow_root_binding_version: Cell::new(0),connected_shadow_roots_version: Cell::new(0),+ document_tree_scope_versions: RefCell::new(HashMap::new()),id_index: RefCell::new(None),name_index: RefCell::new(None),element_query_index: RefCell::new(ElementQueryIndex::default()),@@ -200,6 +201,28 @@ impl DomHost {self.shadow_root_binding_version.get()}+ /// Monotonic version of connected-shadow-root membership.+ ///+ /// Consumers can compare this together with+ /// [`Self::shadow_root_binding_version`] before cloning the cached binding+ /// snapshot. Ordinary DOM mutations that cannot add, remove, connect, or+ /// disconnect a shadow root leave both versions unchanged.+ pub fn connected_shadow_roots_version(&self) -> u64 {+ self.connected_shadow_roots_version.get()+ }++ /// Monotonic identity of one Document's connected ShadowRoot TreeScopes.+ ///+ /// This is deliberately document-local. The page-wide binding counters+ /// exist only to validate the shared connected-root lookup cache.+ pub fn document_tree_scope_version(&self, document: DomHandle) -> u64 {+ self.document_tree_scope_versions+ .borrow()+ .get(&document)+ .copied()+ .unwrap_or(0)+ }+pub(super) fn record_mutation(&self, scope: MutationScope) {self.dom_version.set(self.dom_version.get().saturating_add(1));@@ -222,6 +245,21 @@ impl DomHost {self.connected_shadow_roots_cache.borrow_mut().take();}+ fn record_document_tree_scope_mutation(&self, document: DomHandle) {+ let mut versions = self.document_tree_scope_versions.borrow_mut();+ let version = versions.entry(document).or_default();+ *version = version.saturating_add(1);+ }++ fn record_document_tree_scope_mutations(&self, documents: impl IntoIterator<Item = DomHandle>) {+ let mut seen = HashSet::new();+ for document in documents {+ if seen.insert(document) {+ self.record_document_tree_scope_mutation(document);+ }+ }+ }+pub(super) fn record_query_index_candidates_in_subtree(&self, root: DomHandle) {self.record_query_index_candidates_in_subtrees(std::slice::from_ref(&root));}@@ -318,6 +356,7 @@ impl DomHost {pub fn mark_subtree_connected_preserving_owner_document(&mut self, root: DomHandle) {self.record_query_index_candidates_in_subtree(root);let mut touched_shadow_root = false;+ let mut touched_documents = HashSet::new();let mut stylesheet_owners = Vec::new();let mut stack = vec![root];while let Some(handle) = stack.pop() {@@ -326,6 +365,9 @@ impl DomHost {node.set_tree_scope(owner_document, true, true);}if self.shadow_root_handle(handle).is_some() {+ if let Some(document) = self.tree_scope_owner_document_for_shadow_host(handle) {+ touched_documents.insert(document);+ }touched_shadow_root |= self.mark_shadow_tree_scope_for_subtree(handle,self.tree_scope_owner_document_for_shadow_host(handle),@@ -339,12 +381,14 @@ impl DomHost {}if touched_shadow_root {self.record_connected_shadow_roots_mutation();+ self.record_document_tree_scope_mutations(touched_documents);}self.record_mutation(MutationScope::QueryState);}pub fn mark_subtree_disconnected_preserving_owner_document(&mut self, root: DomHandle) {let mut touched_shadow_root = false;+ let mut touched_documents = HashSet::new();let mut stylesheet_owners = Vec::new();let mut stack = vec![root];while let Some(handle) = stack.pop() {@@ -353,6 +397,9 @@ impl DomHost {node.set_tree_scope(owner_document, false, false);}if self.shadow_root_handle(handle).is_some() {+ if let Some(document) = self.tree_scope_owner_document_for_shadow_host(handle) {+ touched_documents.insert(document);+ }touched_shadow_root |= self.mark_shadow_tree_scope_for_subtree(handle,self.tree_scope_owner_document_for_shadow_host(handle),@@ -366,6 +413,7 @@ impl DomHost {}if touched_shadow_root {self.record_connected_shadow_roots_mutation();+ self.record_document_tree_scope_mutations(touched_documents);}self.record_mutation(MutationScope::QueryState);}@@ -1479,6 +1527,9 @@ impl DomHost {);self.shadow_hosts_by_root.borrow_mut().insert(root, host);self.record_shadow_root_binding_mutation();+ if connected && let Some(document) = owner_document {+ self.record_document_tree_scope_mutation(document);+ }Some(root)}@@ -1494,7 +1545,7 @@ impl DomHost {inserted_roots: &[DomHandle],shadow_hosts: &[DomHandle],) -> Vec<DomStylesheetOwnerChange> {- let mut touched_shadow_root = false;+ let mut membership_documents = HashSet::new();let mut stylesheet_owners = Vec::new();for &root in inserted_roots {let Some(node) = self.node(root) else {@@ -1507,22 +1558,30 @@ impl DomHost {node.flags().connected(),false,);- touched_shadow_root = true;}}for &host in shadow_hosts {let Some(node) = self.node(host) else {continue;};- touched_shadow_root |= self.mark_shadow_tree_scope_for_host(+ let connected = node.flags().connected();+ let owner_document = node.owner_document();+ let touched = self.mark_shadow_tree_scope_for_host(host,- node.owner_document(),- node.flags().connected(),+ owner_document,+ connected,&mut stylesheet_owners,);+ if touched+ && connected+ && let Some(document) = owner_document+ {+ membership_documents.insert(document);+ }}- if touched_shadow_root {+ if !membership_documents.is_empty() {self.record_connected_shadow_roots_mutation();+ self.record_document_tree_scope_mutations(membership_documents);}stylesheet_owners.into_iter()@@ -1539,22 +1598,31 @@ impl DomHost {pub(super) fn sync_shadow_tree_scopes_for_removed_subtree(&mut self,shadow_hosts: &[DomHandle],+ was_connected: bool,) -> Vec<DomStylesheetOwnerChange> {- let mut touched_shadow_root = false;+ let mut membership_documents = HashSet::new();let mut stylesheet_owners = Vec::new();for &host in shadow_hosts {let Some(node) = self.node(host) else {continue;};- touched_shadow_root |= self.mark_shadow_tree_scope_for_host(+ let owner_document = node.owner_document();+ let touched = self.mark_shadow_tree_scope_for_host(host,- node.owner_document(),+ owner_document,node.flags().connected(),&mut stylesheet_owners,);+ if touched+ && was_connected+ && let Some(document) = owner_document+ {+ membership_documents.insert(document);+ }}- if touched_shadow_root {+ if !membership_documents.is_empty() {self.record_connected_shadow_roots_mutation();+ self.record_document_tree_scope_mutations(membership_documents);}stylesheet_owners.into_iter()@@ -1995,6 +2063,7 @@ impl DomHost {pub fn restore_shadow_root_bindings(&mut self, bindings: Vec<ShadowRootBindingSnapshot>) {let mut restored = false;+ let mut membership_documents = HashSet::new();for binding in bindings {let host = binding.host;let root = binding.root;@@ -2014,10 +2083,16 @@ impl DomHost {},);self.shadow_hosts_by_root.borrow_mut().insert(root, host);+ if self.is_connected(host)+ && let Some(document) = self.owner_document_handle(host)+ {+ membership_documents.insert(document);+ }restored = true;}if restored {self.record_shadow_root_binding_mutation();+ self.record_document_tree_scope_mutations(membership_documents);}}diff --git a/moli-dom/src/native/host/mutation/tree.rs b/moli-dom/src/native/host/mutation/tree.rsindex 5f2effe6a..68ac1b37e 100644--- a/moli-dom/src/native/host/mutation/tree.rs+++ b/moli-dom/src/native/host/mutation/tree.rs@@ -48,6 +48,7 @@ impl DomHost {) -> DomMutationEffects {let owner_document = self.owner_document_handle(parent);let records_enabled = self.mutation_records_enabled();+ let removed_tree_was_connected = self.is_connected(child);let removal_context = self.subtree_removal_context(child);let removed_shadow_slot_assignment_snapshots = self.slot_assignment_snapshots_for_removed_shadow_tree_slots(&removal_context.shadow_slots);@@ -77,7 +78,10 @@ impl DomHost {effects.extend_stylesheet_candidate_changes(candidate_changes);self.clear_popover_open_states(&removal_context.open_popovers, &mut effects);effects.extend_stylesheet_owner_changes(- self.sync_shadow_tree_scopes_for_removed_subtree(&removal_context.shadow_hosts),+ self.sync_shadow_tree_scopes_for_removed_subtree(+ &removal_context.shadow_hosts,+ removed_tree_was_connected,+ ),);self.record_mutation(MutationScope::QueryState);if let Some(document) = owner_document {diff --git a/moli-dom/src/native/host/types.rs b/moli-dom/src/native/host/types.rsindex 380f7d6c2..589cfdd7c 100644--- a/moli-dom/src/native/host/types.rs+++ b/moli-dom/src/native/host/types.rs@@ -26,6 +26,13 @@ pub struct DomHost {pub(super) query_version: Cell<u64>,pub(super) shadow_root_binding_version: Cell<u64>,pub(super) connected_shadow_roots_version: Cell<u64>,+ /// Per-Document identity of the connected ShadowRoot TreeScope universe.+ ///+ /// The two counters above belong to the page-wide binding snapshot cache.+ /// Style consumers must not use those global counters: an iframe adding a+ /// ShadowRoot cannot invalidate the retained style world of its parent or+ /// a sibling frame.+ pub(super) document_tree_scope_versions: RefCell<HashMap<DomHandle, u64>>,pub(super) id_index: RefCell<Option<NamedElementIndex>>,pub(super) name_index: RefCell<Option<NamedElementIndex>>,pub(super) element_query_index: RefCell<ElementQueryIndex>,diff --git a/moli-dom/src/native/mod.rs b/moli-dom/src/native/mod.rsindex d50f567cf..401a0b972 100644--- a/moli-dom/src/native/mod.rs+++ b/moli-dom/src/native/mod.rs@@ -1825,6 +1825,43 @@ mod tests {);}+ #[test]+ fn tree_scope_versions_are_isolated_per_document() {+ let mut host = DomHost::from_dom(NativeDom::new_html(test_url()));+ let parent_document = host.document_node_id();+ let child_document = host.create_detached_html_document();+ let child_host = host.create_parser_element_without_attributes_for_document(+ child_document,+ "section".to_owned(),+ "http://www.w3.org/1999/xhtml".to_owned(),+ None,+ );+ assert!(host.append_child(child_document, child_host));+ host.attach_shadow_root(child_host, "open")+ .expect("detached child-document ShadowRoot");+ assert_eq!(host.document_tree_scope_version(parent_document), 0);+ assert_eq!(host.document_tree_scope_version(child_document), 0);++ host.mark_subtree_connected_preserving_owner_document(child_document);+ assert_eq!(+ host.document_tree_scope_version(child_document),+ 1,+ "connecting the child Document must advance only its TreeScope universe"+ );+ assert_eq!(host.document_tree_scope_version(parent_document), 0);++ let parent_host = host.create_element("article");+ assert!(host.append_child(parent_document, parent_host));+ host.attach_shadow_root(parent_host, "open")+ .expect("connected parent-document ShadowRoot");+ assert_eq!(host.document_tree_scope_version(parent_document), 1);+ assert_eq!(+ host.document_tree_scope_version(child_document),+ 1,+ "a parent-document binding must not invalidate the child Document"+ );+ }+#[test]fn connected_shadow_roots_snapshot_cache_uses_shadow_connection_version() {let mut host = DomHost::from_dom(NativeDom::new_html(test_url()));diff --git a/moli-renderer-v8/src/css_resource_urls.rs b/moli-renderer-v8/src/css_resource_urls.rsindex 75dfa97c6..28e46c282 100644--- a/moli-renderer-v8/src/css_resource_urls.rs+++ b/moli-renderer-v8/src/css_resource_urls.rs@@ -1,5 +1,3 @@-use std::collections::HashSet;-use cssparser::{Parser, ParserInput, Token, UnicodeRange};use moli_crypto::sha256_hex;use moli_css_parse::{@@ -128,23 +126,21 @@ impl CompletedStylesheetWebFont {}}-pub(crate) fn stylesheet_load_blocking_resources(+/// Discovers load-blocking web fonts from a newly completed stylesheet.+///+/// CSS images deliberately do not use this text-scanning path. Paint layout+/// reports the computed image URLs of boxes that actually participate in the+/// rendered tree, so unmatched rules and `display: none` subtrees never start+/// image requests merely because their URL appears in stylesheet text.+pub(crate) fn stylesheet_load_blocking_font_resources(css_text: &str,base_url: &Url,optional_resource_fetch_mask: OptionalResourceFetchMask,) -> Vec<StylesheetLoadBlockingResource> {- let mut resources = Vec::new();- if optional_resource_fetch_mask.contains(OptionalResourceFetchMask::IMAGE) {- resources.extend(- stylesheet_image_resource_urls(css_text, base_url)- .into_iter()- .map(StylesheetLoadBlockingResource::image),- );+ if !optional_resource_fetch_mask.contains(OptionalResourceFetchMask::FONT) {+ return Vec::new();}- if optional_resource_fetch_mask.contains(OptionalResourceFetchMask::FONT) {- resources.extend(stylesheet_web_font_resources(css_text, base_url));- }- resources+ stylesheet_web_font_resources(css_text, base_url)}fn stylesheet_web_font_resources(@@ -156,32 +152,37 @@ fn stylesheet_web_font_resources(collect_font_face_rule_css(&rules, &mut font_face_rules);font_face_rules.into_iter()- .filter_map(|css_text| {- let descriptor = parsed_web_font_face(&css_text)?;- let request_url = preferred_font_source_url(descriptor.source(), base_url)?;- // The slot describes a declaration, not a layout generation. Two- // identical declarations may safely share decoded font data, while- // a CSSOM replacement gets a different slot even when it occupies- // the same rule index. This also avoids collisions between separate- // inline/adopted sheets that use the same document base URL.- let mut slot_material =- Vec::with_capacity(base_url.as_str().len() + css_text.len() + 1);- slot_material.extend_from_slice(base_url.as_str().as_bytes());- slot_material.push(0);- slot_material.extend_from_slice(css_text.as_bytes());- let slot = format!("stylesheet-font:{}", sha256_hex(&slot_material));- Some(StylesheetLoadBlockingResource::font(- request_url,- StylesheetWebFont {- slot,- face: descriptor.into_face(),- request_id: None,- },- ))- })+ .filter_map(|css_text| stylesheet_web_font_resource(&css_text, base_url)).collect()}+/// Projects one already-parsed and serialized `@font-face` rule into the+/// typed request metadata retained by the style world.+pub(crate) fn stylesheet_web_font_resource(+ css_text: &str,+ base_url: &Url,+) -> Option<StylesheetLoadBlockingResource> {+ let descriptor = parsed_web_font_face(css_text)?;+ let request_url = preferred_font_source_url(descriptor.source(), base_url)?;+ // The slot describes a declaration, not a layout generation. Two+ // identical declarations may safely share decoded font data, while a+ // CSSOM replacement gets a different slot even when it occupies the same+ // rule index.+ let mut slot_material = Vec::with_capacity(base_url.as_str().len() + css_text.len() + 1);+ slot_material.extend_from_slice(base_url.as_str().as_bytes());+ slot_material.push(0);+ slot_material.extend_from_slice(css_text.as_bytes());+ let slot = format!("stylesheet-font:{}", sha256_hex(&slot_material));+ Some(StylesheetLoadBlockingResource::font(+ request_url,+ StylesheetWebFont {+ slot,+ face: descriptor.into_face(),+ request_id: None,+ },+ ))+}+fn collect_font_face_rule_css(rules: &[moli_css_parse::CssRuleSnapshot], output: &mut Vec<String>) {for rule in rules {if rule.rule_type == style::stylesheets::CssRuleType::FontFace {@@ -399,95 +400,6 @@ fn resolve_font_source_url(raw_url: &str, base_url: &Url) -> Option<Url> {matches!(url.scheme(), "http" | "https" | "data" | "blob").then_some(url)}-pub(crate) fn stylesheet_image_resource_urls(css_text: &str, base_url: &Url) -> Vec<Url> {- let mut input = ParserInput::new(css_text);- let mut parser = Parser::new(&mut input);- let mut seen = HashSet::new();- let mut urls = Vec::new();- collect_css_resource_urls(&mut parser, base_url, &mut seen, &mut urls);- urls-}--fn collect_css_resource_urls<'i, 't>(- input: &mut Parser<'i, 't>,- base_url: &Url,- seen: &mut HashSet<String>,- urls: &mut Vec<Url>,-) {- while let Ok(token) = input.next_including_whitespace_and_comments().cloned() {- match token {- Token::AtKeyword(name) if name.eq_ignore_ascii_case("font-face") => {- skip_css_at_rule_body(input);- }- Token::AtKeyword(name)- if name.eq_ignore_ascii_case("import")- || name.eq_ignore_ascii_case("namespace") =>- {- skip_css_at_rule_body(input);- }- Token::UnquotedUrl(raw_url) => {- push_resolved_css_resource_url(&raw_url, base_url, seen, urls);- }- Token::Function(name) if name.eq_ignore_ascii_case("url") => {- let _ = input.parse_nested_block(|input| {- collect_css_url_function_argument(input, base_url, seen, urls);- Ok::<(), cssparser::ParseError<'_, ()>>(())- });- }- Token::Function(_)- | Token::ParenthesisBlock- | Token::SquareBracketBlock- | Token::CurlyBracketBlock => {- let _ = input.parse_nested_block(|input| {- collect_css_resource_urls(input, base_url, seen, urls);- Ok::<(), cssparser::ParseError<'_, ()>>(())- });- }- _ => {}- }- }-}--fn collect_css_url_function_argument<'i, 't>(- input: &mut Parser<'i, 't>,- base_url: &Url,- seen: &mut HashSet<String>,- urls: &mut Vec<Url>,-) {- while let Ok(token) = input.next_including_whitespace_and_comments().cloned() {- match token {- Token::WhiteSpace(_) | Token::Comment(_) => {}- Token::QuotedString(raw_url) | Token::UnquotedUrl(raw_url) => {- push_resolved_css_resource_url(&raw_url, base_url, seen, urls);- return;- }- _ => return,- }- }-}--fn skip_css_at_rule_body<'i, 't>(input: &mut Parser<'i, 't>) {- while let Ok(token) = input.next_including_whitespace_and_comments().cloned() {- match token {- Token::Semicolon => return,- Token::CurlyBracketBlock => {- let _ = input.parse_nested_block(|input| {- skip_css_block(input);- Ok::<(), cssparser::ParseError<'_, ()>>(())- });- return;- }- Token::Function(_) | Token::ParenthesisBlock | Token::SquareBracketBlock => {- let _ = input.parse_nested_block(|input| {- skip_css_block(input);- Ok::<(), cssparser::ParseError<'_, ()>>(())- });- }- _ => {}- }- }-}-fn skip_css_block<'i, 't>(input: &mut Parser<'i, 't>) {while let Ok(token) = input.next_including_whitespace_and_comments().cloned() {match token {@@ -505,27 +417,6 @@ fn skip_css_block<'i, 't>(input: &mut Parser<'i, 't>) {}}-fn push_resolved_css_resource_url(- raw_url: &str,- base_url: &Url,- seen: &mut HashSet<String>,- urls: &mut Vec<Url>,-) {- let raw_url = raw_url.trim();- if raw_url.is_empty() {- return;- }- let Ok(url) = base_url.join(raw_url).or_else(|_| Url::parse(raw_url)) else {- return;- };- if !matches!(url.scheme(), "http" | "https") {- return;- }- if seen.insert(url.as_str().to_owned()) {- urls.push(url);- }-}-#[cfg(test)]mod tests {use super::*;@@ -534,98 +425,9 @@ mod tests {Url::parse("https://example.test/assets/app.css").expect("base URL should parse")}- #[test]- fn extracts_stylesheet_url_function_resources() {- let urls = stylesheet_image_resource_urls(- r#"- body { background-image: url("hero.png"); }- .icon { mask: url(icons/icon.svg); }- "#,- &base_url(),- );- assert_eq!(- urls.into_iter()- .map(|url| url.to_string())- .collect::<Vec<_>>(),- vec![- "https://example.test/assets/hero.png",- "https://example.test/assets/icons/icon.svg",- ]- );- }-- #[test]- fn ignores_duplicate_and_non_network_urls() {- let urls = stylesheet_image_resource_urls(- r#"- .a { background: url(shared.png); }- .b { background: url("shared.png"); }- .c { background: url("data:image/png;base64,aa"); }- .d { background: url("about:blank"); }- "#,- &base_url(),- );- assert_eq!(- urls.into_iter()- .map(|url| url.to_string())- .collect::<Vec<_>>(),- vec!["https://example.test/assets/shared.png"]- );- }-- #[test]- fn keeps_font_face_urls_out_of_stylesheet_image_resources() {- let image_urls = stylesheet_image_resource_urls(- r#"- @font-face {- font-family: Demo;- src: local("Demo"), url(fonts/demo.woff2) format("woff2");- }- @media screen {- @font-face {- font-family: NestedDemo;- src: url(fonts/nested.woff2);- }- }- @media screen {- body { background-image: url(hero.png); }- }- "#,- &base_url(),- );- assert_eq!(- image_urls- .into_iter()- .map(|url| url.to_string())- .collect::<Vec<_>>(),- vec!["https://example.test/assets/hero.png"]- );- }-- #[test]- fn keeps_non_image_at_rule_urls_out_of_stylesheet_image_resources() {- let image_urls = stylesheet_image_resource_urls(- r#"- @import url(imported.css);- @namespace svg url("http://www.w3.org/2000/svg");- @media screen {- body { background-image: url(hero.png); }- }- "#,- &base_url(),- );- assert_eq!(- image_urls- .into_iter()- .map(|url| url.to_string())- .collect::<Vec<_>>(),- vec!["https://example.test/assets/hero.png"]- );- }-#[test]fn selects_one_supported_source_per_font_face_and_keeps_descriptors() {- let resources = stylesheet_load_blocking_resources(+ let resources = stylesheet_load_blocking_font_resources(r#"@font-face {font-family: Demo;@@ -693,7 +495,7 @@ mod tests {#[test]fn invalid_unicode_range_falls_back_to_the_full_font_face_range() {- let resources = stylesheet_load_blocking_resources(+ let resources = stylesheet_load_blocking_font_resources(r#"@font-face {font-family: Demo;@@ -716,7 +518,7 @@ mod tests {}#[test]- fn load_blocking_resource_selection_obeys_image_and_font_bits_independently() {+ fn load_blocking_font_selection_ignores_image_and_unrelated_bits() {let css = r#"@font-face {font-family: Demo;@@ -725,20 +527,14 @@ mod tests {body { background-image: url(images/hero.png); }"#;let selected = |mask| {- stylesheet_load_blocking_resources(css, &base_url(), mask)+ stylesheet_load_blocking_font_resources(css, &base_url(), mask).into_iter().map(|resource| (resource.kind(), resource.request_url().to_string())).collect::<Vec<_>>()};assert!(selected(OptionalResourceFetchMask::NONE).is_empty());- assert_eq!(- selected(OptionalResourceFetchMask::IMAGE),- vec![(- StylesheetLoadBlockingResourceKind::Image,- "https://example.test/assets/images/hero.png".to_owned(),- )]- );+ assert!(selected(OptionalResourceFetchMask::IMAGE).is_empty());assert_eq!(selected(OptionalResourceFetchMask::FONT),vec![(@@ -748,16 +544,10 @@ mod tests {);assert_eq!(selected(OptionalResourceFetchMask::IMAGE | OptionalResourceFetchMask::FONT),- vec![- (- StylesheetLoadBlockingResourceKind::Image,- "https://example.test/assets/images/hero.png".to_owned(),- ),- (- StylesheetLoadBlockingResourceKind::Font,- "https://example.test/assets/fonts/demo.woff2".to_owned(),- ),- ]+ vec![(+ StylesheetLoadBlockingResourceKind::Font,+ "https://example.test/assets/fonts/demo.woff2".to_owned(),+ )]);for unrelated in [OptionalResourceFetchMask::AUDIO,@@ -767,7 +557,7 @@ mod tests {] {assert!(selected(unrelated).is_empty(),- "{unrelated:?} must not enable CSS image or font requests"+ "{unrelated:?} must not enable stylesheet font requests");}}diff --git a/moli-renderer-v8/src/layout_renderer/mod.rs b/moli-renderer-v8/src/layout_renderer/mod.rsindex d9911734a..c7d9f3602 100644--- a/moli-renderer-v8/src/layout_renderer/mod.rs+++ b/moli-renderer-v8/src/layout_renderer/mod.rs@@ -11,26 +11,12 @@ use moli_layout::{use crate::{document_runtime::DomHandle, native_bridge::JsContextHost};-pub(crate) fn current_native_stylesheet_web_font_resources(+pub(crate) fn current_native_stylesheet_resources(runtime: &JsContextHost,root: DomHandle,-) -> Vec<crate::css_resource_urls::StylesheetLoadBlockingResource> {- let mut reads = crate::native_bridge::element::ComputedStyleReadScope::new(runtime);- let sources = reads.read(root).stylesheet_source_snapshots();- let mut resources = std::collections::BTreeMap::new();- for (css_text, base_url) in sources {- for resource in crate::css_resource_urls::stylesheet_load_blocking_resources(- &css_text,- &base_url,- crate::protocol_types::OptionalResourceFetchMask::FONT,- ) {- let Some(font) = resource.web_font() else {- continue;- };- resources.entry(font.slot().to_owned()).or_insert(resource);- }- }- resources.into_values().collect()+) -> Option<crate::style_engine::StylesheetResourceSnapshot> {+ let mut reads = crate::native_bridge::element::StyleObservation::new(runtime);+ reads.read(root).stylesheet_resource_snapshot()}pub(crate) fn build_native_layout_pass(@@ -63,7 +49,6 @@ fn build_native_layout_pass_recursive(.dom_host().owner_document_handle(root).unwrap_or_else(|| runtime.document_handle());- style_resolver::prepare_layout_style_inputs(runtime, root, document, request.viewport);document_stack.push(document);let source = source_view::NativeLayoutSourceView::with_paint_resources(runtime,@@ -71,7 +56,7 @@ fn build_native_layout_pass_recursive(request.requests_paint(),);let mut styles =- style_resolver::NativeLayoutStyleResolver::new(runtime, document, request.viewport);+ style_resolver::NativeLayoutStyleResolver::new(runtime, root, document, request.viewport);let result = {let mut frames = NativeEmbeddedFrameRenderer {runtime,@@ -161,8 +146,8 @@ pub(crate) fn build_normalized_native_box_tree_for_test(.owner_document_handle(root).unwrap_or_else(|| runtime.document_handle());let viewport = runtime.layout_viewport_for_document(document);- style_resolver::prepare_layout_style_inputs(runtime, root, document, viewport);let source = source_view::NativeLayoutSourceView::new(runtime, root);- let mut styles = style_resolver::NativeLayoutStyleResolver::new(runtime, document, viewport);+ let mut styles =+ style_resolver::NativeLayoutStyleResolver::new(runtime, root, document, viewport);moli_layout::build_layout_world(&source, &mut styles).map(|world| world.normalized_tree())}diff --git a/moli-renderer-v8/src/layout_renderer/style_resolver.rs b/moli-renderer-v8/src/layout_renderer/style_resolver.rsindex c1e5e5327..46f4484b0 100644--- a/moli-renderer-v8/src/layout_renderer/style_resolver.rs+++ b/moli-renderer-v8/src/layout_renderer/style_resolver.rs@@ -5,57 +5,46 @@ use moli_layout::{use crate::{document_runtime::DomHandle,- native_bridge::{JsContextHost, element::ComputedStyleReadScope},+ native_bridge::{JsContextHost, element::StyleObservation},style_engine::{StyleViewport, StyloAnonymousBoxKind},};pub(super) struct NativeLayoutStyleResolver<'a> {runtime: &'a JsContextHost,- reads: ComputedStyleReadScope<'a>,+ reads: StyleObservation<'a>,scripting_enabled: bool,}impl<'a> NativeLayoutStyleResolver<'a> {pub(super) fn new(runtime: &'a JsContextHost,+ root: DomHandle,document: DomHandle,viewport: LayoutViewport,) -> Self {+ let mut reads = layout_style_read_scope(runtime, document, viewport);+ let _ = reads.read(root).computed_values();Self {runtime,- reads: layout_style_read_scope(runtime, document, viewport),+ reads,scripting_enabled: runtime.document_scripting_enabled(document),}}}-/// Completes pending style work before the synchronous, non-reentrant layout-/// pass starts. The pass reads one NativeDom/Stylo view and retains every-/// computed allocation it projects until its pass-local world is dropped.-pub(super) fn prepare_layout_style_inputs(- runtime: &JsContextHost,- root: DomHandle,- document: DomHandle,- viewport: LayoutViewport,-) {- let mut reads = layout_style_read_scope(runtime, document, viewport);- let _ = reads.read(root).computed_values();-}-fn layout_style_read_scope<'a>(runtime: &'a JsContextHost,document: DomHandle,viewport: LayoutViewport,-) -> ComputedStyleReadScope<'a> {+) -> StyleObservation<'a> {let viewport = layout_style_viewport(runtime, viewport);if document == runtime.document_handle() && viewport == runtime.style_viewport() {- // Keep the normal main-document observation key so layout and- // rendered-text collection can reuse the same prepared Stylo input.- // Only an override viewport or an embedded Document needs the explicit- // read-document context below.- ComputedStyleReadScope::new(runtime)+ // Keep the normal main-document observation environment so layout and+ // rendered-text collection read the same persistent style world. Only+ // an override viewport or embedded Document needs an explicit context.+ StyleObservation::new(runtime)} else {- ComputedStyleReadScope::new_for_document_viewport(runtime, document, viewport)+ StyleObservation::new_for_document_viewport(runtime, document, viewport)}}diff --git a/moli-renderer-v8/src/live_stylesheet/import_graph.rs b/moli-renderer-v8/src/live_stylesheet/import_graph.rsindex fd17ed8d5..9107cfc4f 100644--- a/moli-renderer-v8/src/live_stylesheet/import_graph.rs+++ b/moli-renderer-v8/src/live_stylesheet/import_graph.rs@@ -256,9 +256,15 @@ impl LiveStylesheet {pub(super) fn note_import_descendant_mutation(&self) {self.for_each_import_ancestor_including_self(|stylesheet| {+ let generation = stylesheet.cascade_generation.get().saturating_add(1);+ stylesheet.cascade_generation.set(generation);stylesheet- .cascade_generation- .set(stylesheet.cascade_generation.get().saturating_add(1));+ .cascade_mutations+ .lock()+ .push(LiveStylesheetCascadeMutationBatch {+ generation,+ mutation: LiveStylesheetCascadeMutation::Full,+ });stylesheet.derived_state.clear_dependency_summary();stylesheet.font_face_cache.borrow_mut().take();});diff --git a/moli-renderer-v8/src/live_stylesheet/mod.rs b/moli-renderer-v8/src/live_stylesheet/mod.rsindex c6521bb98..604558cd2 100644--- a/moli-renderer-v8/src/live_stylesheet/mod.rs+++ b/moli-renderer-v8/src/live_stylesheet/mod.rs@@ -14,6 +14,7 @@ use style::{context::QuirksMode,custom_properties::AttrTaint,font_face::FontFaceRule,+ invalidation::stylesheets::RuleChangeKind,media_queries::MediaList,parser::{NestingContext, Parse, ParserContext},properties::{PropertyDeclarationBlock, parse_property_declaration_list},@@ -992,6 +993,7 @@ pub(crate) struct LiveStylesheet {cssom_runtime_state: LiveStylesheetCssomRuntimeState,contents_revision: Cell<u64>,cascade_generation: Cell<u64>,+ cascade_mutations: StdArc<Mutex<Vec<LiveStylesheetCascadeMutationBatch>>>,import_generation: Cell<u64>,parent: RefCell<Option<LiveStylesheetParent>>,next_import_edge_id: Cell<u64>,@@ -1014,6 +1016,59 @@ pub(crate) struct LiveStylesheet {>,}+/// One exact Stylo rule mutation retained until every installation that still+/// references an older cascade generation can observe it.+#[derive(Clone, Debug)]+pub(crate) struct LiveStylesheetRuleMutation {+ rule: CssRule,+ ancestors: Vec<CssRule>,+ change_kind: RuleChangeKind,+}++impl LiveStylesheetRuleMutation {+ pub(crate) fn new(rule: CssRule, ancestors: Vec<CssRule>, change_kind: RuleChangeKind) -> Self {+ Self {+ rule,+ ancestors,+ change_kind,+ }+ }++ pub(crate) fn rule(&self) -> &CssRule {+ &self.rule+ }++ pub(crate) fn ancestors(&self) -> &[CssRule] {+ &self.ancestors+ }++ pub(crate) fn change_kind(&self) -> RuleChangeKind {+ self.change_kind+ }+}++#[derive(Clone, Debug)]+pub(crate) enum LiveStylesheetCascadeMutation {+ Full,+ Rules(Vec<LiveStylesheetRuleMutation>),+}++#[derive(Clone, Debug)]+pub(crate) struct LiveStylesheetCascadeMutationBatch {+ generation: u64,+ mutation: LiveStylesheetCascadeMutation,+}++impl LiveStylesheetCascadeMutationBatch {+ pub(crate) fn generation(&self) -> u64 {+ self.generation+ }++ pub(crate) fn mutation(&self) -> &LiveStylesheetCascadeMutation {+ &self.mutation+ }+}+#[derive(Debug)]struct FontFaceRuleIdentity {id: u64,@@ -1216,6 +1271,7 @@ impl LiveStylesheet {cssom_runtime_state,contents_revision: Cell::new(1),cascade_generation: Cell::new(1),+ cascade_mutations: StdArc::new(Mutex::new(Vec::new())),import_generation: Cell::new(1),parent: RefCell::new(None),next_import_edge_id: Cell::new(0),@@ -1283,6 +1339,12 @@ impl LiveStylesheet {self.cascade_generation.get()}+ pub(crate) fn cascade_mutation_journal(+ &self,+ ) -> StdArc<Mutex<Vec<LiveStylesheetCascadeMutationBatch>>> {+ StdArc::clone(&self.cascade_mutations)+ }+pub(crate) fn import_generation(&self) -> u64 {self.import_generation.get()}diff --git a/moli-renderer-v8/src/live_stylesheet/mutation.rs b/moli-renderer-v8/src/live_stylesheet/mutation.rsindex 5f9de3369..a258d81fe 100644--- a/moli-renderer-v8/src/live_stylesheet/mutation.rs+++ b/moli-renderer-v8/src/live_stylesheet/mutation.rs@@ -36,12 +36,19 @@ impl LiveStylesheet {self.reconcile_import_edges();#[cfg(test)]note_native_top_level_mutation_for_test();- self.note_contents_mutation();+ if let Some(mutation) =+ self.rule_mutation_for_rule(rule.clone(), &[], RuleChangeKind::Insertion)+ {+ self.note_exact_rule_mutations(vec![mutation]);+ } else {+ self.note_contents_mutation();+ }Ok(rule)}pub(crate) fn delete_rule(&self, index: usize) -> Result<(), CssRuleInsertError> {let removes_namespace = self.top_level_rule_is_namespace(index)?;+ let removed = self.rule_mutation_at_path(&[index], RuleChangeKind::Removal);self.ensure_owned_contents_for_mutation();let contents = self.current_contents();{@@ -59,7 +66,11 @@ impl LiveStylesheet {self.shift_rule_wrapper_paths_for_top_level_delete(index);#[cfg(test)]note_native_top_level_mutation_for_test();- self.note_contents_mutation();+ if let Some(removed) = removed {+ self.note_exact_rule_mutations(vec![removed]);+ } else {+ self.note_contents_mutation();+ }Ok(())}@@ -70,6 +81,8 @@ impl LiveStylesheet {) -> Result<(), CssRuleInsertError> {let replaces_namespace = self.top_level_rule_is_namespace(index)?;let rule = self.parse_top_level_rule_for_insert(rule_text, index)?;+ let removed = self.rule_mutation_at_path(&[index], RuleChangeKind::Removal);+ let inserted = self.rule_mutation_for_rule(rule.clone(), &[], RuleChangeKind::Insertion);let inserts_namespace = matches!(rule, CssRule::Namespace(_));self.ensure_owned_contents_for_mutation();let contents = self.current_contents();@@ -88,7 +101,12 @@ impl LiveStylesheet {self.replace_rule_wrapper_bindings_at_path(&[index]);#[cfg(test)]note_native_top_level_mutation_for_test();- self.note_contents_mutation();+ match (removed, inserted) {+ (Some(removed), Some(inserted)) => {+ self.note_exact_rule_mutations(vec![removed, inserted]);+ }+ _ => self.note_contents_mutation(),+ }Ok(())}@@ -145,7 +163,13 @@ impl LiveStylesheet {}#[cfg(test)]note_native_nested_mutation_for_test();- self.note_contents_mutation();+ if let Some(mutation) =+ self.rule_mutation_for_rule(rule.clone(), parent_path, RuleChangeKind::Insertion)+ {+ self.note_exact_rule_mutations(vec![mutation]);+ } else {+ self.note_contents_mutation();+ }Ok(rule)}@@ -160,6 +184,9 @@ impl LiveStylesheet {if index >= rule_count {return Err(CssRuleInsertError::IndexSize);}+ let mut removed_path = parent_path.to_vec();+ removed_path.push(index);+ let removed = self.rule_mutation_at_path(&removed_path, RuleChangeKind::Removal);self.ensure_owned_contents_for_mutation();let child_rules = self.mutable_child_rules_at_path(parent_path)@@ -174,7 +201,11 @@ impl LiveStylesheet {self.shift_rule_wrapper_paths_for_delete(parent_path, index);#[cfg(test)]note_native_nested_mutation_for_test();- self.note_contents_mutation();+ if let Some(removed) = removed {+ self.note_exact_rule_mutations(vec![removed]);+ } else {+ self.note_contents_mutation();+ }Ok(())}@@ -194,6 +225,11 @@ impl LiveStylesheet {parse_relative_rule_type,true,)?;+ let mut replaced_path = parent_path.to_vec();+ replaced_path.push(index);+ let removed = self.rule_mutation_at_path(&replaced_path, RuleChangeKind::Removal);+ let inserted =+ self.rule_mutation_for_rule(rule.clone(), parent_path, RuleChangeKind::Insertion);self.ensure_owned_contents_for_mutation();let child_rules = self.mutable_child_rules_at_path(parent_path)@@ -206,12 +242,15 @@ impl LiveStylesheet {};*existing = rule;}- let mut replaced_path = parent_path.to_vec();- replaced_path.push(index);self.replace_rule_wrapper_bindings_at_path(&replaced_path);#[cfg(test)]note_native_nested_mutation_for_test();- self.note_contents_mutation();+ match (removed, inserted) {+ (Some(removed), Some(inserted)) => {+ self.note_exact_rule_mutations(vec![removed, inserted]);+ }+ _ => self.note_contents_mutation(),+ }Ok(())}@@ -256,7 +295,11 @@ impl LiveStylesheet {}#[cfg(test)]note_native_keyframe_mutation_for_test();- self.note_contents_mutation();+ if let Some(mutation) = self.rule_mutation_at_path(parent_path, RuleChangeKind::Generic) {+ self.note_exact_rule_mutations(vec![mutation]);+ } else {+ self.note_contents_mutation();+ }Ok(rule)}@@ -285,7 +328,11 @@ impl LiveStylesheet {self.shift_rule_wrapper_paths_for_delete(parent_path, index);#[cfg(test)]note_native_keyframe_mutation_for_test();- self.note_contents_mutation();+ if let Some(mutation) = self.rule_mutation_at_path(parent_path, RuleChangeKind::Generic) {+ self.note_exact_rule_mutations(vec![mutation]);+ } else {+ self.note_contents_mutation();+ }Ok(())}@@ -317,7 +364,11 @@ impl LiveStylesheet {self.replace_rule_wrapper_bindings_at_path(&replaced_path);#[cfg(test)]note_native_keyframe_mutation_for_test();- self.note_contents_mutation();+ if let Some(mutation) = self.rule_mutation_at_path(parent_path, RuleChangeKind::Generic) {+ self.note_exact_rule_mutations(vec![mutation]);+ } else {+ self.note_contents_mutation();+ }Ok(())}@@ -346,7 +397,7 @@ impl LiveStylesheet {let mut guard = self.stylesheet.shared_lock.write();*rule.media_queries.write_with(&mut guard) = media;drop(guard);- self.note_rule_value_mutation();+ self.note_rule_value_mutation_at_path(rule_path, RuleChangeKind::Generic);Ok(())}@@ -380,7 +431,7 @@ impl LiveStylesheet {let mut guard = imported_stylesheet.shared_lock.write();*imported_stylesheet.media.write_with(&mut guard) = media;drop(guard);- self.note_rule_value_mutation();+ self.note_rule_value_mutation_at_path(rule_path, RuleChangeKind::Generic);Ok(())}@@ -546,7 +597,7 @@ impl LiveStylesheet {// Locked node. make_mut() can replace that Arc when a V8 lease retains// the prior value, so refresh only the wrapper bound to this root.self.refresh_rule_wrapper_bindings_at_path(rule_path);- self.note_rule_value_mutation();+ self.note_rule_value_mutation_at_path(rule_path, RuleChangeKind::Generic);Ok(result)}@@ -575,7 +626,7 @@ impl LiveStylesheet {let mut guard = self.stylesheet.shared_lock.write();*block.write_with(&mut guard) = declarations;drop(guard);- self.note_rule_value_mutation();+ self.note_rule_value_mutation_at_path(rule_path, RuleChangeKind::StyleRuleDeclarations);Ok(())}@@ -604,7 +655,7 @@ impl LiveStylesheet {let mut guard = self.stylesheet.shared_lock.write();*block.write_with(&mut guard) = declarations;drop(guard);- self.note_rule_value_mutation();+ self.note_rule_value_mutation_at_path(rule_path, RuleChangeKind::Generic);Ok(())}@@ -634,7 +685,7 @@ impl LiveStylesheet {let mut guard = self.stylesheet.shared_lock.write();*block.write_with(&mut guard) = declarations;drop(guard);- self.note_rule_value_mutation();+ self.note_rule_value_mutation_at_path(parent_path, RuleChangeKind::Generic);Ok(())}@@ -661,7 +712,7 @@ impl LiveStylesheet {rule.descriptors = parsed.descriptors;rule.descriptor_importance = parsed.descriptor_importance;drop(guard);- self.note_rule_value_mutation();+ self.note_rule_value_mutation_at_path(rule_path, RuleChangeKind::Generic);Ok(())}@@ -690,7 +741,7 @@ impl LiveStylesheet {let mut guard = self.stylesheet.shared_lock.write();*block.write_with(&mut guard) = declarations;drop(guard);- self.note_rule_value_mutation();+ self.note_rule_value_mutation_at_path(rule_path, RuleChangeKind::Generic);Ok(())}@@ -720,7 +771,7 @@ impl LiveStylesheet {let mut guard = self.stylesheet.shared_lock.write();rule.write_with(&mut guard).selectors = selectors;drop(guard);- self.note_rule_value_mutation();+ self.note_rule_value_mutation_at_path(rule_path, RuleChangeKind::Generic);Ok(())}@@ -745,7 +796,7 @@ impl LiveStylesheet {let mut guard = self.stylesheet.shared_lock.write();*rule.block.write_with(&mut guard) = declarations;drop(guard);- self.note_rule_value_mutation();+ self.note_rule_value_mutation_at_path(rule_path, RuleChangeKind::Generic);Ok(())}@@ -776,7 +827,7 @@ impl LiveStylesheet {let mut guard = self.stylesheet.shared_lock.write();rule.write_with(&mut guard).selectors = selectors;drop(guard);- self.note_rule_value_mutation();+ self.note_rule_value_mutation_at_path(rule_path, RuleChangeKind::Generic);Ok(())}@@ -802,7 +853,7 @@ impl LiveStylesheet {let mut guard = self.stylesheet.shared_lock.write();rule.write_with(&mut guard).selector = selector;drop(guard);- self.note_rule_value_mutation();+ self.note_rule_value_mutation_at_path(parent_path, RuleChangeKind::Generic);Ok(())}@@ -826,14 +877,70 @@ impl LiveStylesheet {let mut guard = self.stylesheet.shared_lock.write();rule.write_with(&mut guard).name = KeyframesName::from_ident(name);drop(guard);- self.note_rule_value_mutation();+ self.note_rule_value_mutation_at_path(rule_path, RuleChangeKind::Generic);Ok(())}- fn note_rule_value_mutation(&self) {+ fn note_rule_value_mutation_at_path(&self, rule_path: &[usize], change_kind: RuleChangeKind) {#[cfg(test)]note_native_rule_value_mutation_for_test();+ if let Some(mutation) = self.rule_mutation_at_path(rule_path, change_kind) {+ self.note_exact_rule_mutations(vec![mutation]);+ } else {+ self.note_contents_mutation();+ }+ }++ fn note_exact_rule_mutations(&self, mutations: Vec<LiveStylesheetRuleMutation>) {+ debug_assert!(!mutations.is_empty());self.note_contents_mutation();+ let generation = self.cascade_generation();+ let mut batches = self.cascade_mutations.lock();+ let batch = batches+ .last_mut()+ .expect("a cascade mutation must publish one journal batch");+ debug_assert_eq!(batch.generation, generation);+ batch.mutation = LiveStylesheetCascadeMutation::Rules(mutations);+ }++ fn rule_mutation_at_path(+ &self,+ rule_path: &[usize],+ change_kind: RuleChangeKind,+ ) -> Option<LiveStylesheetRuleMutation> {+ let NativeStylesheetRule::Css(rule) = self.native_rule_at_path(rule_path)? else {+ return None;+ };+ let ancestor_path_len = rule_path.len().saturating_sub(1);+ Some(LiveStylesheetRuleMutation::new(+ rule,+ self.css_rule_ancestors_at_path(&rule_path[..ancestor_path_len])?,+ change_kind,+ ))+ }++ fn rule_mutation_for_rule(+ &self,+ rule: CssRule,+ parent_path: &[usize],+ change_kind: RuleChangeKind,+ ) -> Option<LiveStylesheetRuleMutation> {+ Some(LiveStylesheetRuleMutation::new(+ rule,+ self.css_rule_ancestors_at_path(parent_path)?,+ change_kind,+ ))+ }++ fn css_rule_ancestors_at_path(&self, path: &[usize]) -> Option<Vec<CssRule>> {+ let mut ancestors = Vec::with_capacity(path.len());+ for depth in 1..=path.len() {+ let NativeStylesheetRule::Css(rule) = self.native_rule_at_path(&path[..depth])? else {+ return None;+ };+ ancestors.push(rule);+ }+ Some(ancestors)}fn parse_declaration_block(diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/stylesheets.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/stylesheets.rsindex 605cfc5aa..d69bd92cf 100644--- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/stylesheets.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/stylesheets.rs@@ -248,7 +248,7 @@ impl JsContextHost {// cannot admit stylesheet-dependent resource requests.continue;};- for resource in crate::css_resource_urls::stylesheet_load_blocking_resources(+ for resource in crate::css_resource_urls::stylesheet_load_blocking_font_resources(response.body_text(),&response.final_url,optional_resource_fetch_mask,diff --git a/moli-renderer-v8/src/native_bridge/context_host/core.rs b/moli-renderer-v8/src/native_bridge/context_host/core.rsindex c9130b30b..0c7d7a021 100644--- a/moli-renderer-v8/src/native_bridge/context_host/core.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs@@ -459,9 +459,13 @@ impl JsContextHost {#[cfg(test)]layout_flow_subtree_node_visits: Cell::new(0),#[cfg(test)]- stylo_computed_style_input_builds: Cell::new(0),+ style_world_update_materializations: Cell::new(0),#[cfg(test)]- stylo_style_system_key_builds: Cell::new(0),+ style_world_full_snapshots: Cell::new(0),+ #[cfg(test)]+ style_world_document_scope_materializations: Cell::new(0),+ #[cfg(test)]+ style_world_shadow_scope_materializations: Cell::new(0),#[cfg(test)]stylo_computed_style_property_reads: Cell::new(0),};diff --git a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rsindex bbe683b55..240cabf68 100644--- a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs@@ -1,4 +1,4 @@-use std::{collections::HashSet, rc::Rc};+use std::collections::HashSet;use super::{JsContextHost,@@ -13,10 +13,10 @@ use crate::{network::context::DocumentResourceLoader,style_engine::{AdoptedStyleSheetInstallation, CssCustomPropertyRegistration,- CssCustomPropertyRegistrationError, OwnedStyleSourceDocumentContext, StyleAttributeImpact,- StyleMutationEffect, StyleViewport, StyloComputedStyleInputs,- StyloDocumentComputedStyleInputCacheKey, StyloPreparedComputedStyleInputs,- StyloStylesheetSource,+ CssCustomPropertyRegistrationError, FullStyleWorldSnapshot,+ OwnedStyleSourceDocumentContext, PreparedStyleWorldUpdate, StyleAttributeImpact,+ StyleMutationEffect, StyleObservationSnapshot, StyleViewport, StylesheetResourceSnapshot,+ StyloStyleEnvironment, StyloStylesheetSource,},{RendererWebStorageHandles,@@ -853,13 +853,8 @@ impl JsContextHost {document: DomHandle,installations: Vec<AdoptedStyleSheetInstallation>,) {- let dom_host = self.dom_host() as *const _;self.style_engine- .set_document_adopted_style_sheet_installations_with_host(- unsafe { &*dom_host },- document,- installations,- );+ .set_document_adopted_style_sheet_installations(document, installations);}pub(crate) fn adopted_style_sheet_sources_for_document(@@ -1275,14 +1270,11 @@ impl JsContextHost {) -> Result<(), CssCustomPropertyRegistrationError> {self.clear_layout_rect_cache();let base_url = self.style_base_url_for_document(document);- let dom_host = self.dom_host() as *const _;- self.style_engine- .register_css_custom_property_for_document_with_host(- unsafe { &*dom_host },- document,- registration,- base_url,- )+ self.style_engine.register_css_custom_property_for_document(+ document,+ registration,+ base_url,+ )}pub(crate) fn validate_css_custom_property_registration_for_document(@@ -1317,12 +1309,12 @@ impl JsContextHost {.registered_css_custom_property_registration_for_document(document, name)}- pub(crate) fn script_css_custom_property_registrations(+ pub(crate) fn script_css_custom_property_registration_records(&self,document: DomHandle,- ) -> Vec<CssCustomPropertyRegistration> {+ ) -> Vec<crate::style_engine::CssCustomPropertyRegistrationRecord> {self.style_engine- .script_css_custom_property_registrations_for_document(document)+ .script_css_custom_property_registration_records_for_document(document)}pub(crate) fn computed_style_property_value_from_stylo(@@ -1330,7 +1322,7 @@ impl JsContextHost {handle: DomHandle,property: &str,pseudo_element: Option<&str>,- inputs: &StyloComputedStyleInputs,+ inputs: &FullStyleWorldSnapshot,read_document: DomHandle,viewport: StyleViewport,) -> Option<String> {@@ -1355,6 +1347,33 @@ impl JsContextHost {)}+ /// Runs a compatibility-only provenance probe against an isolated style+ /// engine. The probe must never replace or flush the page's retained+ /// Document style world.+ pub(crate) fn computed_style_property_value_from_ephemeral_stylo(+ &self,+ handle: DomHandle,+ property: &str,+ inputs: &FullStyleWorldSnapshot,+ read_document: DomHandle,+ viewport: StyleViewport,+ ) -> Option<String> {+ let document_context = self.style_source_document_context_for_read_document(read_document);+ let inputs = inputs.independent_style_engine_projection();+ crate::style_engine::MoliStyleEngine::new()+ .computed_style_property_value_with_document_context(+ self.dom_host(),+ &self.document_url_for_handle(read_document),+ handle,+ property,+ None,+ &inputs,+ document_context.as_ref(),+ read_document,+ viewport,+ )+ }+fn style_source_document_context(&self) -> OwnedStyleSourceDocumentContext {OwnedStyleSourceDocumentContext::new(self.document_handle()).with_child_documents(self.child_browsing_context_document_handles@@ -1400,19 +1419,11 @@ impl JsContextHost {&self,read_document: DomHandle,) {- let owner_document = if self- .lightweight_popup_id_for_document_handle(read_document)- .is_some()- {- read_document- } else {- self.document_handle()- };let document_context = self.style_source_document_context_for_read_document(read_document);self.style_engine.drain_pending_style_invalidations_for_computed_style_read_with_document_context(self.dom_host(),- owner_document,+ read_document,document_context.as_ref(),);}@@ -1445,23 +1456,20 @@ impl JsContextHost {.computed_cache_generation_for_document(document)}- pub(crate) fn cached_document_prepared_style_inputs(+ pub(crate) fn stylesheet_resource_snapshot_for_document(&self,document: DomHandle,- key: &StyloDocumentComputedStyleInputCacheKey,- ) -> Option<Rc<StyloPreparedComputedStyleInputs>> {+ ) -> Option<StylesheetResourceSnapshot> {self.style_engine- .cached_document_prepared_style_inputs(document, key)+ .stylesheet_resource_snapshot_for_document(document)}- pub(crate) fn cache_document_prepared_style_inputs(+ pub(crate) fn retained_stylesheet_query_snapshot_for_document(&self,document: DomHandle,- key: StyloDocumentComputedStyleInputCacheKey,- inputs: Rc<StyloPreparedComputedStyleInputs>,- ) {+ ) -> Option<std::rc::Rc<FullStyleWorldSnapshot>> {self.style_engine- .cache_document_prepared_style_inputs(document, key, inputs);+ .retained_stylesheet_query_snapshot_for_document(document)}#[cfg(test)]@@ -1489,28 +1497,56 @@ impl JsContextHost {}#[cfg(test)]- pub(crate) fn note_stylo_computed_style_input_build_for_test(&self) {- self.stylo_computed_style_input_builds.set(- self.stylo_computed_style_input_builds+ pub(crate) fn note_style_world_update_materialization_for_test(&self) {+ self.style_world_update_materializations.set(+ self.style_world_update_materializations+ .get()+ .saturating_add(1),+ );+ }++ #[cfg(test)]+ pub(crate) fn style_world_update_materializations_for_test(&self) -> u64 {+ self.style_world_update_materializations.get()+ }++ #[cfg(test)]+ pub(crate) fn note_style_world_full_snapshot_for_test(&self) {+ self.style_world_full_snapshots+ .set(self.style_world_full_snapshots.get().saturating_add(1));+ }++ #[cfg(test)]+ pub(crate) fn style_world_full_snapshots_for_test(&self) -> u64 {+ self.style_world_full_snapshots.get()+ }++ #[cfg(test)]+ pub(crate) fn note_style_world_document_scope_materialization_for_test(&self) {+ self.style_world_document_scope_materializations.set(+ self.style_world_document_scope_materializations.get().saturating_add(1),);}#[cfg(test)]- pub(crate) fn stylo_computed_style_input_builds_for_test(&self) -> u64 {- self.stylo_computed_style_input_builds.get()+ pub(crate) fn style_world_document_scope_materializations_for_test(&self) -> u64 {+ self.style_world_document_scope_materializations.get()}#[cfg(test)]- pub(crate) fn note_stylo_style_system_key_build_for_test(&self) {- self.stylo_style_system_key_builds- .set(self.stylo_style_system_key_builds.get().saturating_add(1));+ pub(crate) fn note_style_world_shadow_scope_materialization_for_test(&self) {+ self.style_world_shadow_scope_materializations.set(+ self.style_world_shadow_scope_materializations+ .get()+ .saturating_add(1),+ );}#[cfg(test)]- pub(crate) fn stylo_style_system_key_builds_for_test(&self) -> u64 {- self.stylo_style_system_key_builds.get()+ pub(crate) fn style_world_shadow_scope_materializations_for_test(&self) -> u64 {+ self.style_world_shadow_scope_materializations.get()}#[cfg(test)]@@ -1540,6 +1576,24 @@ impl JsContextHost {.retained_style_system_rebuild_count_for_document_for_test(document)}+ #[cfg(test)]+ pub(crate) fn retained_style_system_update_count_for_document_for_test(+ &self,+ document: DomHandle,+ ) -> u64 {+ self.style_engine+ .retained_style_system_update_count_for_document_for_test(document)+ }++ #[cfg(test)]+ pub(crate) fn retained_stylist_identity_for_document_for_test(+ &self,+ document: DomHandle,+ ) -> u64 {+ self.style_engine+ .retained_stylist_identity_for_document_for_test(document)+ }+#[cfg(test)]pub(crate) fn pending_style_invalidation_work_item_count_for_document_for_test(&self,@@ -1552,7 +1606,7 @@ impl JsContextHost {pub(crate) fn computed_style_snapshot_from_stylo_after_style_update(&self,handle: DomHandle,- inputs: &StyloComputedStyleInputs,+ inputs: &FullStyleWorldSnapshot,read_document: DomHandle,viewport: StyleViewport,) -> Option<crate::style_engine::StyloComputedStyleSnapshot> {@@ -1569,15 +1623,36 @@ impl JsContextHost {)}- pub(crate) fn computed_style_snapshot_from_stylo_with_prepared_inputs(+ pub(crate) fn computed_style_snapshot_from_current_observation(&self,handle: DomHandle,- inputs: &StyloPreparedComputedStyleInputs,+ read_document: DomHandle,+ viewport: StyleViewport,+ tree_scope_versions: crate::style_engine::StyleTreeScopeVersions,+ ) -> StyleObservationSnapshot {+ let document_context = self.style_source_document_context_for_read_document(read_document);+ self.style_engine+ .computed_style_snapshot_from_current_observation(+ self.dom_host(),+ self.document_url(),+ handle,+ StyloStyleEnvironment::from_emulated_media(self.emulated_media()),+ document_context.as_ref(),+ read_document,+ viewport,+ tree_scope_versions,+ )+ }++ pub(crate) fn computed_style_snapshot_with_world_update(+ &self,+ handle: DomHandle,+ inputs: &PreparedStyleWorldUpdate,read_document: DomHandle,) -> Option<crate::style_engine::StyloComputedStyleSnapshot> {let document_context = self.style_source_document_context_for_read_document(read_document);self.style_engine- .computed_style_snapshot_after_style_update_with_prepared_inputs(+ .computed_style_snapshot_after_world_update(self.dom_host(),self.document_url(),handle,@@ -1587,43 +1662,39 @@ impl JsContextHost {)}- pub(crate) fn computed_pseudo_style_snapshot_from_stylo_with_prepared_inputs(+ pub(crate) fn computed_pseudo_style_snapshot_from_current_observation(&self,handle: DomHandle,pseudo_element: &str,- inputs: &StyloPreparedComputedStyleInputs,read_document: DomHandle,) -> Option<crate::style_engine::StyloComputedStyleSnapshot> {let document_context = self.style_source_document_context_for_read_document(read_document);self.style_engine- .computed_pseudo_style_snapshot_after_style_update_with_prepared_inputs(+ .computed_pseudo_style_snapshot_from_current_observation(self.dom_host(),self.document_url(),handle,pseudo_element,- inputs,document_context.as_ref(),read_document,)}- pub(crate) fn computed_anonymous_style_snapshot_from_stylo_with_prepared_inputs(+ pub(crate) fn computed_anonymous_style_snapshot_from_current_observation(&self,owner: DomHandle,parent_style: &style::properties::ComputedValues,anonymous_kind: crate::style_engine::StyloAnonymousBoxKind,- inputs: &StyloPreparedComputedStyleInputs,read_document: DomHandle,) -> Option<crate::style_engine::StyloComputedStyleSnapshot> {let document_context = self.style_source_document_context_for_read_document(read_document);self.style_engine- .computed_anonymous_style_snapshot_after_style_update_with_prepared_inputs(+ .computed_anonymous_style_snapshot_from_current_observation(self.dom_host(),self.document_url(),owner,parent_style,anonymous_kind,- inputs,document_context.as_ref(),read_document,)diff --git a/moli-renderer-v8/src/native_bridge/context_host/layout.rs b/moli-renderer-v8/src/native_bridge/context_host/layout.rsindex e6c7602c1..ed64e5c94 100644--- a/moli-renderer-v8/src/native_bridge/context_host/layout.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/layout.rs@@ -421,16 +421,22 @@ impl JsContextHost {.clear_latest_layout();}- pub(crate) fn mark_document_web_font_sources_dirty(&self) {+ pub(crate) fn document_web_font_resources_are_current(+ &self,+ generation: crate::style_engine::StylesheetResourceGeneration,+ ) -> bool {self.document_layout_state- .borrow_mut()- .mark_web_font_sources_dirty();+ .borrow()+ .web_font_resources_are_current(generation)}- pub(crate) fn take_document_web_font_sources_dirty(&self) -> bool {+ pub(crate) fn publish_document_web_font_resource_generation(+ &self,+ generation: crate::style_engine::StylesheetResourceGeneration,+ ) {self.document_layout_state.borrow_mut()- .take_web_font_sources_dirty()+ .publish_web_font_resource_generation(generation);}#[cfg(test)]diff --git a/moli-renderer-v8/src/native_bridge/context_host/layout_state.rs b/moli-renderer-v8/src/native_bridge/context_host/layout_state.rsindex 8679ca849..a093d5000 100644--- a/moli-renderer-v8/src/native_bridge/context_host/layout_state.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/layout_state.rs@@ -7,6 +7,7 @@ use crate::{css_resource_urls::{CompletedStylesheetWebFont, StylesheetLoadBlockingResource},document_runtime::DomHandle,script_vm::web_fonts::{DocumentWebFontCompletion, DocumentWebFontState},+ style_engine::StylesheetResourceGeneration,};/// Layout-facing state whose lifetime is bounded by exactly one main Document.@@ -20,11 +21,12 @@ use crate::{/// The single snapshot slot records the exact root Document it was built for;/// embedded Document member trees remain recursively owned by that same/// snapshot instead of becoming separately keyed cache entries.+#[derive(Default)]pub(super) struct DocumentLayoutState {services: DocumentLayoutServices,embedded_document_services: HashMap<DomHandle, DocumentLayoutServices>,web_fonts: DocumentWebFontState,- web_font_sources_dirty: bool,+ web_font_resource_generation: Option<StylesheetResourceGeneration>,visual_state_generation: u64,latest_layout: LatestLayoutTreeCache,/// Last used content viewport published by each live iframe owner's@@ -34,27 +36,19 @@ pub(super) struct DocumentLayoutState {frame_viewports: HashMap<DomHandle, LayoutViewport>,}-impl Default for DocumentLayoutState {- fn default() -> Self {- Self {- services: DocumentLayoutServices::default(),- embedded_document_services: HashMap::new(),- web_fonts: DocumentWebFontState::default(),- web_font_sources_dirty: true,- visual_state_generation: 0,- latest_layout: LatestLayoutTreeCache::default(),- frame_viewports: HashMap::new(),- }- }-}-impl DocumentLayoutState {- pub(super) fn mark_web_font_sources_dirty(&mut self) {- self.web_font_sources_dirty = true;+ pub(super) fn web_font_resources_are_current(+ &self,+ generation: StylesheetResourceGeneration,+ ) -> bool {+ self.web_font_resource_generation == Some(generation)}- pub(super) fn take_web_font_sources_dirty(&mut self) -> bool {- std::mem::take(&mut self.web_font_sources_dirty)+ pub(super) fn publish_web_font_resource_generation(+ &mut self,+ generation: StylesheetResourceGeneration,+ ) {+ self.web_font_resource_generation = Some(generation);}pub(super) const fn visual_state_generation(&self) -> u64 {diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rsindex 7d64a38f9..61cb2cff3 100644--- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs@@ -1078,9 +1078,13 @@ pub(crate) struct JsContextHost {#[cfg(test)]layout_flow_subtree_node_visits: Cell<u64>,#[cfg(test)]- stylo_computed_style_input_builds: Cell<u64>,+ style_world_update_materializations: Cell<u64>,#[cfg(test)]- stylo_style_system_key_builds: Cell<u64>,+ style_world_full_snapshots: Cell<u64>,+ #[cfg(test)]+ style_world_document_scope_materializations: Cell<u64>,+ #[cfg(test)]+ style_world_shadow_scope_materializations: Cell<u64>,#[cfg(test)]stylo_computed_style_property_reads: Cell<u64>,}diff --git a/moli-renderer-v8/src/native_bridge/document/css_state/projection.rs b/moli-renderer-v8/src/native_bridge/document/css_state/projection.rsindex 804df302e..0fabe2ebd 100644--- a/moli-renderer-v8/src/native_bridge/document/css_state/projection.rs+++ b/moli-renderer-v8/src/native_bridge/document/css_state/projection.rs@@ -114,9 +114,6 @@ impl DocumentCssProjections {}fn apply(self, scope: &mut v8::PinScope<'_, '_>, host: &JsContextHost) {- if !self.projections.is_empty() {- host.mark_document_web_font_sources_dirty();- }let mut font_face_documents = Vec::new();for projection in self.projections {match projection {diff --git a/moli-renderer-v8/src/native_bridge/element.rs b/moli-renderer-v8/src/native_bridge/element.rsindex 0d42f4cc2..e58eeee38 100644--- a/moli-renderer-v8/src/native_bridge/element.rs+++ b/moli-renderer-v8/src/native_bridge/element.rs@@ -65,12 +65,12 @@ pub(crate) use forms::{#[cfg(test)]pub(crate) use styles::iframe_width_attribute_viewport_width;pub(crate) use styles::{- ComputedStyleReadScope, ComputedStyleTargetContext,- STYLE_DECLARATION_FORCED_EMPTY_COMPUTED_SLOT, STYLE_DECLARATION_PSEUDO_ELEMENT_SLOT,- STYLE_DECLARATION_READ_DOCUMENT_SLOT, STYLE_DECLARATION_SCREEN_HEIGHT_SLOT,- STYLE_DECLARATION_SCREEN_WIDTH_SLOT, STYLE_DECLARATION_TARGET_CONTEXT_EPOCH_SLOT,- STYLE_DECLARATION_TARGET_EMPTY_COMPUTED_SLOT, STYLE_DECLARATION_VIEWPORT_HEIGHT_SLOT,- STYLE_DECLARATION_VIEWPORT_WIDTH_SLOT, computed_style_target_context, iframe_handle_viewport,+ ComputedStyleTargetContext, STYLE_DECLARATION_FORCED_EMPTY_COMPUTED_SLOT,+ STYLE_DECLARATION_PSEUDO_ELEMENT_SLOT, STYLE_DECLARATION_READ_DOCUMENT_SLOT,+ STYLE_DECLARATION_SCREEN_HEIGHT_SLOT, STYLE_DECLARATION_SCREEN_WIDTH_SLOT,+ STYLE_DECLARATION_TARGET_CONTEXT_EPOCH_SLOT, STYLE_DECLARATION_TARGET_EMPTY_COMPUTED_SLOT,+ STYLE_DECLARATION_VIEWPORT_HEIGHT_SLOT, STYLE_DECLARATION_VIEWPORT_WIDTH_SLOT,+ StyleObservation, computed_style_target_context, iframe_handle_viewport,marker_pseudo_element_is_generated_for_document_snapshot,};mod stylesheets;diff --git a/moli-renderer-v8/src/native_bridge/element/content.rs b/moli-renderer-v8/src/native_bridge/element/content.rsindex a4c8e65c8..dda6f36c5 100644--- a/moli-renderer-v8/src/native_bridge/element/content.rs+++ b/moli-renderer-v8/src/native_bridge/element/content.rs@@ -20,7 +20,7 @@ use super::{ElementBoxState, ElementContentVisibility, ElementRenderedState, ElementRenderedStyle,rendered_child_participates_in_flat_tree,},- styles::ComputedStyleReadScope,+ styles::StyleObservation,trusted_types::{TrustedHtmlSink, trusted_html_sink_string},};@@ -575,7 +575,7 @@ fn rendered_element_ignores_dom_children(element: &Element) -> bool {fn append_inner_text(runtime: &JsContextHost,- style_scope: &mut ComputedStyleReadScope<'_>,+ style_scope: &mut StyleObservation<'_>,root: DomHandle,root_style: Option<ElementRenderedStyle>,rendered_text_sources: &HashSet<DomHandle>,@@ -811,7 +811,7 @@ fn node_inner_text(} else {HashSet::new()};- let mut style_scope = ComputedStyleReadScope::new(runtime);+ let mut style_scope = StyleObservation::new(runtime);let rendered_state = ElementRenderedState::read_in_scope(&mut style_scope, handle);if rendered_state.has_content_visibility_lock() {return Ok(String::new());diff --git a/moli-renderer-v8/src/native_bridge/element/rendered_state.rs b/moli-renderer-v8/src/native_bridge/element/rendered_state.rsindex 75c344c58..d8c660065 100644--- a/moli-renderer-v8/src/native_bridge/element/rendered_state.rs+++ b/moli-renderer-v8/src/native_bridge/element/rendered_state.rs@@ -16,7 +16,7 @@ use super::{node_runtime_and_handle_from_args_or_detached, require_element_method_receiver,throw_incompatible_method_receiver,},- styles::ComputedStyleReadScope,+ styles::StyleObservation,};#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -46,7 +46,7 @@ pub(super) struct ElementRenderedStyle {}impl ElementRenderedStyle {- pub(super) fn read_in_scope(scope: &mut ComputedStyleReadScope<'_>, handle: DomHandle) -> Self {+ pub(super) fn read_in_scope(scope: &mut StyleObservation<'_>, handle: DomHandle) -> Self {let runtime = scope.runtime();let style = scope.read(handle);let content_visibility = inline_content_visibility(runtime, handle);@@ -204,11 +204,11 @@ pub(super) struct ElementRenderedState {impl ElementRenderedState {pub(super) fn read(runtime: &JsContextHost, handle: DomHandle) -> Self {- let mut scope = ComputedStyleReadScope::new(runtime);+ let mut scope = StyleObservation::new(runtime);Self::read_in_scope(&mut scope, handle)}- pub(super) fn read_in_scope(scope: &mut ComputedStyleReadScope<'_>, handle: DomHandle) -> Self {+ pub(super) fn read_in_scope(scope: &mut StyleObservation<'_>, handle: DomHandle) -> Self {let runtime = scope.runtime();if super::details_dialog::node_is_hidden_by_closed_details(runtime, handle) {return Self {@@ -315,7 +315,7 @@ impl ElementRenderedState {}pub(super) fn rendered_child_participates_in_flat_tree(- scope: &mut ComputedStyleReadScope<'_>,+ scope: &mut StyleObservation<'_>,parent: DomHandle,child: DomHandle,) -> bool {diff --git a/moli-renderer-v8/src/native_bridge/element/styles.rs b/moli-renderer-v8/src/native_bridge/element/styles.rsindex 876a431fb..cd0fa7d76 100644--- a/moli-renderer-v8/src/native_bridge/element/styles.rs+++ b/moli-renderer-v8/src/native_bridge/element/styles.rs@@ -21,7 +21,7 @@ pub(crate) use accessors::{style_css_text_getter_callback, style_css_text_setter_callback, style_length_getter_callback,};pub(in crate::native_bridge::element) use declaration::style_base_url;-pub(crate) use declaration::{ComputedStyleRead, ComputedStyleReadScope};+pub(crate) use declaration::{ComputedStyleRead, StyleObservation};use declaration::{StyleComputationContext, shorthand_longhands, style_property_count_with_context,style_property_value_with_context, style_runtime_and_handle_from_object,diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration.rsindex 1d30ba588..c02b85435 100644--- a/moli-renderer-v8/src/native_bridge/element/styles/declaration.rs+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration.rs@@ -1,10 +1,14 @@mod identity;+mod observation;mod parse;mod properties;+mod style_world;mod values;pub(crate) use identity::StyleMode;pub(super) use identity::style_runtime_and_handle_from_object;+pub(super) use observation::StyleComputationContext;+pub(crate) use observation::{ComputedStyleRead, StyleObservation};pub(crate) use parse::{cssom_style_entry_requires_structured_parser,cssom_style_property_uses_preferred_pdb_supplemental_entries,@@ -35,21 +39,19 @@ pub(super) use properties::{resolve_style_property_name, shorthand_longhands, supported_declared_property,text_decoration_shorthand_longhands, transition_shorthand_longhands,};-pub(in crate::native_bridge::element) use values::style_base_url;-pub(crate) use values::{ComputedStyleRead, ComputedStyleReadScope};-pub(super) use values::{- StyleComputationContext, computed_style_applies, style_css_text_for_computed,- style_property_count_with_context, style_property_index_exists_with_context,- style_property_name_at_with_context, style_property_names_with_context,- style_property_priority, style_property_value_for_pseudo_with_context,- style_property_value_with_context,-};+pub(in crate::native_bridge::element) use style_world::style_base_url;pub(crate) use values::{active_css_animation_transform_value, css_animation_start_applies,raw_inline_style_property_value, serialize_animation_range_shorthand,serialize_animation_shorthand_from_longhands, serialize_transition_shorthand_from_longhands,style_property_value,};+pub(super) use values::{+ computed_style_applies, style_css_text_for_computed, style_property_count_with_context,+ style_property_index_exists_with_context, style_property_name_at_with_context,+ style_property_names_with_context, style_property_priority,+ style_property_value_for_pseudo_with_context, style_property_value_with_context,+};fn normalize_css_integer_token(value: &str) -> Option<String> {let trimmed = value.trim();diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation.rsnew file mode 100644index 000000000..ac750e6d5--- /dev/null+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation.rs@@ -0,0 +1,334 @@+use std::{cell::RefCell, rc::Rc};++use crate::{+ document_runtime::DomHandle,+ style_engine::{+ FullStyleWorldSnapshot, PreparedStyleWorldUpdate, StyleObservationSnapshot, StyleViewport,+ StyleWorldUpdatePlan, StyloComputedStyleSnapshot,+ },+};++use super::super::super::super::JsContextHost;+use super::style_world::{+ StyleObservationKey, prepare_style_world_update, stylesheet_query_fallback,+ stylesheet_source_document_for_handle,+};++#[derive(Clone, Copy, Debug, Default)]+pub(in crate::native_bridge::element::styles) struct StyleComputationContext {+ pub(in crate::native_bridge::element::styles) viewport: StyleViewport,+ pub(in crate::native_bridge::element::styles) read_document: Option<DomHandle>,+}++impl StyleComputationContext {+ pub(in crate::native_bridge::element::styles) const fn new(viewport: StyleViewport) -> Self {+ Self {+ viewport,+ read_document: None,+ }+ }++ pub(in crate::native_bridge::element::styles) const fn viewport_width(self) -> Option<f64> {+ self.viewport.width+ }++ pub(in crate::native_bridge::element::styles) const fn viewport(self) -> StyleViewport {+ self.viewport+ }++ pub(in crate::native_bridge::element::styles) const fn with_read_document(+ mut self,+ read_document: Option<DomHandle>,+ ) -> Self {+ self.read_document = read_document;+ self+ }++ pub(super) fn resolved_read_document(+ self,+ runtime: &JsContextHost,+ handle: DomHandle,+ ) -> DomHandle {+ self.read_document+ .or_else(|| runtime.dom_host().owner_document_handle(handle))+ .unwrap_or_else(|| runtime.document_handle())+ }+}++#[cfg(debug_assertions)]+#[derive(Clone, Copy)]+struct ComputedStyleReadInvariant {+ dom_version: u64,+ source_set_generation: u64,+ retained_style_system_generation: u64,+}++/// One synchronous observation of the persistent style worlds it touches.+///+/// The observation drains pending style work once per Document and reads+/// canonical element styles from the retained world. A complete TreeScope+/// input is materialized only if that world must be updated or a specialized+/// query needs it, then shared by every read in this observation.+pub(crate) struct StyleObservation<'a> {+ runtime: &'a JsContextHost,+ context: StyleComputationContext,+ drained_document: Option<DomHandle>,+ additional_drained_documents: Vec<DomHandle>,+ primary_document: Option<Rc<StyleObservationInputs<'a>>>,+ additional_documents: Vec<Rc<StyleObservationInputs<'a>>>,+ #[cfg(debug_assertions)]+ invariants: Vec<(DomHandle, ComputedStyleReadInvariant)>,+}++pub(super) struct StyleObservationInputs<'a> {+ runtime: &'a JsContextHost,+ key: StyleObservationKey,+ context: StyleComputationContext,+ prepared_update: RefCell<Option<Rc<PreparedStyleWorldUpdate>>>,+ stylesheet_query_snapshot: RefCell<Option<Rc<FullStyleWorldSnapshot>>>,+}++impl<'a> StyleObservationInputs<'a> {+ fn new(+ runtime: &'a JsContextHost,+ source_document: Option<DomHandle>,+ context: StyleComputationContext,+ ) -> Self {+ Self {+ runtime,+ key: StyleObservationKey::for_document(runtime, source_document),+ context,+ prepared_update: RefCell::new(None),+ stylesheet_query_snapshot: RefCell::new(None),+ }+ }++ pub(super) fn source_document(&self) -> Option<DomHandle> {+ self.key.source_document()+ }++ fn tree_scope_versions(&self) -> crate::style_engine::StyleTreeScopeVersions {+ self.key.tree_scope_versions()+ }++ fn prepared_update(&self, plan: &StyleWorldUpdatePlan) -> Rc<PreparedStyleWorldUpdate> {+ if let Some(update) = self.prepared_update.borrow().as_ref() {+ return Rc::clone(update);+ }+ let update = prepare_style_world_update(self.runtime, &self.key, self.context, plan);+ *self.prepared_update.borrow_mut() = Some(Rc::clone(&update));+ update+ }++ pub(super) fn stylesheet_query_snapshot(&self) -> Rc<FullStyleWorldSnapshot> {+ if let Some(inputs) = self.stylesheet_query_snapshot.borrow().as_ref() {+ return Rc::clone(inputs);+ }+ let inputs = self+ .source_document()+ .and_then(|document| {+ self.runtime+ .retained_stylesheet_query_snapshot_for_document(document)+ })+ .unwrap_or_else(|| stylesheet_query_fallback(self.runtime, &self.key, self.context));+ *self.stylesheet_query_snapshot.borrow_mut() = Some(Rc::clone(&inputs));+ inputs+ }+}++pub(super) trait RetainedStyleObservation {+ fn style_snapshot(&self, handle: DomHandle) -> Option<StyloComputedStyleSnapshot>;+}++impl RetainedStyleObservation for StyleObservationInputs<'_> {+ fn style_snapshot(&self, handle: DomHandle) -> Option<StyloComputedStyleSnapshot> {+ let read_document = self.context.resolved_read_document(self.runtime, handle);+ match self+ .runtime+ .computed_style_snapshot_from_current_observation(+ handle,+ read_document,+ self.context.viewport,+ self.tree_scope_versions(),+ ) {+ StyleObservationSnapshot::Current(style) => style,+ StyleObservationSnapshot::NeedsStyleWorldUpdate(plan) => {+ let update = self.prepared_update(&plan);+ self.runtime.computed_style_snapshot_with_world_update(+ handle,+ update.as_ref(),+ read_document,+ )+ }+ }+ }+}++impl<'a> StyleObservation<'a> {+ pub(crate) fn new(runtime: &'a JsContextHost) -> Self {+ Self::new_with_context(+ runtime,+ StyleComputationContext::new(runtime.style_viewport()),+ )+ }++ /// Creates one synchronous style-observation scope for an exact document+ /// viewport selected by layout.+ ///+ /// Embedded documents cannot derive their used viewport from the iframe's+ /// authored width/height alone: parent layout may change it through+ /// box-sizing, padding, constraints, flex/grid sizing, or transforms. The+ /// scoped context keeps viewport units and media queries aligned with the+ /// numeric layout demand without mutating retained document state.+ pub(crate) fn new_for_document_viewport(+ runtime: &'a JsContextHost,+ document: DomHandle,+ viewport: StyleViewport,+ ) -> Self {+ Self::new_with_context(+ runtime,+ StyleComputationContext::new(viewport).with_read_document(Some(document)),+ )+ }++ pub(super) fn new_with_context(+ runtime: &'a JsContextHost,+ context: StyleComputationContext,+ ) -> Self {+ Self {+ runtime,+ context,+ drained_document: None,+ additional_drained_documents: Vec::new(),+ primary_document: None,+ additional_documents: Vec::new(),+ #[cfg(debug_assertions)]+ invariants: Vec::new(),+ }+ }++ pub(crate) const fn runtime(&self) -> &'a JsContextHost {+ self.runtime+ }++ pub(crate) fn read(&mut self, handle: DomHandle) -> ComputedStyleRead<'a> {+ let read_document = self.context.resolved_read_document(self.runtime, handle);+ if self.drained_document != Some(read_document)+ && !self.additional_drained_documents.contains(&read_document)+ {+ if self.drained_document.is_none() {+ self.drained_document = Some(read_document);+ } else {+ self.additional_drained_documents.push(read_document);+ }+ self.runtime+ .drain_pending_style_invalidations_for_computed_style_read_for_document(+ read_document,+ );+ }++ let source_document = stylesheet_source_document_for_handle(self.runtime, handle);+ let observation_inputs = self.observation_inputs(source_document);+ let stylo_style = match self+ .runtime+ .computed_style_snapshot_from_current_observation(+ handle,+ read_document,+ self.context.viewport,+ observation_inputs.tree_scope_versions(),+ ) {+ StyleObservationSnapshot::Current(style) => style,+ StyleObservationSnapshot::NeedsStyleWorldUpdate(plan) => {+ let prepared_update = observation_inputs.prepared_update(&plan);+ self.runtime.computed_style_snapshot_with_world_update(+ handle,+ prepared_update.as_ref(),+ read_document,+ )+ }+ };+ #[cfg(debug_assertions)]+ self.verify_stable_style_world_after_read(source_document);+ ComputedStyleRead {+ runtime: self.runtime,+ handle,+ context: self.context,+ observation_inputs,+ stylo_style,+ }+ }++ fn observation_inputs(+ &mut self,+ source_document: Option<DomHandle>,+ ) -> Rc<StyleObservationInputs<'a>> {+ if let Some(observation) = self.primary_document.as_ref()+ && observation.source_document() == source_document+ {+ return Rc::clone(observation);+ }+ if let Some(observation) = self+ .additional_documents+ .iter()+ .find(|observation| observation.source_document() == source_document)+ {+ return Rc::clone(observation);+ }++ let observation = Rc::new(StyleObservationInputs::new(+ self.runtime,+ source_document,+ self.context,+ ));+ if self.primary_document.is_none() {+ self.primary_document = Some(Rc::clone(&observation));+ } else {+ self.additional_documents.push(Rc::clone(&observation));+ }+ observation+ }++ #[cfg(debug_assertions)]+ fn verify_stable_style_world_after_read(&mut self, source_document: Option<DomHandle>) {+ let Some(document) = source_document else {+ return;+ };+ let (dom_version, source_set_generation, retained_style_system_generation) =+ self.runtime.computed_style_read_invariant_state(document);+ let current = ComputedStyleReadInvariant {+ dom_version,+ source_set_generation,+ retained_style_system_generation,+ };+ let Some((_, previous)) = self+ .invariants+ .iter_mut()+ .find(|(candidate, _)| *candidate == document)+ else {+ self.invariants.push((document, current));+ return;+ };+ if previous.dom_version == current.dom_version+ && previous.source_set_generation == current.source_set_generation+ {+ debug_assert_eq!(+ current.retained_style_system_generation, previous.retained_style_system_generation,+ "one StyleObservation updated or replaced the retained style world without a DOM or style-source mutation",+ );+ } else {+ *previous = current;+ }+ }+}++/// One synchronous computed-style read after the pending style lifecycle has+/// been drained. Chromium updates style once and lets all properties in the+/// read observe the same retained ComputedStyle; Moli follows that model with+/// canonical Stylo `ElementData` and a lazy observation-local slow path.+pub(crate) struct ComputedStyleRead<'a> {+ pub(super) runtime: &'a JsContextHost,+ pub(super) handle: DomHandle,+ pub(super) context: StyleComputationContext,+ pub(super) observation_inputs: Rc<StyleObservationInputs<'a>>,+ pub(super) stylo_style: Option<StyloComputedStyleSnapshot>,+}diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/style_world.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/style_world.rsnew file mode 100644index 000000000..1cdbd201e--- /dev/null+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/style_world.rs@@ -0,0 +1,418 @@+use std::rc::Rc;++use moli_web_mime::is_stylesheet_type_attribute;++use crate::{+ context_bootstrap::evaluate_match_media_query_list_with_viewport,+ document_runtime::DomHandle,+ dom::native::{DomHost, Node},+ style_engine::{+ FullStyleWorldSnapshot, IncrementalStyleWorldUpdate, PreparedStyleWorldUpdate,+ StyleSourceId, StyleTreeScopeVersions, StyleWorldEnvironment, StyleWorldUpdatePlan,+ StyloStyleEnvironment, StyloStylesheetSource, link_rel_qualifies_as_stylesheet,+ },+ stylesheet_blocking::link_rel_includes_token,+};++use super::super::super::super::JsContextHost;+use super::observation::StyleComputationContext;++#[derive(Clone, Debug, Eq, Hash, PartialEq)]+pub(super) struct StyleObservationKey {+ source_document: Option<DomHandle>,+ tree_scope_versions: StyleTreeScopeVersions,+}++impl StyleObservationKey {+ pub(super) fn for_document(+ runtime: &JsContextHost,+ source_document: Option<DomHandle>,+ ) -> Self {+ Self {+ source_document,+ tree_scope_versions: StyleTreeScopeVersions::current(+ runtime.dom_host(),+ source_document,+ ),+ }+ }++ pub(super) fn source_document(&self) -> Option<DomHandle> {+ self.source_document+ }++ pub(super) fn tree_scope_versions(&self) -> StyleTreeScopeVersions {+ self.tree_scope_versions+ }+}++pub(super) fn stylesheet_source_document_for_handle(+ runtime: &JsContextHost,+ handle: DomHandle,+) -> Option<DomHandle> {+ runtime.dom_host().owner_document_handle(handle)+}++pub(in crate::native_bridge::element) fn style_base_url(+ runtime: &JsContextHost,+ handle: DomHandle,+) -> url::Url {+ let document_handle = if runtime+ .dom_host()+ .node(handle)+ .is_some_and(Node::is_document)+ {+ Some(handle)+ } else {+ runtime+ .dom_host()+ .node(handle)+ .and_then(Node::owner_document)+ };+ document_handle+ .map(|document_handle| {+ if document_handle == runtime.dom_host().document_handle() {+ runtime+ .dom_host()+ .document_base_url()+ .unwrap_or_else(|| runtime.document_url().clone())+ } else {+ runtime+ .dom_host()+ .node(document_handle)+ .and_then(Node::as_document)+ .map(|document| document.base_url().clone())+ .unwrap_or_else(|| runtime.document_url().clone())+ }+ })+ .unwrap_or_else(|| runtime.document_url().clone())+}++pub(super) fn prepare_style_world_update(+ runtime: &JsContextHost,+ key: &StyleObservationKey,+ context: StyleComputationContext,+ plan: &StyleWorldUpdatePlan,+) -> Rc<PreparedStyleWorldUpdate> {+ let media = StyloStyleEnvironment::from_emulated_media(runtime.emulated_media());+ let quirks_mode = quirks_mode(runtime, key.source_document());+ let document_url = key+ .source_document()+ .map(|document| runtime.document_url_for_handle(document))+ .unwrap_or_else(|| runtime.document_url().clone());+ let environment = StyleWorldEnvironment::new(+ document_url,+ context.viewport(),+ media,+ quirks_mode,+ key.tree_scope_versions(),+ );+ match plan {+ StyleWorldUpdatePlan::Full => {+ let inputs = complete_style_world_snapshot(runtime, key, context, media);+ #[cfg(test)]+ runtime.note_style_world_full_snapshot_for_test();+ Rc::new(PreparedStyleWorldUpdate::full(environment, inputs))+ }+ StyleWorldUpdatePlan::Incremental(plan) => {+ #[cfg(test)]+ runtime.note_style_world_update_materialization_for_test();+ let document_stylesheet_sources = plan+ .refreshes_document_stylesheets()+ .then(|| document_stylesheet_sources(runtime, key.source_document(), context));+ let shadow_stylesheet_sources = plan+ .shadow_stylesheet_roots()+ .iter()+ .copied()+ .filter(|root| {+ runtime.dom_host().owner_document_handle(*root) == key.source_document()+ && runtime+ .dom_host()+ .shadow_root_host(*root)+ .is_some_and(|host| runtime.dom_host().is_connected(host))+ })+ .map(|root| (root, shadow_stylesheet_sources(runtime, root, context)))+ .collect();+ let script_custom_property_registrations =+ plan.refreshes_custom_property_registrations().then(|| {+ key.source_document()+ .map(|document| {+ runtime.script_css_custom_property_registration_records(document)+ })+ .unwrap_or_default()+ });+ Rc::new(PreparedStyleWorldUpdate::incremental(+ environment,+ IncrementalStyleWorldUpdate::new(+ document_stylesheet_sources,+ shadow_stylesheet_sources,+ plan.connected_shadow_roots().map(|roots| roots.to_vec()),+ script_custom_property_registrations,+ ),+ ))+ }+ }+}++pub(super) fn stylesheet_query_fallback(+ runtime: &JsContextHost,+ key: &StyleObservationKey,+ context: StyleComputationContext,+) -> Rc<FullStyleWorldSnapshot> {+ complete_style_world_snapshot(+ runtime,+ key,+ context,+ StyloStyleEnvironment::from_emulated_media(runtime.emulated_media()),+ )+}++fn complete_style_world_snapshot(+ runtime: &JsContextHost,+ key: &StyleObservationKey,+ context: StyleComputationContext,+ environment: StyloStyleEnvironment,+) -> Rc<FullStyleWorldSnapshot> {+ #[cfg(test)]+ runtime.note_style_world_update_materialization_for_test();+ let source_document = key.source_document();+ let mut inputs = FullStyleWorldSnapshot {+ document_stylesheet_sources: document_stylesheet_sources(runtime, source_document, context),+ shadow_stylesheet_sources: Vec::new(),+ script_custom_property_registrations: source_document+ .map(|document| runtime.script_css_custom_property_registration_records(document))+ .unwrap_or_default(),+ environment,+ quirks_mode: quirks_mode(runtime, source_document),+ };+ for root in source_document+ .map(|document| connected_shadow_roots(runtime.dom_host(), document))+ .unwrap_or_default()+ {+ inputs+ .shadow_stylesheet_sources+ .push((root, shadow_stylesheet_sources(runtime, root, context)));+ }+ Rc::new(inputs)+}++fn quirks_mode(runtime: &JsContextHost, document: Option<DomHandle>) -> style::context::QuirksMode {+ document+ .and_then(|document| runtime.dom_host().node(document))+ .and_then(Node::as_document)+ .map(|document| document.quirks_mode())+ .unwrap_or(style::context::QuirksMode::NoQuirks)+}++#[cfg(test)]+pub(super) fn connected_shadow_roots_for_test(+ host: &DomHost,+ document: DomHandle,+) -> Vec<DomHandle> {+ connected_shadow_roots(host, document)+}++fn connected_shadow_roots(host: &DomHost, document: DomHandle) -> Vec<DomHandle> {+ let mut roots = host+ .snapshot_connected_shadow_roots()+ .into_iter()+ .filter(|root| host.owner_document_handle(*root) == Some(document))+ .collect::<Vec<_>>();+ roots.sort_by_key(|root| root.index());+ roots+}++fn document_stylesheet_sources(+ runtime: &JsContextHost,+ source_document: Option<DomHandle>,+ context: StyleComputationContext,+) -> Vec<StyloStylesheetSource> {+ let mut sources = Vec::new();+ let Some(document) = source_document else {+ return sources;+ };+ #[cfg(test)]+ runtime.note_style_world_document_scope_materialization_for_test();+ for style_handle in+ active_stylesheet_handles(runtime, document, context.read_document.is_some())+ {+ sources.push(stylesheet_source(runtime, style_handle));+ }+ sources.extend(+ runtime+ .adopted_style_sheet_sources_for_document(document)+ .iter()+ .map(|source| {+ let client_id = source+ .adopted_client_id()+ .expect("installed adopted stylesheet must have a client id");+ source+ .clone()+ .with_source_id(Some(StyleSourceId::document_adopted_style_sheet(+ document, client_id,+ )))+ }),+ );+ sources+}++fn shadow_stylesheet_sources(+ runtime: &JsContextHost,+ root: DomHandle,+ context: StyleComputationContext,+) -> Vec<StyloStylesheetSource> {+ #[cfg(test)]+ runtime.note_style_world_shadow_scope_materialization_for_test();+ let mut sources = active_stylesheet_handles(runtime, root, context.read_document.is_some())+ .into_iter()+ .map(|handle| stylesheet_source(runtime, handle))+ .collect::<Vec<_>>();+ sources.extend(+ runtime+ .shadow_root_adopted_style_sheet_sources(root)+ .into_iter()+ .map(|source| {+ let client_id = source+ .adopted_client_id()+ .expect("installed adopted stylesheet must have a client id");+ source.with_source_id(Some(StyleSourceId::shadow_root_adopted_style_sheet(+ root, client_id,+ )))+ }),+ );+ sources+}++pub(super) fn active_stylesheet_handles(+ runtime: &JsContextHost,+ root: DomHandle,+ include_detached: bool,+) -> Vec<DomHandle> {+ let mut handles = runtime+ .dom_host()+ .stylesheet_candidate_handles_for_tree_scope(root)+ .iter()+ .copied()+ .filter(|handle| {+ let Some(element) = runtime.dom_host().node(*handle).and_then(Node::as_element) else {+ return false;+ };+ let style = element.is_inline_style_element()+ && runtime+ .dom_host()+ .get_attribute(*handle, "disabled")+ .is_none();+ let link =+ element.is_html_element("link") && link_stylesheet_is_enabled(runtime, *handle);+ (style || link)+ && (include_detached || stylesheet_is_active_in_scope(runtime, root, *handle))+ && is_stylesheet_type_attribute(+ runtime.dom_host().get_attribute(*handle, "type").as_deref(),+ )+ && stylesheet_media_matches(runtime, *handle)+ })+ .collect::<Vec<_>>();+ let preferred_title = handles+ .iter()+ .filter_map(|handle| {+ runtime+ .dom_host()+ .get_attribute(*handle, "title")+ .filter(|title| !title.is_empty())+ .map(|title| (*handle, title))+ })+ .min_by_key(|(handle, _)| handle.index())+ .map(|(_, title)| title);+ if let Some(preferred_title) = preferred_title {+ handles.retain(|handle| {+ runtime+ .dom_host()+ .get_attribute(*handle, "title")+ .filter(|title| !title.is_empty())+ .is_none_or(|title| title == preferred_title)+ });+ }+ handles+}++pub(super) fn stylesheet_text(runtime: &JsContextHost, handle: DomHandle) -> String {+ stylesheet_source(runtime, handle)+ .serialized_css_text()+ .to_string()+}++fn stylesheet_source(runtime: &JsContextHost, handle: DomHandle) -> StyloStylesheetSource {+ let Some(element) = runtime.dom_host().node(handle).and_then(Node::as_element) else {+ return StyloStylesheetSource::new(String::new(), style_base_url(runtime, handle));+ };+ if element.is_html_element("link") {+ return runtime+ .linked_stylesheet_source_for_owner(handle)+ .unwrap_or_else(|| {+ StyloStylesheetSource::new(String::new(), style_base_url(runtime, handle))+ })+ .with_source_id(StyleSourceId::linked_style_sheet(+ runtime.dom_host(),+ handle,+ ));+ }+ if element.is_inline_style_element()+ && let Some(source) = runtime.owner_style_sheet_source(handle)+ {+ return source.with_source_id(StyleSourceId::owner_style_sheet(runtime.dom_host(), handle));+ }+ StyloStylesheetSource::new(String::new(), style_base_url(runtime, handle))+}++fn stylesheet_media_matches(runtime: &JsContextHost, handle: DomHandle) -> bool {+ let Some(media) = runtime.dom_host().get_attribute(handle, "media") else {+ return true;+ };+ let media = media.trim();+ media.is_empty()+ || evaluate_match_media_query_list_with_viewport(+ media,+ Some(runtime.emulated_media()),+ runtime.style_viewport(),+ )+}++fn link_stylesheet_is_enabled(runtime: &JsContextHost, handle: DomHandle) -> bool {+ if runtime+ .dom_host()+ .get_attribute(handle, "disabled")+ .is_some()+ {+ return false;+ }+ let rel = runtime.dom_host().get_attribute(handle, "rel");+ let Some(rel) = rel.as_deref() else {+ return false;+ };+ let title = runtime.dom_host().get_attribute(handle, "title");+ if !link_rel_qualifies_as_stylesheet(Some(rel), title.as_deref()) {+ return false;+ }+ !link_rel_includes_token(rel, "alternate")+ || runtime+ .dom_host()+ .node(handle)+ .and_then(Node::as_element)+ .is_some_and(|element| element.link_explicitly_enabled())+}++fn stylesheet_is_active_in_scope(+ runtime: &JsContextHost,+ root: DomHandle,+ handle: DomHandle,+) -> bool {+ runtime.dom_host().is_connected(handle)+ || runtime+ .child_browsing_context_host_for_document_handle(root)+ .is_some_and(|frame_handle| runtime.dom_host().is_connected(frame_handle))+ || (runtime.dom_host().is_shadow_root(root)+ && runtime+ .dom_host()+ .shadow_root_host(root)+ .is_some_and(|host| runtime.dom_host().is_connected(host)))+}diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rsindex 145dece24..6928d42be 100644--- a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs@@ -1,9 +1,6 @@use crate::css_custom_function::custom_css_projection_at_rules;-use crate::style_engine::link_rel_qualifies_as_stylesheet;-use crate::stylesheet_blocking::link_rel_includes_token;use crate::{- context_bootstrap::evaluate_match_media_query_list_with_viewport,- dom::native::{DomHost, Node},+ dom::native::Node,{css_style::{CssStyleEntry as StyleEntry, background_shorthand_color, border_shorthand_color,@@ -18,23 +15,25 @@ use crate::{ClientRect, observable_bounding_client_rect, observable_bounding_client_rects,},style_engine::{- ComputedDisplayKind, ComputedRenderedStyleFacts, StyleSourceId, StyleViewport,- StyloAnonymousBoxKind, StyloComputedStyleInputs, StyloComputedStyleSnapshot,- StyloDocumentComputedStyleInputCacheKey, StyloPreparedComputedStyleInputs,- StyloStyleEnvironment, StyloStylesheetSource, computed_property_is_queryable,+ ComputedDisplayKind, ComputedRenderedStyleFacts, FullStyleWorldSnapshot, StyleViewport,+ StylesheetResourceSnapshot, StyloAnonymousBoxKind, StyloComputedStyleSnapshot,+ StyloStylesheetSource, computed_property_is_queryable,},},};use cssparser::{Parser, ParserInput, Token, serialize_identifier, serialize_string};use moli_selector::html_directionality;-use moli_web_mime::is_stylesheet_type_attribute;-use std::{- collections::{HashMap, HashSet},- rc::Rc,-};+use std::collections::{HashMap, HashSet};use style::{properties::ComputedValues, servo_arc::Arc as ServoArc, stylesheets::CssRuleType};use super::super::super::super::JsContextHost;+use super::observation::{+ ComputedStyleRead, RetainedStyleObservation, StyleComputationContext, StyleObservation,+};+use super::style_world::{+ active_stylesheet_handles, style_base_url, stylesheet_source_document_for_handle,+ stylesheet_text,+};use super::{StyleMode, all_shorthand_applies_to, animation_shorthand_longhands, css_wide_keyword,font_variant_longhands, inline_state_property_priority_with_pdb,@@ -44,248 +43,11 @@ use super::{text_decoration_shorthand_longhands, transition_shorthand_longhands,};-#[derive(Clone, Copy, Debug, Default)]-pub(in crate::native_bridge::element::styles) struct StyleComputationContext {- pub(in crate::native_bridge::element::styles) viewport: StyleViewport,- pub(in crate::native_bridge::element::styles) read_document: Option<DomHandle>,-}--impl StyleComputationContext {- pub(in crate::native_bridge::element::styles) const fn new(viewport: StyleViewport) -> Self {- Self {- viewport,- read_document: None,- }- }-- pub(in crate::native_bridge::element::styles) const fn viewport_width(self) -> Option<f64> {- self.viewport.width- }-- pub(in crate::native_bridge::element::styles) const fn viewport(self) -> StyleViewport {- self.viewport- }-- pub(in crate::native_bridge::element::styles) const fn with_read_document(- mut self,- read_document: Option<DomHandle>,- ) -> Self {- self.read_document = read_document;- self- }-- fn resolved_read_document(self, runtime: &JsContextHost, handle: DomHandle) -> DomHandle {- self.read_document- .or_else(|| runtime.dom_host().owner_document_handle(handle))- .unwrap_or_else(|| runtime.document_handle())- }-}--#[derive(Clone, Debug, Eq, Hash, PartialEq)]-struct StyloComputedStyleInputKey {- source_document: Option<DomHandle>,- tree_scope_roots: Vec<DomHandle>,-}--#[cfg(debug_assertions)]-#[derive(Clone, Copy)]-struct ComputedStyleReadInvariant {- dom_version: u64,- source_set_generation: u64,- retained_style_system_generation: u64,-}--/// Prepared style inputs shared by one synchronous rendered-state observation.-///-/// The scope never crosses a JavaScript callback, so DOM and stylesheet-/// mutations cannot occur between reads. Each Document receives one immutable-/// input snapshot containing its complete connected TreeScope universe.-pub(crate) struct ComputedStyleReadScope<'a> {- runtime: &'a JsContextHost,- context: StyleComputationContext,- drained_document: Option<DomHandle>,- additional_drained_documents: Vec<DomHandle>,- primary_input: Option<(- StyloComputedStyleInputKey,- Rc<StyloPreparedComputedStyleInputs>,- )>,- additional_inputs: Vec<(- StyloComputedStyleInputKey,- Rc<StyloPreparedComputedStyleInputs>,- )>,- #[cfg(debug_assertions)]- invariants: Vec<(DomHandle, ComputedStyleReadInvariant)>,-}--impl<'a> ComputedStyleReadScope<'a> {- pub(crate) fn new(runtime: &'a JsContextHost) -> Self {- Self::new_with_context(- runtime,- StyleComputationContext::new(runtime.style_viewport()),- )- }-- /// Creates one synchronous style-observation scope for an exact document- /// viewport selected by layout.- ///- /// Embedded documents cannot derive their used viewport from the iframe's- /// authored width/height alone: parent layout may change it through- /// box-sizing, padding, constraints, flex/grid sizing, or transforms. The- /// scoped context keeps viewport units and media queries aligned with the- /// numeric layout demand without mutating retained document state.- pub(crate) fn new_for_document_viewport(- runtime: &'a JsContextHost,- document: DomHandle,- viewport: StyleViewport,- ) -> Self {- Self::new_with_context(- runtime,- StyleComputationContext::new(viewport).with_read_document(Some(document)),- )- }-- fn new_with_context(runtime: &'a JsContextHost, context: StyleComputationContext) -> Self {- Self {- runtime,- context,- drained_document: None,- additional_drained_documents: Vec::new(),- primary_input: None,- additional_inputs: Vec::new(),- #[cfg(debug_assertions)]- invariants: Vec::new(),- }- }-- pub(crate) const fn runtime(&self) -> &'a JsContextHost {- self.runtime- }-- pub(crate) fn read(&mut self, handle: DomHandle) -> ComputedStyleRead<'a> {- let read_document = self.context.resolved_read_document(self.runtime, handle);- if self.drained_document != Some(read_document)- && !self.additional_drained_documents.contains(&read_document)- {- if self.drained_document.is_none() {- self.drained_document = Some(read_document);- } else {- self.additional_drained_documents.push(read_document);- }- self.runtime- .drain_pending_style_invalidations_for_computed_style_read_for_document(- read_document,- );- }-- let source_document = stylesheet_source_document_for_handle(self.runtime, handle);- let prepared_inputs = self.prepared_inputs(source_document);- let stylo_style = self- .runtime- .computed_style_snapshot_from_stylo_with_prepared_inputs(- handle,- prepared_inputs.as_ref(),- read_document,- );- #[cfg(debug_assertions)]- self.verify_stable_style_world_after_read(source_document);- ComputedStyleRead {- runtime: self.runtime,- handle,- context: self.context,- prepared_inputs,- stylo_style,- }- }-- fn prepared_inputs(- &mut self,- source_document: Option<DomHandle>,- ) -> Rc<StyloPreparedComputedStyleInputs> {- if let Some((prepared_key, inputs)) = self.primary_input.as_ref()- && prepared_key.source_document == source_document- {- return Rc::clone(inputs);- }- if let Some((_, inputs)) = self- .additional_inputs- .iter()- .find(|(prepared_key, _)| prepared_key.source_document == source_document)- {- return Rc::clone(inputs);- }-- let input_key = stylo_computed_style_input_key_for_document(self.runtime, source_document);- let inputs = stylo_prepared_computed_style_inputs_for_observation_scope(- self.runtime,- &input_key,- self.context,- );- if self.primary_input.is_none() {- self.primary_input = Some((input_key, Rc::clone(&inputs)));- } else {- self.additional_inputs.push((input_key, Rc::clone(&inputs)));- }- inputs- }-- #[cfg(debug_assertions)]- fn verify_stable_style_world_after_read(&mut self, source_document: Option<DomHandle>) {- let Some(document) = source_document else {- return;- };- let (dom_version, source_set_generation, retained_style_system_generation) =- self.runtime.computed_style_read_invariant_state(document);- let current = ComputedStyleReadInvariant {- dom_version,- source_set_generation,- retained_style_system_generation,- };- let Some((_, previous)) = self- .invariants- .iter_mut()- .find(|(candidate, _)| *candidate == document)- else {- self.invariants.push((document, current));- return;- };- if previous.dom_version == current.dom_version- && previous.source_set_generation == current.source_set_generation- {- debug_assert_eq!(- current.retained_style_system_generation, previous.retained_style_system_generation,- "one ComputedStyleReadScope rebuilt the retained style system without a DOM or style-source mutation",- );- } else {- *previous = current;- }- }-}--impl Drop for ComputedStyleReadScope<'_> {- fn drop(&mut self) {- if let Some((key, inputs)) = self.primary_input.as_ref() {- cache_stylo_computed_style_inputs_after_observation(- self.runtime,- key,- self.context,- inputs,- );- }- for (key, inputs) in &self.additional_inputs {- cache_stylo_computed_style_inputs_after_observation(- self.runtime,- key,- self.context,- inputs,- );- }- }-}-#[derive(Clone, Copy)]struct StyleResolutionContext<'a> {computation: StyleComputationContext,- inputs: Option<&'a StyloComputedStyleInputs>,+ inputs: Option<&'a FullStyleWorldSnapshot>,+ observation: Option<&'a dyn RetainedStyleObservation>,retained_style: Option<(DomHandle, &'a StyloComputedStyleSnapshot)>,}@@ -294,34 +56,68 @@ impl<'a> StyleResolutionContext<'a> {Self {computation,inputs: None,+ observation: None,retained_style: None,}}const fn prepared(computation: StyleComputationContext,- inputs: &'a StyloComputedStyleInputs,+ inputs: &'a FullStyleWorldSnapshot,) -> Self {Self {computation,inputs: Some(inputs),+ observation: None,retained_style: None,}}const fn retained(computation: StyleComputationContext,- inputs: &'a StyloComputedStyleInputs,+ inputs: &'a FullStyleWorldSnapshot,handle: DomHandle,style: &'a StyloComputedStyleSnapshot,) -> Self {Self {computation,inputs: Some(inputs),+ observation: None,+ retained_style: Some((handle, style)),+ }+ }++ const fn retained_without_inputs(+ computation: StyleComputationContext,+ handle: DomHandle,+ style: &'a StyloComputedStyleSnapshot,+ ) -> Self {+ Self {+ computation,+ inputs: None,+ observation: None,retained_style: Some((handle, style)),}}+ const fn observed(+ computation: StyleComputationContext,+ inputs: Option<&'a FullStyleWorldSnapshot>,+ observation: &'a dyn RetainedStyleObservation,+ handle: DomHandle,+ style: Option<&'a StyloComputedStyleSnapshot>,+ ) -> Self {+ Self {+ computation,+ inputs,+ observation: Some(observation),+ retained_style: match style {+ Some(style) => Some((handle, style)),+ None => None,+ },+ }+ }+fn computed_property(self,runtime: &JsContextHost,@@ -340,6 +136,19 @@ impl<'a> StyleResolutionContext<'a> {.map(|(_, style)| style),);}+ if let Some(observation) = self.observation+ && let Some(style) = observation.style_snapshot(handle)+ {+ return computed_style_property_value_after_style_update(+ runtime,+ handle,+ property,+ self.computation,+ None,+ Some(observation),+ Some(&style),+ );+ }style_property_value_with_context(runtime,handle,@@ -364,22 +173,16 @@ impl<'a> StyleResolutionContext<'a> {self.computation,);}+ if let Some(observation) = self.observation {+ return observation+ .style_snapshot(handle)+ .and_then(|style| style.property_value(property))+ .unwrap_or_default();+ }raw_stylo_computed_style_value(runtime, handle, property)}}-/// One synchronous computed-style read after the pending style lifecycle has-/// been drained. Chromium updates style once and lets all properties in the-/// read observe the same retained ComputedStyle; this is the no-layout-engine-/// equivalent for Moli's immutable Stylo input snapshot.-pub(crate) struct ComputedStyleRead<'a> {- runtime: &'a JsContextHost,- handle: DomHandle,- context: StyleComputationContext,- prepared_inputs: Rc<StyloPreparedComputedStyleInputs>,- stylo_style: Option<StyloComputedStyleSnapshot>,-}-impl<'a> ComputedStyleRead<'a> {pub(crate) fn new(runtime: &'a JsContextHost, handle: DomHandle) -> Self {let context = StyleComputationContext::new(runtime.style_viewport());@@ -391,7 +194,7 @@ impl<'a> ComputedStyleRead<'a> {handle: DomHandle,context: StyleComputationContext,) -> Self {- ComputedStyleReadScope::new_with_context(runtime, context).read(handle)+ StyleObservation::new_with_context(runtime, context).read(handle)}pub(in crate::native_bridge::element) fn property(&self, property: &str) -> String {@@ -417,39 +220,26 @@ impl<'a> ComputedStyleRead<'a> {.map(StyloComputedStyleSnapshot::computed_values)}- /// Returns the exact stylesheet source snapshots used by this read.- ///- /// Font resource reconciliation consumes the same immutable source set as- /// layout style resolution instead of rescanning live DOM owners through a- /// second ordering model. The returned text/base pairs own their data and- /// do not escape a borrow of Stylo's retained system.- pub(crate) fn stylesheet_source_snapshots(&self) -> Vec<(std::sync::Arc<str>, url::Url)> {- let inputs = self.prepared_inputs.inputs();- inputs- .document_stylesheet_sources- .iter()- .chain(- inputs- .shadow_stylesheet_sources- .iter()- .flat_map(|(_, sources)| sources),- )- .map(|source| (source.serialized_css_text(), source.base_url().clone()))- .collect()+ /// Returns the typed resource manifest published with this read's exact+ /// retained stylesheet world. No CSS text is serialized or reparsed.+ pub(crate) fn stylesheet_resource_snapshot(&self) -> Option<StylesheetResourceSnapshot> {+ let document = self.observation_inputs.source_document()?;+ self.runtime+ .stylesheet_resource_snapshot_for_document(document)}pub(crate) fn pseudo_computed_values(&self,pseudo_element: &str,) -> Option<ServoArc<ComputedValues>> {+ self.stylo_style.as_ref()?;let read_document = self.context.resolved_read_document(self.runtime, self.handle);self.runtime- .computed_pseudo_style_snapshot_from_stylo_with_prepared_inputs(+ .computed_pseudo_style_snapshot_from_current_observation(self.handle,pseudo_element,- self.prepared_inputs.as_ref(),read_document,).map(|snapshot| snapshot.computed_values())@@ -460,27 +250,31 @@ impl<'a> ComputedStyleRead<'a> {parent_style: &ComputedValues,anonymous_kind: StyloAnonymousBoxKind,) -> Option<ServoArc<ComputedValues>> {+ self.stylo_style.as_ref()?;let read_document = self.context.resolved_read_document(self.runtime, self.handle);self.runtime- .computed_anonymous_style_snapshot_from_stylo_with_prepared_inputs(+ .computed_anonymous_style_snapshot_from_current_observation(self.handle,parent_style,anonymous_kind,- self.prepared_inputs.as_ref(),read_document,).map(|snapshot| snapshot.computed_values())}fn property_in_prepared_scope(&self, property: &str) -> String {+ let stylesheet_query_snapshot =+ computed_property_requires_stylesheet_sources(property, self.stylo_style.as_ref())+ .then(|| self.observation_inputs.stylesheet_query_snapshot());computed_style_property_value_after_style_update(self.runtime,self.handle,property,self.context,- Some(self.prepared_inputs.inputs()),+ stylesheet_query_snapshot.as_deref(),+ Some(self.observation_inputs.as_ref()),self.stylo_style.as_ref(),)}@@ -497,17 +291,22 @@ impl<'a> ComputedStyleRead<'a> {.context.resolved_read_document(self.runtime, self.handle);self.runtime- .computed_style_property_value_from_stylo(+ .computed_pseudo_style_snapshot_from_current_observation(self.handle,- &property,- Some(pseudo_element),- self.prepared_inputs.inputs(),+ pseudo_element,read_document,- self.context.viewport,)+ .and_then(|style| style.resolved_property_value(&property)).unwrap_or_default()}+ fn raw_primary_property(&self, property: &str) -> Option<String> {+ let property = canonical_computed_cssom_query_property_name(property)?;+ self.stylo_style+ .as_ref()+ .and_then(|style| style.property_value(&property))+ }+pub(in crate::native_bridge::element::styles) fn custom_property_names(&self) -> Vec<String> {self.stylo_style.as_ref()@@ -530,160 +329,6 @@ impl<'a> ComputedStyleRead<'a> {}}-fn style_media_matches(runtime: &JsContextHost, handle: DomHandle) -> bool {- let Some(media) = runtime.dom_host().get_attribute(handle, "media") else {- return true;- };- let media = media.trim();- media.is_empty()- || evaluate_match_media_query_list_with_viewport(- media,- Some(runtime.emulated_media()),- runtime.style_viewport(),- )-}--fn style_is_enabled(runtime: &JsContextHost, handle: DomHandle) -> bool {- runtime- .dom_host()- .get_attribute(handle, "disabled")- .is_none()-}--fn link_stylesheet_is_enabled(runtime: &JsContextHost, handle: DomHandle) -> bool {- if runtime- .dom_host()- .get_attribute(handle, "disabled")- .is_some()- {- return false;- }- let rel = runtime.dom_host().get_attribute(handle, "rel");- let Some(rel) = rel.as_deref() else {- return false;- };- let title = runtime.dom_host().get_attribute(handle, "title");- if !link_rel_qualifies_as_stylesheet(Some(rel), title.as_deref()) {- return false;- }- !link_rel_includes_token(rel, "alternate")- || runtime- .dom_host()- .node(handle)- .and_then(Node::as_element)- .is_some_and(|element| element.link_explicitly_enabled())-}--fn stylesheet_preferred_title(runtime: &JsContextHost, handle: DomHandle) -> Option<String> {- runtime- .dom_host()- .get_attribute(handle, "title")- .filter(|title| !title.is_empty())-}--fn linked_stylesheet_source(- runtime: &JsContextHost,- handle: DomHandle,-) -> Option<StyloStylesheetSource> {- runtime.linked_stylesheet_source_for_owner(handle)-}--fn collect_stylesheet_handles(- runtime: &JsContextHost,- root: DomHandle,- include_detached: bool,-) -> Vec<DomHandle> {- let mut handles = runtime- .dom_host()- .stylesheet_candidate_handles_for_tree_scope(root)- .iter()- .copied()- .filter(|handle| {- let Some(element) = runtime.dom_host().node(*handle).and_then(Node::as_element) else {- return false;- };- let style = element.is_inline_style_element() && style_is_enabled(runtime, *handle);- let link =- element.is_html_element("link") && link_stylesheet_is_enabled(runtime, *handle);- (style || link)- && (include_detached- || stylesheet_handle_is_active_in_scope(runtime, root, *handle))- && is_stylesheet_type_attribute(- runtime.dom_host().get_attribute(*handle, "type").as_deref(),- )- && style_media_matches(runtime, *handle)- })- .collect::<Vec<_>>();- let preferred_title = handles- .iter()- .filter_map(|handle| {- stylesheet_preferred_title(runtime, *handle).map(|title| (*handle, title))- })- .min_by_key(|(handle, _)| handle.index())- .map(|(_, title)| title);- if let Some(preferred_title) = preferred_title {- handles.retain(|handle| {- stylesheet_preferred_title(runtime, *handle)- .is_none_or(|title| title == preferred_title)- });- }- handles-}--fn stylesheet_handle_is_active_in_scope(- runtime: &JsContextHost,- root: DomHandle,- handle: DomHandle,-) -> bool {- runtime.dom_host().is_connected(handle)- || runtime- .child_browsing_context_host_for_document_handle(root)- .is_some_and(|frame_handle| runtime.dom_host().is_connected(frame_handle))- || (runtime.dom_host().is_shadow_root(root)- && runtime- .dom_host()- .shadow_root_host(root)- .is_some_and(|host| runtime.dom_host().is_connected(host)))-}--fn stylesheet_source_for_handle(- runtime: &JsContextHost,- handle: DomHandle,-) -> StyloStylesheetSource {- let Some(element) = runtime.dom_host().node(handle).and_then(Node::as_element) else {- return StyloStylesheetSource::new(String::new(), style_base_url(runtime, handle));- };- if element.is_html_element("link") {- return linked_stylesheet_source(runtime, handle)- .unwrap_or_else(|| {- StyloStylesheetSource::new(String::new(), style_base_url(runtime, handle))- })- .with_source_id(StyleSourceId::linked_style_sheet(- runtime.dom_host(),- handle,- ));- }- if element.is_inline_style_element()- && let Some(source) = runtime.owner_style_sheet_source(handle)- {- return source.with_source_id(StyleSourceId::owner_style_sheet(runtime.dom_host(), handle));- }- StyloStylesheetSource::new(String::new(), style_base_url(runtime, handle))-}--fn cascade_stylesheet_sources_for_handle(- runtime: &JsContextHost,- handle: DomHandle,-) -> Vec<StyloStylesheetSource> {- vec![stylesheet_source_for_handle(runtime, handle)]-}--fn stylesheet_text_for_handle(runtime: &JsContextHost, handle: DomHandle) -> String {- stylesheet_source_for_handle(runtime, handle)- .serialized_css_text()- .to_string()-}-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@@ -705,8 +350,8 @@ pub(crate) fn css_animation_start_applies(runtime: &JsContextHost, handle: DomHalet Some(document) = stylesheet_source_document_for_handle(runtime, handle) else {return false;};- for stylesheet in collect_stylesheet_handles(runtime, document, false) {- let css_text = stylesheet_text_for_handle(runtime, stylesheet);+ for stylesheet in active_stylesheet_handles(runtime, document, false) {+ let css_text = stylesheet_text(runtime, stylesheet);if keyframe_has_supported_animation_values(&css_text, &names) {return true;}@@ -831,8 +476,8 @@ fn active_css_animation_property_values_with_resolution(return None;}let document = stylesheet_source_document_for_handle(runtime, handle)?;- for stylesheet in collect_stylesheet_handles(runtime, document, false) {- let css_text = stylesheet_text_for_handle(runtime, stylesheet);+ for stylesheet in active_stylesheet_handles(runtime, document, false) {+ let css_text = stylesheet_text(runtime, stylesheet);if let Some(values) = keyframe_property_values(&css_text, &names, property) {return Some(values);}@@ -840,13 +485,6 @@ fn active_css_animation_property_values_with_resolution(None}-fn stylesheet_source_document_for_handle(- runtime: &JsContextHost,- handle: DomHandle,-) -> Option<DomHandle> {- runtime.dom_host().owner_document_handle(handle)-}-fn active_css_animation_names(runtime: &JsContextHost, handle: DomHandle) -> Vec<String> {active_css_animation_names_with_context(runtime,@@ -1105,237 +743,13 @@ fn transform_translate_x_px(value: &str) -> Option<f64> {moli_css_parse::parse_px_length(raw, moli_css_parse::UnitlessLength::ZeroOnly)}-fn document_scope_stylesheet_sources(- runtime: &JsContextHost,- source_document: Option<DomHandle>,- context: StyleComputationContext,-) -> Vec<StyloStylesheetSource> {- let mut sources = Vec::new();- let Some(document) = source_document else {- return sources;- };- for style_handle in- collect_stylesheet_handles(runtime, document, context.read_document.is_some())- {- sources.extend(cascade_stylesheet_sources_for_handle(runtime, style_handle));- }- sources.extend(- runtime- .adopted_style_sheet_sources_for_document(document)- .iter()- .enumerate()- .map(|(index, source)| {- source- .clone()- .with_source_id(Some(StyleSourceId::document_adopted_style_sheet(- document, index,- )))- }),- );- sources-}--fn shadow_stylesheet_sources(- runtime: &JsContextHost,- root: DomHandle,- context: StyleComputationContext,-) -> Vec<StyloStylesheetSource> {- let mut sources = Vec::new();- for style_handle in collect_stylesheet_handles(runtime, root, context.read_document.is_some()) {- sources.extend(cascade_stylesheet_sources_for_handle(runtime, style_handle));- }- let adopted_sources = runtime.shadow_root_adopted_style_sheet_sources(root);- sources.extend(- adopted_sources- .into_iter()- .enumerate()- .map(|(index, source)| {- source.with_source_id(Some(StyleSourceId::shadow_root_adopted_style_sheet(- root, index,- )))- }),- );- sources-}--fn stylo_computed_style_inputs(- runtime: &JsContextHost,- handle: DomHandle,- context: StyleComputationContext,-) -> Rc<StyloComputedStyleInputs> {- let key = stylo_computed_style_input_key(runtime, handle);- stylo_computed_style_inputs_for_key(runtime, &key, context)-}--fn stylo_computed_style_input_key(- runtime: &JsContextHost,- handle: DomHandle,-) -> StyloComputedStyleInputKey {- stylo_computed_style_input_key_for_document(- runtime,- stylesheet_source_document_for_handle(runtime, handle),- )-}--fn stylo_computed_style_input_key_for_document(- runtime: &JsContextHost,- source_document: Option<DomHandle>,-) -> StyloComputedStyleInputKey {- StyloComputedStyleInputKey {- source_document,- tree_scope_roots: source_document- .map(|document| connected_shadow_roots_for_document(runtime.dom_host(), document))- .unwrap_or_default(),- }-}--fn stylo_computed_style_inputs_for_key(- runtime: &JsContextHost,- key: &StyloComputedStyleInputKey,- context: StyleComputationContext,-) -> Rc<StyloComputedStyleInputs> {- let source_document = key.source_document;- let (script_custom_property_base_url, environment) =- stylo_computed_style_input_environment(runtime, source_document);- stylo_computed_style_inputs_with_environment(- runtime,- key,- context,- script_custom_property_base_url,- environment,- )-}--fn stylo_prepared_computed_style_inputs_for_observation_scope(- runtime: &JsContextHost,- key: &StyloComputedStyleInputKey,- context: StyleComputationContext,-) -> Rc<StyloPreparedComputedStyleInputs> {- let source_document = key.source_document;- let (script_custom_property_base_url, environment) =- stylo_computed_style_input_environment(runtime, source_document);- if let Some(document) = source_document {- let cache_key = StyloDocumentComputedStyleInputCacheKey::new(- context.read_document,- &key.tree_scope_roots,- runtime.document_url(),- context.viewport,- environment,- &script_custom_property_base_url,- );- if let Some(inputs) = runtime.cached_document_prepared_style_inputs(document, &cache_key) {- return inputs;- }- }- let inputs = stylo_computed_style_inputs_with_environment(- runtime,- key,- context,- script_custom_property_base_url,- environment,- );- #[cfg(test)]- runtime.note_stylo_style_system_key_build_for_test();- Rc::new(StyloPreparedComputedStyleInputs::new(- runtime.document_url(),- inputs,- context.viewport,- ))-}--fn cache_stylo_computed_style_inputs_after_observation(- runtime: &JsContextHost,- key: &StyloComputedStyleInputKey,- context: StyleComputationContext,- inputs: &Rc<StyloPreparedComputedStyleInputs>,-) {- let Some(document) = key.source_document else {- return;- };- let cache_key = StyloDocumentComputedStyleInputCacheKey::new(- context.read_document,- &key.tree_scope_roots,- runtime.document_url(),- context.viewport,- inputs.inputs().environment,- &inputs.inputs().script_custom_property_base_url,- );- runtime.cache_document_prepared_style_inputs(document, cache_key, Rc::clone(inputs));-}--fn stylo_computed_style_input_environment(- runtime: &JsContextHost,- source_document: Option<DomHandle>,-) -> (url::Url, StyloStyleEnvironment) {- let script_custom_property_base_url = source_document- .map(|document| runtime.document_base_url_for_handle(document))- .unwrap_or_else(|| url::Url::parse("about:blank").expect("static about:blank URL parses"));- let environment = StyloStyleEnvironment::from_emulated_media(runtime.emulated_media());- (script_custom_property_base_url, environment)-}--fn stylo_computed_style_inputs_with_environment(- runtime: &JsContextHost,- key: &StyloComputedStyleInputKey,- context: StyleComputationContext,- script_custom_property_base_url: url::Url,- environment: StyloStyleEnvironment,-) -> Rc<StyloComputedStyleInputs> {- let source_document = key.source_document;- #[cfg(test)]- runtime.note_stylo_computed_style_input_build_for_test();- let script_custom_property_registrations = source_document- .map(|document| runtime.script_css_custom_property_registrations(document))- .unwrap_or_default();- let mut inputs = StyloComputedStyleInputs {- document_stylesheet_sources: document_scope_stylesheet_sources(- runtime,- source_document,- context,- ),- shadow_stylesheet_sources: Vec::new(),- script_custom_property_registrations,- script_custom_property_base_url,- environment,- quirks_mode: source_document- .and_then(|document| runtime.dom_host().node(document))- .and_then(crate::dom::native::Node::as_document)- .map(|document| document.quirks_mode())- .unwrap_or(style::context::QuirksMode::NoQuirks),- };- for root in key.tree_scope_roots.iter().copied() {- let sources = shadow_stylesheet_sources(runtime, root, context);- inputs.shadow_stylesheet_sources.push((root, sources));- }- Rc::new(inputs)-}--fn connected_shadow_roots_for_document(host: &DomHost, document: DomHandle) -> Vec<DomHandle> {- let mut roots = host- .snapshot_connected_shadow_roots()- .into_iter()- .filter(|root| host.owner_document_handle(*root) == Some(document))- .collect::<Vec<_>>();- roots.sort_by_key(|root| root.index());- roots-}-fn stylo_computed_style_value(runtime: &JsContextHost,handle: DomHandle,property: &str,context: StyleComputationContext,) -> Option<String> {- let inputs = stylo_computed_style_inputs(runtime, handle, context);- let read_document = context.resolved_read_document(runtime, handle);- runtime.computed_style_property_value_from_stylo(- handle,- property,- None,- &inputs,- read_document,- context.viewport,- )+ ComputedStyleRead::new_with_context(runtime, handle, context).raw_primary_property(property)}fn stylo_computed_pseudo_style_value(@@ -1345,16 +759,9 @@ fn stylo_computed_pseudo_style_value(property: &str,context: StyleComputationContext,) -> Option<String> {- let inputs = stylo_computed_style_inputs(runtime, handle, context);- let read_document = context.resolved_read_document(runtime, handle);- runtime.computed_style_property_value_from_stylo(- handle,- property,- Some(pseudo_element),- &inputs,- read_document,- context.viewport,- )+ let read = ComputedStyleRead::new_with_context(runtime, handle, context);+ let value = read.raw_pseudo_property(pseudo_element, property);+ (!value.is_empty()).then_some(value)}fn normalized_stylo_computed_style_value(@@ -1372,7 +779,7 @@ fn normalized_stylo_computed_style_value_with_inputs(handle: DomHandle,property: &str,context: StyleComputationContext,- inputs: &StyloComputedStyleInputs,+ inputs: &FullStyleWorldSnapshot,) -> Option<String> {let read_document = context.resolved_read_document(runtime, handle);let value = runtime.computed_style_property_value_from_stylo(@@ -2079,17 +1486,7 @@ fn inherited_computed_style_value(}fn inherited_style_parent(runtime: &JsContextHost, handle: DomHandle) -> Option<DomHandle> {- if runtime.dom_host().is_shadow_root(handle) {- return runtime.dom_host().shadow_root_host(handle);- }- let parent = runtime- .dom_host()- .node(handle)- .and_then(Node::parent_node)?;- if runtime.dom_host().is_shadow_root(parent) {- return runtime.dom_host().shadow_root_host(parent);- }- Some(parent)+ flat_tree_element_parent(runtime, handle)}pub(crate) fn style_property_value(@@ -2900,9 +2297,7 @@ fn computed_style_property_value_with_context(property: &str,context: StyleComputationContext,) -> String {- let read_document = context.resolved_read_document(runtime, handle);- runtime.drain_pending_style_invalidations_for_computed_style_read_for_document(read_document);- computed_style_property_value_after_style_update(runtime, handle, property, context, None, None)+ ComputedStyleRead::new_with_context(runtime, handle, context).property(property)}fn computed_style_property_value_after_style_update(@@ -2910,7 +2305,8 @@ fn computed_style_property_value_after_style_update(handle: DomHandle,property: &str,context: StyleComputationContext,- prepared_inputs: Option<&StyloComputedStyleInputs>,+ prepared_inputs: Option<&FullStyleWorldSnapshot>,+ observation: Option<&dyn RetainedStyleObservation>,prepared_style: Option<&StyloComputedStyleSnapshot>,) -> String {if !computed_style_applies(runtime, handle) {@@ -2919,17 +2315,19 @@ fn computed_style_property_value_after_style_update(if property == "display" && element_has_hidden_attribute(runtime, handle) {return "none".to_owned();}- let owned_inputs;- let inputs = if let Some(inputs) = prepared_inputs {- inputs- } else {- owned_inputs = stylo_computed_style_inputs(runtime, handle, context);- owned_inputs.as_ref()- };- let resolution = if let Some(style) = prepared_style {- StyleResolutionContext::retained(context, inputs, handle, style)- } else {+ let inputs = prepared_inputs;+ let resolution = if let Some(observation) = observation {+ StyleResolutionContext::observed(context, inputs, observation, handle, prepared_style)+ } else if let Some(style) = prepared_style {+ if let Some(inputs) = inputs {+ StyleResolutionContext::retained(context, inputs, handle, style)+ } else {+ StyleResolutionContext::retained_without_inputs(context, handle, style)+ }+ } else if let Some(inputs) = inputs {StyleResolutionContext::prepared(context, inputs)+ } else {+ StyleResolutionContext::independent(context)};if property == "direction" {return computed_direction_with_resolution(runtime, handle, resolution);@@ -3027,10 +2425,12 @@ fn computed_style_property_value_after_style_update(runtime, handle, property, &value, resolution,)})- } else {+ } else if let Some(inputs) = inputs {normalized_stylo_computed_style_value_with_inputs(runtime, handle, property, context, inputs,)+ } else {+ None}.or_else(|| computed_style_property_value_from_moli(runtime, handle, property));let value = raw_value@@ -3045,18 +2445,31 @@ fn computed_style_property_value_after_style_update() {return value;}- let value =- resolve_computed_custom_function_calls(runtime, handle, property, &value, inputs, context);- resolve_moli_computed_style_value(- runtime, handle, property, &value, inputs, context, resolution,- )+ let value = inputs+ .map(|inputs| {+ resolve_computed_custom_function_calls(+ runtime, handle, property, &value, inputs, context,+ )+ })+ .unwrap_or(value);+ resolve_moli_computed_style_value(runtime, handle, property, &value, context, resolution)+}++fn computed_property_requires_stylesheet_sources(+ property: &str,+ style: Option<&StyloComputedStyleSnapshot>,+) -> bool {+ property.starts_with("--")+ && style+ .and_then(|style| style.property_value(property))+ .is_some_and(|value| !dashed_no_arg_function_calls(&value).is_empty())}fn computed_style_property_value_with_prepared_inputs(runtime: &JsContextHost,handle: DomHandle,property: &str,- inputs: &StyloComputedStyleInputs,+ inputs: &FullStyleWorldSnapshot,context: StyleComputationContext,prepared_style: Option<&StyloComputedStyleSnapshot>,) -> String {@@ -3066,6 +2479,7 @@ fn computed_style_property_value_with_prepared_inputs(property,context,Some(inputs),+ None,prepared_style,)}@@ -3619,21 +3033,6 @@ fn css_numeric_context_with_viewport()}-fn css_numeric_context_with_viewport_and_inputs(- runtime: &JsContextHost,- handle: DomHandle,- viewport: StyleViewport,- inputs: &StyloComputedStyleInputs,- context: StyleComputationContext,-) -> moli_css_parse::CssNumericContext {- css_numeric_context_with_viewport_and_resolution(- runtime,- handle,- viewport,- StyleResolutionContext::prepared(context, inputs),- )-}-fn css_numeric_context_with_viewport_and_resolution(runtime: &JsContextHost,handle: DomHandle,@@ -3646,7 +3045,12 @@ fn css_numeric_context_with_viewport_and_resolution(.unwrap_or(16.0);let root_font_size = runtime.dom_host()- .document_element_handle()+ .owner_document_handle(handle)+ .and_then(|document| {+ runtime+ .dom_host()+ .document_element_handle_for_document(document)+ }).and_then(|document_element| {inline_font_size_px(runtime, document_element).or_else(|| {computed_font_size_px_with_resolution(runtime, document_element, resolution)@@ -3686,7 +3090,7 @@ fn nearest_size_container_width(handle: DomHandle,resolution: StyleResolutionContext<'_>,) -> Option<f64> {- let mut current = flat_tree_parent(runtime, handle);+ let mut current = flat_tree_element_parent(runtime, handle);let mut visited = HashSet::new();while let Some(candidate) = current {if !visited.insert(candidate) {@@ -3695,7 +3099,7 @@ fn nearest_size_container_width(if element_is_size_container(runtime, candidate, resolution) {return inline_width_px_with_resolution(runtime, candidate, resolution);}- current = flat_tree_parent(runtime, candidate);+ current = flat_tree_element_parent(runtime, candidate);}None}@@ -5148,7 +4552,7 @@ fn resolve_computed_custom_function_calls(handle: DomHandle,property: &str,value: &str,- inputs: &StyloComputedStyleInputs,+ inputs: &FullStyleWorldSnapshot,context: StyleComputationContext,) -> String {if !property.starts_with("--") || !value.contains("--") || !value.contains("()") {@@ -5231,7 +4635,7 @@ fn computed_custom_property_source_scope(handle: DomHandle,property: &str,value: &str,- inputs: &StyloComputedStyleInputs,+ inputs: &FullStyleWorldSnapshot,viewport_width: Option<f64>,) -> Option<DomHandle> {for (root, sources) in inputs.shadow_stylesheet_sources.iter().rev() {@@ -5266,15 +4670,14 @@ fn stylesheet_sources_compute_custom_property_value(handle: DomHandle,property: &str,value: &str,- inputs: &StyloComputedStyleInputs,+ inputs: &FullStyleWorldSnapshot,scoped_sources: Option<(DomHandle, &[StyloStylesheetSource])>,viewport_width: Option<f64>,) -> bool {- let mut scoped_inputs = StyloComputedStyleInputs {+ let mut scoped_inputs = FullStyleWorldSnapshot {document_stylesheet_sources: Vec::new(),shadow_stylesheet_sources: Vec::new(),script_custom_property_registrations: inputs.script_custom_property_registrations.clone(),- script_custom_property_base_url: inputs.script_custom_property_base_url.clone(),environment: inputs.environment,quirks_mode: inputs.quirks_mode,};@@ -5293,10 +4696,9 @@ fn stylesheet_sources_compute_custom_property_value(return false;};runtime- .computed_style_property_value_from_stylo(+ .computed_style_property_value_from_ephemeral_stylo(handle,property,- None,&scoped_inputs,read_document,viewport,@@ -5329,7 +4731,7 @@ struct CustomFunctionContainerRuleText {fn visible_custom_functions_for_scope(runtime: &JsContextHost,- inputs: &StyloComputedStyleInputs,+ inputs: &FullStyleWorldSnapshot,scope: DomHandle,) -> HashMap<String, CustomCssFunction> {let mut functions = HashMap::new();@@ -5535,7 +4937,7 @@ fn named_container_width(container_name: &str,context: StyleComputationContext,) -> Option<f64> {- let mut current = flat_tree_parent(runtime, handle);+ let mut current = flat_tree_element_parent(runtime, handle);let mut visited = HashSet::new();while let Some(candidate) = current {if !visited.insert(candidate) {@@ -5544,14 +4946,21 @@ fn named_container_width(if element_is_named_size_container(runtime, candidate, container_name, context) {return inline_width_px(runtime, candidate);}- current = flat_tree_parent(runtime, candidate);+ current = flat_tree_element_parent(runtime, candidate);}None}-fn flat_tree_parent(runtime: &JsContextHost, handle: DomHandle) -> Option<DomHandle> {+fn flat_tree_element_parent(runtime: &JsContextHost, handle: DomHandle) -> Option<DomHandle> {if let Some(slot) = runtime.dom_host().assigned_slot_for_node(handle) {- return Some(slot);+ return runtime+ .dom_host()+ .node(slot)+ .is_some_and(Node::is_element)+ .then_some(slot);+ }+ if runtime.dom_host().is_shadow_root(handle) {+ return runtime.dom_host().shadow_root_host(handle);}let parent = runtime.dom_host()@@ -5560,7 +4969,11 @@ fn flat_tree_parent(runtime: &JsContextHost, handle: DomHandle) -> Option<DomHanif runtime.dom_host().is_shadow_root(parent) {return runtime.dom_host().shadow_root_host(parent);}- Some(parent)+ runtime+ .dom_host()+ .node(parent)+ .is_some_and(Node::is_element)+ .then_some(parent)}fn element_is_named_size_container(@@ -5638,7 +5051,6 @@ fn resolve_moli_computed_style_value(handle: DomHandle,property: &str,value: &str,- inputs: &StyloComputedStyleInputs,context: StyleComputationContext,resolution: StyleResolutionContext<'_>,) -> String {@@ -5673,15 +5085,14 @@ fn resolve_moli_computed_style_value(return normalize_cssom_font_family_value(value).unwrap_or_else(|| value.to_owned());}if property == "width"- && let Some(width) = resolve_computed_width_with_inline_fallback(- runtime, handle, value, inputs, context, resolution,- )+ && let Some(width) =+ resolve_computed_width_with_inline_fallback(runtime, handle, value, context, resolution){return width;}if property == "height"&& let Some(height) = resolve_computed_height_with_inline_fallback(- runtime, handle, value, inputs, context, resolution,+ runtime, handle, value, context, resolution,){return height;@@ -5693,20 +5104,17 @@ fn resolve_moli_computed_style_value(return line_height;}// Horizontal used-value resolution recursively reads the containing block- // and the element's own width. Keep those reads on this exact prepared- // context: reconstructing it from only `viewport.width` drops viewport- // height and screen dimensions, which makes the retained style key- // oscillate and is especially wrong for child-frame viewports.+ // and the element's own width from this exact retained observation.if matches!(property, "margin-left" | "margin-right")&& let Some(margin) = resolve_computed_horizontal_auto_margin(- runtime, handle, property, value, inputs, context,+ runtime, handle, property, value, context, resolution,){return margin;}if matches!(property, "margin-left" | "margin-right")&& let Some(margin) = resolve_computed_horizontal_margin_with_inline_fallback(- runtime, handle, property, value, inputs, context,+ runtime, handle, property, value, context, resolution,){return margin;@@ -6148,7 +5556,7 @@ fn resolve_computed_auto_min_size(if !aspect_ratio.is_empty() && aspect_ratio != "auto" {return "auto".to_owned();}- if let Some(parent) = runtime.dom_host().node(handle).and_then(Node::parent_node) {+ if let Some(parent) = flat_tree_element_parent(runtime, handle) {let parent_display = resolution.computed_property(runtime, parent, "display");if matches!(parent_display.as_str(),@@ -6170,10 +5578,7 @@ fn display_none_ancestor(if resolution.computed_property(runtime, candidate, "display") == "none" {return true;}- current = runtime- .dom_host()- .node(candidate)- .and_then(Node::parent_node);+ current = flat_tree_element_parent(runtime, candidate);}false}@@ -6345,7 +5750,7 @@ fn raw_stylo_computed_style_value_with_inputs(runtime: &JsContextHost,handle: DomHandle,property: &str,- inputs: &StyloComputedStyleInputs,+ inputs: &FullStyleWorldSnapshot,context: StyleComputationContext,) -> String {let read_document = context.resolved_read_document(runtime, handle);@@ -6366,15 +5771,7 @@ fn raw_stylo_computed_style_value_with_context(property: &str,context: StyleComputationContext,) -> Option<String> {- let inputs = stylo_computed_style_inputs(runtime, handle, context);- let value = raw_stylo_computed_style_value_with_inputs(- runtime,- handle,- property,- inputs.as_ref(),- context,- );- (!value.is_empty()).then_some(value)+ ComputedStyleRead::new_with_context(runtime, handle, context).raw_primary_property(property)}fn computed_inset_containing_block_size(@@ -6717,28 +6114,21 @@ fn resolve_computed_horizontal_auto_margin(handle: DomHandle,property: &str,value: &str,- inputs: &StyloComputedStyleInputs,context: StyleComputationContext,+ resolution: StyleResolutionContext<'_>,) -> Option<String> {if !value.eq_ignore_ascii_case("auto") {return None;}- let parent_width = containing_block_width_with_inputs(runtime, handle, inputs, context, 0)?;- let own_width = parse_css_px(&computed_style_property_value_with_prepared_inputs(- runtime, handle, "width", inputs, context, None,- ))?;+ let parent_width =+ containing_block_width_with_resolution(runtime, handle, context, resolution, 0)?;+ let own_width = parse_css_px(&resolution.computed_property(runtime, handle, "width"))?;let other_property = if property == "margin-left" {"margin-right"} else {"margin-left"};- let other = raw_stylo_computed_style_value_with_inputs(- runtime,- handle,- other_property,- inputs,- context,- );+ let other = resolution.raw_property(runtime, handle, other_property);let other_margin = if other.eq_ignore_ascii_case("auto") {None} else {@@ -6757,22 +6147,22 @@ fn resolve_computed_horizontal_margin(runtime: &JsContextHost,handle: DomHandle,value: &str,- inputs: &StyloComputedStyleInputs,context: StyleComputationContext,+ resolution: StyleResolutionContext<'_>,) -> Option<String> {if value.eq_ignore_ascii_case("auto") {return None;}- let parent_width = containing_block_width_with_inputs(runtime, handle, inputs, context, 0)?;+ let parent_width =+ containing_block_width_with_resolution(runtime, handle, context, resolution, 0)?;let resolved = resolve_length_percentage_with_context(value,parent_width,- css_numeric_context_with_viewport_and_inputs(+ css_numeric_context_with_viewport_and_resolution(runtime,handle,context.viewport(),- inputs,- context,+ resolution,),)?;Some(format_css_px(resolved))@@ -6783,21 +6173,37 @@ fn resolve_computed_horizontal_margin_with_inline_fallback(handle: DomHandle,property: &str,value: &str,- inputs: &StyloComputedStyleInputs,context: StyleComputationContext,+ resolution: StyleResolutionContext<'_>,) -> Option<String> {if computed_length_percentage_value_needs_moli_context(value) {inline_style_entry_for_inline_style(runtime, handle, property).and_then(|entry| {- resolve_computed_horizontal_margin(runtime, handle, &entry.value, inputs, context)+ resolve_computed_horizontal_margin(+ runtime,+ handle,+ &entry.value,+ context,+ resolution,+ )})- .or_else(|| resolve_computed_horizontal_margin(runtime, handle, value, inputs, context))- } else {- resolve_computed_horizontal_margin(runtime, handle, value, inputs, context).or_else(|| {- inline_style_entry_for_inline_style(runtime, handle, property).and_then(|entry| {- resolve_computed_horizontal_margin(runtime, handle, &entry.value, inputs, context)+ .or_else(|| {+ resolve_computed_horizontal_margin(runtime, handle, value, context, resolution)})- })+ } else {+ resolve_computed_horizontal_margin(runtime, handle, value, context, resolution).or_else(+ || {+ inline_style_entry_for_inline_style(runtime, handle, property).and_then(|entry| {+ resolve_computed_horizontal_margin(+ runtime,+ handle,+ &entry.value,+ context,+ resolution,+ )+ })+ },+ )}}@@ -6885,7 +6291,6 @@ fn resolve_computed_width(runtime: &JsContextHost,handle: DomHandle,value: &str,- inputs: &StyloComputedStyleInputs,context: StyleComputationContext,resolution: StyleResolutionContext<'_>,) -> Option<String> {@@ -6893,7 +6298,8 @@ fn resolve_computed_width(return None;}let viewport = context.viewport();- let parent_width = containing_block_width_with_inputs(runtime, handle, inputs, context, 0)?;+ let parent_width =+ containing_block_width_with_resolution(runtime, handle, context, resolution, 0)?;let resolved = resolve_length_percentage_with_context(value,parent_width,@@ -6906,20 +6312,19 @@ fn resolve_computed_width_with_inline_fallback(runtime: &JsContextHost,handle: DomHandle,value: &str,- inputs: &StyloComputedStyleInputs,context: StyleComputationContext,resolution: StyleResolutionContext<'_>,) -> Option<String> {if computed_length_percentage_value_needs_moli_context(value) {inline_style_entry_for_inline_style(runtime, handle, "width").and_then(|entry| {- resolve_computed_width(runtime, handle, &entry.value, inputs, context, resolution)+ resolve_computed_width(runtime, handle, &entry.value, context, resolution)})- .or_else(|| resolve_computed_width(runtime, handle, value, inputs, context, resolution))+ .or_else(|| resolve_computed_width(runtime, handle, value, context, resolution))} else {- resolve_computed_width(runtime, handle, value, inputs, context, resolution).or_else(|| {+ resolve_computed_width(runtime, handle, value, context, resolution).or_else(|| {inline_style_entry_for_inline_style(runtime, handle, "width").and_then(|entry| {- resolve_computed_width(runtime, handle, &entry.value, inputs, context, resolution)+ resolve_computed_width(runtime, handle, &entry.value, context, resolution)})})}@@ -6951,11 +6356,11 @@ fn element_has_no_used_height()}-fn containing_block_width_with_inputs(+fn containing_block_width_with_resolution(runtime: &JsContextHost,handle: DomHandle,- inputs: &StyloComputedStyleInputs,context: StyleComputationContext,+ resolution: StyleResolutionContext<'_>,depth: usize,) -> Option<f64> {if depth > 32 {@@ -6965,19 +6370,19 @@ fn containing_block_width_with_inputs(.dom_host().node(handle).and_then(Node::parent_node)?;- if let Some(width) = raw_computed_width_px(runtime, parent, inputs, context) {+ if let Some(width) = raw_computed_width_px(runtime, parent, resolution) {return Some(width);}let parent_is_viewport_box = runtime.dom_host().node(parent).is_some_and(|node| {node.is_html_element_named("body") || node.is_html_element_named("html")});- if let Some(percent) = raw_computed_width_percent(runtime, parent, inputs, context) {+ if let Some(percent) = raw_computed_width_percent(runtime, parent, resolution) {let viewport_width = context.viewport_width();let parent_parent_width = if parent_is_viewport_box {viewport_width.unwrap_or(moli_browser_profile::DEFAULT_WINDOW_SURFACE_PROFILE.inner_width)} else {- containing_block_width_with_inputs(runtime, parent, inputs, context, depth + 1)?+ containing_block_width_with_resolution(runtime, parent, context, resolution, depth + 1)?};return Some(parent_parent_width * percent / 100.0);}@@ -6988,14 +6393,13 @@ fn containing_block_width_with_inputs(.unwrap_or(moli_browser_profile::DEFAULT_WINDOW_SURFACE_PROFILE.inner_width),);}- containing_block_width_with_inputs(runtime, parent, inputs, context, depth + 1)+ containing_block_width_with_resolution(runtime, parent, context, resolution, depth + 1)}fn resolve_computed_height(runtime: &JsContextHost,handle: DomHandle,value: &str,- inputs: &StyloComputedStyleInputs,context: StyleComputationContext,resolution: StyleResolutionContext<'_>,) -> Option<String> {@@ -7006,7 +6410,7 @@ fn resolve_computed_height(return None;}let viewport = context.viewport();- let parent_height = containing_block_height(runtime, handle, inputs, context, 0)?;+ let parent_height = containing_block_height(runtime, handle, context, resolution, 0)?;let resolved = resolve_length_percentage_with_context(value,parent_height,@@ -7019,22 +6423,19 @@ fn resolve_computed_height_with_inline_fallback(runtime: &JsContextHost,handle: DomHandle,value: &str,- inputs: &StyloComputedStyleInputs,context: StyleComputationContext,resolution: StyleResolutionContext<'_>,) -> Option<String> {if computed_length_percentage_value_needs_moli_context(value) {inline_style_entry_for_inline_style(runtime, handle, "height").and_then(|entry| {- resolve_computed_height(runtime, handle, &entry.value, inputs, context, resolution)- })- .or_else(|| {- resolve_computed_height(runtime, handle, value, inputs, context, resolution)+ resolve_computed_height(runtime, handle, &entry.value, context, resolution)})+ .or_else(|| resolve_computed_height(runtime, handle, value, context, resolution))} else {- resolve_computed_height(runtime, handle, value, inputs, context, resolution).or_else(|| {+ resolve_computed_height(runtime, handle, value, context, resolution).or_else(|| {inline_style_entry_for_inline_style(runtime, handle, "height").and_then(|entry| {- resolve_computed_height(runtime, handle, &entry.value, inputs, context, resolution)+ resolve_computed_height(runtime, handle, &entry.value, context, resolution)})})}@@ -7063,8 +6464,8 @@ fn resolve_length_percentage_with_context(fn containing_block_height(runtime: &JsContextHost,handle: DomHandle,- inputs: &StyloComputedStyleInputs,context: StyleComputationContext,+ resolution: StyleResolutionContext<'_>,depth: usize,) -> Option<f64> {if depth > 32 {@@ -7074,13 +6475,13 @@ fn containing_block_height(.dom_host().node(handle).and_then(Node::parent_node)?;- if let Some(height) = raw_computed_height_px(runtime, parent, inputs, context) {+ if let Some(height) = raw_computed_height_px(runtime, parent, resolution) {return Some(height);}let parent_is_viewport_box = runtime.dom_host().node(parent).is_some_and(|node| {node.is_html_element_named("body") || node.is_html_element_named("html")});- if let Some(percent) = raw_computed_height_percent(runtime, parent, inputs, context) {+ if let Some(percent) = raw_computed_height_percent(runtime, parent, resolution) {let viewport_height = context.viewport().height@@ -7088,7 +6489,7 @@ fn containing_block_height(let parent_parent_height = if parent_is_viewport_box {viewport_height} else {- containing_block_height(runtime, parent, inputs, context, depth + 1)?+ containing_block_height(runtime, parent, context, resolution, depth + 1)?};return Some(parent_parent_height * percent / 100.0);}@@ -7100,51 +6501,39 @@ fn containing_block_height(.unwrap_or(moli_browser_profile::DEFAULT_WINDOW_SURFACE_PROFILE.inner_height),);}- containing_block_height(runtime, parent, inputs, context, depth + 1)+ containing_block_height(runtime, parent, context, resolution, depth + 1)}fn raw_computed_width_px(runtime: &JsContextHost,handle: DomHandle,- inputs: &StyloComputedStyleInputs,- context: StyleComputationContext,+ resolution: StyleResolutionContext<'_>,) -> Option<f64> {- parse_css_px(&raw_stylo_computed_style_value_with_inputs(- runtime, handle, "width", inputs, context,- ))+ parse_css_px(&resolution.raw_property(runtime, handle, "width"))}fn raw_computed_width_percent(runtime: &JsContextHost,handle: DomHandle,- inputs: &StyloComputedStyleInputs,- context: StyleComputationContext,+ resolution: StyleResolutionContext<'_>,) -> Option<f64> {- parse_css_percent(&raw_stylo_computed_style_value_with_inputs(- runtime, handle, "width", inputs, context,- ))+ parse_css_percent(&resolution.raw_property(runtime, handle, "width"))}fn raw_computed_height_px(runtime: &JsContextHost,handle: DomHandle,- inputs: &StyloComputedStyleInputs,- context: StyleComputationContext,+ resolution: StyleResolutionContext<'_>,) -> Option<f64> {- parse_css_px(&raw_stylo_computed_style_value_with_inputs(- runtime, handle, "height", inputs, context,- ))+ parse_css_px(&resolution.raw_property(runtime, handle, "height"))}fn raw_computed_height_percent(runtime: &JsContextHost,handle: DomHandle,- inputs: &StyloComputedStyleInputs,- context: StyleComputationContext,+ resolution: StyleResolutionContext<'_>,) -> Option<f64> {- parse_css_percent(&raw_stylo_computed_style_value_with_inputs(- runtime, handle, "height", inputs, context,- ))+ parse_css_percent(&resolution.raw_property(runtime, handle, "height"))}fn parse_css_px(value: &str) -> Option<f64> {@@ -7206,41 +6595,6 @@ fn resolve_background_image_url(value: &str, base_url: &url::Url) -> String {resolve_css_url_function(value, base_url)}-pub(in crate::native_bridge::element) fn style_base_url(- runtime: &JsContextHost,- handle: DomHandle,-) -> url::Url {- let document_handle = if runtime- .dom_host()- .node(handle)- .is_some_and(Node::is_document)- {- Some(handle)- } else {- runtime- .dom_host()- .node(handle)- .and_then(Node::owner_document)- };- document_handle- .map(|document_handle| {- if document_handle == runtime.dom_host().document_handle() {- runtime- .dom_host()- .document_base_url()- .unwrap_or_else(|| runtime.document_url().clone())- } else {- runtime- .dom_host()- .node(document_handle)- .and_then(Node::as_document)- .map(|document| document.base_url().clone())- .unwrap_or_else(|| runtime.document_url().clone())- }- })- .unwrap_or_else(|| runtime.document_url().clone())-}-fn compress_box_shorthand_value(value: &str) -> String {box_shorthand_value_components(value).and_then(|values| compress_box_components(&values))@@ -7694,11 +7048,12 @@ pub(in crate::native_bridge::element::styles) fn computed_style_applies(#[cfg(test)]mod tests {+ use super::super::style_world::connected_shadow_roots_for_test;use super::{KEYFRAME_NESTING_DEPTH_LIMIT, animation_shorthand_names, box_shorthand_component,collect_custom_functions_from_css, compress_box_shorthand_value,- connected_shadow_roots_for_document, custom_function_container_rule_texts,- format_css_number, keyframe_has_supported_animation_values, keyframe_property_values,+ custom_function_container_rule_texts, format_css_number,+ keyframe_has_supported_animation_values, keyframe_property_values,normalize_computed_color_functions, normalize_css_integer_token, normalize_style_value,simple_var_function_parts,};@@ -7755,11 +7110,11 @@ mod tests {host.mark_subtree_connected_preserving_owner_document(child_document);assert_eq!(- connected_shadow_roots_for_document(&host, document),+ connected_shadow_roots_for_test(&host, document),vec![active_root]);assert_eq!(- connected_shadow_roots_for_document(&host, child_document),+ connected_shadow_roots_for_test(&host, child_document),vec![child_root]);}diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rsindex 8c25bcc76..ebe039660 100644--- a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs+++ b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs@@ -4081,7 +4081,7 @@ async fn page_vm_failed_child_stylesheet_installs_empty_sheet_before_host_load()}#[tokio::test]-async fn page_vm_child_stylesheet_subresources_block_complete_until_exact_terminals() {+async fn page_vm_child_stylesheet_fonts_block_complete_until_the_exact_terminal() {run_page_vm_async_test(async move {let (base_url, server) = spawn_concurrent_path_response_http_server(vec![(@@ -4094,12 +4094,6 @@ body { background-image: url('/css-image.png'); }.to_owned(),Duration::from_millis(80),),- (- "/css-image.png",- "HTTP/1.1 200 OK",- "image-body".to_owned(),- Duration::from_millis(260),- ),("/demo.woff2","HTTP/1.1 200 OK",@@ -4115,16 +4109,14 @@ body { background-image: url('/css-image.png'); }| crate::protocol_types::OptionalResourceFetchMask::FONT,);let document_url = Url::parse(&format!("{base_url}/page")).expect("page url");- let expected_css_image_url = format!("{base_url}/css-image.png");let page_vm = test_page_vm_with_loader_and_document_url(&loader, Vec::new(), document_url);let local_executor = page_vm.local_executor.clone();- let (stylesheet_outcome, lifecycle_readiness_after_terminals, final_events) =- local_executor- .run(async move {- let mut page_vm = page_vm;- page_vm.vm_mut().eval(&format!(- r#"+ let (stylesheet_outcome, lifecycle_ready_after_font, final_events) = local_executor+ .run(async move {+ let mut page_vm = page_vm;+ page_vm.vm_mut().eval(&format!(+ r#"(() => {{globalThis.__childCssResourceEvents = [];const root = document.documentElement || document.appendChild(document.createElement("html"));@@ -4135,123 +4127,115 @@ body { background-image: url('/css-image.png'); }body.appendChild(frame);}})()"#- ))?;+ ))?;- run_expected_child_frame_task_source_after_realm_prerequisite_for_wait(- &mut page_vm,- ChildFrameSemanticTurnKind::NavigationCommit,- "CSS-resource child navigation commit",- )- .await;- run_expected_child_frame_task_source_after_realm_prerequisite_for_wait(- &mut page_vm,- ChildFrameSemanticTurnKind::DocumentLifecycle,- "CSS-resource child interactive transition",- )- .await;- run_expected_child_frame_task_source_after_realm_prerequisite_for_wait(- &mut page_vm,- ChildFrameSemanticTurnKind::DocumentLifecycle,- "CSS-resource child DOMContentLoaded transition",- )- .await;+ run_expected_child_frame_task_source_after_realm_prerequisite_for_wait(+ &mut page_vm,+ ChildFrameSemanticTurnKind::NavigationCommit,+ "CSS-resource child navigation commit",+ )+ .await;+ run_expected_child_frame_task_source_after_realm_prerequisite_for_wait(+ &mut page_vm,+ ChildFrameSemanticTurnKind::DocumentLifecycle,+ "CSS-resource child interactive transition",+ )+ .await;+ run_expected_child_frame_task_source_after_realm_prerequisite_for_wait(+ &mut page_vm,+ ChildFrameSemanticTurnKind::DocumentLifecycle,+ "CSS-resource child DOMContentLoaded transition",+ )+ .await;- if !page_vm- .page_resource_completion_queue()- .has_ready_completion()- {- tokio::time::timeout(- Duration::from_secs(2),- wait_for_typed_page_resource_completion(&mut page_vm),+ if !page_vm+ .page_resource_completion_queue()+ .has_ready_completion()+ {+ tokio::time::timeout(+ Duration::from_secs(2),+ wait_for_typed_page_resource_completion(&mut page_vm),+ )+ .await+ .expect("stylesheet completion should arrive");+ }+ let stylesheet_outcome =+ run_next_resource_completion_as_typed_page_turn(&mut page_vm)?;+ assert!(+ !page_vm+ .run_exact_selected_page_task_for_test(+ PageSelectedTaskTestSelector::ChildHostLoad,+ &loader,)- .await- .expect("stylesheet completion should arrive");- }- let stylesheet_outcome =- run_next_resource_completion_as_typed_page_turn(&mut page_vm)?;- assert!(- !page_vm- .run_exact_selected_page_task_for_test(- PageSelectedTaskTestSelector::ChildHostLoad,- &loader,- )- .await?,- "HostLoad must remain blocked while stylesheet subresources are pending"- );-- let mut lifecycle_readiness_after_terminals = Vec::new();- for terminal_index in 0..2 {- if !page_vm- .page_resource_completion_queue()- .has_ready_completion()- {- tokio::time::timeout(- Duration::from_secs(2),- wait_for_typed_page_resource_completion(&mut page_vm),- )- .await- .unwrap_or_else(|_| {- panic!("CSS resource terminal {terminal_index} should arrive")- });- }- let outcome =- run_next_resource_completion_as_typed_page_turn(&mut page_vm)?;- assert_eq!(- outcome.action.source(),- RendererOwnerResourceActivitySource::AsyncSubresource,- "CSS resource terminal {terminal_index} must use Networking"- );- lifecycle_readiness_after_terminals.push(- page_vm.has_ready_child_frame_semantic_turn_for_test(- ChildFrameSemanticTurnKind::DocumentLifecycle,- ),- );- assert_eq!(- page_vm- .vm_mut()- .eval("__childCssResourceEvents.join('|')")?,- "",- "CSS network completion must not inline-dispatch iframe load"- );- }+ .await?,+ "HostLoad must remain blocked while stylesheet subresources are pending"+ );- run_expected_child_frame_task_source_after_realm_prerequisite_for_wait(- &mut page_vm,- ChildFrameSemanticTurnKind::DocumentLifecycle,- "CSS-resource child complete transition",- )- .await;- run_expected_child_frame_task_source_after_realm_prerequisite_for_wait(- &mut page_vm,- ChildFrameSemanticTurnKind::HostLoad,- "CSS-resource child iframe load",+ if !page_vm+ .page_resource_completion_queue()+ .has_ready_completion()+ {+ tokio::time::timeout(+ Duration::from_secs(2),+ wait_for_typed_page_resource_completion(&mut page_vm),)- .await;- let final_events = page_vm- .vm_mut()- .eval("__childCssResourceEvents.join('|')")?;- assert_eq!(- page_vm.vm().css_image_resource_observability_for_test(),- (0, 0, 0, 1, vec![expected_css_image_url]),- "the real HTTP image terminal must settle the exact child Document CSS image slot"+ .await+ .expect("stylesheet font terminal should arrive");+ }+ let outcome = run_next_resource_completion_as_typed_page_turn(&mut page_vm)?;+ assert_eq!(+ outcome.action.source(),+ RendererOwnerResourceActivitySource::AsyncSubresource,+ "the stylesheet font terminal must use Networking"+ );+ let lifecycle_ready_after_font = page_vm+ .has_ready_child_frame_semantic_turn_for_test(+ ChildFrameSemanticTurnKind::DocumentLifecycle,);- Ok::<_, anyhow::Error>((- stylesheet_outcome,- lifecycle_readiness_after_terminals,- final_events,- ))- })- .await- .expect("stylesheet subresource lifecycle test should run");+ assert_eq!(+ page_vm+ .vm_mut()+ .eval("__childCssResourceEvents.join('|')")?,+ "",+ "the font terminal must not inline-dispatch iframe load"+ );++ run_expected_child_frame_task_source_after_realm_prerequisite_for_wait(+ &mut page_vm,+ ChildFrameSemanticTurnKind::DocumentLifecycle,+ "CSS-resource child complete transition",+ )+ .await;+ run_expected_child_frame_task_source_after_realm_prerequisite_for_wait(+ &mut page_vm,+ ChildFrameSemanticTurnKind::HostLoad,+ "CSS-resource child iframe load",+ )+ .await;+ let final_events = page_vm+ .vm_mut()+ .eval("__childCssResourceEvents.join('|')")?;+ assert_eq!(+ page_vm.vm().css_image_resource_observability_for_test(),+ (0, 0, 0, 0, Vec::<String>::new()),+ "raw stylesheet text must not eagerly admit CSS image slots before paint layout"+ );+ Ok::<_, anyhow::Error>((+ stylesheet_outcome,+ lifecycle_ready_after_font,+ final_events,+ ))+ })+ .await+ .expect("stylesheet subresource lifecycle test should run");assert_eq!(stylesheet_outcome.action.source(),RendererOwnerResourceActivitySource::ChildBlockingStylesheet);- assert_eq!(- lifecycle_readiness_after_terminals,- vec![false, true],- "only the final exact CSS resource token may make complete runnable"+ assert!(+ lifecycle_ready_after_font,+ "the exact stylesheet font token must make complete runnable");assert_eq!(final_events, "load");serverdiff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rsindex dae33cfba..9fce8e112 100644--- a/moli-renderer-v8/src/script_vm.rs+++ b/moli-renderer-v8/src/script_vm.rs@@ -2601,32 +2601,49 @@ impl ScriptVm {let Some(root) = root else {return;};- if !self+ let Some(resources) = crate::layout_renderer::current_native_stylesheet_resources(+ &self._context_host.borrow(),+ root,+ ) else {+ return;+ };+ tracing::trace!(+ stylesheet_import_dependency_count = resources.imports().len(),+ stylesheet_web_font_dependency_count = resources.web_fonts().len(),+ "observed typed stylesheet resource manifest"+ );+ let generation = resources.generation();+ if self._context_host.borrow()- .take_document_web_font_sources_dirty()+ .document_web_font_resources_are_current(generation){return;}- let resources = crate::layout_renderer::current_native_stylesheet_web_font_resources(- &self._context_host.borrow(),- root,- );+ let resources = resources.web_fonts().to_vec();self._context_host.borrow().retain_document_web_font_slots(resources.iter());if resources.is_empty() {+ self._context_host+ .borrow()+ .publish_document_web_font_resource_generation(generation);return;}+ let resource_count = resources.len();let bound = {let mut host = self._context_host.borrow_mut();- resources+ let bound = resources.into_iter().filter_map(|resource| {host.accept_current_main_stylesheet_subresource_load_delay().map(|binding| (binding, resource))})- .collect::<Vec<_>>()+ .collect::<Vec<_>>();+ if bound.len() == resource_count {+ host.publish_document_web_font_resource_generation(generation);+ }+ bound};self.start_stylesheet_subresource_fetches(bound);}@@ -2880,6 +2897,26 @@ impl ScriptVm {.retained_style_system_rebuild_count_for_document_for_test(document)}+ #[cfg(test)]+ pub(crate) fn retained_style_system_update_count_for_document_for_test(+ &self,+ document: DomHandle,+ ) -> u64 {+ self._context_host+ .borrow()+ .retained_style_system_update_count_for_document_for_test(document)+ }++ #[cfg(test)]+ pub(crate) fn retained_stylist_identity_for_document_for_test(+ &self,+ document: DomHandle,+ ) -> u64 {+ self._context_host+ .borrow()+ .retained_stylist_identity_for_document_for_test(document)+ }+#[cfg(test)]pub(crate) fn shared_worker_client_count_for_test(&self) -> usize {self._context_hostdiff --git a/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs b/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rsindex 083e1bb95..cbd8794d7 100644--- a/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs+++ b/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs@@ -2560,11 +2560,13 @@ impl ScriptVm {// current document after its exact owner/root authority was// revoked.if has_stylesheet_install_authority && validated_response.is_some() {- for resource in crate::css_resource_urls::stylesheet_load_blocking_resources(- &stylesheet_text,- &stylesheet_base_url,- optional_resource_fetch_mask,- ) {+ for resource in+ crate::css_resource_urls::stylesheet_load_blocking_font_resources(+ &stylesheet_text,+ &stylesheet_base_url,+ optional_resource_fetch_mask,+ )+ {let Some(binding) =host.accept_current_main_stylesheet_subresource_load_delay()else {@@ -2616,11 +2618,13 @@ impl ScriptVm {if !response.successful {continue;}- for resource in crate::css_resource_urls::stylesheet_load_blocking_resources(- &response.css_text,- &response.response_url,- optional_resource_fetch_mask,- ) {+ for resource in+ crate::css_resource_urls::stylesheet_load_blocking_font_resources(+ &response.css_text,+ &response.response_url,+ optional_resource_fetch_mask,+ )+ {let Some(binding) =host.accept_current_main_stylesheet_subresource_load_delay()else {@@ -2758,13 +2762,13 @@ mod tests {use super::*;#[test]- fn stylesheet_image_resources_require_the_image_bit() {+ fn stylesheet_images_are_not_discovered_from_raw_css_text() {let stylesheet_base_url =Url::parse("https://example.test/assets/app.css").expect("stylesheet url");let stylesheet_text = "#hero { background-image: url(hero.png); }";assert!(- crate::css_resource_urls::stylesheet_load_blocking_resources(+ crate::css_resource_urls::stylesheet_load_blocking_font_resources(stylesheet_text,&stylesheet_base_url,crate::protocol_types::OptionalResourceFetchMask::NONE,@@ -2772,21 +2776,13 @@ mod tests {.is_empty());- let resources = crate::css_resource_urls::stylesheet_load_blocking_resources(+ let resources = crate::css_resource_urls::stylesheet_load_blocking_font_resources(stylesheet_text,&stylesheet_base_url,crate::protocol_types::OptionalResourceFetchMask::IMAGE,);- assert_eq!(resources.len(), 1);- assert_eq!(- resources[0].request_url().as_str(),- "https://example.test/assets/hero.png"- );- assert_eq!(- resources[0].kind(),- crate::css_resource_urls::StylesheetLoadBlockingResourceKind::Image- );+ assert!(resources.is_empty());}#[test]@@ -2803,7 +2799,7 @@ mod tests {body { background-image: url(hero.png); }"#;- let resources = crate::css_resource_urls::stylesheet_load_blocking_resources(+ let resources = crate::css_resource_urls::stylesheet_load_blocking_font_resources(stylesheet_text,&stylesheet_base_url,crate::protocol_types::OptionalResourceFetchMask::FONT,diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rsindex 7d6b140b2..c051f0bca 100644--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs@@ -320,6 +320,393 @@ fn registered_custom_property_for_document(vm: &ScriptVm, document: DomHandle, n.is_some()}+#[test]+fn style_observation_reuses_current_world_without_materializing_an_update() {+ let mut vm = new_parsed_test_vm(+ "https://style-observation-current-world.test/",+ "<!doctype html><style>.target { color: rgb(1, 2, 3); }</style><div id=target class=target></div>",+ );+ assert_eq!(+ vm.eval("getComputedStyle(document.getElementById('target')).color")+ .expect("initial style should establish the retained world"),+ "rgb(1, 2, 3)"+ );+ let target = element_handle_by_id(&vm, "target");+ let host = vm._context_host.borrow();+ let update_materializations = host.style_world_update_materializations_for_test();+ let full_snapshots = host.style_world_full_snapshots_for_test();++ let mut observation = crate::native_bridge::element::StyleObservation::new(&host);+ let first = observation+ .read(target)+ .computed_values()+ .expect("connected target should have computed values");+ let second = observation+ .read(target)+ .computed_values()+ .expect("a repeated read should retain computed values");++ assert!(style::servo_arc::Arc::ptr_eq(&first, &second));+ assert_eq!(+ host.style_world_update_materializations_for_test(),+ update_materializations+ );+ assert_eq!(host.style_world_full_snapshots_for_test(), full_snapshots);+}++#[test]+fn style_observation_refreshes_dirty_element_without_materializing_a_world_update() {+ let mut vm = new_parsed_test_vm(+ "https://style-observation-dirty-element.test/",+ "<!doctype html><div id=target style='color: rgb(1, 2, 3)'></div>",+ );+ assert_eq!(+ vm.eval("getComputedStyle(document.getElementById('target')).color")+ .expect("initial style should establish the retained world"),+ "rgb(1, 2, 3)"+ );+ let target = element_handle_by_id(&vm, "target");+ let before = {+ let host = vm._context_host.borrow();+ let mut observation = crate::native_bridge::element::StyleObservation::new(&host);+ observation+ .read(target)+ .computed_values()+ .expect("initial computed values")+ };+ vm.eval("document.getElementById('target').style.color = 'rgb(4, 5, 6)' ")+ .expect("inline mutation should complete");++ let host = vm._context_host.borrow();+ let update_materializations = host.style_world_update_materializations_for_test();+ let full_snapshots = host.style_world_full_snapshots_for_test();+ let mut observation = crate::native_bridge::element::StyleObservation::new(&host);+ let after = observation+ .read(target)+ .computed_values()+ .expect("dirty target should be recomputed");++ assert!(!style::servo_arc::Arc::ptr_eq(&before, &after));+ assert_eq!(+ host.style_world_update_materializations_for_test(),+ update_materializations+ );+ assert_eq!(host.style_world_full_snapshots_for_test(), full_snapshots);+}++#[test]+fn style_observation_materializes_dirty_scope_once_without_a_full_snapshot() {+ let mut vm = new_parsed_test_vm(+ "https://style-observation-dirty-source.test/",+ "<!doctype html><style id=sheet>.target { color: rgb(1, 2, 3); }</style><div id=target class=target></div>",+ );+ assert_eq!(+ vm.eval("getComputedStyle(document.getElementById('target')).color")+ .expect("initial style should establish the retained world"),+ "rgb(1, 2, 3)"+ );+ vm.eval("document.getElementById('sheet').textContent = '.target { color: rgb(4, 5, 6); }'")+ .expect("stylesheet mutation should complete");+ let target = element_handle_by_id(&vm, "target");+ let host = vm._context_host.borrow();+ let update_materializations = host.style_world_update_materializations_for_test();+ let full_snapshots = host.style_world_full_snapshots_for_test();+ let document_scopes = host.style_world_document_scope_materializations_for_test();+ let shadow_scopes = host.style_world_shadow_scope_materializations_for_test();++ let mut observation = crate::native_bridge::element::StyleObservation::new(&host);+ let first = observation+ .read(target)+ .computed_values()+ .expect("dirty stylesheet world should be refreshed");+ let second = observation+ .read(target)+ .computed_values()+ .expect("the refreshed world should be reused");++ assert!(style::servo_arc::Arc::ptr_eq(&first, &second));+ assert_eq!(+ host.style_world_update_materializations_for_test()+ .saturating_sub(update_materializations),+ 1+ );+ assert_eq!(+ host.style_world_full_snapshots_for_test()+ .saturating_sub(full_snapshots),+ 0,+ "an incremental scope update must not materialize a full style-world snapshot"+ );+ assert_eq!(+ host.style_world_document_scope_materializations_for_test(),+ document_scopes + 1+ );+ assert_eq!(+ host.style_world_shadow_scope_materializations_for_test(),+ shadow_scopes+ );+}++#[test]+fn document_stylesheet_mutation_reprojects_only_the_dirty_source() {+ let mut vm = new_parsed_test_vm(+ "https://style-observation-dirty-source-id.test/",+ r#"<!doctype html>+ <style id=sheet-a>.a { color: rgb(1, 2, 3); }</style>+ <style id=sheet-b>.b { color: rgb(4, 5, 6); }</style>+ <div id=target-a class=a></div><div id=target-b class=b></div>"#,+ );+ assert_eq!(+ vm.eval(+ r#"JSON.stringify([+ getComputedStyle(document.getElementById('target-a')).color,+ getComputedStyle(document.getElementById('target-b')).color,+ ])"#,+ )+ .expect("both stylesheet sources should initialize"),+ r#"["rgb(1, 2, 3)","rgb(4, 5, 6)"]"#+ );+ crate::style_engine::reset_source_cascade_rebuild_count_for_test();++ assert_eq!(+ vm.eval(+ r#"+document.getElementById('sheet-a').textContent = '.a { color: rgb(7, 8, 9); }';+JSON.stringify([+ getComputedStyle(document.getElementById('target-a')).color,+ getComputedStyle(document.getElementById('target-b')).color,+]);+"#,+ )+ .expect("the dirty stylesheet should update"),+ r#"["rgb(7, 8, 9)","rgb(4, 5, 6)"]"#+ );+ assert_eq!(+ crate::style_engine::source_cascade_rebuild_count_for_test(),+ 1,+ "a single source mutation must not rebuild unrelated source cascade data"+ );+}++#[test]+fn style_observation_reconciles_an_empty_shadow_scope_once_per_version_change() {+ let mut vm = new_parsed_test_vm(+ "https://style-observation-shadow-version.test/",+ "<!doctype html><style>#target { color: rgb(1, 2, 3); }</style><div id=shadow-host></div><div id=target></div>",+ );+ assert_eq!(+ vm.eval("getComputedStyle(document.getElementById('target')).color")+ .expect("initial style should establish the retained world"),+ "rgb(1, 2, 3)"+ );+ let update_materializations_before_shadow = vm+ ._context_host+ .borrow()+ .style_world_update_materializations_for_test();+ let document_scopes_before_shadow = vm+ ._context_host+ .borrow()+ .style_world_document_scope_materializations_for_test();+ let shadow_scopes_before_shadow = vm+ ._context_host+ .borrow()+ .style_world_shadow_scope_materializations_for_test();+ vm.eval("document.getElementById('shadow-host').attachShadow({ mode: 'open' })")+ .expect("an empty connected ShadowRoot should attach");+ assert_eq!(+ vm.eval("getComputedStyle(document.getElementById('target')).color")+ .expect("the first read after attachment should reconcile TreeScopes"),+ "rgb(1, 2, 3)"+ );+ assert_eq!(+ vm._context_host+ .borrow()+ .style_world_update_materializations_for_test(),+ update_materializations_before_shadow + 1,+ "one TreeScope version change must materialize one incremental update batch"+ );+ assert_eq!(+ vm._context_host+ .borrow()+ .style_world_document_scope_materializations_for_test(),+ document_scopes_before_shadow,+ "adding an empty ShadowRoot must not recollect document stylesheets"+ );+ assert_eq!(+ vm._context_host+ .borrow()+ .style_world_shadow_scope_materializations_for_test(),+ shadow_scopes_before_shadow + 1,+ "only the newly connected ShadowRoot should be materialized"+ );+ let update_materializations_after_reconciliation = vm+ ._context_host+ .borrow()+ .style_world_update_materializations_for_test();+ assert_eq!(+ vm.eval("getComputedStyle(document.getElementById('target')).color")+ .expect("a clean read should reuse the reconciled TreeScope universe"),+ "rgb(1, 2, 3)"+ );+ assert_eq!(+ vm._context_host+ .borrow()+ .style_world_update_materializations_for_test(),+ update_materializations_after_reconciliation,+ "a clean observation must compare versions without recollecting TreeScope sources"+ );++ vm.eval("document.getElementById('shadow-host').remove()")+ .expect("the ShadowRoot host should disconnect");+ assert_eq!(+ vm.eval("getComputedStyle(document.getElementById('target')).color")+ .expect("the first read after disconnection should remove the stale TreeScope"),+ "rgb(1, 2, 3)"+ );+ assert_eq!(+ vm._context_host+ .borrow()+ .style_world_update_materializations_for_test(),+ update_materializations_after_reconciliation + 1,+ "disconnecting a ShadowRoot host must reconcile the TreeScope universe once"+ );+ assert_eq!(+ vm._context_host+ .borrow()+ .style_world_shadow_scope_materializations_for_test(),+ shadow_scopes_before_shadow + 1,+ "removing a scope needs only its retained identity, not a source snapshot"+ );+}++#[test]+fn shadow_stylesheet_mutation_materializes_only_the_dirty_scope() {+ let mut vm = new_parsed_test_vm(+ "https://style-observation-dirty-shadow.test/",+ "<!doctype html><div id=host-a></div><div id=host-b></div>",+ );+ assert_eq!(+ vm.eval(+ r#"+const rootA = document.getElementById('host-a').attachShadow({ mode: 'open' });+rootA.innerHTML = '<style id=sheet>.target { color: rgb(1, 2, 3); }</style><span class=target></span>';+const rootB = document.getElementById('host-b').attachShadow({ mode: 'open' });+rootB.innerHTML = '<style>.target { color: rgb(4, 5, 6); }</style><span class=target></span>';+globalThis.__dirtyScopeRootA = rootA;+globalThis.__dirtyScopeRootB = rootB;+JSON.stringify([+ getComputedStyle(rootA.querySelector('.target')).color,+ getComputedStyle(rootB.querySelector('.target')).color,+]);+"#,+ )+ .expect("two ShadowRoot style worlds should initialize"),+ r#"["rgb(1, 2, 3)","rgb(4, 5, 6)"]"#+ );+ let host = vm._context_host.borrow();+ let document_scopes = host.style_world_document_scope_materializations_for_test();+ let shadow_scopes = host.style_world_shadow_scope_materializations_for_test();+ drop(host);++ assert_eq!(+ vm.eval(+ r#"+__dirtyScopeRootA.getElementById('sheet').textContent =+ '.target { color: rgb(7, 8, 9); }';+JSON.stringify([+ getComputedStyle(__dirtyScopeRootA.querySelector('.target')).color,+ getComputedStyle(__dirtyScopeRootB.querySelector('.target')).color,+]);+"#,+ )+ .expect("the dirty ShadowRoot should update"),+ r#"["rgb(7, 8, 9)","rgb(4, 5, 6)"]"#+ );+ let host = vm._context_host.borrow();+ assert_eq!(+ host.style_world_document_scope_materializations_for_test(),+ document_scopes,+ "a ShadowRoot mutation must not recollect document stylesheets"+ );+ assert_eq!(+ host.style_world_shadow_scope_materializations_for_test(),+ shadow_scopes + 1,+ "Shadow A must update without materializing Shadow B"+ );+}++#[test]+fn stylesheet_resource_manifest_reuses_current_world_and_tracks_revisions() {+ let mut vm = new_storage_test_vm("https://style-resource-manifest.test/document.html");+ vm.eval(+ r#"+const style = document.createElement('style');+style.id = 'resource-sheet';+style.textContent = '@font-face { font-family: First; src: url(font-a.woff2); }';+(document.head || document.documentElement || document).appendChild(style);+"#,+ )+ .expect("resource stylesheet fixture should initialize");+ let root = vm+ ._context_host+ .borrow()+ .dom_host()+ .document_element_handle()+ .expect("fixture should retain a document element");++ let first = crate::layout_renderer::current_native_stylesheet_resources(+ &vm._context_host.borrow(),+ root,+ )+ .expect("the first observation should publish a resource manifest");+ assert_eq!(first.web_fonts().len(), 1);+ assert_eq!(+ first.web_fonts()[0].request_url().as_str(),+ "https://style-resource-manifest.test/font-a.woff2"+ );+ let update_materializations_after_first = vm+ ._context_host+ .borrow()+ .style_world_update_materializations_for_test();++ let clean = crate::layout_renderer::current_native_stylesheet_resources(+ &vm._context_host.borrow(),+ root,+ )+ .expect("a clean observation should reuse the resource manifest");+ assert_eq!(clean.generation(), first.generation());+ assert_eq!(+ vm._context_host+ .borrow()+ .style_world_update_materializations_for_test(),+ update_materializations_after_first,+ "a clean resource observation must not materialize a style-world update"+ );++ vm.eval(+ "document.getElementById('resource-sheet').textContent = \+ '@font-face { font-family: Second; src: url(font-b.woff2); }'",+ )+ .expect("resource stylesheet should mutate");+ let revised = crate::layout_renderer::current_native_stylesheet_resources(+ &vm._context_host.borrow(),+ root,+ )+ .expect("the revised observation should publish a resource manifest");+ assert_ne!(revised.generation(), first.generation());+ assert_eq!(revised.web_fonts().len(), 1);+ assert_eq!(+ revised.web_fonts()[0].request_url().as_str(),+ "https://style-resource-manifest.test/font-b.woff2"+ );+ assert_eq!(+ vm._context_host+ .borrow()+ .style_world_update_materializations_for_test(),+ update_materializations_after_first + 1,+ "one stylesheet revision should materialize one incremental world update"+ );+}+#[test]fn disconnected_element_computed_style_returns_empty_without_caching() {let mut vm = new_storage_test_vm("https://disconnected-computed-style.test/page.html");@@ -1827,14 +2214,14 @@ fn child_layout_uses_complete_stable_tree_scope_universe() {let child_document = child_document_handle_for_frame_id(&vm, "tree-scope-universe-frame");let rebuilds_before =vm.retained_style_system_rebuild_count_for_document_for_test(child_document);- let builds_before = vm+ let update_materializations_before = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_before = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_before = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();vm.screenshot_layout_snapshot(moli_layout::PaintViewport::new(800, 600, 1.0)).expect("child TreeScope universe paint layout should succeed")@@ -1849,23 +2236,135 @@ fn child_layout_uses_complete_stable_tree_scope_universe() {assert_eq!(vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test()- .saturating_sub(builds_before),+ .style_world_update_materializations_for_test()+ .saturating_sub(update_materializations_before),2,- "the paint layout must prepare exactly one input for each document",+ "the paint layout must materialize exactly one style-world update per document",);assert_eq!(vm._context_host.borrow()- .stylo_style_system_key_builds_for_test()- .saturating_sub(key_builds_before),+ .style_world_full_snapshots_for_test()+ .saturating_sub(full_snapshots_before),2,- "the paint layout must hash exactly one style-system key for each document",+ "the first paint layout must materialize one full snapshot per document",+ );+}++#[test]+fn child_tree_scope_membership_update_does_not_touch_parent_style_world() {+ let mut vm = new_storage_test_vm("https://tree-scope-document-isolation.test/");+ assert_eq!(+ vm.eval(+ r#"+const parentStyle = document.createElement('style');+parentStyle.textContent = '#parent-target { color: rgb(1, 2, 3); }';+const root = document.documentElement || document.appendChild(document.createElement('html'));+const head = document.head || root.appendChild(document.createElement('head'));+const body = document.body || root.appendChild(document.createElement('body'));+head.appendChild(parentStyle);+const parentTarget = document.createElement('div');+parentTarget.id = 'parent-target';+body.appendChild(parentTarget);+const frame = document.createElement('iframe');+frame.id = 'tree-scope-isolation-frame';+body.appendChild(frame);+const childDocument = frame.contentDocument;+childDocument.open();+childDocument.write('<style>#child-target { color: rgb(4, 5, 6); }</style><body><div id=child-target></div></body>');+childDocument.close();+JSON.stringify([+ getComputedStyle(parentTarget).color,+ frame.contentWindow.getComputedStyle(childDocument.getElementById('child-target')).color,+]);+"#,+ )+ .expect("parent and child style worlds should initialize"),+ r#"["rgb(1, 2, 3)","rgb(4, 5, 6)"]"#+ );++ let parent_document = vm.document_handle_for_test();+ let child_document = child_document_handle_for_frame_id(&vm, "tree-scope-isolation-frame");+ let parent_identity = vm.retained_stylist_identity_for_document_for_test(parent_document);+ let child_identity = vm.retained_stylist_identity_for_document_for_test(child_document);+ let parent_updates =+ vm.retained_style_system_update_count_for_document_for_test(parent_document);+ let child_updates = vm.retained_style_system_update_count_for_document_for_test(child_document);+ let shadow_materializations = vm+ ._context_host+ .borrow()+ .style_world_shadow_scope_materializations_for_test();++ assert_eq!(+ vm.eval(+ r#"+const childHost = document.getElementById('tree-scope-isolation-frame')+ .contentDocument.createElement('section');+document.getElementById('tree-scope-isolation-frame')+ .contentDocument.body.appendChild(childHost);+childHost.attachShadow({ mode: 'open' });+getComputedStyle(document.getElementById('parent-target')).color;+"#,+ )+ .expect("a parent-only observation should ignore the child TreeScope change"),+ "rgb(1, 2, 3)"+ );+ assert_eq!(+ vm.retained_style_system_update_count_for_document_for_test(parent_document),+ parent_updates+ );+ assert_eq!(+ vm.retained_style_system_update_count_for_document_for_test(child_document),+ child_updates+ );+ assert_eq!(+ vm._context_host+ .borrow()+ .style_world_shadow_scope_materializations_for_test(),+ shadow_materializations,+ "the child scope must stay lazy until the child Document is observed"+ );++ assert_eq!(+ vm.eval(+ r#"+const observedFrame = document.getElementById('tree-scope-isolation-frame');+observedFrame.contentWindow.getComputedStyle(+ observedFrame.contentDocument.getElementById('child-target')+).color;+"#,+ )+ .expect("the child observation should reconcile its own TreeScopes"),+ "rgb(4, 5, 6)"+ );+ assert_eq!(+ vm.retained_style_system_update_count_for_document_for_test(parent_document),+ parent_updates,+ "observing the child must leave the parent world untouched"+ );+ assert_eq!(+ vm.retained_style_system_update_count_for_document_for_test(child_document),+ child_updates + 1+ );+ assert_eq!(+ vm.retained_stylist_identity_for_document_for_test(parent_document),+ parent_identity+ );+ assert_eq!(+ vm.retained_stylist_identity_for_document_for_test(child_document),+ child_identity,+ "TreeScope membership changes must update the child Stylist in place"+ );+ assert_eq!(+ vm._context_host+ .borrow()+ .style_world_shadow_scope_materializations_for_test(),+ shadow_materializations + 1);}#[test]-fn empty_shadow_root_universe_changes_rebuild_once_per_dom_mutation() {+fn empty_shadow_root_universe_updates_once_per_dom_mutation() {let mut vm = new_storage_test_vm("https://empty-shadow-universe-mutation.test/");let document = vm.document_handle_for_test();@@ -1886,6 +2385,8 @@ fn empty_shadow_root_universe_changes_rebuild_once_per_dom_mutation() {assert_eq!(initial, "block");let rebuilds_after_initial =vm.retained_style_system_rebuild_count_for_document_for_test(document);+ let updates_after_initial =+ vm.retained_style_system_update_count_for_document_for_test(document);let attached = vm.eval(@@ -1912,8 +2413,15 @@ fn empty_shadow_root_universe_changes_rebuild_once_per_dom_mutation() {vm.retained_style_system_rebuild_count_for_document_for_test(document);assert_eq!(rebuilds_after_attach.saturating_sub(rebuilds_after_initial),+ 0,+ "attaching an empty Shadow Root must preserve the Document Stylist",+ );+ let updates_after_attach =+ vm.retained_style_system_update_count_for_document_for_test(document);+ assert_eq!(+ updates_after_attach.saturating_sub(updates_after_initial),1,- "attaching one empty Shadow Root must replace the document universe exactly once",+ "attaching one empty Shadow Root must update the retained TreeScope universe exactly once",);let removed = vm@@ -1931,8 +2439,14 @@ fn empty_shadow_root_universe_changes_rebuild_once_per_dom_mutation() {assert_eq!(vm.retained_style_system_rebuild_count_for_document_for_test(document).saturating_sub(rebuilds_after_attach),+ 0,+ "disconnecting an empty Shadow Root must preserve the Document Stylist",+ );+ assert_eq!(+ vm.retained_style_system_update_count_for_document_for_test(document)+ .saturating_sub(updates_after_attach),1,- "disconnecting one empty Shadow Root must replace the document universe exactly once",+ "disconnecting one empty Shadow Root must update the retained TreeScope universe exactly once",);}#[test]@@ -2073,6 +2587,7 @@ fn computed_style_wrapper_reflects_constructed_stylesheet_mutations() {assert!(vm.computed_style_cache_entry_count_for_document_for_test(document) > 0);let generation_after_setup = vm.computed_style_cache_generation_for_document_for_test(document);crate::live_stylesheet::reset_live_stylesheet_css_text_projection_count_for_test();+ crate::style_engine::reset_live_stylesheet_update_counts_for_test();let mutated = vm.eval(@@ -2119,6 +2634,16 @@ fn computed_style_wrapper_reflects_constructed_stylesheet_mutations() {generation_after_setup);assert!(vm.computed_style_cache_entry_count_for_document_for_test(document) > 0);+ assert_eq!(+ crate::style_engine::exact_rule_change_notification_count_for_test(),+ 2,+ "insertRule and deleteRule should use exact Stylo rule notifications",+ );+ assert_eq!(+ crate::style_engine::full_cascade_update_fallback_count_for_test(),+ 3,+ "whole-sheet replacement and disabled toggles should remain explicit full-update fallbacks",+ );}#[test]@@ -2165,6 +2690,7 @@ fn one_constructed_stylesheet_mutation_reaches_document_and_all_shadow_adopters(assert_eq!(initial, "rgb(1, 2, 3)|rgb(1, 2, 3)|rgb(1, 2, 3)");crate::live_stylesheet::reset_live_stylesheet_css_text_projection_count_for_test();+ crate::style_engine::reset_live_stylesheet_update_counts_for_test();let mutated = vm.eval(@@ -2200,7 +2726,105 @@ fn one_constructed_stylesheet_mutation_reaches_document_and_all_shadow_adopters(0,"all adopter notifications must stay on the parsed stylesheet path",);+ assert_eq!(+ crate::style_engine::exact_rule_change_notification_count_for_test(),+ 9,+ "three exact CSSOM mutations must be delivered independently to the Document and two ShadowRoot installations",+ );+ assert_eq!(+ crate::style_engine::full_cascade_update_fallback_count_for_test(),+ 0,+ "ordinary rule/declaration mutations must not dirty an entire author scope",+ );+}++#[test]+fn live_stylesheet_rule_journal_batches_multiple_mutations_until_observation() {+ let mut vm = new_storage_test_vm("https://constructed-sheet-rule-journal.test/");++ assert_eq!(+ vm.eval(+ r#"+const target = document.createElement('div');+target.className = 'journal-target';+(document.body || document.documentElement || document).appendChild(target);+globalThis.__journalSheet = new CSSStyleSheet();+globalThis.__journalSheet.replaceSync('.journal-target { color: rgb(1, 2, 3); }');+document.adoptedStyleSheets = [globalThis.__journalSheet];+getComputedStyle(target).color;+"#,+ )+ .expect("rule journal setup should evaluate"),+ "rgb(1, 2, 3)"+ );+ crate::style_engine::reset_live_stylesheet_update_counts_for_test();++ assert_eq!(+ vm.eval(+ r#"+__journalSheet.cssRules[0].style.color = 'rgb(4, 5, 6)';+__journalSheet.insertRule('.journal-target { color: rgb(7, 8, 9); }', 1);+__journalSheet.deleteRule(0);+getComputedStyle(target).color;+"#,+ )+ .expect("batched rule journal mutations should evaluate"),+ "rgb(7, 8, 9)"+ );+ assert_eq!(+ crate::style_engine::exact_rule_change_notification_count_for_test(),+ 3,+ "all generations since the last observation must be replayed in order",+ );+ assert_eq!(+ crate::style_engine::full_cascade_update_fallback_count_for_test(),+ 0,+ );+}++#[test]+fn nested_live_rule_journal_preserves_grouping_rule_ancestors() {+ let mut vm = new_storage_test_vm("https://nested-live-rule-journal.test/");++ assert_eq!(+ vm.eval(+ r#"+const style = document.createElement('style');+style.textContent = '@media all { .nested-journal-target { color: rgb(1, 2, 3); } }';+(document.head || document.documentElement || document).appendChild(style);+const target = document.createElement('div');+target.className = 'nested-journal-target';+(document.body || document.documentElement || document).appendChild(target);+globalThis.__nestedJournalRule = style.sheet.cssRules[0].cssRules[0];+getComputedStyle(target).color;+"#,+ )+ .expect("nested rule journal setup should evaluate"),+ "rgb(1, 2, 3)"+ );+ crate::style_engine::reset_live_stylesheet_update_counts_for_test();++ assert_eq!(+ vm.eval(+ r#"+__nestedJournalRule.style.color = 'rgb(4, 5, 6)';+getComputedStyle(document.querySelector('.nested-journal-target')).color;+"#,+ )+ .expect("nested declaration mutation should evaluate"),+ "rgb(4, 5, 6)"+ );+ assert_eq!(+ crate::style_engine::exact_rule_change_notification_count_for_test(),+ 1,+ );+ assert_eq!(+ crate::style_engine::full_cascade_update_fallback_count_for_test(),+ 0,+ "a nested rule with a retained @media ancestor must remain exactly expressible",+ );}+#[test]fn computed_style_wrapper_reflects_style_element_media_mutations() {let mut vm = new_storage_test_vm("https://style-media-computed-wrapper-refresh.test/");@@ -2256,6 +2880,73 @@ fn computed_style_wrapper_reflects_style_element_media_mutations() {);assert!(vm.computed_style_cache_entry_count_for_document_for_test(document) > 0);}++#[test]+fn shadow_style_media_mutations_update_only_the_retained_tree_scope() {+ let mut vm = new_storage_test_vm("https://shadow-style-media-refresh.test/");+ let document = vm.document_handle_for_test();++ let initial = vm+ .eval(+ r#"+(() => {+ const body = document.body || document.documentElement || document;+ const host = document.createElement('div');+ body.appendChild(host);+ const shadow = host.attachShadow({ mode: 'open' });+ const style = document.createElement('style');+ style.media = 'print';+ style.textContent = '.target { color: rgb(4, 5, 6); }';+ const target = document.createElement('div');+ target.className = 'target';+ shadow.append(style, target);+ globalThis.__shadowMediaStyle = style;+ globalThis.__shadowMediaComputed = getComputedStyle(target);+ return __shadowMediaComputed.color;+})()+"#,+ )+ .expect("shadow style media fixture should evaluate");++ assert_eq!(initial, "rgb(0, 0, 0)");+ let stylist_identity = vm.retained_stylist_identity_for_document_for_test(document);+ let rebuilds = vm.retained_style_system_rebuild_count_for_document_for_test(document);+ let updates = vm.retained_style_system_update_count_for_document_for_test(document);++ let result = vm+ .eval(+ r#"+(() => {+ __shadowMediaStyle.media = 'screen';+ const active = __shadowMediaComputed.color;+ __shadowMediaStyle.media = 'print';+ const inactive = __shadowMediaComputed.color;+ __shadowMediaStyle.removeAttribute('media');+ const restored = __shadowMediaComputed.color;+ return [active, inactive, restored].join('|');+})()+"#,+ )+ .expect("shadow style media mutations should evaluate");++ assert_eq!(result, "rgb(4, 5, 6)|rgb(0, 0, 0)|rgb(4, 5, 6)");+ assert_eq!(+ vm.retained_stylist_identity_for_document_for_test(document),+ stylist_identity,+ "ShadowRoot media changes must retain the document Stylist"+ );+ assert_eq!(+ vm.retained_style_system_rebuild_count_for_document_for_test(document),+ rebuilds,+ "ShadowRoot media changes must not rebuild the style world"+ );+ assert_eq!(+ vm.retained_style_system_update_count_for_document_for_test(document),+ updates + 3,+ "each observed media mutation must update the retained ShadowRoot scope once"+ );+}+#[test]fn computed_style_wrapper_reflects_emulated_media_changes() {let mut vm = new_storage_test_vm("https://emulated-media-computed-style.test/");@@ -4609,7 +5300,7 @@ fn box_metrics_use_computed_display_and_real_used_sizes() {}#[test]-fn box_metric_uses_one_computed_style_input_snapshot_for_nested_resolution() {+fn box_metric_materializes_one_style_world_update_for_nested_resolution() {let mut vm = new_storage_test_vm("https://box-metric-style-snapshot.test/");vm.eval(@@ -4638,24 +5329,24 @@ fn box_metric_uses_one_computed_style_input_snapshot_for_nested_resolution() {"#,).expect("nested box-metric fixture should initialize");- let builds_before = vm+ let update_materializations_before = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();+ .style_world_update_materializations_for_test();let result = vm.eval("String(document.getElementById('target').offsetWidth)").expect("box metric should resolve a nested percentage width");assert_eq!(result, "100");- let input_builds = vm+ let update_materializations = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test()- .saturating_sub(builds_before);+ .style_world_update_materializations_for_test()+ .saturating_sub(update_materializations_before);assert_eq!(- input_builds, 1,- "one synchronous box metric must carry one immutable style input snapshot"+ update_materializations, 1,+ "one synchronous box metric must materialize one style-world update");}@@ -4674,23 +5365,23 @@ body.appendChild(target);"#,).expect("inline-style fixture should initialize");- let builds_before = vm+ let update_materializations_before = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();+ .style_world_update_materializations_for_test();let result = vm.eval("document.getElementById('target').style.fontSize").expect("missing inline font-size should remain readable");assert_eq!(result, "");- let input_builds = vm+ let update_materializations = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test()- .saturating_sub(builds_before);+ .style_world_update_materializations_for_test()+ .saturating_sub(update_materializations_before);assert_eq!(- input_builds, 0,+ update_materializations, 0,"a non-logical inline property must not resolve writing mode or direction");}@@ -5673,7 +6364,7 @@ fn computed_style_property_names_are_sorted() {}#[test]-fn computed_style_index_enumeration_does_not_rebuild_inputs_per_standard_property() {+fn computed_style_index_enumeration_does_not_rematerialize_world_per_standard_property() {let mut vm = new_storage_test_vm("https://computed-style-index-cost.test/");vm.eval(r#"@@ -5684,10 +6375,10 @@ globalThis.__computedStyleForIndexCost = getComputedStyle(target);"#,).expect("computed-style fixture should initialize");- let builds_before = vm+ let update_materializations_before = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();+ .style_world_update_materializations_for_test();let length = vm.eval("String(__computedStyleForIndexCost.length)")@@ -5695,46 +6386,49 @@ globalThis.__computedStyleForIndexCost = getComputedStyle(target);let after_length = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();+ .style_world_update_materializations_for_test();vm.eval("String(__computedStyleForIndexCost[0])").expect("first indexed computed property should be readable");let after_index = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();+ .style_world_update_materializations_for_test();vm.eval("String(__computedStyleForIndexCost.item(0))").expect("first computed style item should be readable");let after_item = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();+ .style_world_update_materializations_for_test();vm.eval("String(0 in __computedStyleForIndexCost)").expect("first computed style index should be queryable");let after_query = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();+ .style_world_update_materializations_for_test();let count = vm.eval("String(Array.from(__computedStyleForIndexCost).length)").expect("computed properties should be enumerable").parse::<u64>().expect("computed property count");- let input_builds = vm+ let update_materializations = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test()- .saturating_sub(builds_before);+ .style_world_update_materializations_for_test()+ .saturating_sub(update_materializations_before);assert!(count >= 266, "unexpectedly narrow computed style: {count}");- assert_eq!(after_length.saturating_sub(builds_before), 1);+ assert_eq!(+ after_length.saturating_sub(update_materializations_before),+ 1+ );assert_eq!(after_index.saturating_sub(after_length), 0);assert_eq!(after_item.saturating_sub(after_index), 0);assert_eq!(after_query.saturating_sub(after_item), 0);assert!(- input_builds <= 8,- "indexed enumeration rebuilt style inputs {input_builds} times for {count} properties; \+ update_materializations <= 8,+ "indexed enumeration materialized {update_materializations} style-world updates for {count} properties; \length={length}, deltas length/index/item/query={}/{}/{}/{}",- after_length.saturating_sub(builds_before),+ after_length.saturating_sub(update_materializations_before),after_index.saturating_sub(after_length),after_item.saturating_sub(after_index),after_query.saturating_sub(after_item),@@ -5781,7 +6475,7 @@ fn held_computed_style_count_cache_tracks_custom_property_mutations() {}#[test]-fn inspector_computed_style_bulk_read_uses_one_input_snapshot() {+fn inspector_computed_style_bulk_read_prepares_dirty_world_once_and_reuses_clean_world() {let mut vm = new_storage_test_vm("https://computed-style-inspector-bulk.test/");vm.eval(r#"@@ -5816,10 +6510,10 @@ unrelatedHost.attachShadow({ mode: 'open' }).innerHTML =).expect("inspector computed-style fixture should initialize");let target = element_handle_by_id(&vm, "target");- let builds_before = vm+ let update_materializations_before = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();+ .style_world_update_materializations_for_test();let property_reads_before = vm._context_host.borrow()@@ -5829,19 +6523,19 @@ unrelatedHost.attachShadow({ mode: 'open' }).innerHTML =.computed_style_properties_for_inspector_handle(target).expect("live element should resolve");- let input_builds = vm+ let update_materializations = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test()- .saturating_sub(builds_before);+ .style_world_update_materializations_for_test()+ .saturating_sub(update_materializations_before);let property_reads = vm._context_host.borrow().stylo_computed_style_property_reads_for_test().saturating_sub(property_reads_before);assert_eq!(- input_builds, 1,- "one inspector bulk read must carry one immutable style input snapshot"+ update_materializations, 1,+ "one inspector bulk read must materialize one style-world update");assert!(properties.len() >= 267);assert!(@@ -5872,6 +6566,33 @@ unrelatedHost.attachShadow({ mode: 'open' }).innerHTML =] {assert_eq!(properties.get(name).map(String::as_str), Some(expected));}++ let clean_update_materializations = vm+ ._context_host+ .borrow()+ .style_world_update_materializations_for_test();+ let clean_full_snapshots = vm+ ._context_host+ .borrow()+ .style_world_full_snapshots_for_test();+ let clean_properties = vm+ .computed_style_properties_for_inspector_handle(target)+ .expect("a clean retained world should remain readable");+ assert_eq!(clean_properties.len(), properties.len());+ assert_eq!(+ vm._context_host+ .borrow()+ .style_world_update_materializations_for_test(),+ clean_update_materializations,+ "a clean inspector bulk read must not materialize a style-world update"+ );+ assert_eq!(+ vm._context_host+ .borrow()+ .style_world_full_snapshots_for_test(),+ clean_full_snapshots,+ "a clean inspector bulk read must not materialize a full style-world snapshot"+ );}#[test]@@ -5933,7 +6654,7 @@ childDocument.close();}#[test]-fn inspector_computed_style_bulk_read_uses_target_shadow_scope_once() {+fn inspector_computed_style_bulk_read_reuses_clean_shadow_world() {let mut vm = new_storage_test_vm("https://computed-style-inspector-shadow.test/");vm.eval(r#"@@ -5952,10 +6673,10 @@ host.attachShadow({ mode: 'open' }).innerHTML = `).expect("shadow inspector computed-style fixture should initialize");let target = element_handle_by_id(&vm, "inspector-shadow-target");- let builds_before = vm+ let update_materializations_before = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();+ .style_world_update_materializations_for_test();let properties = vm.computed_style_properties_for_inspector_handle(target)@@ -5963,14 +6684,14 @@ host.attachShadow({ mode: 'open' }).innerHTML = `.into_iter().collect::<std::collections::HashMap<_, _>>();- let input_builds = vm+ let update_materializations = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test()- .saturating_sub(builds_before);+ .style_world_update_materializations_for_test()+ .saturating_sub(update_materializations_before);assert_eq!(- input_builds, 1,- "one shadow-target inspector bulk read must use one input snapshot",+ update_materializations, 1,+ "one shadow-target inspector bulk read must materialize one style-world update",);for (name, expected) in [("color", "rgb(1, 2, 3)"),@@ -5979,6 +6700,22 @@ host.attachShadow({ mode: 'open' }).innerHTML = `] {assert_eq!(properties.get(name).map(String::as_str), Some(expected));}++ let clean_update_materializations = vm+ ._context_host+ .borrow()+ .style_world_update_materializations_for_test();+ let clean_properties = vm+ .computed_style_properties_for_inspector_handle(target)+ .expect("clean shadow target should resolve");+ assert_eq!(clean_properties.len(), properties.len());+ assert_eq!(+ vm._context_host+ .borrow()+ .style_world_update_materializations_for_test(),+ clean_update_materializations,+ "a clean ShadowRoot observation must not rebuild TreeScope inputs"+ );}#[test]@@ -6384,7 +7121,11 @@ fn isolated_world_css_register_property_uses_root_document_world() {.expect("isolated CSS.registerProperty setup should evaluate");assert_eq!(initial, "rgb(0, 0, 0)");- assert!(computed_style_cache_entry_count_for_document(&vm, document) > 0);+ let cache_entries = computed_style_cache_entry_count_for_document(&vm, document);+ assert!(cache_entries > 0);+ let stylist_identity = vm.retained_stylist_identity_for_document_for_test(document);+ let rebuilds = vm.retained_style_system_rebuild_count_for_document_for_test(document);+ let updates = vm.retained_style_system_update_count_for_document_for_test(document);let context_id = vm.create_isolated_world("style-register-property-test", false)@@ -6409,7 +7150,22 @@ fn isolated_world_css_register_property_uses_root_document_world() {assert_eq!(registered, "function");assert_eq!(computed_style_cache_entry_count_for_document(&vm, document),- 0+ cache_entries,+ "registerProperty must defer invalidation until the next style observation"+ );+ assert_eq!(+ vm.retained_stylist_identity_for_document_for_test(document),+ stylist_identity,+ "registerProperty must keep the existing document Stylist"+ );+ assert_eq!(+ vm.retained_style_system_rebuild_count_for_document_for_test(document),+ rebuilds+ );+ assert_eq!(+ vm.retained_style_system_update_count_for_document_for_test(document),+ updates,+ "registerProperty must only mark the style world dirty");let resolved = vm@@ -6422,6 +7178,19 @@ fn isolated_world_css_register_property_uses_root_document_world() {assert_eq!(resolved, "rgb(10, 20, 30)");assert!(computed_style_cache_entry_count_for_document(&vm, document) > 0);+ assert_eq!(+ vm.retained_stylist_identity_for_document_for_test(document),+ stylist_identity+ );+ assert_eq!(+ vm.retained_style_system_rebuild_count_for_document_for_test(document),+ rebuilds+ );+ assert_eq!(+ vm.retained_style_system_update_count_for_document_for_test(document),+ updates + 1,+ "the first post-registration observation must update the retained Stylist once"+ );}#[test]@@ -6472,8 +7241,17 @@ fn popup_css_register_property_uses_popup_document_world() {);let popup_document = owner_document_handle_for_element_id(&vm, "popup-register-target");assert_ne!(popup_document, document);- assert!(computed_style_cache_entry_count_for_document(&vm, document) > 0);- assert!(computed_style_cache_entry_count_for_document(&vm, popup_document) > 0);+ let document_cache_entries = computed_style_cache_entry_count_for_document(&vm, document);+ let popup_cache_entries = computed_style_cache_entry_count_for_document(&vm, popup_document);+ assert!(document_cache_entries > 0);+ assert!(popup_cache_entries > 0);+ let document_stylist_identity = vm.retained_stylist_identity_for_document_for_test(document);+ let popup_stylist_identity = vm.retained_stylist_identity_for_document_for_test(popup_document);+ let document_rebuilds = vm.retained_style_system_rebuild_count_for_document_for_test(document);+ let popup_rebuilds =+ vm.retained_style_system_rebuild_count_for_document_for_test(popup_document);+ let document_updates = vm.retained_style_system_update_count_for_document_for_test(document);+ let popup_updates = vm.retained_style_system_update_count_for_document_for_test(popup_document);assert!(!registered_custom_property_for_document(&vm,document,@@ -6502,10 +7280,39 @@ fn popup_css_register_property_uses_popup_document_world() {.expect("popup CSS.registerProperty should evaluate");assert_eq!(registered, "function");- assert!(computed_style_cache_entry_count_for_document(&vm, document) > 0);+ assert_eq!(+ computed_style_cache_entry_count_for_document(&vm, document),+ document_cache_entries+ );assert_eq!(computed_style_cache_entry_count_for_document(&vm, popup_document),- 0+ popup_cache_entries,+ "popup registration must defer invalidation until its next observation"+ );+ assert_eq!(+ vm.retained_stylist_identity_for_document_for_test(document),+ document_stylist_identity+ );+ assert_eq!(+ vm.retained_stylist_identity_for_document_for_test(popup_document),+ popup_stylist_identity+ );+ assert_eq!(+ vm.retained_style_system_rebuild_count_for_document_for_test(document),+ document_rebuilds+ );+ assert_eq!(+ vm.retained_style_system_rebuild_count_for_document_for_test(popup_document),+ popup_rebuilds+ );+ assert_eq!(+ vm.retained_style_system_update_count_for_document_for_test(document),+ document_updates+ );+ assert_eq!(+ vm.retained_style_system_update_count_for_document_for_test(popup_document),+ popup_updates,+ "registration must only mark the popup style world dirty");assert!(!registered_custom_property_for_document(&vm,@@ -6541,6 +7348,32 @@ fn popup_css_register_property_uses_popup_document_world() {);assert!(computed_style_cache_entry_count_for_document(&vm, document) > 0);assert!(computed_style_cache_entry_count_for_document(&vm, popup_document) > 0);+ assert_eq!(+ vm.retained_stylist_identity_for_document_for_test(document),+ document_stylist_identity+ );+ assert_eq!(+ vm.retained_stylist_identity_for_document_for_test(popup_document),+ popup_stylist_identity+ );+ assert_eq!(+ vm.retained_style_system_rebuild_count_for_document_for_test(document),+ document_rebuilds+ );+ assert_eq!(+ vm.retained_style_system_rebuild_count_for_document_for_test(popup_document),+ popup_rebuilds+ );+ assert_eq!(+ vm.retained_style_system_update_count_for_document_for_test(document),+ document_updates,+ "reading the clean opener document must not update its style world"+ );+ assert_eq!(+ vm.retained_style_system_update_count_for_document_for_test(popup_document),+ popup_updates + 1,+ "the first popup observation must update its retained Stylist once"+ );}#[test]@@ -10277,3 +11110,51 @@ fn computed_custom_functions_resolve_shadow_scoped_container_queries() {assert_eq!(result, "5px|5px|5px 5px|5px 5px|--cont|size|--cont|size");}++#[test]+fn custom_function_provenance_probe_preserves_the_retained_style_world() {+ let mut vm = new_parsed_test_vm(+ "https://custom-function-retained-world.test/",+ r#"<!doctype html><style>+ @function --answer() { result: 42px; }+ #target { color: rgb(1, 2, 3); --resolved: --answer(); }+ </style><div id=target></div>"#,+ );+ assert_eq!(+ vm.eval("getComputedStyle(document.getElementById('target')).color")+ .expect("ordinary style should establish the retained world"),+ "rgb(1, 2, 3)"+ );+ let document = vm.document_handle_for_test();+ let stylist_identity = vm.retained_stylist_identity_for_document_for_test(document);+ let rebuilds = vm.retained_style_system_rebuild_count_for_document_for_test(document);+ let updates = vm.retained_style_system_update_count_for_document_for_test(document);++ assert_eq!(+ vm.eval(+ "getComputedStyle(document.getElementById('target')).getPropertyValue('--resolved')",+ )+ .expect("custom function should resolve through the isolated provenance probe"),+ "42px"+ );+ assert_eq!(+ vm.retained_stylist_identity_for_document_for_test(document),+ stylist_identity,+ "a compatibility probe must not replace the Document Stylist"+ );+ assert_eq!(+ vm.retained_style_system_rebuild_count_for_document_for_test(document),+ rebuilds,+ "a compatibility probe must not rebuild the retained style world"+ );+ assert_eq!(+ vm.retained_style_system_update_count_for_document_for_test(document),+ updates,+ "a compatibility probe must not flush the retained style world"+ );+ assert_eq!(+ vm.eval("getComputedStyle(document.getElementById('target')).color")+ .expect("the retained world should remain readable after the probe"),+ "rgb(1, 2, 3)"+ );+}diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom.rsindex 37aa0f7c6..261f12ad0 100644--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom.rs+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom.rs@@ -7856,9 +7856,9 @@ fn rendered_style_facts_refresh_after_synchronous_mutations() {}#[test]-fn inner_text_reuses_prepared_style_inputs_within_each_synchronous_read() {+fn inner_text_reuses_retained_style_world_across_synchronous_reads() {let mut vm = new_parsed_test_vm(- "https://inner-text-prepared-style-inputs.test/",+ "https://inner-text-retained-style-world.test/",r#"<!doctype html><html><head><style>.upper { text-transform: uppercase; }</style></head><body><div id="target"></div></body></html>"#,@@ -7873,30 +7873,30 @@ for (let index = 0; index < 128; index++) {}"#,)- .expect("innerText prepared-input fixture should initialize");+ .expect("innerText retained-style fixture should initialize");- let builds_before = vm+ let update_materializations_before = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_before = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_before = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();let layout_before = vm.layout_pass_observability_for_test();let first = vm.eval("(() => { const text = target.innerText; return [text.length, text[0], text[127]].join('|'); })()",).expect("first innerText read should evaluate");- let builds_after_first = vm+ let update_materializations_after_first = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_after_first = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_after_first = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();let layout_after_first = vm.layout_pass_observability_for_test();let repeated = vm@@ -7904,14 +7904,14 @@ for (let index = 0; index < 128; index++) {"(() => { const text = target.innerText; return [text.length, text[0], text[127]].join('|'); })()",).expect("repeated innerText read should evaluate");- let builds_after_repeated = vm+ let update_materializations_after_repeated = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_after_repeated = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_after_repeated = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();let layout_after_repeated = vm.layout_pass_observability_for_test();let second = vm@@ -7919,14 +7919,14 @@ for (let index = 0; index < 128; index++) {"target.className = 'upper'; (() => { const text = target.innerText; return [text.length, text[0], text[127]].join('|'); })()",).expect("mutated innerText read should evaluate");- let builds_after_second = vm+ let update_materializations_after_second = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_after_second = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_after_second = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();let layout_after_second = vm.layout_pass_observability_for_test();let stylesheet_mutation = vm@@ -7934,14 +7934,14 @@ for (let index = 0; index < 128; index++) {"document.querySelector('style').textContent = '.upper { text-transform: lowercase; }'; (() => { const text = target.innerText; return [text.length, text[0], text[127]].join('|'); })()",).expect("stylesheet-mutated innerText read should evaluate");- let builds_after_stylesheet_mutation = vm+ let update_materializations_after_stylesheet_mutation = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_after_stylesheet_mutation = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_after_stylesheet_mutation = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();let layout_after_stylesheet_mutation = vm.layout_pass_observability_for_test();assert_eq!(first, "128|a|a");@@ -7960,44 +7960,45 @@ for (let index = 0; index < 128; index++) {assert_eq!(layout_after_second.1, layout_after_first.1);assert_eq!(layout_after_stylesheet_mutation.1, layout_after_first.1);assert_eq!(- builds_after_first.saturating_sub(builds_before),+ update_materializations_after_first.saturating_sub(update_materializations_before),1,- "one innerText traversal should prepare one document input"+ "one cold innerText traversal should materialize the initial style world");assert_eq!(- builds_after_repeated.saturating_sub(builds_after_first),+ update_materializations_after_repeated.saturating_sub(update_materializations_after_first),0,- "an unchanged generation should reuse its document input across getters"+ "an unchanged generation should reuse its retained style world across getters");assert_eq!(- builds_after_second.saturating_sub(builds_after_repeated),- 1,- "a later innerText read must prepare one fresh input after mutation"+ update_materializations_after_second.saturating_sub(update_materializations_after_repeated),+ 0,+ "an element-only mutation must reuse the retained stylesheet world");assert_eq!(- builds_after_stylesheet_mutation.saturating_sub(builds_after_second),+ update_materializations_after_stylesheet_mutation+ .saturating_sub(update_materializations_after_second),1,- "a stylesheet mutation must invalidate the cross-getter document input"+ "a stylesheet mutation should materialize one incremental update");assert_eq!(- key_builds_after_first.saturating_sub(key_builds_before),+ full_snapshots_after_first.saturating_sub(full_snapshots_before),1,- "one traversal must hash one retained-system key, not one key per descendant"+ "one cold traversal should build one full style-world snapshot");assert_eq!(- key_builds_after_repeated.saturating_sub(key_builds_after_first),+ full_snapshots_after_repeated.saturating_sub(full_snapshots_after_first),0,- "an unchanged generation should reuse the prepared retained-system key"+ "an unchanged generation should not rebuild a full style-world snapshot");assert_eq!(- key_builds_after_second.saturating_sub(key_builds_after_repeated),- 1,- "a style mutation must prepare one fresh retained-system key"+ full_snapshots_after_second.saturating_sub(full_snapshots_after_repeated),+ 0,+ "an element-only mutation must not build a full style-world snapshot");assert_eq!(- key_builds_after_stylesheet_mutation.saturating_sub(key_builds_after_second),- 1,- "a stylesheet mutation must prepare one fresh retained-system key"+ full_snapshots_after_stylesheet_mutation.saturating_sub(full_snapshots_after_second),+ 0,+ "an ordinary stylesheet mutation must stay on the incremental update path");}@@ -8045,35 +8046,35 @@ fn inner_text_new_sources_wait_for_a_fresh_paint_layout() {}#[test]-fn inner_text_document_input_cache_tracks_emulated_media_changes() {+fn inner_text_updates_device_in_place_without_full_style_world_snapshots() {let mut vm = new_parsed_test_vm(- "https://inner-text-emulated-media-inputs.test/",+ "https://inner-text-emulated-media-style-world.test/",r#"<!doctype html><html><head><style>@media print { #target { text-transform: uppercase; } }</style></head><body><div id="target">mixed</div></body></html>"#,);- let builds_before = vm+ let update_materializations_before = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_before = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_before = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();assert_eq!(vm.eval("document.getElementById('target').innerText").expect("screen innerText read should evaluate"),"mixed");- let builds_after_screen = vm+ let update_materializations_after_screen = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_after_screen = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_after_screen = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();vm.set_emulated_media(&crate::protocol_types::EmulatedMediaOverrides {media: Some("print".to_owned()),@@ -8084,14 +8085,14 @@ fn inner_text_document_input_cache_tracks_emulated_media_changes() {.expect("print innerText read should evaluate"),"MIXED");- let builds_after_print = vm+ let update_materializations_after_print = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_after_print = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_after_print = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();vm.set_emulated_media(&crate::protocol_types::EmulatedMediaOverrides::default());assert_eq!(@@ -8099,33 +8100,47 @@ fn inner_text_document_input_cache_tracks_emulated_media_changes() {.expect("restored screen innerText read should evaluate"),"mixed");- let builds_after_restore = vm+ let update_materializations_after_restore = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_after_restore = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_after_restore = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();- assert_eq!(builds_after_screen.saturating_sub(builds_before), 1);- assert_eq!(builds_after_print.saturating_sub(builds_after_screen), 1);- assert_eq!(builds_after_restore.saturating_sub(builds_after_print), 1);- assert_eq!(key_builds_after_screen.saturating_sub(key_builds_before), 1);assert_eq!(- key_builds_after_print.saturating_sub(key_builds_after_screen),+ update_materializations_after_screen.saturating_sub(update_materializations_before),1);assert_eq!(- key_builds_after_restore.saturating_sub(key_builds_after_print),+ update_materializations_after_print.saturating_sub(update_materializations_after_screen),1);+ assert_eq!(+ update_materializations_after_restore.saturating_sub(update_materializations_after_print),+ 1+ );+ assert_eq!(+ full_snapshots_after_screen.saturating_sub(full_snapshots_before),+ 1+ );+ assert_eq!(+ full_snapshots_after_print.saturating_sub(full_snapshots_after_screen),+ 0,+ "a device update must preserve the retained style world"+ );+ assert_eq!(+ full_snapshots_after_restore.saturating_sub(full_snapshots_after_print),+ 0,+ "restoring the device must remain an incremental update"+ );}#[test]-fn inner_text_document_input_cache_tracks_document_url_changes() {+fn inner_text_replaces_style_world_after_document_url_change() {let mut vm = new_parsed_test_vm(- "https://inner-text-document-url-inputs.test/start/index.html",+ "https://inner-text-document-url-style-world.test/start/index.html",r#"<!doctype html><html><head><base href="https://cdn.test/stable-base/"><style>#target { text-transform: uppercase; }</style>@@ -8137,14 +8152,14 @@ fn inner_text_document_input_cache_tracks_document_url_changes() {.expect("initial innerText read should evaluate"),"MIXED");- let builds_after_initial = vm+ let update_materializations_after_initial = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_after_initial = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_after_initial = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();assert_eq!(vm.eval(@@ -8153,44 +8168,46 @@ fn inner_text_document_input_cache_tracks_document_url_changes() {.expect("innerText after same-document URL mutation should evaluate"),"MIXED");- let builds_after_url_change = vm+ let update_materializations_after_url_change = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_after_url_change = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_after_url_change = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();assert_eq!(vm.eval("document.getElementById('target').innerText").expect("repeated innerText after URL mutation should evaluate"),"MIXED");- let builds_after_repeated = vm+ let update_materializations_after_repeated = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_after_repeated = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_after_repeated = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();assert_eq!(- builds_after_url_change.saturating_sub(builds_after_initial),+ update_materializations_after_url_change+ .saturating_sub(update_materializations_after_initial),1);assert_eq!(- key_builds_after_url_change.saturating_sub(key_builds_after_initial),+ full_snapshots_after_url_change.saturating_sub(full_snapshots_after_initial),1,- "a path-changing history mutation must not reuse a prepared key for the old document URL"+ "a path-changing history mutation is an explicit style-world replacement boundary");assert_eq!(- builds_after_repeated.saturating_sub(builds_after_url_change),+ update_materializations_after_repeated+ .saturating_sub(update_materializations_after_url_change),0);assert_eq!(- key_builds_after_repeated.saturating_sub(key_builds_after_url_change),+ full_snapshots_after_repeated.saturating_sub(full_snapshots_after_url_change),0);}@@ -8198,7 +8215,7 @@ fn inner_text_document_input_cache_tracks_document_url_changes() {#[test]fn inner_text_reuses_one_document_style_world_across_shadow_scopes() {let mut vm = new_parsed_test_vm(- "https://inner-text-shadow-style-inputs.test/",+ "https://inner-text-shadow-style-world.test/",r#"<!doctype html><html><body><div id="host"><span>assigned</span><span slot="missing">hidden</span></div></body></html>"#,@@ -8210,40 +8227,40 @@ host.attachShadow({mode: 'open'}).innerHTML ='<style>::slotted(span) { text-transform: uppercase; }</style><slot></slot>';"#,)- .expect("shadow innerText prepared-input fixture should initialize");- let builds_before = vm+ .expect("shadow innerText retained-style fixture should initialize");+ let update_materializations_before = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_before = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_before = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();let layout_before = vm.layout_pass_observability_for_test();let first_text = vm.eval("host.innerText").expect("shadow innerText read should evaluate");- let builds_after_first = vm+ let update_materializations_after_first = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_after_first = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_after_first = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();let layout_after_first = vm.layout_pass_observability_for_test();let second_text = vm.eval("host.innerText").expect("repeated shadow innerText read should evaluate");- let builds_after_second = vm+ let update_materializations_after_second = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_after_second = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_after_second = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();let layout_after_second = vm.layout_pass_observability_for_test();assert_eq!(first_text, "ASSIGNED");@@ -8252,29 +8269,30 @@ host.attachShadow({mode: 'open'}).innerHTML =assert_eq!(layout_after_first.1, layout_before.1 + 1);assert_eq!(layout_after_second.1, layout_after_first.1);assert_eq!(- builds_after_first.saturating_sub(builds_before),+ update_materializations_after_first.saturating_sub(update_materializations_before),1,"layout and rendered-text collection must share one document TreeScope universe");assert_eq!(- builds_after_second.saturating_sub(builds_after_first),+ update_materializations_after_second.saturating_sub(update_materializations_after_first),0,- "an unchanged document TreeScope universe must reuse its prepared input"+ "an unchanged document TreeScope universe must reuse its retained style world");assert_eq!(- key_builds_after_first.saturating_sub(key_builds_before),+ full_snapshots_after_first.saturating_sub(full_snapshots_before),1,- "one observation must build one retained-system key for the document"+ "one cold observation must build one full style-world snapshot");assert_eq!(- key_builds_after_second.saturating_sub(key_builds_after_first),+ full_snapshots_after_second.saturating_sub(full_snapshots_after_first),0,- "the rendered-text collector must reuse the unchanged document key"+ "the rendered-text collector must reuse the unchanged retained style world");}#[test]fn paint_layout_reuses_one_style_world_across_many_empty_shadow_roots() {+ crate::style_engine::reset_author_source_text_parse_count_for_test();let mut vm = new_parsed_test_vm("https://paint-empty-shadow-style-world.test/",r#"<!doctype html><html><head><style>@@ -8303,28 +8321,46 @@ for (let index = 0; index < 64; index += 1) {let document = vm.document_handle_for_test();let rebuilds_before = vm.retained_style_system_rebuild_count_for_document_for_test(document);- let builds_before = vm+ let update_materializations_before = vm+ ._context_host+ .borrow()+ .style_world_update_materializations_for_test();+ let full_snapshots_before = vm+ ._context_host+ .borrow()+ .style_world_full_snapshots_for_test();+ let document_scopes_before = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_before = vm+ .style_world_document_scope_materializations_for_test();+ let shadow_scopes_before = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_shadow_scope_materializations_for_test();vm.screenshot_layout_snapshot(moli_layout::PaintViewport::new(800, 600, 1.0)).expect("first empty shadow-root paint layout should succeed").expect("the fixture should have a layout root");let rebuilds_after_first =vm.retained_style_system_rebuild_count_for_document_for_test(document);- let builds_after_first = vm+ let update_materializations_after_first = vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test();- let key_builds_after_first = vm+ .style_world_update_materializations_for_test();+ let full_snapshots_after_first = vm._context_host.borrow()- .stylo_style_system_key_builds_for_test();+ .style_world_full_snapshots_for_test();+ let document_scopes_after_first = vm+ ._context_host+ .borrow()+ .style_world_document_scope_materializations_for_test();+ let shadow_scopes_after_first = vm+ ._context_host+ .borrow()+ .style_world_shadow_scope_materializations_for_test();+ let updates_after_first = vm.retained_style_system_update_count_for_document_for_test(document);+ let parses_after_first = crate::style_engine::author_source_text_parse_count_for_test();vm.screenshot_layout_snapshot(moli_layout::PaintViewport::new(800, 600, 1.0)).expect("second empty shadow-root paint layout should succeed")@@ -8340,19 +8376,59 @@ for (let index = 0; index < 64; index += 1) {rebuilds_after_first,"an unchanged fresh paint layout must retain the same document style system",);- assert_eq!(builds_after_first.saturating_sub(builds_before), 1);- assert_eq!(key_builds_after_first.saturating_sub(key_builds_before), 1);+ assert_eq!(+ update_materializations_after_first.saturating_sub(update_materializations_before),+ 1+ );+ assert_eq!(+ full_snapshots_after_first.saturating_sub(full_snapshots_before),+ 1+ );+ assert_eq!(+ document_scopes_after_first.saturating_sub(document_scopes_before),+ 1,+ "the initial paint should materialize the Document scope once"+ );+ assert_eq!(+ shadow_scopes_after_first.saturating_sub(shadow_scopes_before),+ 72,+ "64 direct and 8 nested ShadowRoots should each materialize once"+ );assert_eq!(vm._context_host.borrow()- .stylo_computed_style_input_builds_for_test(),- builds_after_first,+ .style_world_update_materializations_for_test(),+ update_materializations_after_first,);assert_eq!(vm._context_host.borrow()- .stylo_style_system_key_builds_for_test(),- key_builds_after_first,+ .style_world_full_snapshots_for_test(),+ full_snapshots_after_first,+ );+ assert_eq!(+ vm._context_host+ .borrow()+ .style_world_document_scope_materializations_for_test(),+ document_scopes_after_first,+ "a clean screenshot must not recollect Document stylesheets"+ );+ assert_eq!(+ vm._context_host+ .borrow()+ .style_world_shadow_scope_materializations_for_test(),+ shadow_scopes_after_first,+ "a clean screenshot must not recollect ShadowRoot stylesheets"+ );+ assert_eq!(+ vm.retained_style_system_update_count_for_document_for_test(document),+ updates_after_first,+ "a clean screenshot must not flush the retained style world"+ );+ assert_eq!(+ crate::style_engine::author_source_text_parse_count_for_test(),+ parses_after_first,+ "a clean screenshot must not parse author stylesheets");}diff --git a/moli-renderer-v8/src/script_vm/web_fonts.rs b/moli-renderer-v8/src/script_vm/web_fonts.rsindex 926b5e198..0fb445315 100644--- a/moli-renderer-v8/src/script_vm/web_fonts.rs+++ b/moli-renderer-v8/src/script_vm/web_fonts.rs@@ -152,13 +152,13 @@ impl DocumentWebFontState {#[cfg(test)]mod tests {use super::*;- use crate::css_resource_urls::stylesheet_load_blocking_resources;+ use crate::css_resource_urls::stylesheet_load_blocking_font_resources;use crate::protocol_types::OptionalResourceFetchMask;const TEST_FONT: &[u8] = include_bytes!("../../../moli-layout/tests/fixtures/moli-ahem.woff2");fn resource(css: &str) -> StylesheetLoadBlockingResource {- stylesheet_load_blocking_resources(+ stylesheet_load_blocking_font_resources(css,&Url::parse("https://example.test/style.css").unwrap(),OptionalResourceFetchMask::FONT,diff --git a/moli-renderer-v8/src/style_engine/active_stylesheets.rs b/moli-renderer-v8/src/style_engine/active_stylesheets.rsnew file mode 100644index 000000000..1708f7ac6--- /dev/null+++ b/moli-renderer-v8/src/style_engine/active_stylesheets.rs@@ -0,0 +1,343 @@+use std::sync::Arc;+use style::{+ shared_lock::SharedRwLockReadGuard, stylesheets::DocumentStyleSheet, stylist::Stylist,+};++use crate::css_resource_urls::StylesheetLoadBlockingResource;++use super::source::store::{LiveStylesheetCascadeUpdate, StyloStylesheetSource};++#[cfg(test)]+thread_local! {+ static EXACT_RULE_CHANGE_NOTIFICATION_COUNT: std::cell::Cell<usize> = const {+ std::cell::Cell::new(0)+ };+ static FULL_CASCADE_UPDATE_FALLBACK_COUNT: std::cell::Cell<usize> = const {+ std::cell::Cell::new(0)+ };+}++#[cfg(test)]+pub(crate) fn reset_live_stylesheet_update_counts_for_test() {+ EXACT_RULE_CHANGE_NOTIFICATION_COUNT.with(|count| count.set(0));+ FULL_CASCADE_UPDATE_FALLBACK_COUNT.with(|count| count.set(0));+}++#[cfg(test)]+pub(crate) fn exact_rule_change_notification_count_for_test() -> usize {+ EXACT_RULE_CHANGE_NOTIFICATION_COUNT.with(std::cell::Cell::get)+}++#[cfg(test)]+pub(crate) fn full_cascade_update_fallback_count_for_test() -> usize {+ FULL_CASCADE_UPDATE_FALLBACK_COUNT.with(std::cell::Cell::get)+}++pub(super) fn note_exact_rule_change_notifications(count: usize) {+ #[cfg(test)]+ EXACT_RULE_CHANGE_NOTIFICATION_COUNT.with(|current| {+ current.set(current.get().saturating_add(count));+ });+ #[cfg(not(test))]+ let _ = count;+}++pub(super) fn note_full_cascade_update_fallback() {+ #[cfg(test)]+ FULL_CASCADE_UPDATE_FALLBACK_COUNT.with(|count| {+ count.set(count.get().saturating_add(1));+ });+}++/// One stylesheet installation retained by a document or shadow-tree scope.+///+/// `source` carries the stable installation/revision identity used to diff a+/// later active-sheet list. `stylesheet` is the parsed Stylo object installed+/// in the owning `Stylist`/`AuthorStyles`; retaining it makes clean observations+/// and unrelated scope updates parse-free.+#[derive(Clone)]+pub(super) struct ActiveStylesheet {+ source: StyloStylesheetSource,+ stylesheet: DocumentStyleSheet,+ web_font_resources: Arc<[StylesheetLoadBlockingResource]>,+ import_urls: Arc<[url::Url]>,+}++impl ActiveStylesheet {+ pub(super) fn new(+ source: StyloStylesheetSource,+ stylesheet: DocumentStyleSheet,+ web_font_resources: Arc<[StylesheetLoadBlockingResource]>,+ import_urls: Arc<[url::Url]>,+ ) -> Self {+ Self {+ source,+ stylesheet,+ web_font_resources,+ import_urls,+ }+ }++ pub(super) fn source(&self) -> &StyloStylesheetSource {+ &self.source+ }++ pub(super) fn stylesheet(&self) -> &DocumentStyleSheet {+ &self.stylesheet+ }++ pub(super) fn web_font_resources(&self) -> &[StylesheetLoadBlockingResource] {+ self.web_font_resources.as_ref()+ }++ pub(super) fn import_urls(&self) -> &[url::Url] {+ self.import_urls.as_ref()+ }+}++#[derive(Default)]+pub(super) struct ActiveStylesheetCollection {+ entries: Vec<ActiveStylesheet>,+}++pub(super) struct ActiveStylesheetReconciliation {+ previous_stylesheets: Vec<DocumentStyleSheet>,+ stylesheet_set_changed: bool,+ stylesheet_removed: bool,+ in_place_updates: Vec<ActiveStylesheetInPlaceUpdate>,+}++pub(super) struct ActiveStylesheetInPlaceUpdate {+ stylesheet: DocumentStyleSheet,+ cascade_update: LiveStylesheetCascadeUpdate,+}++impl ActiveStylesheetReconciliation {+ pub(super) fn previous_stylesheets(&self) -> &[DocumentStyleSheet] {+ &self.previous_stylesheets+ }++ pub(super) fn stylesheet_set_changed(&self) -> bool {+ self.stylesheet_set_changed+ }++ pub(super) fn stylesheet_removed(&self) -> bool {+ self.stylesheet_removed+ }++ pub(super) fn in_place_updates(&self) -> &[ActiveStylesheetInPlaceUpdate] {+ &self.in_place_updates+ }+}++impl ActiveStylesheetInPlaceUpdate {+ pub(super) fn stylesheet(&self) -> &DocumentStyleSheet {+ &self.stylesheet+ }++ pub(super) fn cascade_update(&self) -> &LiveStylesheetCascadeUpdate {+ &self.cascade_update+ }+}++impl ActiveStylesheetCollection {+ pub(super) fn new(entries: Vec<ActiveStylesheet>) -> Self {+ Self { entries }+ }++ pub(super) fn entries(&self) -> &[ActiveStylesheet] {+ &self.entries+ }++ pub(super) fn matches_sources(&self, sources: &[StyloStylesheetSource]) -> bool {+ self.entries.len() == sources.len()+ && self+ .entries+ .iter()+ .zip(sources)+ .all(|(entry, source)| entry.source() == source)+ }++ /// Reconciles an ordered active list while retaining parsed stylesheet+ /// objects for unchanged installations, including reorder-only changes.+ pub(super) fn reconcile(+ &mut self,+ sources: &[StyloStylesheetSource],+ mut install: impl FnMut(&StyloStylesheetSource) -> ActiveStylesheet,+ ) -> Option<ActiveStylesheetReconciliation> {+ if self.matches_sources(sources) {+ return None;+ }++ let mut previous = std::mem::take(&mut self.entries);+ let previous_stylesheets = previous+ .iter()+ .map(|entry| entry.stylesheet().clone())+ .collect::<Vec<_>>();+ let mut in_place_updates = Vec::new();+ self.entries = sources+ .iter()+ .map(|source| {+ if let Some(index) = previous.iter().position(|entry| entry.source() == source) {+ return previous.remove(index);+ }+ let Some(index) = previous+ .iter()+ .position(|entry| has_same_installation(entry.source(), source))+ else {+ return install(source);+ };+ let previous_entry = previous.remove(index);+ if previous_entry.source().has_same_stylesheet_revision(source) {+ return ActiveStylesheet::new(+ source.clone(),+ previous_entry.stylesheet().clone(),+ Arc::clone(&previous_entry.web_font_resources),+ Arc::clone(&previous_entry.import_urls),+ );+ }+ let next_entry = install(source);+ if previous_entry.stylesheet() == next_entry.stylesheet() {+ in_place_updates.push(ActiveStylesheetInPlaceUpdate {+ stylesheet: next_entry.stylesheet().clone(),+ cascade_update: source.live_cascade_update_since(previous_entry.source()),+ });+ }+ next_entry+ })+ .collect();+ let stylesheet_set_changed = previous_stylesheets+ .iter()+ .ne(self.entries.iter().map(ActiveStylesheet::stylesheet));+ let stylesheet_removed = previous_stylesheets.iter().any(|stylesheet| {+ !self+ .entries+ .iter()+ .any(|entry| entry.stylesheet() == stylesheet)+ });+ Some(ActiveStylesheetReconciliation {+ previous_stylesheets,+ stylesheet_set_changed,+ stylesheet_removed,+ in_place_updates,+ })+ }+}++fn has_same_installation(previous: &StyloStylesheetSource, next: &StyloStylesheetSource) -> bool {+ match (previous.adopted_client_id(), next.adopted_client_id()) {+ (Some(previous), Some(next)) => previous == next,+ (Some(_), None) | (None, Some(_)) => false,+ (None, None) => previous.has_same_installation_identity(next),+ }+}++pub(super) enum StylesheetSetUpdate {+ Remove(DocumentStyleSheet),+ InsertBefore {+ stylesheet: DocumentStyleSheet,+ before: DocumentStyleSheet,+ },+ Append(DocumentStyleSheet),+}++pub(super) fn stylesheet_set_updates(+ previous: &[DocumentStyleSheet],+ next: &[DocumentStyleSheet],+) -> Vec<StylesheetSetUpdate> {+ let mut current = previous.to_vec();+ let mut updates = Vec::new();++ for index in (0..current.len()).rev() {+ if !next.contains(¤t[index]) {+ updates.push(StylesheetSetUpdate::Remove(current.remove(index)));+ }+ }+ for (index, stylesheet) in next.iter().enumerate() {+ if current.get(index) == Some(stylesheet) {+ continue;+ }+ if let Some(current_index) = current.iter().position(|current| current == stylesheet) {+ let stylesheet = current.remove(current_index);+ updates.push(StylesheetSetUpdate::Remove(stylesheet));+ }+ if let Some(before) = current.get(index).cloned() {+ updates.push(StylesheetSetUpdate::InsertBefore {+ stylesheet: stylesheet.clone(),+ before,+ });+ current.insert(index, stylesheet.clone());+ } else {+ updates.push(StylesheetSetUpdate::Append(stylesheet.clone()));+ current.push(stylesheet.clone());+ }+ }+ while current.len() > next.len() {+ updates.push(StylesheetSetUpdate::Remove(+ current+ .pop()+ .expect("current stylesheet list cannot be empty here"),+ ));+ }+ updates+}++pub(super) fn update_document_stylesheet_set(+ stylist: &mut Stylist,+ previous: &[DocumentStyleSheet],+ next: &[DocumentStyleSheet],+ guard: &SharedRwLockReadGuard<'_>,+) {+ for update in stylesheet_set_updates(previous, next) {+ match update {+ StylesheetSetUpdate::Remove(stylesheet) => {+ stylist.remove_stylesheet(stylesheet, guard);+ }+ StylesheetSetUpdate::InsertBefore { stylesheet, before } => {+ stylist.insert_stylesheet_before(stylesheet, before, guard)+ }+ StylesheetSetUpdate::Append(stylesheet) => {+ stylist.append_stylesheet(stylesheet, guard);+ }+ }+ }+}++/// Publishes exact live-CSSOM changes into the persistent Document Stylist.+/// Returns `true` when at least one generation was not representable by the+/// journal and the caller must conservatively dirty the author origin.+pub(super) fn notify_document_stylesheet_rule_changes(+ stylist: &mut Stylist,+ reconciliation: &ActiveStylesheetReconciliation,+ guard: &SharedRwLockReadGuard<'_>,+) -> bool {+ if reconciliation+ .in_place_updates()+ .iter()+ .any(|update| matches!(update.cascade_update(), LiveStylesheetCascadeUpdate::Full))+ {+ note_full_cascade_update_fallback();+ return true;+ }+ for update in reconciliation.in_place_updates() {+ let LiveStylesheetCascadeUpdate::Rules(changes) = update.cascade_update() else {+ unreachable!("full updates were handled above");+ };+ note_exact_rule_change_notifications(changes.len());+ for change in changes {+ let ancestors = change+ .ancestors()+ .iter()+ .map(style::stylesheets::CssRuleRef::from)+ .collect::<Vec<_>>();+ stylist.rule_changed(+ update.stylesheet(),+ change.rule(),+ guard,+ change.change_kind(),+ &ancestors,+ );+ }+ }+ false+}diff --git a/moli-renderer-v8/src/style_engine/cache.rs b/moli-renderer-v8/src/style_engine/cache.rsindex 860afaf6f..37c05243f 100644--- a/moli-renderer-v8/src/style_engine/cache.rs+++ b/moli-renderer-v8/src/style_engine/cache.rs@@ -1,102 +1,23 @@use std::{cell::{Cell, RefCell},collections::{HashMap, HashSet},- rc::Rc,};use style::{- data::ElementStyles, properties::ComputedValues, selector_parser::PseudoElement,- servo_arc::Arc as ServoArc,+ properties::ComputedValues, selector_parser::PseudoElement, servo_arc::Arc as ServoArc,};use crate::document_runtime::DomHandle;-use super::{StyloDocumentComputedStyleInputCacheKey, StyloPreparedComputedStyleInputs};--const DOCUMENT_COMPUTED_STYLE_INPUT_CACHE_LIMIT: usize = 2;--/// Generations that can change the immutable inputs and retained-system key-/// supplied to Stylo.+/// Resolution index for canonical Stylo element data plus a pseudo-style cache.///-/// The retained-style-system generation is deliberately excluded: resolving-/// the first element from freshly built inputs can create that system. Inputs-/// are published after the observation, against the resulting canonical-/// source/computed/target generations.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub(super) struct ComputedStyleInputCacheGeneration {- pub(super) source_set: u64,- pub(super) computed_values: u64,- pub(super) target_context: u64,-}--pub(super) struct ComputedStyleInputCache {- generation: Cell<Option<ComputedStyleInputCacheGeneration>>,- entries: RefCell<- Vec<(- StyloDocumentComputedStyleInputCacheKey,- Rc<StyloPreparedComputedStyleInputs>,- )>,- >,-}--impl ComputedStyleInputCache {- pub(super) fn new() -> Self {- Self {- generation: Cell::new(None),- entries: RefCell::new(Vec::new()),- }- }-- pub(super) fn clear(&self) {- self.generation.set(None);- self.entries.borrow_mut().clear();- }-- pub(super) fn get(- &self,- generation: ComputedStyleInputCacheGeneration,- key: &StyloDocumentComputedStyleInputCacheKey,- ) -> Option<Rc<StyloPreparedComputedStyleInputs>> {- self.synchronize_generation(generation);- self.entries- .borrow()- .iter()- .find(|(candidate, _)| candidate == key)- .map(|(_, inputs)| Rc::clone(inputs))- }-- pub(super) fn insert(- &self,- generation: ComputedStyleInputCacheGeneration,- key: StyloDocumentComputedStyleInputCacheKey,- inputs: Rc<StyloPreparedComputedStyleInputs>,- ) {- self.synchronize_generation(generation);- let mut entries = self.entries.borrow_mut();- if let Some((_, cached_inputs)) =- entries.iter_mut().find(|(candidate, _)| candidate == &key)- {- *cached_inputs = inputs;- return;- }- if entries.len() == DOCUMENT_COMPUTED_STYLE_INPUT_CACHE_LIMIT {- entries.remove(0);- }- entries.push((key, inputs));- }-- fn synchronize_generation(&self, generation: ComputedStyleInputCacheGeneration) {- if self.generation.get() == Some(generation) {- return;- }- self.entries.borrow_mut().clear();- self.generation.set(Some(generation));- }-}-+/// Primary `ComputedValues` are never duplicated here: they remain owned by+/// Stylo `ElementData`. Primary entries only let invalidation find already+/// published elements; pseudo styles have no equivalent canonical slot and are+/// therefore retained by value until their generation is invalidated.pub(super) struct ComputedStyleCache {- entries: RefCell<HashMap<ComputedElementStyleCacheKey, ElementStyles>>,- lazy_pseudo_entries: RefCell<HashMap<ComputedElementStyleCacheKey, ServoArc<ComputedValues>>>,+ primary_entries: RefCell<HashSet<ComputedElementStyleCacheKey>>,+ pseudo_entries: RefCell<HashMap<ComputedElementStyleCacheKey, ServoArc<ComputedValues>>>,keys_by_handle: RefCell<HashMap<DomHandle, HashSet<ComputedElementStyleCacheKey>>>,write_generation: Cell<u64>,}@@ -111,46 +32,52 @@ pub(super) struct ComputedElementStyleCacheKey {impl ComputedStyleCache {pub(super) fn new() -> Self {Self {- entries: RefCell::new(HashMap::new()),- lazy_pseudo_entries: RefCell::new(HashMap::new()),+ primary_entries: RefCell::new(HashSet::new()),+ pseudo_entries: RefCell::new(HashMap::new()),keys_by_handle: RefCell::new(HashMap::new()),write_generation: Cell::new(0),}}pub(super) fn clear(&self) {- self.entries.borrow_mut().clear();- self.lazy_pseudo_entries.borrow_mut().clear();+ self.primary_entries.borrow_mut().clear();+ self.pseudo_entries.borrow_mut().clear();self.keys_by_handle.borrow_mut().clear();}- pub(super) fn get(&self, key: &ComputedElementStyleCacheKey) -> Option<ElementStyles> {- self.entries.borrow().get(key).cloned()- }-- pub(super) fn insert(&self, key: ComputedElementStyleCacheKey, styles: ElementStyles) {- self.index_key(&key);- self.entries.borrow_mut().insert(key, styles);- self.bump_write_generation();+ pub(super) fn record_primary(&self, key: ComputedElementStyleCacheKey) {+ debug_assert!(key.pseudo_element.is_none());+ if self.primary_entries.borrow_mut().insert(key.clone()) {+ self.index_key(&key);+ self.bump_write_generation();+ }}- pub(super) fn get_lazy_pseudo(+ pub(super) fn get_pseudo(&self,key: &ComputedElementStyleCacheKey,) -> Option<ServoArc<ComputedValues>> {- self.lazy_pseudo_entries.borrow().get(key).cloned()+ self.pseudo_entries.borrow().get(key).cloned()}- pub(super) fn insert_lazy_pseudo(+ pub(super) fn insert_pseudo(&self,key: ComputedElementStyleCacheKey,style: ServoArc<ComputedValues>,) {- self.index_key(&key);- self.lazy_pseudo_entries.borrow_mut().insert(key, style);- self.bump_write_generation();+ debug_assert!(key.pseudo_element.is_some());+ let is_new = self+ .pseudo_entries+ .borrow_mut()+ .insert(key.clone(), style)+ .is_none();+ if is_new {+ self.index_key(&key);+ self.bump_write_generation();+ }}+ #[cfg(test)]pub(super) fn write_generation(&self) -> u64 {self.write_generation.get()}@@ -168,11 +95,11 @@ impl ComputedStyleCache {if keys.is_empty() {return;}- let mut entries = self.entries.borrow_mut();- let mut lazy_pseudo_entries = self.lazy_pseudo_entries.borrow_mut();+ let mut primary_entries = self.primary_entries.borrow_mut();+ let mut pseudo_entries = self.pseudo_entries.borrow_mut();for key in keys {- entries.remove(&key);- lazy_pseudo_entries.remove(&key);+ primary_entries.remove(&key);+ pseudo_entries.remove(&key);}}@@ -194,14 +121,14 @@ impl ComputedStyleCache {}pub(super) fn is_empty(&self) -> bool {- self.entries.borrow().is_empty()- && self.lazy_pseudo_entries.borrow().is_empty()+ self.primary_entries.borrow().is_empty()+ && self.pseudo_entries.borrow().is_empty()&& self.keys_by_handle.borrow().is_empty()}#[cfg(test)]pub(super) fn len(&self) -> usize {- self.entries.borrow().len() + self.lazy_pseudo_entries.borrow().len()+ self.primary_entries.borrow().len() + self.pseudo_entries.borrow().len()}#[cfg(test)]@@ -218,88 +145,3 @@ impl ComputedStyleCache {.unwrap_or(0)}}--#[cfg(test)]-mod tests {- use std::rc::Rc;-- use super::{- ComputedStyleInputCache, ComputedStyleInputCacheGeneration,- StyloDocumentComputedStyleInputCacheKey, StyloPreparedComputedStyleInputs,- };- use crate::style_engine::StyloComputedStyleInputs;- use crate::style_engine::{StyleViewport, StyloStyleEnvironment};-- fn key(path: &str) -> StyloDocumentComputedStyleInputCacheKey {- StyloDocumentComputedStyleInputCacheKey::new(- None,- &[],- &url::Url::parse(&format!("https://document.test/{path}"))- .expect("cache test document URL should parse"),- StyleViewport::default(),- StyloStyleEnvironment::default(),- &url::Url::parse(&format!("https://cache.test/{path}"))- .expect("cache test URL should parse"),- )- }-- #[test]- fn computed_style_input_cache_is_bounded_and_generation_scoped() {- let cache = ComputedStyleInputCache::new();- let generation = ComputedStyleInputCacheGeneration {- source_set: 1,- computed_values: 2,- target_context: 3,- };- let first_key = key("first");- let second_key = key("second");- let third_key = key("third");- let document_url = url::Url::parse("https://cache.test/document")- .expect("cache test document URL should parse");- let prepared = || {- Rc::new(StyloPreparedComputedStyleInputs::new(- &document_url,- Rc::new(StyloComputedStyleInputs::default()),- StyleViewport::default(),- ))- };- let first = prepared();- let second = prepared();- let third = prepared();-- cache.insert(generation, first_key.clone(), Rc::clone(&first));- cache.insert(generation, second_key.clone(), Rc::clone(&second));- assert!(Rc::ptr_eq(- &cache- .get(generation, &first_key)- .expect("first cache entry should exist"),- &first- ));-- cache.insert(generation, third_key.clone(), Rc::clone(&third));- assert!(cache.get(generation, &first_key).is_none());- assert!(Rc::ptr_eq(- &cache- .get(generation, &second_key)- .expect("second cache entry should remain after bounded eviction"),- &second- ));- assert!(Rc::ptr_eq(- &cache- .get(generation, &third_key)- .expect("third cache entry should exist"),- &third- ));-- let next_generation = ComputedStyleInputCacheGeneration {- target_context: 4,- ..generation- };- assert!(cache.get(next_generation, &second_key).is_none());- assert!(cache.get(next_generation, &third_key).is_none());-- cache.insert(next_generation, third_key.clone(), Rc::clone(&third));- cache.clear();- assert!(cache.get(next_generation, &third_key).is_none());- }-}diff --git a/moli-renderer-v8/src/style_engine/cleanup.rs b/moli-renderer-v8/src/style_engine/cleanup.rsindex 734818cfd..e4b05d74c 100644--- a/moli-renderer-v8/src/style_engine/cleanup.rs+++ b/moli-renderer-v8/src/style_engine/cleanup.rs@@ -37,45 +37,27 @@ impl<'a> StyleCacheCleanup<'a> {}}- pub(super) fn clear_for_author_stylesheet_set_change(&self, _host: &DomHost) {+ pub(super) fn clear_for_retained_style_system_rebuild(&self) {self.document_state.clear_invalidation_clear_all_fallback_reasons();self.clear_shadow_cascade_data_for_document_world();self.clear_document_element_side_tables();self.computed_style_cache.clear();- self.document_state.clear_retained_style_system();self.document_state.clear_selector_caches();self.document_state.bump_computed_cache_generation();- self.document_state.bump_target_context_epoch();- }-- pub(super) fn clear_for_retained_style_system_rebuild(&self, _host: &DomHost) {- self.document_state- .clear_invalidation_clear_all_fallback_reasons();- self.clear_shadow_cascade_data_for_document_world();- self.clear_document_element_side_tables();- self.computed_style_cache.clear();- self.document_state.clear_selector_caches();- self.document_state.bump_computed_cache_generation();- }-- pub(super) fn clear_for_scoped_retained_style_system_rebuild(- &self,- host: &DomHost,- roots: impl IntoIterator<Item = DomHandle>,- ) -> bool {- self.document_state- .clear_invalidation_clear_all_fallback_reasons();- let roots = self.existing_subtree_roots(host, roots);- let cleared = self- .invalidate_existing_subtree_roots(host, &roots)- .is_some();- self.clear_shadow_cascade_data_in_subtrees(host, &roots);- cleared}- pub(super) fn computed_style_cache_write_generation(&self) -> u64 {- self.computed_style_cache.write_generation()+ /// Expands Stylo's matched stylesheet invalidations to already-published+ /// descendants. Moli resolves demanded elements one at a time, so it does+ /// not have a later full-tree traversal that would propagate inherited+ /// style changes from a `RESTYLE_SELF` ancestor.+ pub(super) fn invalidate_stylesheet_dirty_subtrees(&self, host: &DomHost) {+ let roots = self.existing_subtree_roots(+ host,+ self.dom_adapter+ .dirty_element_style_handles_for_document(self.document),+ );+ self.invalidate_existing_subtree_roots(host, &roots);}pub(super) fn invalidate_detached_subtrees(@@ -112,7 +94,7 @@ impl<'a> StyleCacheCleanup<'a> {}let handles = self.cached_handles_in_style_subtrees(host, &roots);for &handle in &handles {- self.dom_adapter.clear_element_data(handle);+ self.dom_adapter.mark_element_style_dirty(handle);}self.dom_adapter.clear_inline_style_attribute(root);self.computed_style_cache@@ -122,7 +104,6 @@ impl<'a> StyleCacheCleanup<'a> {true}- #[cfg(test)]pub(super) fn invalidate_subtrees(&self,host: &DomHost,@@ -304,7 +285,7 @@ impl<'a> StyleCacheCleanup<'a> {}let handles = self.cached_handles_in_style_subtrees(host, roots);for &handle in &handles {- self.dom_adapter.clear_element_style_values(handle);+ self.dom_adapter.mark_element_style_dirty(handle);}self.computed_style_cache.invalidate_handles(handles.iter().copied());@@ -323,7 +304,6 @@ impl StyleInvalidationCleanupApplicationSink for StyleCacheCleanup<'_> {fn apply_clear_all_cleanup_application(&self,- _host: &DomHost,context: &StyleInvalidationCleanupApplicationContext,) -> bool {self.clear_all_for_invalidation_fallback(context);diff --git a/moli-renderer-v8/src/style_engine/computed.rs b/moli-renderer-v8/src/style_engine/computed.rsindex c5b270171..227946812 100644--- a/moli-renderer-v8/src/style_engine/computed.rs+++ b/moli-renderer-v8/src/style_engine/computed.rs@@ -42,11 +42,16 @@ use crate::{use moli_selector::StyloElement;use super::{- MoliStyleEngine, StyleViewport, StyloComputedStyleInputs, StyloPreparedComputedStyleInputs,+ FullStyleWorldSnapshot, MoliStyleEngine, PreparedStyleWorldUpdate, StyleViewport,+ StyleWorldUpdate, StyleWorldUpdatePlan,cache::ComputedElementStyleCacheKey,document_world::DocumentStyleWorld,source_lifecycle::StyleSourceDocumentContext,- system::{StyleSystemCacheKey, ensure_retained_style_system},+ world_key::StyleWorldKey,+ world_lifecycle::{+ ensure_retained_style_system, ensure_retained_style_system_incrementally,+ retained_style_world_update_plan,+ },};#[derive(Clone)]@@ -54,6 +59,11 @@ pub(crate) struct StyloComputedStyleSnapshot {primary: ServoArc<ComputedValues>,}+pub(crate) enum StyleObservationSnapshot {+ Current(Option<StyloComputedStyleSnapshot>),+ NeedsStyleWorldUpdate(StyleWorldUpdatePlan),+}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub(crate) enum ComputedDisplayKind {None,@@ -274,7 +284,7 @@ pub(super) fn computed_style_property_value(handle: DomHandle,property: &str,pseudo_element: Option<&str>,- inputs: &StyloComputedStyleInputs,+ inputs: &FullStyleWorldSnapshot,document_context: StyleSourceDocumentContext<'_>,read_document: DomHandle,viewport: StyleViewport,@@ -298,7 +308,12 @@ pub(super) fn computed_style_property_value(Some(pseudo_element) => Some(stylo_pseudo_element_for_computed_style(pseudo_element)?),None => None,};- let style_system_key = StyleSystemCacheKey::new(document_url, inputs, viewport);+ let style_system_key = StyleWorldKey::new_for_observation(+ document_url,+ inputs,+ viewport,+ super::StyleTreeScopeVersions::current(host, Some(owner_document)),+ );if property.starts_with("--") {if let Some(ref pseudo_element) = pseudo_element&& pseudo_element.is_lazy()@@ -315,7 +330,7 @@ pub(super) fn computed_style_property_value(|style| serialize_computed_custom_property(style, property),);}- return with_resolved_styles(+ return with_resolved_style(engine,host,document_url,@@ -324,14 +339,7 @@ pub(super) fn computed_style_property_value(inputs,document_context,pseudo_element.as_ref(),- |styles| {- let style = if let Some(ref pseudo_element) = pseudo_element {- styles.pseudos.get(pseudo_element)?- } else {- styles.primary()- };- serialize_computed_custom_property(style, property)- },+ |style| serialize_computed_custom_property(style, property),);}let property_id = PropertyId::parse_enabled_for_all_content(property).ok()?;@@ -350,7 +358,7 @@ pub(super) fn computed_style_property_value(|style| serialize_resolved_computed_property(style, property_id.clone()),);}- with_resolved_styles(+ with_resolved_style(engine,host,document_url,@@ -359,14 +367,7 @@ pub(super) fn computed_style_property_value(inputs,document_context,pseudo_element.as_ref(),- |styles| {- let style = if let Some(ref pseudo_element) = pseudo_element {- styles.pseudos.get(pseudo_element)?- } else {- styles.primary()- };- serialize_resolved_computed_property(style, property_id)- },+ |style| serialize_resolved_computed_property(style, property_id),)}@@ -375,12 +376,18 @@ pub(super) fn computed_style_snapshot_after_style_update(host: &DomHost,document_url: &url::Url,handle: DomHandle,- inputs: &StyloComputedStyleInputs,+ inputs: &FullStyleWorldSnapshot,document_context: StyleSourceDocumentContext<'_>,read_document: DomHandle,viewport: StyleViewport,) -> Option<StyloComputedStyleSnapshot> {- let style_system_key = StyleSystemCacheKey::new(document_url, inputs, viewport);+ let owner_document = owner_document_for_computed_style_read(host, handle)?;+ let style_system_key = StyleWorldKey::new_for_observation(+ document_url,+ inputs,+ viewport,+ super::StyleTreeScopeVersions::current(host, Some(owner_document)),+ );computed_style_snapshot_after_style_update_with_key(engine,host,@@ -393,34 +400,152 @@ pub(super) fn computed_style_snapshot_after_style_update()}-pub(super) fn computed_style_snapshot_after_style_update_with_prepared_inputs(+pub(super) fn computed_style_snapshot_from_current_observation(engine: &MoliStyleEngine,host: &DomHost,document_url: &url::Url,handle: DomHandle,- inputs: &StyloPreparedComputedStyleInputs,+ environment: super::StyloStyleEnvironment,document_context: StyleSourceDocumentContext<'_>,read_document: DomHandle,-) -> Option<StyloComputedStyleSnapshot> {- computed_style_snapshot_after_style_update_with_key(+ viewport: StyleViewport,+ tree_scope_versions: super::StyleTreeScopeVersions,+) -> StyleObservationSnapshot {+ let Some(owner_document) = owner_document_for_computed_style_read(host, handle) else {+ return StyleObservationSnapshot::Current(None);+ };+ trace_computed_style_read(+ document_url,+ handle,+ owner_document,+ read_document,+ "<computed-style-observation>",+ None,+ document_context,+ );+ let quirks_mode = host+ .node(owner_document)+ .and_then(Node::as_document)+ .map(|document| document.quirks_mode())+ .unwrap_or(QuirksMode::NoQuirks);+ let style_document_url = host+ .document_url_for_handle(owner_document)+ .unwrap_or(document_url);+ let world = engine.world_for_document(owner_document);+ if !world+ .document_state+ .retained_style_system_is_current_for_observation(+ style_document_url,+ viewport,+ environment,+ quirks_mode,+ tree_scope_versions,+ )+ {+ return StyleObservationSnapshot::NeedsStyleWorldUpdate(retained_style_world_update_plan(+ host,+ &world.document_state,+ owner_document,+ style_document_url,+ viewport,+ environment,+ quirks_mode,+ tree_scope_versions,+ ));+ }+ StyleObservationSnapshot::Current(with_resolved_style_in_current_world(engine,host,document_url,handle,- inputs.style_system_key(),- inputs.inputs(),- document_context,- read_document,- )+ &world,+ quirks_mode,+ None,+ |style| {+ Some(StyloComputedStyleSnapshot {+ primary: style.clone(),+ })+ },+ ))}-pub(super) fn computed_pseudo_style_snapshot_after_style_update_with_prepared_inputs(+pub(super) fn computed_style_snapshot_after_world_update(+ engine: &MoliStyleEngine,+ host: &DomHost,+ document_url: &url::Url,+ handle: DomHandle,+ update: &PreparedStyleWorldUpdate,+ document_context: StyleSourceDocumentContext<'_>,+ read_document: DomHandle,+) -> Option<StyloComputedStyleSnapshot> {+ match update.update() {+ StyleWorldUpdate::Full(inputs) => {+ let environment = update.environment();+ let style_system_key = StyleWorldKey::new_for_observation(+ &environment.document_url,+ inputs,+ environment.viewport,+ environment.tree_scope_versions,+ );+ computed_style_snapshot_after_style_update_with_key(+ engine,+ host,+ document_url,+ handle,+ &style_system_key,+ inputs,+ document_context,+ read_document,+ )+ }+ StyleWorldUpdate::Incremental(incremental) => {+ let owner_document = owner_document_for_computed_style_read(host, handle)?;+ trace_computed_style_read(+ document_url,+ handle,+ owner_document,+ read_document,+ "<incremental-computed-style-snapshot>",+ None,+ document_context,+ );+ let world = engine.world_for_document(owner_document);+ let source_stores = world.borrow_source_stores();+ ensure_retained_style_system_incrementally(+ host,+ &engine.dom_adapter,+ &world.document_state,+ &source_stores,+ document_context,+ owner_document,+ engine.cache_cleanup_for_world(&world),+ update.environment(),+ incremental,+ );+ with_resolved_style_in_current_world(+ engine,+ host,+ document_url,+ handle,+ &world,+ update.environment().quirks_mode,+ None,+ |style| {+ Some(StyloComputedStyleSnapshot {+ primary: style.clone(),+ })+ },+ )+ }+ }+}++pub(super) fn computed_pseudo_style_snapshot_from_current_observation(engine: &MoliStyleEngine,host: &DomHost,document_url: &url::Url,handle: DomHandle,pseudo_element: &str,- inputs: &StyloPreparedComputedStyleInputs,document_context: StyleSourceDocumentContext<'_>,read_document: DomHandle,) -> Option<StyloComputedStyleSnapshot> {@@ -430,20 +555,25 @@ pub(super) fn computed_pseudo_style_snapshot_after_style_update_with_prepared_inhandle,owner_document,read_document,- "<computed-pseudo-style-snapshot>",+ "<current-computed-pseudo-style-snapshot>",Some(pseudo_element),document_context,);let pseudo_element = stylo_pseudo_element_for_computed_style(pseudo_element)?;+ let world = engine.world_for_document(owner_document);+ let quirks_mode = host+ .node(owner_document)+ .and_then(Node::as_document)+ .map(|document| document.quirks_mode())+ .unwrap_or(QuirksMode::NoQuirks);if pseudo_element.is_lazy() {- return with_lazily_resolved_pseudo_style(+ return with_lazily_resolved_pseudo_style_in_current_world(engine,host,document_url,handle,- inputs.style_system_key(),- inputs.inputs(),- document_context,+ &world,+ quirks_mode,&pseudo_element,|style| {Some(StyloComputedStyleSnapshot {@@ -452,31 +582,29 @@ pub(super) fn computed_pseudo_style_snapshot_after_style_update_with_prepared_in},);}- with_resolved_styles(+ with_resolved_style_in_current_world(engine,host,document_url,handle,- inputs.style_system_key(),- inputs.inputs(),- document_context,+ &world,+ quirks_mode,Some(&pseudo_element),- |styles| {+ |style| {Some(StyloComputedStyleSnapshot {- primary: styles.pseudos.get(&pseudo_element)?.clone(),+ primary: style.clone(),})},)}-pub(super) fn computed_anonymous_style_snapshot_after_style_update_with_prepared_inputs(+pub(super) fn computed_anonymous_style_snapshot_from_current_observation(engine: &MoliStyleEngine,host: &DomHost,document_url: &url::Url,owner: DomHandle,parent_style: &ComputedValues,anonymous_kind: StyloAnonymousBoxKind,- inputs: &StyloPreparedComputedStyleInputs,document_context: StyleSourceDocumentContext<'_>,read_document: DomHandle,) -> Option<StyloComputedStyleSnapshot> {@@ -486,21 +614,27 @@ pub(super) fn computed_anonymous_style_snapshot_after_style_update_with_preparedowner,owner_document,read_document,- "<computed-anonymous-style-snapshot>",+ "<current-computed-anonymous-style-snapshot>",Some(anonymous_kind.trace_name()),document_context,);let world = engine.world_for_document(owner_document);- ensure_retained_style_system_for_computed_read(+ computed_anonymous_style_snapshot_in_current_world(engine,host,&world,- owner_document,- inputs.style_system_key(),- inputs.inputs(),- document_context,- );+ parent_style,+ anonymous_kind,+ )+}+fn computed_anonymous_style_snapshot_in_current_world(+ engine: &MoliStyleEngine,+ host: &DomHost,+ world: &DocumentStyleWorld,+ parent_style: &ComputedValues,+ anonymous_kind: StyloAnonymousBoxKind,+) -> Option<StyloComputedStyleSnapshot> {engine.dom_adapter.with_bound_host(host, |dom_adapter| {let shared_lock = dom_adapter.shared_lock().clone();let guard = shared_lock.read();@@ -521,8 +655,8 @@ fn computed_style_snapshot_after_style_update_with_key(host: &DomHost,document_url: &url::Url,handle: DomHandle,- style_system_key: &StyleSystemCacheKey,- inputs: &StyloComputedStyleInputs,+ style_system_key: &StyleWorldKey,+ inputs: &FullStyleWorldSnapshot,document_context: StyleSourceDocumentContext<'_>,read_document: DomHandle,) -> Option<StyloComputedStyleSnapshot> {@@ -536,7 +670,7 @@ fn computed_style_snapshot_after_style_update_with_key(None,document_context,);- with_resolved_styles(+ with_resolved_style(engine,host,document_url,@@ -545,9 +679,9 @@ fn computed_style_snapshot_after_style_update_with_key(inputs,document_context,None,- |styles| {+ |style| {Some(StyloComputedStyleSnapshot {- primary: styles.primary().clone(),+ primary: style.clone(),})},)@@ -566,16 +700,16 @@ fn computed_custom_property_names_for_style(style: &ComputedValues) -> Vec<Strinnames}-fn with_resolved_styles<R>(+fn with_resolved_style<R>(engine: &MoliStyleEngine,host: &DomHost,document_url: &url::Url,handle: DomHandle,- style_system_key: &StyleSystemCacheKey,- inputs: &StyloComputedStyleInputs,+ style_system_key: &StyleWorldKey,+ inputs: &FullStyleWorldSnapshot,document_context: StyleSourceDocumentContext<'_>,pseudo_element: Option<&PseudoElement>,- callback: impl FnOnce(&ElementStyles) -> Option<R>,+ callback: impl FnOnce(&ServoArc<ComputedValues>) -> Option<R>,) -> Option<R> {let owner_document = owner_document_for_computed_style_read(host, handle)?;let world = engine.world_for_document(owner_document);@@ -588,92 +722,177 @@ fn with_resolved_styles<R>(inputs,document_context,);- let computed_key = ComputedElementStyleCacheKey {- computed_cache_generation: world.document_state.computed_cache_generation(),+ with_resolved_style_in_current_world(+ engine,+ host,+ document_url,handle,- pseudo_element: pseudo_element.cloned(),- };- if let Some(styles) = world.computed_style_cache.get(&computed_key) {- return callback(&styles);+ &world,+ inputs.quirks_mode,+ pseudo_element,+ callback,+ )+}++fn with_resolved_style_in_current_world<R>(+ engine: &MoliStyleEngine,+ host: &DomHost,+ document_url: &url::Url,+ handle: DomHandle,+ world: &DocumentStyleWorld,+ quirks_mode: QuirksMode,+ pseudo_element: Option<&PseudoElement>,+ callback: impl FnOnce(&ServoArc<ComputedValues>) -> Option<R>,+) -> Option<R> {+ let computed_cache_generation = world.document_state.computed_cache_generation();+ if let Some(pseudo_element) = pseudo_element {+ let pseudo_key = ComputedElementStyleCacheKey {+ computed_cache_generation,+ handle,+ pseudo_element: Some(pseudo_element.clone()),+ };+ if let Some(style) = world.computed_style_cache.get_pseudo(&pseudo_key) {+ return callback(&style);+ }}engine.dom_adapter.with_bound_host(host, |dom_adapter| {let element = dom_adapter.element(host, handle)?;-- dom_adapter.clear_element_data(handle);- populate_inline_style_attributes_for_resolution(- engine,- host,- document_url,- handle,- inputs.quirks_mode,- );-- world- .document_state- .with_shadow_cascade_data(|shadow_cascade_data| {- for (root, cascade_data) in shadow_cascade_data {- dom_adapter.set_shadow_cascade_data(*root, cascade_data.clone());+ let canonical_styles = element+ .borrow_data()+ .filter(|data| data.has_styles() && data.hint.is_empty())+ .map(|data| data.styles.clone())+ .unwrap_or_else(|| {+ populate_inline_style_attributes_for_resolution(+ engine,+ host,+ document_url,+ handle,+ quirks_mode,+ );+ install_shadow_cascade_data_for_resolution(world, dom_adapter);+ // `resolve_style` is the single-node initial-style API. Keep+ // dirty values published until this observation begins, then+ // make only the element being recomputed unstyled.+ unsafe {+ element.ensure_data().styles = ElementStyles::default();}+ let styles = resolve_element_styles(world, dom_adapter, element, None);+ unsafe {+ let mut data = element.ensure_data();+ data.styles = styles.clone();+ data.clear_restyle_state();+ }+ styles});- let shared_lock = dom_adapter.shared_lock().clone();- let guard = shared_lock.read();- let guards = StylesheetGuards::same(&guard);+ let style = if let Some(pseudo_element) = pseudo_element {+ let style = canonical_styles+ .pseudos+ .get(pseudo_element)+ .cloned()+ .or_else(|| {+ install_shadow_cascade_data_for_resolution(world, dom_adapter);+ resolve_element_styles(world, dom_adapter, element, Some(pseudo_element))+ .pseudos+ .get(pseudo_element)+ .cloned()+ })?;+ world.computed_style_cache.insert_pseudo(+ ComputedElementStyleCacheKey {+ computed_cache_generation,+ handle,+ pseudo_element: Some(pseudo_element.clone()),+ },+ style.clone(),+ );+ style+ } else {+ world+ .computed_style_cache+ .record_primary(ComputedElementStyleCacheKey {+ computed_cache_generation,+ handle,+ pseudo_element: None,+ });+ canonical_styles.primary().clone()+ };+ callback(&style)+ })+}- let snapshot_map = SnapshotMap::new();- let empty_painters = EmptyRegisteredSpeculativePainters;- let mut retained_selector_caches = world.document_state.take_selector_caches();- let styles = {- world.document_state.with_retained_style_system(|retained| {- let shared = SharedStyleContext {- stylist: &retained.stylist,- visited_styles_enabled: false,- options: StyleSystemOptions::default(),- guards,- current_time_for_animations: 0.0,- traversal_flags: TraversalFlags::empty(),- snapshot_map: &snapshot_map,- animations: DocumentAnimationSet::default(),- registered_speculative_painters: &empty_painters,- };- let _layout_thread_state = StyloLayoutThreadStateGuard::enter();- let mut thread_local = ThreadLocalStyleContext::new();- std::mem::swap(- &mut thread_local.selector_caches,- &mut retained_selector_caches,- );- let mut context = StyleContext {- shared: &shared,- thread_local: &mut thread_local,- };- materialize_ancestor_styles_for_resolution(&mut context, element);- let styles = resolve_style(- &mut context,- element,- RuleInclusion::All,- pseudo_element,- None,- );- std::mem::swap(- &mut context.thread_local.selector_caches,- &mut retained_selector_caches,- );- styles- })+fn install_shadow_cascade_data_for_resolution(+ world: &DocumentStyleWorld,+ dom_adapter: &moli_selector::StyloDomHostBinding<'_>,+) {+ world+ .document_state+ .with_shadow_cascade_data(|shadow_cascade_data| {+ for (root, cascade_data) in shadow_cascade_data {+ dom_adapter.set_shadow_cascade_data(*root, cascade_data.clone());+ }+ });+}++fn resolve_element_styles(+ world: &DocumentStyleWorld,+ dom_adapter: &moli_selector::StyloDomHostBinding<'_>,+ element: StyloElement<'_>,+ pseudo_element: Option<&PseudoElement>,+) -> ElementStyles {+ let shared_lock = dom_adapter.shared_lock().clone();+ let guard = shared_lock.read();+ let guards = StylesheetGuards::same(&guard);+ let snapshot_map = SnapshotMap::new();+ let empty_painters = EmptyRegisteredSpeculativePainters;+ let mut retained_selector_caches = world.document_state.take_selector_caches();+ let styles = world.document_state.with_retained_style_system(|retained| {+ let shared = SharedStyleContext {+ stylist: &retained.stylist,+ visited_styles_enabled: false,+ options: StyleSystemOptions::default(),+ guards,+ current_time_for_animations: 0.0,+ traversal_flags: TraversalFlags::empty(),+ snapshot_map: &snapshot_map,+ animations: DocumentAnimationSet::default(),+ registered_speculative_painters: &empty_painters,+ };+ let _layout_thread_state = StyloLayoutThreadStateGuard::enter();+ let mut thread_local = ThreadLocalStyleContext::new();+ std::mem::swap(+ &mut thread_local.selector_caches,+ &mut retained_selector_caches,+ );+ let mut context = StyleContext {+ shared: &shared,+ thread_local: &mut thread_local,};+ let ancestor_resolution_count =+ materialize_ancestor_styles_for_resolution(&mut context, element);+ let styles = resolve_style(+ &mut context,+ element,+ RuleInclusion::All,+ pseudo_element,+ None,+ );+ std::mem::swap(+ &mut context.thread_local.selector_caches,+ &mut retained_selector_caches,+ );world.document_state- .replace_selector_caches(retained_selector_caches);-- world- .computed_style_cache- .insert(computed_key, styles.clone());- callback(&styles)- })+ .note_element_style_resolutions(ancestor_resolution_count.saturating_add(1));+ styles+ });+ world+ .document_state+ .replace_selector_caches(retained_selector_caches);+ styles}-fn materialize_ancestor_styles_for_resolution<E>(context: &mut StyleContext<E>, element: E)+fn materialize_ancestor_styles_for_resolution<E>(context: &mut StyleContext<E>, element: E) -> u64whereE: TElement,{@@ -684,15 +903,26 @@ wherecurrent = ancestor.traversal_parent();}+ let mut resolution_count = 0_u64;for ancestor in ancestors.into_iter().rev() {- if ancestor.borrow_data().is_some_and(|data| data.has_styles()) {+ if ancestor+ .borrow_data()+ .is_some_and(|data| data.has_styles() && data.hint.is_empty())+ {continue;}+ unsafe {+ ancestor.ensure_data().styles = ElementStyles::default();+ }let styles = resolve_style(context, ancestor, RuleInclusion::All, None, None);+ resolution_count = resolution_count.saturating_add(1);unsafe {- ancestor.ensure_data().styles = styles;+ let mut data = ancestor.ensure_data();+ data.styles = styles;+ data.clear_restyle_state();}}+ resolution_count}fn with_lazily_resolved_pseudo_style<R>(@@ -700,8 +930,8 @@ fn with_lazily_resolved_pseudo_style<R>(host: &DomHost,document_url: &url::Url,handle: DomHandle,- style_system_key: &StyleSystemCacheKey,- inputs: &StyloComputedStyleInputs,+ style_system_key: &StyleWorldKey,+ inputs: &FullStyleWorldSnapshot,document_context: StyleSourceDocumentContext<'_>,pseudo_element: &PseudoElement,callback: impl FnOnce(&ComputedValues) -> Option<R>,@@ -718,25 +948,47 @@ fn with_lazily_resolved_pseudo_style<R>(inputs,document_context,);+ with_lazily_resolved_pseudo_style_in_current_world(+ engine,+ host,+ document_url,+ handle,+ &world,+ inputs.quirks_mode,+ pseudo_element,+ callback,+ )+}++fn with_lazily_resolved_pseudo_style_in_current_world<R>(+ engine: &MoliStyleEngine,+ host: &DomHost,+ document_url: &url::Url,+ handle: DomHandle,+ world: &DocumentStyleWorld,+ quirks_mode: QuirksMode,+ pseudo_element: &PseudoElement,+ callback: impl FnOnce(&ComputedValues) -> Option<R>,+) -> Option<R> {+ debug_assert!(pseudo_element.is_lazy());let computed_key = ComputedElementStyleCacheKey {computed_cache_generation: world.document_state.computed_cache_generation(),handle,pseudo_element: Some(pseudo_element.clone()),};- if let Some(style) = world.computed_style_cache.get_lazy_pseudo(&computed_key) {+ if let Some(style) = world.computed_style_cache.get_pseudo(&computed_key) {return callback(&style);}- let primary_style = with_resolved_styles(+ let primary_style = with_resolved_style_in_current_world(engine,host,document_url,handle,- style_system_key,- inputs,- document_context,+ world,+ quirks_mode,None,- |styles| Some(styles.primary().clone()),+ |style| Some(style.clone()),)?;engine.dom_adapter.with_bound_host(host, |dom_adapter| {@@ -769,7 +1021,7 @@ fn with_lazily_resolved_pseudo_style<R>(})?;world.computed_style_cache- .insert_lazy_pseudo(computed_key, style.clone());+ .insert_pseudo(computed_key, style.clone());callback(&style)})}@@ -779,8 +1031,8 @@ fn ensure_retained_style_system_for_computed_read(host: &DomHost,world: &DocumentStyleWorld,retained_document: DomHandle,- key: &StyleSystemCacheKey,- inputs: &StyloComputedStyleInputs,+ key: &StyleWorldKey,+ inputs: &FullStyleWorldSnapshot,document_context: StyleSourceDocumentContext<'_>,) {let source_stores = world.borrow_source_stores();@@ -894,8 +1146,8 @@ pub(super) fn ensure_retained_style_system_for_document_for_test(engine: &MoliStyleEngine,host: &DomHost,document: DomHandle,- key: StyleSystemCacheKey,- inputs: &StyloComputedStyleInputs,+ key: StyleWorldKey,+ inputs: &FullStyleWorldSnapshot,) {let world = engine.world_for_document(document);ensure_retained_style_system_for_computed_read(diff --git a/moli-renderer-v8/src/style_engine/document_world.rs b/moli-renderer-v8/src/style_engine/document_world.rsindex c5fbfa723..b46f44b4b 100644--- a/moli-renderer-v8/src/style_engine/document_world.rs+++ b/moli-renderer-v8/src/style_engine/document_world.rs@@ -3,7 +3,7 @@ use std::{cell::RefCell, collections::HashMap, rc::Rc};use crate::document_runtime::DomHandle;use super::{- cache::{ComputedStyleCache, ComputedStyleInputCache},+ cache::ComputedStyleCache,pending_invalidation::PendingStyleInvalidations,pending_mutation::PendingStructuralStyleMutations,registered_properties::CssCustomPropertyRegistry,@@ -22,7 +22,6 @@ pub(super) struct DocumentStyleWorld {pub(super) pending_invalidations: PendingStyleInvalidations,pub(super) pending_structural_mutations: PendingStructuralStyleMutations,pub(super) computed_style_cache: ComputedStyleCache,- pub(super) computed_style_input_cache: ComputedStyleInputCache,pub(super) owner_style_sheet_sources: RefCell<OwnerStyleSheetSources>,pub(super) linked_stylesheet_sources: RefCell<LinkedStylesheetSources>,pub(super) adopted_style_sheet_sources: RefCell<AdoptedStyleSheetSources>,@@ -42,7 +41,6 @@ impl DocumentStyleWorld {pending_invalidations: PendingStyleInvalidations::new(),pending_structural_mutations: PendingStructuralStyleMutations::new(),computed_style_cache: ComputedStyleCache::new(),- computed_style_input_cache: ComputedStyleInputCache::new(),owner_style_sheet_sources: RefCell::new(OwnerStyleSheetSources::default()),linked_stylesheet_sources: RefCell::new(LinkedStylesheetSources::default()),adopted_style_sheet_sources: RefCell::new(AdoptedStyleSheetSources::default()),@@ -55,7 +53,6 @@ impl DocumentStyleWorld {self.pending_invalidations.clear();self.pending_structural_mutations.clear();self.computed_style_cache.clear();- self.computed_style_input_cache.clear();self.document_state.clear_retained_style_system();self.document_state.bump_source_set_generation();self.document_state.bump_computed_cache_generation();diff --git a/moli-renderer-v8/src/style_engine/media_list.rs b/moli-renderer-v8/src/style_engine/media_list.rsindex 401a0f157..eca1bdab1 100644--- a/moli-renderer-v8/src/style_engine/media_list.rs+++ b/moli-renderer-v8/src/style_engine/media_list.rs@@ -21,7 +21,7 @@ use style::{use style_traits::{CSSPixel, DevicePixel, ParsingMode, ToCss};use super::{StyleViewport, StyloStyleEnvironment};-use crate::style_engine::system::{DEFAULT_VIEWPORT_HEIGHT, DEFAULT_VIEWPORT_WIDTH};+use crate::style_engine::world_key::{DEFAULT_VIEWPORT_HEIGHT, DEFAULT_VIEWPORT_WIDTH};pub(crate) fn normalize_media_query_list(media_text: &str) -> String {with_stylo_media_context(|context| parse_stylo_media_list(context, media_text).to_css_string())diff --git a/moli-renderer-v8/src/style_engine/mod.rs b/moli-renderer-v8/src/style_engine/mod.rsindex 34f42afd9..63ec6f5f1 100644--- a/moli-renderer-v8/src/style_engine/mod.rs+++ b/moli-renderer-v8/src/style_engine/mod.rs@@ -3,16 +3,8 @@ use std::sync::Arc as StdArc;use std::sync::Once;use std::{cell::RefCell, collections::HashMap, rc::Rc};-use dom::ElementState as StyloElementState;-#[cfg(test)]-use style::Atom;-use style::{- context::QuirksMode, device::servo::ServoMediaFeaturePreferences, media_queries::MediaType,- queries::values::PrefersColorScheme, servo::media_features::PrefersContrast,- values::specified::color::ForcedColors,-};-use crate::{document_runtime::DomHandle, dom::native::DomHost};+use dom::ElementState as StyloElementState;#[cfg(test)]use indexmap::IndexSet;use moli_selector::StyloDomStyleAdapter;@@ -26,7 +18,15 @@ use moli_selector::stylo_element_dependency_snapshot as style_element_dependencyuse moli_selector::{StyloStylesheetSourceScopeFallbackInput, stylo_stylesheet_source_scope_fallback_roots,};+#[cfg(test)]+use style::Atom;+mod active_stylesheets;+#[cfg(test)]+pub(crate) use active_stylesheets::{+ exact_rule_change_notification_count_for_test, full_cascade_update_fallback_count_for_test,+ reset_live_stylesheet_update_counts_for_test,+};mod cache;mod cause;mod cleanup;@@ -47,44 +47,56 @@ mod query;mod registered_properties;mod request;mod retained;-pub(crate) use retained::{+pub(crate) use stylesheet::{NativeStylesheetFontFaceProjection, NativeStylesheetFontFaceRuleProjection,StylesheetFontFaceProjection, StylesheetFontFaceRuleProjection,native_font_face_projection_for_stylesheet, native_font_face_rules_for_stylesheet,};#[cfg(test)]-pub(crate) use retained::{+pub(crate) use stylesheet::{author_source_text_parse_count_for_test, reset_author_source_text_parse_count_for_test,};mod retained_plan;mod runtime_invalidation;mod schedule;mod scope;+mod shadow_scopes;mod snapshot;mod source;+mod source_cascade;+#[cfg(test)]+pub(crate) use source_cascade::{+ reset_source_cascade_rebuild_count_for_test, source_cascade_rebuild_count_for_test,+};mod source_dirty;mod source_document;mod source_id;+mod source_key;mod source_lifecycle;mod source_owner;mod source_owner_text;mod source_record;mod source_scope_plan;mod state;-mod system;+mod stylesheet;+mod stylesheet_resources;mod target_plan;mod target_queries;mod target_result;#[cfg(test)]mod tests;mod ua;+mod world_environment;+mod world_key;+mod world_lifecycle;+mod world_trace;+mod world_update;-use cache::ComputedStyleInputCacheGeneration;use cleanup::StyleCacheCleanup;pub(crate) use computed::{ComputedDisplayKind, ComputedRenderedStyleFacts, ComputedTextTransformKind,- ComputedTextWrapModeKind, ComputedWhiteSpaceCollapseKind, StyloAnonymousBoxKind,- StyloComputedStyleSnapshot,+ ComputedTextWrapModeKind, ComputedWhiteSpaceCollapseKind, StyleObservationSnapshot,+ StyloAnonymousBoxKind, StyloComputedStyleSnapshot,};use document_world::{DocumentStyleWorld, DocumentStyleWorlds};pub(in crate::style_engine) use drain::StyleInvalidationDrainBoundary;@@ -101,6 +113,7 @@ pub(crate) use property_metadata::{};pub(crate) use registered_properties::{CssCustomPropertyRegistration, CssCustomPropertyRegistrationError,+ CssCustomPropertyRegistrationRecord,};#[cfg(test)]use scope::style_source_scope_for_mutation_effects;@@ -117,9 +130,23 @@ use source_id::{StyleInvalidationSourceTarget, StyleScopeId};pub(crate) use source_lifecycle::OwnedStyleSourceDocumentContext;use source_lifecycle::StyleSourceDocumentContext;pub(crate) use source_owner::link_rel_qualifies_as_stylesheet;-use system::StyleSystemCacheKey;+pub(crate) use stylesheet_resources::{StylesheetResourceGeneration, StylesheetResourceSnapshot};+#[cfg(test)]+use stylesheet_resources::{+ reset_stylesheet_resource_manifest_build_count_for_test,+ stylesheet_resource_manifest_build_count_for_test,+};#[cfg(test)]use target_queries::PendingStyleInvalidationTargetQueries;+pub(crate) use world_environment::{+ StyleTreeScopeVersions, StyleViewport, StyleWorldEnvironment, StyloStyleEnvironment,+};+#[cfg(test)]+use world_key::StyleWorldKey;+pub(crate) use world_update::{+ FullStyleWorldSnapshot, IncrementalStyleWorldUpdate, PreparedStyleWorldUpdate,+ StyleWorldUpdate, StyleWorldUpdatePlan,+};/// Page-level facade for document-owned style state.///@@ -135,288 +162,6 @@ pub(crate) struct MoliStyleEngine {inline_style_metadata_documents: RefCell<HashMap<DomHandle, DomHandle>>,}-#[derive(Clone, Debug)]-pub(crate) struct StyloComputedStyleInputs {- pub(crate) document_stylesheet_sources: Vec<StyloStylesheetSource>,- pub(crate) shadow_stylesheet_sources: Vec<(DomHandle, Vec<StyloStylesheetSource>)>,- pub(crate) script_custom_property_registrations: Vec<CssCustomPropertyRegistration>,- pub(crate) script_custom_property_base_url: url::Url,- pub(crate) environment: StyloStyleEnvironment,- pub(crate) quirks_mode: QuirksMode,-}--/// Immutable Stylo inputs paired with the exact retained-system identity they-/// determine for one document/viewport observation context.-///-/// Keeping the key beside the inputs prevents descendant reads from hashing-/// the same stylesheet source set again. The pair is generation-scoped by the-/// owning document cache, so callers must not manufacture it across style-/// lifecycle boundaries.-#[derive(Debug)]-pub(crate) struct StyloPreparedComputedStyleInputs {- inputs: Rc<StyloComputedStyleInputs>,- style_system_key: StyleSystemCacheKey,-}--impl StyloPreparedComputedStyleInputs {- pub(crate) fn new(- document_url: &url::Url,- inputs: Rc<StyloComputedStyleInputs>,- viewport: StyleViewport,- ) -> Self {- let style_system_key = StyleSystemCacheKey::new(document_url, inputs.as_ref(), viewport);- Self {- inputs,- style_system_key,- }- }-- pub(crate) fn inputs(&self) -> &StyloComputedStyleInputs {- self.inputs.as_ref()- }-- pub(in crate::style_engine) fn style_system_key(&self) -> &StyleSystemCacheKey {- &self.style_system_key- }-}--impl Default for StyloComputedStyleInputs {- fn default() -> Self {- Self {- document_stylesheet_sources: Vec::new(),- shadow_stylesheet_sources: Vec::new(),- script_custom_property_registrations: Vec::new(),- script_custom_property_base_url: url::Url::parse("about:blank")- .expect("static about:blank URL parses"),- environment: StyloStyleEnvironment::default(),- quirks_mode: QuirksMode::NoQuirks,- }- }-}--#[derive(Clone, Copy, Debug, Default, PartialEq)]-pub(crate) struct StyleViewport {- pub(crate) width: Option<f64>,- pub(crate) height: Option<f64>,- pub(crate) screen_width: Option<f64>,- pub(crate) screen_height: Option<f64>,-}--impl StyleViewport {- pub(crate) const fn new(width: Option<f64>, height: Option<f64>) -> Self {- Self {- width,- height,- screen_width: None,- screen_height: None,- }- }-- pub(crate) const fn from_width(width: Option<f64>) -> Self {- Self {- width,- height: None,- screen_width: None,- screen_height: None,- }- }-- pub(crate) const fn with_screen_size(- self,- screen_width: Option<f64>,- screen_height: Option<f64>,- ) -> Self {- Self {- screen_width,- screen_height,- ..self- }- }-- pub(crate) fn from_viewport_surface(surface: crate::protocol_types::ViewportSurface) -> Self {- Self::new(- Some(f64::from(surface.inner_width)),- Some(f64::from(surface.inner_height)),- )- .with_screen_size(- Some(f64::from(surface.screen_width)),- Some(f64::from(surface.screen_height)),- )- }-}--impl From<Option<f64>> for StyleViewport {- fn from(width: Option<f64>) -> Self {- Self::from_width(width)- }-}--#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]-pub(crate) struct StyloStyleEnvironment {- media_type: StyloStyleMediaType,- color_scheme: StyloStyleColorScheme,- reduced_motion: StyloStyleReducedPreference,- reduced_data: StyloStyleReducedPreference,- reduced_transparency: StyloStyleReducedPreference,- contrast: StyloStyleContrastPreference,- forced_colors: StyloStyleForcedColors,-}--/// Non-generation context for one document-owned prepared-input entry.-///-/// The source document is implicit in the owning `DocumentStyleWorld`; source-/// content and tree changes are represented by the cache generation.-#[derive(Clone, Debug, PartialEq, Eq)]-pub(crate) struct StyloDocumentComputedStyleInputCacheKey {- read_document: Option<DomHandle>,- tree_scope_roots: Vec<DomHandle>,- document_url: url::Url,- viewport_width_bits: Option<u64>,- viewport_height_bits: Option<u64>,- screen_width_bits: Option<u64>,- screen_height_bits: Option<u64>,- environment: StyloStyleEnvironment,- script_custom_property_base_url: url::Url,-}--impl StyloDocumentComputedStyleInputCacheKey {- pub(crate) fn new(- read_document: Option<DomHandle>,- tree_scope_roots: &[DomHandle],- document_url: &url::Url,- viewport: StyleViewport,- environment: StyloStyleEnvironment,- script_custom_property_base_url: &url::Url,- ) -> Self {- let mut document_url = document_url.clone();- document_url.set_fragment(None);- Self {- read_document,- tree_scope_roots: tree_scope_roots.to_vec(),- document_url,- viewport_width_bits: viewport.width.map(f64::to_bits),- viewport_height_bits: viewport.height.map(f64::to_bits),- screen_width_bits: viewport.screen_width.map(f64::to_bits),- screen_height_bits: viewport.screen_height.map(f64::to_bits),- environment,- script_custom_property_base_url: script_custom_property_base_url.clone(),- }- }-}--#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]-enum StyloStyleMediaType {- #[default]- Screen,- Print,-}--#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]-enum StyloStyleColorScheme {- #[default]- Light,- Dark,-}--#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]-enum StyloStyleReducedPreference {- #[default]- NoPreference,- Reduce,-}--#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]-enum StyloStyleContrastPreference {- More,- Less,- Custom,- #[default]- NoPreference,-}--#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]-enum StyloStyleForcedColors {- #[default]- None,- Active,-}--impl StyloStyleEnvironment {- pub(crate) fn from_emulated_media(- overrides: &crate::protocol_types::EmulatedMediaOverrides,- ) -> Self {- Self {- media_type: if overrides.media.as_deref() == Some("print") {- StyloStyleMediaType::Print- } else {- StyloStyleMediaType::Screen- },- color_scheme: if overrides.color_scheme.as_deref() == Some("dark") {- StyloStyleColorScheme::Dark- } else {- StyloStyleColorScheme::Light- },- reduced_motion: match overrides.reduced_motion.as_deref() {- Some("reduce") => StyloStyleReducedPreference::Reduce,- Some("no-preference") | None => StyloStyleReducedPreference::NoPreference,- Some(_) => StyloStyleReducedPreference::NoPreference,- },- reduced_data: StyloStyleReducedPreference::NoPreference,- reduced_transparency: StyloStyleReducedPreference::NoPreference,- contrast: match overrides.contrast.as_deref() {- Some("more") => StyloStyleContrastPreference::More,- Some("less") => StyloStyleContrastPreference::Less,- Some("custom") => StyloStyleContrastPreference::Custom,- Some("no-preference") | None => StyloStyleContrastPreference::NoPreference,- Some(_) => StyloStyleContrastPreference::NoPreference,- },- forced_colors: match overrides.forced_colors.as_deref() {- Some("active") => StyloStyleForcedColors::Active,- Some("none") | None => StyloStyleForcedColors::None,- Some(_) => StyloStyleForcedColors::None,- },- }- }-- fn stylo_media_type(self) -> MediaType {- match self.media_type {- StyloStyleMediaType::Screen => MediaType::screen(),- StyloStyleMediaType::Print => MediaType::print(),- }- }-- fn stylo_prefers_color_scheme(self) -> PrefersColorScheme {- match self.color_scheme {- StyloStyleColorScheme::Light => PrefersColorScheme::Light,- StyloStyleColorScheme::Dark => PrefersColorScheme::Dark,- }- }-- fn stylo_media_feature_preferences(self) -> ServoMediaFeaturePreferences {- ServoMediaFeaturePreferences {- prefers_reduced_motion: self.reduced_motion.prefers_reduced(),- prefers_reduced_data: self.reduced_data.prefers_reduced(),- prefers_reduced_transparency: self.reduced_transparency.prefers_reduced(),- prefers_contrast: match self.contrast {- StyloStyleContrastPreference::More => PrefersContrast::More,- StyloStyleContrastPreference::Less => PrefersContrast::Less,- StyloStyleContrastPreference::Custom => PrefersContrast::Custom,- StyloStyleContrastPreference::NoPreference => PrefersContrast::NoPreference,- },- forced_colors: match self.forced_colors {- StyloStyleForcedColors::None => ForcedColors::None,- StyloStyleForcedColors::Active => ForcedColors::Active,- },- }- }-}--impl StyloStyleReducedPreference {- fn prefers_reduced(self) -> bool {- matches!(self, Self::Reduce)- }-}-impl Default for MoliStyleEngine {fn default() -> Self {Self::new()@@ -472,50 +217,67 @@ impl MoliStyleEngine {self.document_worlds.observation_generations(documents)}- #[cfg(debug_assertions)]- pub(crate) fn computed_style_read_invariant_state(&self, document: DomHandle) -> (u64, u64) {- let world = self.world_for_document(document);- let generations = world.document_state.generation_snapshot();- (- generations.source_set_generation,- generations.retained_style_system_generation,- )+ pub(crate) fn stylesheet_resource_snapshot_for_document(+ &self,+ document: DomHandle,+ ) -> Option<StylesheetResourceSnapshot> {+ self.world_for_document(document)+ .document_state+ .stylesheet_resource_snapshot(document)}- pub(crate) fn cached_document_prepared_style_inputs(+ /// Returns the source projection already installed in the retained world+ /// for compatibility queries that need stylesheet provenance.+ ///+ /// This clones cheap source handles; it does not walk stylesheet owners,+ /// serialize CSS, parse a sheet, or mutate the style world.+ pub(crate) fn retained_stylesheet_query_snapshot_for_document(&self,document: DomHandle,- key: &StyloDocumentComputedStyleInputCacheKey,- ) -> Option<Rc<StyloPreparedComputedStyleInputs>> {+ ) -> Option<Rc<FullStyleWorldSnapshot>> {let world = self.world_for_document(document);- let generations = world.document_state.generation_snapshot();- world.computed_style_input_cache.get(- ComputedStyleInputCacheGeneration {- source_set: generations.source_set_generation,- computed_values: generations.computed_cache_generation,- target_context: generations.target_context_epoch,- },- key,- )+ world+ .document_state+ .try_with_retained_style_system(|retained| {+ Rc::new(FullStyleWorldSnapshot {+ document_stylesheet_sources: retained+ .document_stylesheets+ .entries()+ .iter()+ .map(|entry| entry.source().clone())+ .collect(),+ shadow_stylesheet_sources: retained+ .shadow_scopes+ .iter()+ .map(|scope| {+ (+ scope.root(),+ scope+ .active_stylesheets()+ .entries()+ .iter()+ .map(|entry| entry.source().clone())+ .collect(),+ )+ })+ .collect(),+ script_custom_property_registrations: retained+ .script_custom_property_registrations+ .clone(),+ environment: retained.key.environment,+ quirks_mode: retained.key.quirks_mode,+ })+ })}- pub(crate) fn cache_document_prepared_style_inputs(- &self,- document: DomHandle,- key: StyloDocumentComputedStyleInputCacheKey,- inputs: Rc<StyloPreparedComputedStyleInputs>,- ) {+ #[cfg(debug_assertions)]+ pub(crate) fn computed_style_read_invariant_state(&self, document: DomHandle) -> (u64, u64) {let world = self.world_for_document(document);let generations = world.document_state.generation_snapshot();- world.computed_style_input_cache.insert(- ComputedStyleInputCacheGeneration {- source_set: generations.source_set_generation,- computed_values: generations.computed_cache_generation,- target_context: generations.target_context_epoch,- },- key,- inputs,- );+ (+ generations.source_set_generation,+ generations.retained_style_system_generation,+ )}#[cfg(test)]@@ -568,6 +330,16 @@ impl MoliStyleEngine {self.world_for_document(document).computed_style_cache.len()}+ #[cfg(test)]+ pub(crate) fn computed_style_publication_generation_for_document_for_test(+ &self,+ document: DomHandle,+ ) -> u64 {+ self.world_for_document(document)+ .computed_style_cache+ .write_generation()+ }+#[cfg(test)]pub(crate) fn computed_style_cache_contains_handle_for_document_for_test(&self,@@ -662,25 +434,71 @@ impl MoliStyleEngine {}#[cfg(test)]- pub(in crate::style_engine) fn retained_style_system_matches_for_document_for_test(+ pub(crate) fn retained_style_system_update_count_for_document_for_test(&self,document: DomHandle,- key: &StyleSystemCacheKey,- ) -> bool {+ ) -> u64 {self.world_for_document(document).document_state- .retained_style_system_matches(key)+ .retained_style_system_update_count()}#[cfg(test)]- pub(crate) fn retained_style_system_is_none_for_document_for_test(+ pub(crate) fn retained_stylist_identity_for_document_for_test(&self,document: DomHandle,+ ) -> u64 {+ self.world_for_document(document)+ .document_state+ .with_retained_style_system(|retained| retained.stylist_identity)+ }++ #[cfg(test)]+ pub(crate) fn retained_stylist_flush_count_for_document_for_test(+ &self,+ document: DomHandle,+ ) -> u64 {+ self.world_for_document(document)+ .document_state+ .with_retained_style_system(|retained| retained.stylist.num_rebuilds() as u64)+ }++ #[cfg(test)]+ pub(crate) fn retained_shadow_scope_flush_count_for_document_for_test(+ &self,+ document: DomHandle,+ root: DomHandle,+ ) -> Option<u64> {+ self.world_for_document(document)+ .document_state+ .with_retained_style_system(|retained| {+ retained+ .shadow_scopes+ .iter()+ .find(|scope| scope.root() == root)+ .map(shadow_scopes::ShadowScopeStyles::flush_count_for_test)+ })+ }++ #[cfg(test)]+ pub(crate) fn element_style_resolution_count_for_document_for_test(+ &self,+ document: DomHandle,+ ) -> u64 {+ self.world_for_document(document)+ .document_state+ .element_style_resolution_count()+ }++ #[cfg(test)]+ pub(in crate::style_engine) fn retained_style_system_matches_for_document_for_test(+ &self,+ document: DomHandle,+ key: &StyleWorldKey,) -> bool {self.world_for_document(document).document_state- .try_with_retained_style_system(|_| ())- .is_none()+ .retained_style_system_matches(key)}#[cfg(test)]@@ -774,8 +592,8 @@ impl MoliStyleEngine {&self,host: &DomHost,document: DomHandle,- key: StyleSystemCacheKey,- inputs: &StyloComputedStyleInputs,+ key: StyleWorldKey,+ inputs: &FullStyleWorldSnapshot,) {computed::ensure_retained_style_system_for_document_for_test(self, host, document, key, inputs,@@ -989,7 +807,7 @@ impl MoliStyleEngine {handle: DomHandle,property: &str,pseudo_element: Option<&str>,- inputs: &StyloComputedStyleInputs,+ inputs: &FullStyleWorldSnapshot,viewport: impl Into<StyleViewport>,) -> Option<String> {let owner_document = host.owner_document_handle(handle)?;@@ -1013,7 +831,7 @@ impl MoliStyleEngine {handle: DomHandle,property: &str,pseudo_element: Option<&str>,- inputs: &StyloComputedStyleInputs,+ inputs: &FullStyleWorldSnapshot,document_context: StyleSourceDocumentContext<'_>,read_document: DomHandle,viewport: StyleViewport,@@ -1037,7 +855,7 @@ impl MoliStyleEngine {host: &DomHost,document_url: &url::Url,handle: DomHandle,- inputs: &StyloComputedStyleInputs,+ inputs: &FullStyleWorldSnapshot,document_context: StyleSourceDocumentContext<'_>,read_document: DomHandle,viewport: StyleViewport,@@ -1054,16 +872,40 @@ impl MoliStyleEngine {)}- pub(crate) fn computed_style_snapshot_after_style_update_with_prepared_inputs(+ pub(crate) fn computed_style_snapshot_from_current_observation(+ &self,+ host: &DomHost,+ document_url: &url::Url,+ handle: DomHandle,+ environment: StyloStyleEnvironment,+ document_context: StyleSourceDocumentContext<'_>,+ read_document: DomHandle,+ viewport: StyleViewport,+ tree_scope_versions: StyleTreeScopeVersions,+ ) -> StyleObservationSnapshot {+ computed::computed_style_snapshot_from_current_observation(+ self,+ host,+ document_url,+ handle,+ environment,+ document_context,+ read_document,+ viewport,+ tree_scope_versions,+ )+ }++ pub(crate) fn computed_style_snapshot_after_world_update(&self,host: &DomHost,document_url: &url::Url,handle: DomHandle,- inputs: &StyloPreparedComputedStyleInputs,+ inputs: &PreparedStyleWorldUpdate,document_context: StyleSourceDocumentContext<'_>,read_document: DomHandle,) -> Option<StyloComputedStyleSnapshot> {- computed::computed_style_snapshot_after_style_update_with_prepared_inputs(+ computed::computed_style_snapshot_after_world_update(self,host,document_url,@@ -1074,47 +916,43 @@ impl MoliStyleEngine {)}- pub(crate) fn computed_pseudo_style_snapshot_after_style_update_with_prepared_inputs(+ pub(crate) fn computed_pseudo_style_snapshot_from_current_observation(&self,host: &DomHost,document_url: &url::Url,handle: DomHandle,pseudo_element: &str,- inputs: &StyloPreparedComputedStyleInputs,document_context: StyleSourceDocumentContext<'_>,read_document: DomHandle,) -> Option<StyloComputedStyleSnapshot> {- computed::computed_pseudo_style_snapshot_after_style_update_with_prepared_inputs(+ computed::computed_pseudo_style_snapshot_from_current_observation(self,host,document_url,handle,pseudo_element,- inputs,document_context,read_document,)}- pub(crate) fn computed_anonymous_style_snapshot_after_style_update_with_prepared_inputs(+ pub(crate) fn computed_anonymous_style_snapshot_from_current_observation(&self,host: &DomHost,document_url: &url::Url,owner: DomHandle,parent_style: &style::properties::ComputedValues,anonymous_kind: StyloAnonymousBoxKind,- inputs: &StyloPreparedComputedStyleInputs,document_context: StyleSourceDocumentContext<'_>,read_document: DomHandle,) -> Option<StyloComputedStyleSnapshot> {- computed::computed_anonymous_style_snapshot_after_style_update_with_prepared_inputs(+ computed::computed_anonymous_style_snapshot_from_current_observation(self,host,document_url,owner,parent_style,anonymous_kind,- inputs,document_context,read_document,)@@ -1155,7 +993,7 @@ fn stylo_source_metadata_for_css_text(css_text: &str,base_url: &url::Url,) -> source::store::StyleSourceMetadata {- retained::style_source_metadata_for_css_text(css_text, base_url)+ stylesheet::style_source_metadata_for_css_text(css_text, base_url)}fn retain_owner_documents_except_document(diff --git a/moli-renderer-v8/src/style_engine/outcome.rs b/moli-renderer-v8/src/style_engine/outcome.rsindex 24ee72279..d2fcc9893 100644--- a/moli-renderer-v8/src/style_engine/outcome.rs+++ b/moli-renderer-v8/src/style_engine/outcome.rs@@ -165,7 +165,6 @@ pub(super) trait StyleInvalidationCleanupApplicationSink {fn apply_clear_all_cleanup_application(&self,- host: &DomHost,context: &StyleInvalidationCleanupApplicationContext,) -> bool;@@ -440,7 +439,7 @@ impl StyleInvalidationCleanupApplication {target.apply_noop_cleanup_application()}StyleInvalidationCleanupApplicationTarget::ClearAll => {- target.apply_clear_all_cleanup_application(host, &self.context)+ target.apply_clear_all_cleanup_application(&self.context)}StyleInvalidationCleanupApplicationTarget::SubtreeRoots(subtrees) => {target.apply_subtree_roots_cleanup_application(host, subtrees, &self.context)diff --git a/moli-renderer-v8/src/style_engine/registered_properties.rs b/moli-renderer-v8/src/style_engine/registered_properties.rsindex 269d8d5e3..e6e6a4fd4 100644--- a/moli-renderer-v8/src/style_engine/registered_properties.rs+++ b/moli-renderer-v8/src/style_engine/registered_properties.rs@@ -3,8 +3,7 @@ use std::cell::RefCell;use indexmap::IndexMap;use style::{stylesheets::UrlExtraData, stylist::RegisterCustomPropertyResult};-use super::MoliStyleEngine;-use crate::dom::native::DomHost;+use super::{MoliStyleEngine, source_dirty::StyleSourceDirtyReason, source_id::StyleScopeId};#[derive(Clone, Debug, PartialEq, Eq)]pub(crate) struct CssCustomPropertyRegistration {@@ -14,6 +13,15 @@ pub(crate) struct CssCustomPropertyRegistration {pub(crate) initial_value: Option<String>,}+/// One successful registration paired with the URL environment in which its+/// initial value was parsed. A later `<base>` mutation must not reinterpret an+/// already-registered custom property.+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) struct CssCustomPropertyRegistrationRecord {+ pub(crate) registration: CssCustomPropertyRegistration,+ pub(crate) base_url: url::Url,+}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub(crate) enum CssCustomPropertyRegistrationError {AlreadyRegistered,@@ -21,7 +29,7 @@ pub(crate) enum CssCustomPropertyRegistrationError {#[derive(Debug, Default)]pub(super) struct CssCustomPropertyRegistry {- registrations: RefCell<IndexMap<String, CssCustomPropertyRegistration>>,+ registrations: RefCell<IndexMap<String, CssCustomPropertyRegistrationRecord>>,}impl CssCustomPropertyRegistry {@@ -36,21 +44,30 @@ impl CssCustomPropertyRegistry {fn register(&self,registration: CssCustomPropertyRegistration,- _base_url: url::Url,+ base_url: url::Url,) -> Result<(), CssCustomPropertyRegistrationError> {let mut registrations = self.registrations.borrow_mut();if registrations.contains_key(®istration.name) {return Err(CssCustomPropertyRegistrationError::AlreadyRegistered);}- registrations.insert(registration.name.clone(), registration);+ registrations.insert(+ registration.name.clone(),+ CssCustomPropertyRegistrationRecord {+ registration,+ base_url,+ },+ );Ok(())}fn registration(&self, name: &str) -> Option<CssCustomPropertyRegistration> {- self.registrations.borrow().get(name).cloned()+ self.registrations+ .borrow()+ .get(name)+ .map(|record| record.registration.clone())}- pub(super) fn registrations(&self) -> Vec<CssCustomPropertyRegistration> {+ pub(super) fn registration_records(&self) -> Vec<CssCustomPropertyRegistrationRecord> {self.registrations.borrow().values().cloned().collect()}}@@ -69,9 +86,8 @@ impl MoliStyleEngine {)}- pub(crate) fn register_css_custom_property_for_document_with_host(+ pub(crate) fn register_css_custom_property_for_document(&mut self,- host: &DomHost,document: crate::document_runtime::DomHandle,registration: CssCustomPropertyRegistration,base_url: url::Url,@@ -80,7 +96,12 @@ impl MoliStyleEngine {world.registered_custom_properties.register(registration, base_url)?;- self.invalidate_author_stylesheet_set_for_world_with_host(host, &world);+ world.document_state.record_source_dirty_scope(+ StyleScopeId::Document(document),+ StyleSourceDirtyReason::CustomPropertyRegistration,+ std::iter::empty(),+ [document],+ );Ok(())}@@ -94,12 +115,12 @@ impl MoliStyleEngine {.registration(name)}- pub(crate) fn script_css_custom_property_registrations_for_document(+ pub(crate) fn script_css_custom_property_registration_records_for_document(&self,document: crate::document_runtime::DomHandle,- ) -> Vec<CssCustomPropertyRegistration> {+ ) -> Vec<CssCustomPropertyRegistrationRecord> {self.world_for_document(document).registered_custom_properties- .registrations()+ .registration_records()}}diff --git a/moli-renderer-v8/src/style_engine/retained.rs b/moli-renderer-v8/src/style_engine/retained.rsindex 0954ad89d..ca68a3e8c 100644--- a/moli-renderer-v8/src/style_engine/retained.rs+++ b/moli-renderer-v8/src/style_engine/retained.rs@@ -1,79 +1,86 @@-use euclid::{Scale, Size2D};-use moli_selector::StyloSourceDependencySummary;-use std::collections::{HashMap, HashSet};-use std::ptr::NonNull;-use std::sync::{Arc as StdArc, LazyLock};+use std::collections::HashSet;+use std::sync::atomic::{AtomicU64, Ordering};use style::{author_styles::AuthorStyles,- context::QuirksMode,- device::{Device, servo::FontMetricsProvider},- font_face::FontFaceRule,- font_metrics::FontMetrics,- media_queries::MediaList,- properties::{ComputedValues, style_structs::Font},- servo::media_features::PointerCapabilities,+ invalidation::stylesheets::StylesheetInvalidationSet,servo_arc::Arc as ServoArc,- shared_lock::{Locked, SharedRwLock, StylesheetGuards, ToCssWithGuard},- stylesheets::{- AllowImportRules, CssRule, CustomMediaMap, DocumentStyleSheet, Origin, Stylesheet,- StylesheetInDocument, UrlExtraData, scope_rule::ImplicitScopeRoot,- },- stylist::{CascadeData, Stylist},- values::computed::{- CSSPixelLength, Length,- font::{GenericFontFamily, SingleFontFamily},- },- values::specified::font::QueryFontMetricsFlags,+ shared_lock::{SharedRwLock, StylesheetGuards},+ stylesheets::{CustomMediaMap, DocumentStyleSheet, Origin, OriginSet, UrlExtraData},+ stylist::Stylist,};-use style_traits::{CSSPixel, CssWriter, DevicePixel, ToCss};-use crate::dom::native::DomHost;+use crate::{document_runtime::DomHandle, dom::native::DomHost};use super::{- StyloComputedStyleInputs, StyloStyleEnvironment,- source::store::{StyleSourceMetadata, StyloStylesheetSource},- source_id::{StyleSourceId, StyleSourceKind},+ CssCustomPropertyRegistrationRecord, FullStyleWorldSnapshot,+ active_stylesheets::{notify_document_stylesheet_rule_changes, update_document_stylesheet_set},+ shadow_scopes::{ShadowScopeStyles, reconcile_dirty_shadow_scopes, reconcile_shadow_scopes},+ source::store::StyloStylesheetSource,+ source_cascade::{build_source_cascade_data, update_source_cascade_data_for_scopes},+ source_id::{StyleScopeId, StyleSourceId},source_record::RetainedStylesheetSourceRecord,state::RetainedStyleSystem,- system::{DEFAULT_VIEWPORT_HEIGHT, DEFAULT_VIEWPORT_WIDTH, StyleSystemCacheKey},+ stylesheet::{+ append_stylesheet_to_stylist, install_active_stylesheet, install_active_stylesheets,+ new_style_device_with_viewport_bits, new_stylist_with_viewport_bits,+ },+ stylesheet_resources::StylesheetResourceManifest,ua::HTML_STYLESHEET as MOLI_UA_STYLESHEET,+ world_key::StyleWorldKey,+ world_update::IncrementalStyleWorldUpdate,};-static MOLI_UA_SOURCE_METADATA: LazyLock<StyleSourceMetadata> = LazyLock::new(|| {- style_source_metadata_for_css_text_with_origin(- MOLI_UA_STYLESHEET,- &url::Url::parse("about:blank").expect("valid built-in stylesheet base URL"),- Origin::UserAgent,- )-});+static NEXT_STYLIST_IDENTITY: AtomicU64 = AtomicU64::new(1);-static MOLI_UA_SOURCE_DEPENDENCY_SUMMARY: LazyLock<StdArc<StyloSourceDependencySummary>> =- LazyLock::new(|| StdArc::new(MOLI_UA_SOURCE_METADATA.dependency_summary.clone()));--#[cfg(test)]-thread_local! {- static AUTHOR_SOURCE_TEXT_PARSE_COUNT: std::cell::Cell<usize> = const {- std::cell::Cell::new(0)- };+pub(super) struct RetainedStyleInvalidations {+ pub(super) document: Option<StylesheetInvalidationSet>,+ pub(super) document_scope_fallback: bool,+ pub(super) shadow_scopes: Vec<(DomHandle, StylesheetInvalidationSet)>,+ pub(super) shadow_scope_fallbacks: Vec<DomHandle>,+ pub(super) removed_shadow_scopes: Vec<DomHandle>,}-#[cfg(test)]-pub(crate) fn reset_author_source_text_parse_count_for_test() {- AUTHOR_SOURCE_TEXT_PARSE_COUNT.with(|count| count.set(0));+/// Compares an explicit full-world snapshot with the canonical retained+/// collections. This is used only by the low-level full-snapshot API and the+/// fresh-world test oracle; normal observations are driven by dirty state and+/// never materialize these vectors merely to check freshness.+pub(super) fn retained_style_system_matches_full_snapshot(+ retained: &RetainedStyleSystem,+ key: &StyleWorldKey,+ inputs: &FullStyleWorldSnapshot,+) -> bool {+ retained.key == *key+ && retained+ .document_stylesheets+ .matches_sources(&inputs.document_stylesheet_sources)+ && retained.script_custom_property_registrations+ == inputs.script_custom_property_registrations+ && retained.shadow_scopes.len() == inputs.shadow_stylesheet_sources.len()+ && retained+ .shadow_scopes+ .iter()+ .zip(&inputs.shadow_stylesheet_sources)+ .all(|(scope, (root, sources))| {+ scope.root() == *root && scope.active_stylesheets().matches_sources(sources)+ })}-#[cfg(test)]-pub(crate) fn author_source_text_parse_count_for_test() -> usize {- AUTHOR_SOURCE_TEXT_PARSE_COUNT.with(std::cell::Cell::get)+impl RetainedStyleInvalidations {+ fn new() -> Self {+ Self {+ document: None,+ document_scope_fallback: false,+ shadow_scopes: Vec::new(),+ shadow_scope_fallbacks: Vec::new(),+ removed_shadow_scopes: Vec::new(),+ }+ }}-#[derive(Debug)]-struct HeadlessFontMetricsProvider;-pub(super) fn build_retained_style_system(host: &DomHost,- key: StyleSystemCacheKey,- inputs: &StyloComputedStyleInputs,+ key: StyleWorldKey,+ inputs: &FullStyleWorldSnapshot,shared_lock: &SharedRwLock,retained_source_records: &[RetainedStylesheetSourceRecord<'_>],) -> RetainedStyleSystem {@@ -94,65 +101,51 @@ pub(super) fn build_retained_style_system(Origin::UserAgent,key.quirks_mode,);- for source in &inputs.document_stylesheet_sources {- append_author_stylesheet_source_to_stylist(- &mut stylist,- shared_lock,- host,- source,- key.quirks_mode,- );- }- let mut sources_by_id = HashMap::<StyleSourceId, Vec<StyloStylesheetSource>>::new();- for source in &inputs.document_stylesheet_sources {- let Some(source_id) = source.source_id().cloned() else {- continue;- };- sources_by_id- .entry(source_id)- .or_default()- .push(source.clone());+ let document_stylesheets = install_active_stylesheets(+ host,+ shared_lock,+ &inputs.document_stylesheet_sources,+ key.quirks_mode,+ );+ {+ let guard = shared_lock.read();+ for entry in document_stylesheets.entries() {+ stylist.append_stylesheet(entry.stylesheet().clone(), &guard);+ }}+ let mut shadow_scopes = Vec::new();let mut shadow_cascade_data = Vec::new();for (root, sources) in &inputs.shadow_stylesheet_sources {- let cascade_data =- build_author_cascade_data(host, &mut stylist, shared_lock, sources, key.quirks_mode);- shadow_cascade_data.push((*root, cascade_data));- for source in sources {- let Some(source_id) = source.source_id().cloned() else {- continue;- };- sources_by_id- .entry(source_id)- .or_default()- .push(source.clone());+ let active_stylesheets =+ install_active_stylesheets(host, shared_lock, sources, key.quirks_mode);+ let mut author_styles = AuthorStyles::<DocumentStyleSheet>::new();+ let custom_media = CustomMediaMap::default();+ let guard = shared_lock.read();+ for entry in active_stylesheets.entries() {+ author_styles.stylesheets.append_stylesheet(+ None,+ &custom_media,+ entry.stylesheet().clone(),+ &guard,+ );}+ author_styles.flush(&mut stylist, &guard);+ shadow_cascade_data.push((*root, author_styles.data.clone()));+ shadow_scopes.push(ShadowScopeStyles::new(+ *root,+ active_stylesheets,+ author_styles,+ ));}- let mut source_cascade_data =- HashMap::with_capacity(retained_source_records.len().max(sources_by_id.len()));- for (source_id, sources) in sources_by_id {- source_cascade_data.insert(- source_id,- build_author_cascade_data(host, &mut stylist, shared_lock, &sources, key.quirks_mode),- );- }- for record in retained_source_records {- if source_cascade_data.contains_key(record.id()) {- continue;- }- let source_id = record.id().clone();- let source = record.to_stylo_source();- source_cascade_data.insert(- source_id,- build_author_cascade_data(- host,- &mut stylist,- shared_lock,- std::slice::from_ref(&source),- key.quirks_mode,- ),- );- }+ let (source_cascade_data, source_cascade_keys) = build_source_cascade_data(+ &mut stylist,+ shared_lock,+ &document_stylesheets,+ &shadow_scopes,+ retained_source_records,+ None,+ |source| install_active_stylesheet(host, shared_lock, source, key.quirks_mode),+ );let guard = shared_lock.read();stylist.flush(&StylesheetGuards::same(&guard));let user_agent_cascade_data = ServoArc::new(@@ -161,439 +154,311 @@ pub(super) fn build_retained_style_system(.borrow_for_origin(Origin::UserAgent).clone(),);+ let stylesheet_resources =+ StylesheetResourceManifest::from_active_stylesheets(&document_stylesheets, &shadow_scopes);RetainedStyleSystem {+ stylist_identity: NEXT_STYLIST_IDENTITY.fetch_add(1, Ordering::Relaxed),key,stylist,+ document_stylesheets,+ shadow_scopes,+ stylesheet_resources,+ // `StyleDocumentState::set_retained_style_system` assigns the+ // document-monotonic revision after comparing any replaced world.+ stylesheet_resource_revision: 0,user_agent_cascade_data,shadow_cascade_data,source_cascade_data,+ source_cascade_keys,+ script_custom_property_registrations: inputs.script_custom_property_registrations.clone(),}}-fn register_script_custom_properties(stylist: &mut Stylist, inputs: &StyloComputedStyleInputs) {- let url_data = UrlExtraData::from(inputs.script_custom_property_base_url.clone());- for registration in &inputs.script_custom_property_registrations {- let _ = stylist.register_custom_property(- &url_data,- ®istration.name,- ®istration.syntax,- registration.inherits,- registration.initial_value.as_deref(),- );- }-}--pub(super) fn style_source_metadata_for_css_text(- css_text: &str,- base_url: &url::Url,-) -> StyleSourceMetadata {- style_source_metadata_for_css_text_with_origin(css_text, base_url, Origin::Author)-}--pub(in crate::style_engine) fn style_source_metadata_for_stylesheet(- stylesheet: &ServoArc<Stylesheet>,-) -> StyleSourceMetadata {- let guard = stylesheet.shared_lock.read();- let quirks_mode = stylesheet.contents.read_with(&guard).quirks_mode;- let stylist = new_stylist_with_viewport_bits(- DEFAULT_VIEWPORT_WIDTH.to_bits(),- crate::style_engine::system::DEFAULT_VIEWPORT_HEIGHT.to_bits(),- DEFAULT_VIEWPORT_WIDTH.to_bits(),- crate::style_engine::system::DEFAULT_VIEWPORT_HEIGHT.to_bits(),- StyloStyleEnvironment::default(),- quirks_mode,+/// Updates the persistent document style world without replacing its Stylist.+///+/// This full-snapshot reconciliation is kept for the explicit style-engine API+/// and the fresh-world test oracle. Normal CSSOM/layout observations use+/// `update_retained_style_system_incrementally` and materialize only the dirty+/// collections named by their update plan.+pub(super) fn update_retained_style_system(+ retained: &mut RetainedStyleSystem,+ host: &DomHost,+ key: StyleWorldKey,+ inputs: &FullStyleWorldSnapshot,+ shared_lock: &SharedRwLock,+ retained_source_records: &[RetainedStylesheetSourceRecord<'_>],+) -> RetainedStyleInvalidations {+ let mut invalidations = RetainedStyleInvalidations::new();+ let document_update = update_document_scope(+ retained,+ host,+ &key,+ shared_lock,+ Some(&inputs.document_stylesheet_sources),+ Some(&inputs.script_custom_property_registrations),);- let mut cascade_data = CascadeData::new();- let document_stylesheet = DocumentStyleSheet::new(stylesheet.clone());- if cascade_data- .add_stylesheet_for_moli_source_metadata(- stylist.device(),- quirks_mode,- &document_stylesheet,- 0,- &guard,- )- .is_err()- {- return StyleSourceMetadata::default();- }- style_source_metadata_from_cascade_data(&cascade_data)-}--#[derive(Clone, Debug)]-pub(crate) struct StylesheetFontFaceRuleProjection {- pub(crate) rule_identity: u64,- pub(crate) rule_fingerprint: String,- pub(crate) descriptor: moli_css_parse::CssFontFace,-}--#[derive(Clone, Debug, Default)]-pub(crate) struct StylesheetFontFaceProjection {- pub(crate) all_rules: Vec<StylesheetFontFaceRuleProjection>,- pub(crate) effective_rule_identities: HashSet<u64>,-}--#[derive(Clone, Debug)]-pub(crate) struct NativeStylesheetFontFaceRuleProjection {- pub(crate) rule: ServoArc<Locked<FontFaceRule>>,- pub(crate) rule_fingerprint: String,- pub(crate) descriptor: moli_css_parse::CssFontFace,-}+ invalidations.document = document_update.invalidations;+ invalidations.document_scope_fallback = document_update.scope_fallback;-#[derive(Clone, Debug, Default)]-pub(crate) struct NativeStylesheetFontFaceProjection {- pub(crate) all_rules: Vec<NativeStylesheetFontFaceRuleProjection>,- pub(crate) effective_rule_addresses: HashSet<usize>,+ let shadow_reconciliation = reconcile_shadow_scopes(+ retained,+ shared_lock,+ &inputs.shadow_stylesheet_sources,+ document_update.device_changed,+ |source| install_active_stylesheet(host, shared_lock, source, key.quirks_mode),+ );+ invalidations.shadow_scopes = shadow_reconciliation.invalidations;+ invalidations.shadow_scope_fallbacks = shadow_reconciliation.scope_fallbacks;+ invalidations.removed_shadow_scopes = shadow_reconciliation.removed_roots;++ let previous_source_cascade_data = std::mem::take(&mut retained.source_cascade_data);+ let previous_source_cascade_keys = std::mem::take(&mut retained.source_cascade_keys);+ let (source_cascade_data, source_cascade_keys) = build_source_cascade_data(+ &mut retained.stylist,+ shared_lock,+ &retained.document_stylesheets,+ &retained.shadow_scopes,+ retained_source_records,+ Some((&previous_source_cascade_data, &previous_source_cascade_keys)),+ |source| install_active_stylesheet(host, shared_lock, source, key.quirks_mode),+ );+ retained.source_cascade_data = source_cascade_data;+ retained.source_cascade_keys = source_cascade_keys;+ refresh_retained_derived_state(+ retained,+ document_update.device_changed,+ document_update.stylesheets_changed || shadow_reconciliation.collections_changed,+ );+ retained.key = key;+ invalidations}-pub(crate) fn native_font_face_projection_for_stylesheet(- stylesheet: &ServoArc<Stylesheet>,- environment: StyloStyleEnvironment,- viewport: super::StyleViewport,-) -> NativeStylesheetFontFaceProjection {- let guard = stylesheet.shared_lock.read();- let quirks_mode = stylesheet.contents.read_with(&guard).quirks_mode;- let viewport_width = viewport.width.unwrap_or(DEFAULT_VIEWPORT_WIDTH as f64) as f32;- let viewport_height = viewport.height.unwrap_or(DEFAULT_VIEWPORT_HEIGHT as f64) as f32;- let screen_width = viewport.screen_width.unwrap_or(f64::from(viewport_width)) as f32;- let screen_height = viewport.screen_height.unwrap_or(f64::from(viewport_height)) as f32;- let stylist = new_stylist_with_viewport_bits(- viewport_width.to_bits(),- viewport_height.to_bits(),- screen_width.to_bits(),- screen_height.to_bits(),- environment,- quirks_mode,+/// Applies a dirty-plan update without reconstructing clean TreeScope input+/// vectors. Parsed stylesheets and AuthorStyles for untouched scopes stay in+/// place.+pub(super) fn update_retained_style_system_incrementally(+ retained: &mut RetainedStyleSystem,+ host: &DomHost,+ document: DomHandle,+ key: StyleWorldKey,+ update: &IncrementalStyleWorldUpdate,+ shared_lock: &SharedRwLock,+ retained_source_records: &[RetainedStylesheetSourceRecord<'_>],+ dirty_source_ids: &HashSet<StyleSourceId>,+ full_source_projection_scopes: &HashSet<StyleScopeId>,+) -> RetainedStyleInvalidations {+ let mut invalidations = RetainedStyleInvalidations::new();+ let document_update = update_document_scope(+ retained,+ host,+ &key,+ shared_lock,+ update.document_stylesheet_sources.as_deref(),+ update.script_custom_property_registrations.as_deref(),);+ invalidations.document = document_update.invalidations;+ invalidations.document_scope_fallback = document_update.scope_fallback;- let mut projection = NativeStylesheetFontFaceProjection::default();- let contents = stylesheet.contents(&guard);- collect_font_face_rule_projections(contents.rules(&guard), &guard, &mut projection.all_rules);-- let document_stylesheet = DocumentStyleSheet::new(stylesheet.clone());- let custom_media = CustomMediaMap::default();- if document_stylesheet.enabled()- && document_stylesheet.is_effective_for_device(stylist.device(), &custom_media, &guard)- {- projection.effective_rule_addresses.extend(- contents- .effective_rules(stylist.device(), &custom_media, &guard)- .filter_map(|rule| match rule {- CssRule::FontFace(rule) => Some(rule.raw_ptr().as_ptr() as usize),- _ => None,- }),+ let shadow_reconciliation = reconcile_dirty_shadow_scopes(+ retained,+ shared_lock,+ &update.shadow_stylesheet_sources,+ update.connected_shadow_roots.as_deref(),+ document_update.device_changed,+ |source| install_active_stylesheet(host, shared_lock, source, key.quirks_mode),+ );+ invalidations.shadow_scopes = shadow_reconciliation.invalidations;+ invalidations.shadow_scope_fallbacks = shadow_reconciliation.scope_fallbacks;+ invalidations.removed_shadow_scopes = shadow_reconciliation.removed_roots;++ let mut dirty_source_scopes = full_source_projection_scopes.clone();+ if document_update.device_changed {+ dirty_source_scopes.insert(StyleScopeId::Document(document));+ dirty_source_scopes.extend(+ retained+ .shadow_scopes+ .iter()+ .map(|scope| StyleScopeId::ShadowRoot(scope.root())),);}- projection-}--pub(crate) fn native_font_face_rules_for_stylesheet(- stylesheet: &ServoArc<Stylesheet>,-) -> Vec<NativeStylesheetFontFaceRuleProjection> {- let guard = stylesheet.shared_lock.read();- let mut rules = Vec::new();- collect_font_face_rule_projections(- stylesheet.contents(&guard).rules(&guard),- &guard,- &mut rules,+ dirty_source_scopes.extend(+ invalidations+ .removed_shadow_scopes+ .iter()+ .copied()+ .map(StyleScopeId::ShadowRoot),);- rules-}--fn collect_font_face_rule_projections(- rules: &[CssRule],- guard: &style::shared_lock::SharedRwLockReadGuard<'_>,- projections: &mut Vec<NativeStylesheetFontFaceRuleProjection>,-) {- for rule in rules {- if let CssRule::FontFace(rule) = rule {- let locked_rule = rule.read_with(guard);- let Some(family) = locked_rule.descriptors.font_family.as_ref() else {- continue;- };- let Some(source) = locked_rule.descriptors.src.as_ref() else {- continue;- };- let mut serialized_source = String::new();- if source- .to_css(&mut CssWriter::new(&mut serialized_source))- .is_ok()- {- projections.push(NativeStylesheetFontFaceRuleProjection {- rule: rule.clone(),- rule_fingerprint: locked_rule.to_css_string(guard),- descriptor: moli_css_parse::CssFontFace {- family: family.name.to_string(),- source: serialized_source,- },- });- }- continue;- }- collect_font_face_rule_projections(rule.children(guard), guard, projections);- }-}--pub(super) fn moli_user_agent_source_dependency_summary() -> StdArc<StyloSourceDependencySummary> {- StdArc::clone(&MOLI_UA_SOURCE_DEPENDENCY_SUMMARY)-}--fn style_source_metadata_for_css_text_with_origin(- css_text: &str,- base_url: &url::Url,- origin: Origin,-) -> StyleSourceMetadata {- let shared_lock = SharedRwLock::new();- let stylesheet = DocumentStyleSheet::new(ServoArc::new(parse_stylesheet(- &shared_lock,- base_url,- css_text,- origin,- QuirksMode::NoQuirks,- )));- let guard = shared_lock.read();- let stylist = new_stylist_with_viewport_bits(- DEFAULT_VIEWPORT_WIDTH.to_bits(),- crate::style_engine::system::DEFAULT_VIEWPORT_HEIGHT.to_bits(),- DEFAULT_VIEWPORT_WIDTH.to_bits(),- crate::style_engine::system::DEFAULT_VIEWPORT_HEIGHT.to_bits(),- StyloStyleEnvironment::default(),- QuirksMode::NoQuirks,+ update_source_cascade_data_for_scopes(+ retained,+ shared_lock,+ retained_source_records,+ dirty_source_ids,+ &dirty_source_scopes,+ |source| install_active_stylesheet(host, shared_lock, source, key.quirks_mode),);- let mut cascade_data = CascadeData::new();- if cascade_data- .add_stylesheet_for_moli_source_metadata(- stylist.device(),- style::context::QuirksMode::NoQuirks,- &stylesheet,- 0,- &guard,- )- .is_err()- {- return StyleSourceMetadata::default();- }- style_source_metadata_from_cascade_data(&cascade_data)-}--fn style_source_metadata_from_cascade_data(cascade_data: &CascadeData) -> StyleSourceMetadata {- let dependency_summary = StyloSourceDependencySummary::from_cascade_data(cascade_data);- StyleSourceMetadata { dependency_summary }+ refresh_retained_derived_state(+ retained,+ document_update.device_changed,+ document_update.stylesheets_changed || shadow_reconciliation.collections_changed,+ );+ retained.key = key;+ invalidations}-fn new_stylist_with_viewport_bits(- viewport_width_bits: u32,- viewport_height_bits: u32,- screen_width_bits: u32,- screen_height_bits: u32,- environment: StyloStyleEnvironment,- quirks_mode: QuirksMode,-) -> Stylist {- let width = f32::from_bits(viewport_width_bits);- let height = f32::from_bits(viewport_height_bits);- let screen_width = f32::from_bits(screen_width_bits);- let screen_height = f32::from_bits(screen_height_bits);- let initial_style = ComputedValues::initial_values_with_font_override(Font::initial_values());- let mut device = Device::new(- environment.stylo_media_type(),- quirks_mode,- Size2D::<f32, CSSPixel>::new(width, height),- Size2D::<f32, DevicePixel>::new(screen_width, screen_height),- Scale::<f32, CSSPixel, DevicePixel>::new(1.0),- Box::new(HeadlessFontMetricsProvider),- initial_style,- environment.stylo_prefers_color_scheme(),- PointerCapabilities::default(),- PointerCapabilities::default(),- );- device.set_media_feature_preferences(environment.stylo_media_feature_preferences());- Stylist::new(device, quirks_mode)+struct DocumentScopeUpdate {+ invalidations: Option<StylesheetInvalidationSet>,+ scope_fallback: bool,+ device_changed: bool,+ stylesheets_changed: bool,}-fn build_author_cascade_data(+fn update_document_scope(+ retained: &mut RetainedStyleSystem,host: &DomHost,- stylist: &mut Stylist,+ key: &StyleWorldKey,shared_lock: &SharedRwLock,- sources: &[StyloStylesheetSource],- quirks_mode: QuirksMode,-) -> ServoArc<style::stylist::CascadeData> {- let stylesheets = sources- .iter()- .map(|source| {- document_stylesheet_for_source(- host,- source,- author_stylesheet_for_source(shared_lock, source, quirks_mode),- )- })- .collect::<Vec<_>>();- let mut author_styles = AuthorStyles::<DocumentStyleSheet>::new();- let custom_media = CustomMediaMap::default();- let guard = shared_lock.read();- for stylesheet in stylesheets {- author_styles- .stylesheets- .append_stylesheet(None, &custom_media, stylesheet, &guard);+ stylesheet_sources: Option<&[StyloStylesheetSource]>,+ custom_property_registrations: Option<&[CssCustomPropertyRegistrationRecord]>,+) -> DocumentScopeUpdate {+ let custom_properties_changed = custom_property_registrations.is_some_and(|registrations| {+ retained.script_custom_property_registrations.as_slice() != registrations+ });+ if let Some(registrations) = custom_property_registrations.filter(|_| custom_properties_changed)+ {+ debug_assert!(+ retained.script_custom_property_registrations.len() <= registrations.len()+ && retained.script_custom_property_registrations+ == registrations[..retained.script_custom_property_registrations.len()],+ "registered custom properties must be append-only within a retained style world"+ );+ for record in registrations+ .iter()+ .skip(retained.script_custom_property_registrations.len())+ {+ let registration = &record.registration;+ let url_data = UrlExtraData::from(record.base_url.clone());+ let _ = retained.stylist.register_custom_property(+ &url_data,+ ®istration.name,+ ®istration.syntax,+ registration.inherits,+ registration.initial_value.as_deref(),+ );+ }+ retained.script_custom_property_registrations = registrations.to_vec();+ retained+ .stylist+ .force_stylesheet_origins_dirty(OriginSet::ORIGIN_AUTHOR);}- author_styles.flush(stylist, &guard);- author_styles.data-}-fn document_stylesheet_for_source(- host: &DomHost,- source: &StyloStylesheetSource,- stylesheet: ServoArc<Stylesheet>,-) -> DocumentStyleSheet {- implicit_scope_root_for_source(host, source.source_id())- .map(|root| DocumentStyleSheet::with_implicit_scope_root(stylesheet.clone(), root))- .unwrap_or_else(|| DocumentStyleSheet::new(stylesheet))-}+ let device_changed = retained.key.viewport_width_bits != key.viewport_width_bits+ || retained.key.viewport_height_bits != key.viewport_height_bits+ || retained.key.screen_width_bits != key.screen_width_bits+ || retained.key.screen_height_bits != key.screen_height_bits+ || retained.key.environment != key.environment;+ if device_changed {+ let device = new_style_device_with_viewport_bits(+ key.viewport_width_bits,+ key.viewport_height_bits,+ key.screen_width_bits,+ key.screen_height_bits,+ key.environment,+ key.quirks_mode,+ );+ let guard = shared_lock.read();+ let guards = StylesheetGuards::same(&guard);+ let affected_origins = retained.stylist.set_device(device, &guards);+ retained+ .stylist+ .force_stylesheet_origins_dirty(affected_origins);+ }-fn implicit_scope_root_for_source(- host: &DomHost,- source_id: Option<&StyleSourceId>,-) -> Option<ImplicitScopeRoot> {- let source_id = source_id?;- match &source_id.kind {- StyleSourceKind::OwnerStyleSheet { owner }- | StyleSourceKind::LinkedStyleSheet { owner } => {- implicit_scope_root_for_stylesheet_owner(host, *owner)+ let stylesheet_reconciliation = stylesheet_sources.and_then(|sources| {+ retained.document_stylesheets.reconcile(sources, |source| {+ install_active_stylesheet(host, shared_lock, source, key.quirks_mode)+ })+ });+ let mut scope_fallback = false;+ if let Some(reconciliation) = stylesheet_reconciliation.as_ref() {+ let guard = shared_lock.read();+ scope_fallback |= reconciliation.stylesheet_removed();+ if reconciliation.stylesheet_set_changed() {+ let next_stylesheets = retained+ .document_stylesheets+ .entries()+ .iter()+ .map(|entry| entry.stylesheet().clone())+ .collect::<Vec<_>>();+ update_document_stylesheet_set(+ &mut retained.stylist,+ reconciliation.previous_stylesheets(),+ &next_stylesheets,+ &guard,+ );+ }+ if notify_document_stylesheet_rule_changes(&mut retained.stylist, reconciliation, &guard) {+ // Media/disabled/import-descendant changes and whole-sheet+ // replacement are explicit journal fallbacks.+ scope_fallback = true;+ retained+ .stylist+ .force_stylesheet_origins_dirty(OriginSet::ORIGIN_AUTHOR);}- StyleSourceKind::DocumentAdoptedStyleSheet { .. } => Some(ImplicitScopeRoot::Constructed),- StyleSourceKind::ShadowRootAdoptedStyleSheet { .. } => Some(ImplicitScopeRoot::Constructed),}-}-fn implicit_scope_root_for_stylesheet_owner(- host: &DomHost,- owner: crate::document_runtime::DomHandle,-) -> Option<ImplicitScopeRoot> {- let parent = host.node(owner)?.parent_node()?;- if host.is_shadow_root(parent) {- return host- .shadow_root_host(parent)- .and_then(|host_element| opaque_element_for_handle(host, host_element))- .map(ImplicitScopeRoot::ShadowHost);- }- let parent_node = host.node(parent)?;- parent_node.as_element()?;- let opaque_parent = opaque_element_for_handle(host, parent)?;- if host.containing_shadow_root(parent).is_some() {- Some(ImplicitScopeRoot::InShadowTree(opaque_parent))- } else {- Some(ImplicitScopeRoot::InLightTree(opaque_parent))+ let stylesheets_changed = stylesheet_reconciliation.is_some();+ let must_flush = device_changed || stylesheets_changed || custom_properties_changed;+ let invalidations = must_flush.then(|| {+ let guard = shared_lock.read();+ retained.stylist.flush(&StylesheetGuards::same(&guard))+ });+ DocumentScopeUpdate {+ invalidations,+ scope_fallback,+ device_changed,+ stylesheets_changed,}}-fn opaque_element_for_handle(- host: &DomHost,- handle: crate::document_runtime::DomHandle,-) -> Option<selectors::OpaqueElement> {- let node = host.node(handle)?;- node.as_element()?;- Some(selectors::OpaqueElement::from_non_null_ptr(- NonNull::new(node as *const crate::dom::native::Node as *mut ())- .expect("DOM node pointers are never null"),- ))-}--fn append_stylesheet_to_stylist(- stylist: &mut Stylist,- shared_lock: &SharedRwLock,- css_text: &str,- base_url: &url::Url,- origin: Origin,- quirks_mode: QuirksMode,+fn refresh_retained_derived_state(+ retained: &mut RetainedStyleSystem,+ device_changed: bool,+ stylesheet_collections_changed: bool,) {- let stylesheet = parse_stylesheet(shared_lock, base_url, css_text, origin, quirks_mode);- let guard = shared_lock.read();- stylist.append_stylesheet(DocumentStyleSheet::new(ServoArc::new(stylesheet)), &guard);-}--fn append_author_stylesheet_source_to_stylist(- stylist: &mut Stylist,- shared_lock: &SharedRwLock,- host: &DomHost,- source: &StyloStylesheetSource,- quirks_mode: QuirksMode,-) {- let stylesheet = author_stylesheet_for_source(shared_lock, source, quirks_mode);- let stylesheet = document_stylesheet_for_source(host, source, stylesheet);- let guard = shared_lock.read();- stylist.append_stylesheet(stylesheet, &guard);-}--fn author_stylesheet_for_source(- shared_lock: &SharedRwLock,- source: &StyloStylesheetSource,- quirks_mode: QuirksMode,-) -> ServoArc<Stylesheet> {- if let Some(stylesheet) = source.parsed_stylesheet() {- return stylesheet;+ if device_changed {+ retained.user_agent_cascade_data = ServoArc::new(+ retained+ .stylist+ .cascade_data()+ .borrow_for_origin(Origin::UserAgent)+ .clone(),+ );}- #[cfg(test)]- AUTHOR_SOURCE_TEXT_PARSE_COUNT.with(|count| count.set(count.get() + 1));- let css_text = source- .input_css_text()- .expect("stylesheet without parsed contents must remain text-backed");- ServoArc::new(parse_stylesheet(- shared_lock,- source.base_url(),- css_text,- Origin::Author,- quirks_mode,- ))-}--fn parse_stylesheet(- shared_lock: &SharedRwLock,- base_url: &url::Url,- css_text: &str,- origin: Origin,- quirks_mode: QuirksMode,-) -> Stylesheet {- let media = ServoArc::new(shared_lock.wrap(MediaList::empty()));- Stylesheet::from_str(- css_text,- UrlExtraData::from(base_url.clone()),- origin,- media,- shared_lock.clone(),- None,- None,- quirks_mode,- AllowImportRules::No,- )-}--impl FontMetricsProvider for HeadlessFontMetricsProvider {- fn query_font_metrics(- &self,- _vertical: bool,- font: &Font,- base_size: CSSPixelLength,- _flags: QueryFontMetricsFlags,- ) -> FontMetrics {- let mut metrics = FontMetrics::default();- if font_family_list_starts_with_ahem(font) {- metrics.zero_advance_measure = Some(base_size);- }- metrics+ if !stylesheet_collections_changed {+ return;}-- fn base_size_for_generic(&self, _generic: GenericFontFamily) -> Length {- Length::new(16.0)+ let stylesheet_resources = StylesheetResourceManifest::from_active_stylesheets(+ &retained.document_stylesheets,+ &retained.shadow_scopes,+ );+ if retained.stylesheet_resources != stylesheet_resources {+ retained.stylesheet_resources = stylesheet_resources;+ retained.stylesheet_resource_revision =+ retained.stylesheet_resource_revision.saturating_add(1);}}-fn font_family_list_starts_with_ahem(font: &Font) -> bool {- font.clone_font_family()- .families- .iter()- .next()- .is_some_and(|family| match family {- SingleFontFamily::FamilyName(name) => name.name.as_ref().eq_ignore_ascii_case("Ahem"),- SingleFontFamily::Generic(_) => false,- })+fn register_script_custom_properties(stylist: &mut Stylist, inputs: &FullStyleWorldSnapshot) {+ for record in &inputs.script_custom_property_registrations {+ let registration = &record.registration;+ let url_data = UrlExtraData::from(record.base_url.clone());+ let _ = stylist.register_custom_property(+ &url_data,+ ®istration.name,+ ®istration.syntax,+ registration.inherits,+ registration.initial_value.as_deref(),+ );+ }}diff --git a/moli-renderer-v8/src/style_engine/shadow_scopes.rs b/moli-renderer-v8/src/style_engine/shadow_scopes.rsnew file mode 100644index 000000000..ab7e4cfa8--- /dev/null+++ b/moli-renderer-v8/src/style_engine/shadow_scopes.rs@@ -0,0 +1,402 @@+use std::collections::HashSet;++use style::{+ author_styles::AuthorStyles,+ invalidation::stylesheets::StylesheetInvalidationSet,+ shared_lock::{SharedRwLock, SharedRwLockReadGuard},+ stylesheets::{CustomMediaMap, DocumentStyleSheet},+ stylist::Stylist,+};++use crate::document_runtime::DomHandle;++use super::{+ active_stylesheets::{+ ActiveStylesheet, ActiveStylesheetCollection, ActiveStylesheetReconciliation,+ StylesheetSetUpdate, note_exact_rule_change_notifications,+ note_full_cascade_update_fallback, stylesheet_set_updates,+ },+ source::store::{LiveStylesheetCascadeUpdate, StyloStylesheetSource},+ state::RetainedStyleSystem,+};++/// Persistent author-style state for one connected ShadowRoot TreeScope.+/// Empty scopes deliberately retain an empty `AuthorStyles`, matching Blink's+/// stable TreeScope universe and Stylo's shared empty CascadeData semantics.+pub(super) struct ShadowScopeStyles {+ root: DomHandle,+ active_stylesheets: ActiveStylesheetCollection,+ author_styles: AuthorStyles<DocumentStyleSheet>,+ flush_count: u64,+}++impl ShadowScopeStyles {+ pub(super) fn new(+ root: DomHandle,+ active_stylesheets: ActiveStylesheetCollection,+ author_styles: AuthorStyles<DocumentStyleSheet>,+ ) -> Self {+ Self {+ root,+ active_stylesheets,+ author_styles,+ flush_count: 1,+ }+ }++ pub(super) fn root(&self) -> DomHandle {+ self.root+ }++ pub(super) fn active_stylesheets(&self) -> &ActiveStylesheetCollection {+ &self.active_stylesheets+ }++ pub(super) fn active_stylesheets_mut(&mut self) -> &mut ActiveStylesheetCollection {+ &mut self.active_stylesheets+ }++ pub(super) fn author_styles(&self) -> &AuthorStyles<DocumentStyleSheet> {+ &self.author_styles+ }++ pub(super) fn author_styles_mut(&mut self) -> &mut AuthorStyles<DocumentStyleSheet> {+ &mut self.author_styles+ }++ pub(super) fn flush(+ &mut self,+ stylist: &mut Stylist,+ guard: &SharedRwLockReadGuard<'_>,+ ) -> StylesheetInvalidationSet {+ self.flush_count = self.flush_count.saturating_add(1);+ self.author_styles.flush(stylist, guard)+ }++ #[cfg(test)]+ pub(super) fn flush_count_for_test(&self) -> u64 {+ self.flush_count+ }+}++pub(super) struct ShadowScopeReconciliation {+ pub(super) invalidations: Vec<(DomHandle, StylesheetInvalidationSet)>,+ pub(super) removed_roots: Vec<DomHandle>,+ pub(super) scope_fallbacks: Vec<DomHandle>,+ pub(super) collections_changed: bool,+}++/// Reconciles exactly the dirty ShadowRoot collections plus an optional+/// connected-root membership snapshot. Clean `AuthorStyles` stay in place and+/// are not flushed.+pub(super) fn reconcile_dirty_shadow_scopes(+ retained: &mut RetainedStyleSystem,+ shared_lock: &SharedRwLock,+ dirty_scopes: &[(DomHandle, Vec<StyloStylesheetSource>)],+ connected_roots: Option<&[DomHandle]>,+ device_changed: bool,+ mut install: impl FnMut(&StyloStylesheetSource) -> ActiveStylesheet,+) -> ShadowScopeReconciliation {+ let mut invalidations = Vec::new();+ let mut removed_roots = Vec::new();+ let mut scope_fallbacks = Vec::new();+ let mut collections_changed = false;+ let mut newly_built_roots = HashSet::new();++ if let Some(connected_roots) = connected_roots {+ let mut previous_scopes = std::mem::take(&mut retained.shadow_scopes);+ let mut next_scopes = Vec::with_capacity(connected_roots.len());+ for root in connected_roots {+ if let Some(index) = previous_scopes+ .iter()+ .position(|scope| scope.root() == *root)+ {+ next_scopes.push(previous_scopes.remove(index));+ continue;+ }+ let sources = dirty_scopes+ .iter()+ .find_map(|(candidate, sources)| (candidate == root).then_some(sources.as_slice()))+ .unwrap_or_default();+ let (scope, scope_invalidations) = build_shadow_scope(+ &mut retained.stylist,+ shared_lock,+ *root,+ sources,+ &mut install,+ );+ newly_built_roots.insert(*root);+ invalidations.push((*root, scope_invalidations));+ next_scopes.push(scope);+ collections_changed = true;+ }+ removed_roots.extend(previous_scopes.into_iter().map(|scope| scope.root()));+ collections_changed |= !removed_roots.is_empty();+ retained.shadow_scopes = next_scopes;+ }++ for (root, sources) in dirty_scopes {+ if newly_built_roots.contains(root) {+ continue;+ }+ let Some(scope) = retained+ .shadow_scopes+ .iter_mut()+ .find(|scope| scope.root() == *root)+ else {+ continue;+ };+ let reconciliation = scope+ .active_stylesheets_mut()+ .reconcile(sources, &mut install);+ if let Some(reconciliation) = reconciliation.as_ref() {+ collections_changed = true;+ if apply_stylesheet_set_reconciliation(+ scope,+ &retained.stylist,+ shared_lock,+ reconciliation,+ ) {+ scope_fallbacks.push(*root);+ }+ }+ }++ let dirty_roots = dirty_scopes+ .iter()+ .map(|(root, _)| *root)+ .collect::<HashSet<_>>();+ for scope in &mut retained.shadow_scopes {+ if newly_built_roots.contains(&scope.root()) {+ continue;+ }+ let must_flush = dirty_roots.contains(&scope.root()) || device_changed;+ if !must_flush {+ continue;+ }+ if device_changed {+ scope.author_styles_mut().stylesheets.force_dirty();+ }+ let guard = shared_lock.read();+ invalidations.push((scope.root(), scope.flush(&mut retained.stylist, &guard)));+ }++ publish_shadow_cascade_data(retained);+ ShadowScopeReconciliation {+ invalidations,+ removed_roots,+ scope_fallbacks,+ collections_changed,+ }+}++/// Full-snapshot compatibility path used by initial construction tests and+/// exceptional callers. It still preserves existing scopes by identity.+pub(super) fn reconcile_shadow_scopes(+ retained: &mut RetainedStyleSystem,+ shared_lock: &SharedRwLock,+ desired_scopes: &[(DomHandle, Vec<StyloStylesheetSource>)],+ device_changed: bool,+ mut install: impl FnMut(&StyloStylesheetSource) -> ActiveStylesheet,+) -> ShadowScopeReconciliation {+ let mut previous_scopes = std::mem::take(&mut retained.shadow_scopes);+ let mut next_scopes = Vec::with_capacity(desired_scopes.len());+ let mut invalidations = Vec::new();+ let mut scope_fallbacks = Vec::new();+ let mut collections_changed = false;+ for (root, sources) in desired_scopes {+ let mut scope = if let Some(index) = previous_scopes+ .iter()+ .position(|scope| scope.root() == *root)+ {+ previous_scopes.remove(index)+ } else {+ collections_changed = true;+ let (scope, scope_invalidations) = build_shadow_scope(+ &mut retained.stylist,+ shared_lock,+ *root,+ sources,+ &mut install,+ );+ invalidations.push((*root, scope_invalidations));+ scope+ };++ let reconciliation = scope+ .active_stylesheets_mut()+ .reconcile(sources, &mut install);+ if let Some(reconciliation) = reconciliation.as_ref() {+ collections_changed = true;+ if apply_stylesheet_set_reconciliation(+ &mut scope,+ &retained.stylist,+ shared_lock,+ reconciliation,+ ) {+ scope_fallbacks.push(*root);+ }+ }+ if device_changed {+ scope.author_styles_mut().stylesheets.force_dirty();+ }+ if reconciliation.is_some() || device_changed {+ let guard = shared_lock.read();+ invalidations.push((*root, scope.flush(&mut retained.stylist, &guard)));+ }+ next_scopes.push(scope);+ }+ retained.shadow_scopes = next_scopes;+ publish_shadow_cascade_data(retained);+ let removed_roots = previous_scopes+ .into_iter()+ .map(|scope| scope.root())+ .collect::<Vec<_>>();+ collections_changed |= !removed_roots.is_empty();+ ShadowScopeReconciliation {+ invalidations,+ removed_roots,+ scope_fallbacks,+ collections_changed,+ }+}++fn build_shadow_scope(+ stylist: &mut Stylist,+ shared_lock: &SharedRwLock,+ root: DomHandle,+ sources: &[StyloStylesheetSource],+ install: &mut impl FnMut(&StyloStylesheetSource) -> ActiveStylesheet,+) -> (ShadowScopeStyles, StylesheetInvalidationSet) {+ let active_stylesheets = ActiveStylesheetCollection::new(sources.iter().map(install).collect());+ let mut author_styles = AuthorStyles::<DocumentStyleSheet>::new();+ let custom_media = CustomMediaMap::default();+ let guard = shared_lock.read();+ for entry in active_stylesheets.entries() {+ author_styles.stylesheets.append_stylesheet(+ Some(stylist.device()),+ &custom_media,+ entry.stylesheet().clone(),+ &guard,+ );+ }+ let invalidations = author_styles.flush(stylist, &guard);+ (+ ShadowScopeStyles::new(root, active_stylesheets, author_styles),+ invalidations,+ )+}++fn apply_stylesheet_set_reconciliation(+ scope: &mut ShadowScopeStyles,+ stylist: &Stylist,+ shared_lock: &SharedRwLock,+ reconciliation: &ActiveStylesheetReconciliation,+) -> bool {+ let custom_media = CustomMediaMap::default();+ let guard = shared_lock.read();+ if reconciliation.stylesheet_set_changed() {+ let next_stylesheets = scope+ .active_stylesheets()+ .entries()+ .iter()+ .map(|entry| entry.stylesheet().clone())+ .collect::<Vec<_>>();+ update_shadow_stylesheet_set(+ scope.author_styles_mut(),+ stylist.device(),+ &custom_media,+ reconciliation.previous_stylesheets(),+ &next_stylesheets,+ &guard,+ );+ }+ let full_cascade_fallback = notify_shadow_stylesheet_rule_changes(+ scope.author_styles_mut(),+ stylist.device(),+ &custom_media,+ reconciliation,+ &guard,+ );+ if full_cascade_fallback {+ scope.author_styles_mut().stylesheets.force_dirty();+ }+ reconciliation.stylesheet_removed() || full_cascade_fallback+}++fn update_shadow_stylesheet_set(+ author_styles: &mut AuthorStyles<DocumentStyleSheet>,+ device: &style::device::Device,+ custom_media: &CustomMediaMap,+ previous: &[DocumentStyleSheet],+ next: &[DocumentStyleSheet],+ guard: &SharedRwLockReadGuard<'_>,+) {+ for update in stylesheet_set_updates(previous, next) {+ match update {+ StylesheetSetUpdate::Remove(stylesheet) => author_styles.stylesheets.remove_stylesheet(+ Some(device),+ custom_media,+ stylesheet,+ guard,+ ),+ StylesheetSetUpdate::InsertBefore { stylesheet, before } => author_styles+ .stylesheets+ .insert_stylesheet_before(Some(device), custom_media, stylesheet, before, guard),+ StylesheetSetUpdate::Append(stylesheet) => author_styles.stylesheets.append_stylesheet(+ Some(device),+ custom_media,+ stylesheet,+ guard,+ ),+ }+ }+}++fn notify_shadow_stylesheet_rule_changes(+ author_styles: &mut AuthorStyles<DocumentStyleSheet>,+ device: &style::device::Device,+ custom_media: &CustomMediaMap,+ reconciliation: &ActiveStylesheetReconciliation,+ guard: &SharedRwLockReadGuard<'_>,+) -> bool {+ if reconciliation+ .in_place_updates()+ .iter()+ .any(|update| matches!(update.cascade_update(), LiveStylesheetCascadeUpdate::Full))+ {+ note_full_cascade_update_fallback();+ return true;+ }+ for update in reconciliation.in_place_updates() {+ let LiveStylesheetCascadeUpdate::Rules(changes) = update.cascade_update() else {+ unreachable!("full updates were handled above");+ };+ note_exact_rule_change_notifications(changes.len());+ for change in changes {+ let ancestors = change+ .ancestors()+ .iter()+ .map(style::stylesheets::CssRuleRef::from)+ .collect::<Vec<_>>();+ author_styles.stylesheets.rule_changed(+ Some(device),+ custom_media,+ update.stylesheet(),+ change.rule(),+ guard,+ change.change_kind(),+ &ancestors,+ );+ }+ }+ false+}++fn publish_shadow_cascade_data(retained: &mut RetainedStyleSystem) {+ retained.shadow_cascade_data = retained+ .shadow_scopes+ .iter()+ .map(|scope| (scope.root(), scope.author_styles().data.clone()))+ .collect();+}diff --git a/moli-renderer-v8/src/style_engine/source/adopted.rs b/moli-renderer-v8/src/style_engine/source/adopted.rsindex 9814f7d09..e179dc4b9 100644--- a/moli-renderer-v8/src/style_engine/source/adopted.rs+++ b/moli-renderer-v8/src/style_engine/source/adopted.rs@@ -1,4 +1,4 @@-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use indexmap::IndexSet;@@ -51,7 +51,25 @@ impl InstalledAdoptedStylesheetClient {}#[cfg(test)]- fn from_source_snapshot(source: StyloStylesheetSource) -> Self {+ fn from_source_snapshot(mut source: StyloStylesheetSource) -> Self {+ if source.adopted_client_id().is_none() {+ let synthetic_client_id =+ source+ .source_id()+ .and_then(|source_id| match source_id.kind {+ super::super::source_id::StyleSourceKind::DocumentAdoptedStyleSheet {+ client_id,+ }+ | super::super::source_id::StyleSourceKind::ShadowRootAdoptedStyleSheet {+ client_id,+ } => Some(client_id),+ super::super::source_id::StyleSourceKind::OwnerStyleSheet { .. }+ | super::super::source_id::StyleSourceKind::LinkedStyleSheet { .. } => None,+ });+ if let Some(client_id) = synthetic_client_id {+ source = source.with_adopted_client_id(client_id);+ }+ }Self {source,_live_stylesheet: None,@@ -159,6 +177,7 @@ impl AdoptedStyleSheetSources {.cloned().unwrap_or_default();let mut reused = vec![false; previous.len()];+ let mut assigned_client_ids = HashSet::new();for client in &mut clients {let reused_client_id = previous.iter().enumerate().find_map(|(index, candidate)| {(!reused[index]@@ -171,7 +190,15 @@ impl AdoptedStyleSheetSources {}).flatten()});- let client_id = reused_client_id.unwrap_or_else(|| self.allocate_client_id());+ let requested_client_id = client+ .source()+ .adopted_client_id()+ .filter(|client_id| !assigned_client_ids.contains(client_id));+ let client_id = reused_client_id+ .or(requested_client_id)+ .unwrap_or_else(|| self.allocate_client_id_avoiding(&assigned_client_ids));+ self.next_client_id = self.next_client_id.max(client_id);+ assigned_client_ids.insert(client_id);client.source = client.source.clone().with_adopted_client_id(client_id);}if self@@ -194,6 +221,15 @@ impl AdoptedStyleSheetSources {self.next_client_id}+ fn allocate_client_id_avoiding(&mut self, assigned_client_ids: &HashSet<u64>) -> u64 {+ loop {+ let client_id = self.allocate_client_id();+ if !assigned_client_ids.contains(&client_id) {+ return client_id;+ }+ }+ }+fn sources(&self,owner: AdoptedStyleSheetOwner,@@ -233,19 +269,33 @@ impl AdoptedStyleSheetSources {.len()}- pub(in crate::style_engine) fn shadow_root_source_count(&self, root: DomHandle) -> usize {- self.sources_or_empty(AdoptedStyleSheetOwner::ShadowRoot(root))- .len()+ pub(in crate::style_engine) fn document_source_ids(+ &self,+ document: DomHandle,+ ) -> Vec<StyleSourceId> {+ self.source_ids(AdoptedStyleSheetOwner::Document(document), |client_id| {+ StyleSourceId::document_adopted_style_sheet(document, client_id)+ })+ }++ pub(in crate::style_engine) fn shadow_root_source_ids(+ &self,+ root: DomHandle,+ ) -> Vec<StyleSourceId> {+ self.source_ids(AdoptedStyleSheetOwner::ShadowRoot(root), |client_id| {+ StyleSourceId::shadow_root_adopted_style_sheet(root, client_id)+ })}fn source(&self,owner: AdoptedStyleSheetOwner,- index: usize,+ client_id: u64,) -> Option<&StyloStylesheetSource> {self.sources_by_owner.get(&owner)?- .get(index)+ .iter()+ .find(|client| client.source().adopted_client_id() == Some(client_id)).map(InstalledAdoptedStylesheetClient::source)}@@ -253,9 +303,9 @@ impl AdoptedStyleSheetSources {&'a self,source_id: StyleSourceId,owner: AdoptedStyleSheetOwner,- index: usize,+ client_id: u64,) -> Option<RetainedStylesheetSourceRecord<'a>> {- let source = self.source(owner, index)?;+ let source = self.source(owner, client_id)?;Some(RetainedStylesheetSourceRecord::registered(source_id, source,))@@ -277,12 +327,16 @@ impl AdoptedStyleSheetSources {if !lifecycle_owner.retained_source_records_are_available(host) {return;}- for index in 0..sources.len() {- let source_id = StyleSourceId::document_adopted_style_sheet(document, index);+ for source in sources {+ let client_id = source+ .source()+ .adopted_client_id()+ .expect("installed adopted stylesheet must have a client id");+ let source_id = StyleSourceId::document_adopted_style_sheet(document, client_id);if let Some(record) = self.retained_source_record(source_id,AdoptedStyleSheetOwner::Document(document),- index,+ client_id,) {callback(record);}@@ -342,12 +396,16 @@ impl AdoptedStyleSheetSources {if !lifecycle_owner.retained_source_records_are_available(host) {continue;}- for index in 0..sources.len() {- let source_id = StyleSourceId::shadow_root_adopted_style_sheet(root, index);+ for source in sources {+ let client_id = source+ .source()+ .adopted_client_id()+ .expect("installed adopted stylesheet must have a client id");+ let source_id = StyleSourceId::shadow_root_adopted_style_sheet(root, client_id);if let Some(record) = self.retained_source_record(source_id,AdoptedStyleSheetOwner::ShadowRoot(root),- index,+ client_id,) {callback(record);}@@ -480,19 +538,19 @@ impl AdoptedStyleSheetSources {match (&source_id.scope_id, &source_id.kind) {(super::super::source_id::StyleScopeId::Document(document),- super::super::source_id::StyleSourceKind::DocumentAdoptedStyleSheet { index },+ super::super::source_id::StyleSourceKind::DocumentAdoptedStyleSheet { client_id },) => self.retained_source_record(source_id.clone(),AdoptedStyleSheetOwner::Document(*document),- *index,+ *client_id,),(super::super::source_id::StyleScopeId::ShadowRoot(root),- super::super::source_id::StyleSourceKind::ShadowRootAdoptedStyleSheet { index },+ super::super::source_id::StyleSourceKind::ShadowRootAdoptedStyleSheet { client_id },) => self.retained_source_record(source_id.clone(),AdoptedStyleSheetOwner::ShadowRoot(*root),- *index,+ *client_id,),_ => None,}@@ -519,7 +577,7 @@ impl AdoptedStyleSheetSources {Some(lifecycle_owner.tracked_entry(host, || {self.tracked_source_ids(AdoptedStyleSheetOwner::Document(document),- |index| StyleSourceId::document_adopted_style_sheet(document, index),+ |client_id| StyleSourceId::document_adopted_style_sheet(document, client_id),StyleSourceLifecycleWithoutSourceReason::EmptyDocumentAdoptedStyleSheets,)}))@@ -537,7 +595,7 @@ impl AdoptedStyleSheetSources {Some(lifecycle_owner.tracked_entry(host, || {self.tracked_source_ids(AdoptedStyleSheetOwner::ShadowRoot(root),- |index| StyleSourceId::shadow_root_adopted_style_sheet(root, index),+ |client_id| StyleSourceId::shadow_root_adopted_style_sheet(root, client_id),StyleSourceLifecycleWithoutSourceReason::EmptyShadowRootAdoptedStyleSheets,)}))@@ -546,16 +604,44 @@ impl AdoptedStyleSheetSources {fn tracked_source_ids(&self,owner: AdoptedStyleSheetOwner,- make_source_id: impl Fn(usize) -> StyleSourceId,+ make_source_id: impl Fn(u64) -> StyleSourceId,empty_reason: StyleSourceLifecycleWithoutSourceReason,) -> TrackedStyleSourceIds {let Some(sources) = self.sources(owner) else {return TrackedStyleSourceIds::WithoutSource(empty_reason);};- let source_ids: Vec<_> = (0..sources.len()).map(make_source_id).collect();+ let source_ids = sources+ .iter()+ .map(|client| {+ make_source_id(+ client+ .source()+ .adopted_client_id()+ .expect("installed adopted stylesheet must have a client id"),+ )+ })+ .collect();TrackedStyleSourceIds::retained_or_without_source(source_ids, empty_reason)}+ fn source_ids(+ &self,+ owner: AdoptedStyleSheetOwner,+ make_source_id: impl Fn(u64) -> StyleSourceId,+ ) -> Vec<StyleSourceId> {+ self.sources_or_empty(owner)+ .iter()+ .map(|client| {+ make_source_id(+ client+ .source()+ .adopted_client_id()+ .expect("installed adopted stylesheet must have a client id"),+ )+ })+ .collect()+ }+fn tracked_shadow_roots_for_document<'a>(&'a self,host: &'a DomHost,@@ -604,7 +690,10 @@ mod tests {};use super::{AdoptedStyleSheetInstallation, AdoptedStyleSheetSources};- use crate::{dom::native::NativeNodeId, live_stylesheet::LiveStylesheetRegistry};+ use crate::{+ dom::native::NativeNodeId, live_stylesheet::LiveStylesheetRegistry,+ style_engine::StyleSourceId,+ };fn live_stylesheet(registry: &LiveStylesheetRegistry,@@ -643,6 +732,15 @@ mod tests {assert_eq!(initial_ids.len(), 3);assert_ne!(initial_ids[0], initial_ids[1]);assert_ne!(initial_ids[1], initial_ids[2]);+ assert_eq!(+ sources.document_source_ids(document),+ initial_ids+ .iter()+ .map(|client_id| {+ StyleSourceId::document_adopted_style_sheet(document, *client_id)+ })+ .collect::<Vec<_>>()+ );assert!(ServoArc::ptr_eq(&initial[0].parsed_stylesheet().unwrap(),&first.stylesheet(),@@ -668,6 +766,13 @@ mod tests {.collect::<Vec<_>>(),vec![initial_ids[2], initial_ids[0], initial_ids[1]],);+ assert_eq!(+ sources.document_source_ids(document),+ [initial_ids[2], initial_ids[0], initial_ids[1]]+ .into_iter()+ .map(|client_id| StyleSourceId::document_adopted_style_sheet(document, client_id))+ .collect::<Vec<_>>()+ );assert!(sources.set_document_installations(document,diff --git a/moli-renderer-v8/src/style_engine/source/mod.rs b/moli-renderer-v8/src/style_engine/source/mod.rsindex cce5879e1..a04ab72d5 100644--- a/moli-renderer-v8/src/style_engine/source/mod.rs+++ b/moli-renderer-v8/src/style_engine/source/mod.rs@@ -15,8 +15,8 @@ use crate::{use self::adopted::AdoptedStyleSheetInstallation;use self::store::StyloStylesheetSource;use super::{- MoliStyleEngine, source_owner::stylesheet_source_base_url,- source_scope_plan::StyleSourceScopeCleanupPlan,+ MoliStyleEngine, source_dirty::StyleSourceDirtyReason, source_id::StyleScopeId,+ source_owner::stylesheet_source_base_url, source_scope_plan::StyleSourceScopeCleanupPlan,};impl MoliStyleEngine {@@ -48,6 +48,33 @@ impl MoliStyleEngine {)}+ #[cfg(test)]+ pub(crate) fn document_adopted_style_sheet_source_ids_for_test(+ &self,+ document: DomHandle,+ ) -> Vec<super::StyleSourceId> {+ self.world_for_document(document)+ .adopted_style_sheet_sources+ .borrow()+ .document_source_ids(document)+ }++ #[cfg(test)]+ pub(crate) fn shadow_root_adopted_style_sheet_source_ids_for_test(+ &self,+ host: &DomHost,+ root: DomHandle,+ ) -> Vec<super::StyleSourceId> {+ self.owner_document_world(host, root)+ .map(|world| {+ world+ .adopted_style_sheet_sources+ .borrow()+ .shadow_root_source_ids(root)+ })+ .unwrap_or_default()+ }+#[cfg(test)]pub(crate) fn linked_stylesheet_owner_registry_counts_for_document_for_test(&self,@@ -60,52 +87,54 @@ impl MoliStyleEngine {}#[cfg(test)]- pub(crate) fn set_document_adopted_style_sheet_sources_with_host(+ pub(crate) fn set_document_adopted_style_sheet_sources(&mut self,- host: &DomHost,document: DomHandle,sources: Vec<StyloStylesheetSource>,) {let world = self.world_for_document(document);- let previous_source_count = world+ let previous_source_ids = world.adopted_style_sheet_sources.borrow()- .document_source_count(document);- let next_source_count = sources.len();+ .document_source_ids(document);if world.adopted_style_sheet_sources.borrow_mut().set_document_sources(document, sources){- self.invalidate_document_stylesheet_set_for_document_with_host(- host,+ let next_source_ids = world+ .adopted_style_sheet_sources+ .borrow()+ .document_source_ids(document);+ self.invalidate_document_stylesheet_set_for_document(document,- previous_source_count.max(next_source_count),+ previous_source_ids.into_iter().chain(next_source_ids),);}}- pub(crate) fn set_document_adopted_style_sheet_installations_with_host(+ pub(crate) fn set_document_adopted_style_sheet_installations(&mut self,- host: &DomHost,document: DomHandle,installations: Vec<AdoptedStyleSheetInstallation>,) {let world = self.world_for_document(document);- let previous_source_count = world+ let previous_source_ids = world.adopted_style_sheet_sources.borrow()- .document_source_count(document);- let next_source_count = installations.len();+ .document_source_ids(document);if world.adopted_style_sheet_sources.borrow_mut().set_document_installations(document, installations){- self.invalidate_document_stylesheet_set_for_document_with_host(- host,+ let next_source_ids = world+ .adopted_style_sheet_sources+ .borrow()+ .document_source_ids(document);+ self.invalidate_document_stylesheet_set_for_document(document,- previous_source_count.max(next_source_count),+ previous_source_ids.into_iter().chain(next_source_ids),);}}@@ -177,7 +206,7 @@ impl MoliStyleEngine {.replace_processed_source(owner, css_text, parser_base);self.invalidate_owner_stylesheet_set_for_owner_with_host(host, owner);for previous_document in previous_documents {- self.invalidate_author_stylesheet_set_for_document_with_host(host, previous_document);+ self.mark_document_stylesheet_set_dirty(previous_document);}}@@ -207,7 +236,7 @@ impl MoliStyleEngine {self.invalidate_owner_stylesheet_set_for_owner_with_host(host, owner);}for previous_document in previous_documents {- self.invalidate_author_stylesheet_set_for_document_with_host(host, previous_document);+ self.mark_document_stylesheet_set_dirty(previous_document);}}@@ -496,6 +525,7 @@ impl MoliStyleEngine {DomStylesheetOwnerChangeKind::Unregistered| DomStylesheetOwnerChangeKind::TreeConnectionChanged { connected: false }) {+ self.remove_owner_style_sheet_source(owner);let previous_documents = self.linked_stylesheet_owner_documents(owner);self.remove_linked_stylesheet_owner_from_documents(host,@@ -777,20 +807,23 @@ impl MoliStyleEngine {let Some(world) = self.owner_document_world(host, root) else {return;};- let previous_source_count = world+ let previous_source_ids = world.adopted_style_sheet_sources.borrow()- .shadow_root_source_count(root);- let next_source_count = sources.len();+ .shadow_root_source_ids(root);if world.adopted_style_sheet_sources.borrow_mut().set_shadow_root_sources(root, sources){+ let next_source_ids = world+ .adopted_style_sheet_sources+ .borrow()+ .shadow_root_source_ids(root);self.invalidate_shadow_root_stylesheet_set_for_owner_with_host(host,root,- previous_source_count.max(next_source_count),+ previous_source_ids.into_iter().chain(next_source_ids),);}}@@ -804,20 +837,23 @@ impl MoliStyleEngine {let Some(world) = self.owner_document_world(host, root) else {return;};- let previous_source_count = world+ let previous_source_ids = world.adopted_style_sheet_sources.borrow()- .shadow_root_source_count(root);- let next_source_count = installations.len();+ .shadow_root_source_ids(root);if world.adopted_style_sheet_sources.borrow_mut().set_shadow_root_installations(root, installations){+ let next_source_ids = world+ .adopted_style_sheet_sources+ .borrow()+ .shadow_root_source_ids(root);self.invalidate_shadow_root_stylesheet_set_for_owner_with_host(host,root,- previous_source_count.max(next_source_count),+ previous_source_ids.into_iter().chain(next_source_ids),);}}@@ -848,25 +884,24 @@ impl MoliStyleEngine {.tracks_shadow_root(root)}- pub(crate) fn invalidate_author_stylesheet_set_for_document_with_host(- &mut self,- host: &DomHost,- document: DomHandle,- ) {+ pub(crate) fn mark_document_stylesheet_set_dirty(&mut self, document: DomHandle) {let world = self.world_for_document(document);world.document_state.bump_source_set_generation();- self.invalidate_author_stylesheet_set_for_world_with_host(host, &world);+ world.document_state.record_source_dirty_scope(+ StyleScopeId::Document(document),+ StyleSourceDirtyReason::DocumentStyleSheets,+ std::iter::empty(),+ [document],+ );}- fn invalidate_document_stylesheet_set_for_document_with_host(+ fn invalidate_document_stylesheet_set_for_document(&mut self,- host: &DomHost,document: DomHandle,- source_count: usize,+ source_ids: impl IntoIterator<Item = super::StyleSourceId>,) {- let plan =- StyleSourceScopeCleanupPlan::document_adopted_stylesheets(document, source_count);- self.apply_source_scope_cleanup_plan_with_host(host, plan);+ let plan = StyleSourceScopeCleanupPlan::document_adopted_stylesheets(document, source_ids);+ self.apply_source_scope_cleanup_plan(plan);}fn invalidate_owner_stylesheet_set_for_owner_with_host(@@ -875,7 +910,7 @@ impl MoliStyleEngine {owner: DomHandle,) {let plan = StyleSourceScopeCleanupPlan::owner_stylesheet(host, owner);- self.apply_source_scope_cleanup_plan_with_host(host, plan);+ self.apply_source_scope_cleanup_plan(plan);}fn invalidate_linked_stylesheet_set_for_owner_handles_with_host(@@ -885,27 +920,23 @@ impl MoliStyleEngine {) {let plan =StyleSourceScopeCleanupPlan::linked_stylesheet_owners(host, owners.iter().copied());- self.apply_source_scope_cleanup_plan_with_host(host, plan);+ self.apply_source_scope_cleanup_plan(plan);}fn invalidate_shadow_root_stylesheet_set_for_owner_with_host(&mut self,host: &DomHost,root: DomHandle,- source_count: usize,+ source_ids: impl IntoIterator<Item = super::StyleSourceId>,) {let plan =- StyleSourceScopeCleanupPlan::shadow_root_adopted_stylesheets(host, root, source_count);- self.apply_source_scope_cleanup_plan_with_host(host, plan);+ StyleSourceScopeCleanupPlan::shadow_root_adopted_stylesheets(host, root, source_ids);+ self.apply_source_scope_cleanup_plan(plan);}- fn apply_source_scope_cleanup_plan_with_host(- &mut self,- host: &DomHost,- plan: StyleSourceScopeCleanupPlan,- ) {+ fn apply_source_scope_cleanup_plan(&mut self, plan: StyleSourceScopeCleanupPlan) {for document in plan.full_documents() {- self.invalidate_author_stylesheet_set_for_document_with_host(host, document);+ self.mark_document_stylesheet_set_dirty(document);}let mut source_set_generation_bumped_documents = HashSet::new();for entry in plan.scoped_entries_by_document() {@@ -915,35 +946,15 @@ impl MoliStyleEngine {world.document_state.bump_source_set_generation();}let roots = entry.roots().clone();- let cache_write_generation = world.computed_style_cache.write_generation();- let cache_cleanup_already_applied = world- .document_state- .source_dirty_scope_snapshot()- .cache_cleanup_covers(roots.iter().copied(), cache_write_generation);- if !cache_cleanup_already_applied {- self.cache_cleanup_for_world(&world)- .clear_for_scoped_retained_style_system_rebuild(host, roots.iter().copied());- }world.document_state.record_source_dirty_scope(entry.scope_id(),entry.reason(),entry.source_ids(),roots.iter().copied(),- cache_write_generation,);}}- pub(super) fn invalidate_author_stylesheet_set_for_world_with_host(- &self,- host: &DomHost,- world: &super::document_world::DocumentStyleWorld,- ) {- world.pending_invalidations.clear();- self.cache_cleanup_for_world(world)- .clear_for_author_stylesheet_set_change(host);- }-fn remove_linked_stylesheet_owner_from_document(&self,document: DomHandle,@@ -994,6 +1005,24 @@ impl MoliStyleEngine {documents}+ fn remove_owner_style_sheet_source(&mut self, owner: DomHandle) {+ let Some(document) = self+ .owner_stylesheet_source_documents+ .borrow_mut()+ .remove(&owner)+ else {+ return;+ };+ if self+ .world_for_document(document)+ .owner_style_sheet_sources+ .borrow_mut()+ .remove_owner(owner)+ {+ self.mark_document_stylesheet_set_dirty(document);+ }+ }+fn migrate_inline_style_metadata_to_current_owner_document_with_host(&self,host: &DomHost,@@ -1100,7 +1129,7 @@ impl MoliStyleEngine {if Some(document) == scoped_cleanup_document {continue;}- self.invalidate_author_stylesheet_set_for_document_with_host(host, document);+ self.mark_document_stylesheet_set_dirty(document);}}}diff --git a/moli-renderer-v8/src/style_engine/source/shared_cache.rs b/moli-renderer-v8/src/style_engine/source/shared_cache.rsindex edc5e2e3b..c12f03956 100644--- a/moli-renderer-v8/src/style_engine/source/shared_cache.rs+++ b/moli-renderer-v8/src/style_engine/source/shared_cache.rs@@ -8,7 +8,7 @@ use moli_crypto::Sha256Context;use moli_selector::StyloSourceDependencySummary;use parking_lot::Mutex;-use super::super::{retained::style_source_metadata_for_css_text, system::StyleSystemSourceKey};+use super::super::{source_key::StyleSourceKey, stylesheet::style_source_metadata_for_css_text};use super::store::{StyleSourceMetadata, StylesheetFontFaceDescriptor};const RETAINED_BYTES_LIMIT: usize = 64 * 1024;@@ -36,6 +36,7 @@ struct SharedStyleSourceMetadata {css_fingerprint: [u8; 32],source_dependency_summary: Arc<StyloSourceDependencySummary>,font_faces: Arc<[StylesheetFontFaceDescriptor]>,+ import_urls: Arc<[url::Url]>,}#[derive(Debug)]@@ -59,6 +60,7 @@ pub(super) fn shared_style_source_contents(let source = Arc::new(SharedStyleSourceContents {source_metadata: SharedStyleSourceMetadata::from_metadata(&css_text,+ &base_url,key.css_fingerprint,metadata,),@@ -97,6 +99,10 @@ impl SharedStyleSourceContents {Arc::clone(&self.source_metadata.font_faces)}+ pub(super) fn import_urls(&self) -> Arc<[url::Url]> {+ Arc::clone(&self.source_metadata.import_urls)+ }+fn matches_input(&self, css_text: &str, base_url: &url::Url) -> bool {self.css_text.as_ref() == css_text && self.base_url.as_ref() == base_url}@@ -105,6 +111,7 @@ impl SharedStyleSourceContents {impl SharedStyleSourceMetadata {fn from_metadata(css_text: &str,+ base_url: &url::Url,css_fingerprint: [u8; 32],metadata: StyleSourceMetadata,) -> Self {@@ -116,6 +123,11 @@ impl SharedStyleSourceMetadata {.map(|face| StylesheetFontFaceDescriptor::new(face.family, face.source)).collect::<Vec<_>>().into(),+ import_urls: super::imports::stylesheet_top_level_import_urls(+ css_text, base_url, false,+ )+ .unwrap_or_default()+ .into(),}}}@@ -124,7 +136,7 @@ impl SharedStyleSourceCacheKey {fn new(css_text: &str, base_url: &url::Url) -> Self {let base_url = base_url.as_str();Self {- css_fingerprint: StyleSystemSourceKey::css_fingerprint(css_text),+ css_fingerprint: StyleSourceKey::css_fingerprint(css_text),css_text_len: css_text.len(),base_url_fingerprint: fingerprint(base_url),base_url_len: base_url.len(),@@ -248,6 +260,7 @@ mod tests {let source = Arc::new(SharedStyleSourceContents {source_metadata: SharedStyleSourceMetadata::from_metadata(&css_text,+ &base_url,key.css_fingerprint,metadata,),diff --git a/moli-renderer-v8/src/style_engine/source/store.rs b/moli-renderer-v8/src/style_engine/source/store.rsindex a0af69a1a..b05a3796b 100644--- a/moli-renderer-v8/src/style_engine/source/store.rs+++ b/moli-renderer-v8/src/style_engine/source/store.rs@@ -5,10 +5,11 @@ use std::{use moli_crypto::Sha256Context;use moli_selector::StyloSourceDependencySummary;+use style::stylesheets::{CssRule, StylesheetInDocument};use super::super::{source_id::{StyleScopeId, StyleSourceId, StyleSourceKind},- system::{StyleSystemSourceKey, StyleSystemSourceSetKey},+ source_key::{StyleSourceKey, StyleSourceSetKey},};use super::imports::stylesheet_top_level_import_urls;use super::shared_cache::{SharedStyleSourceContents, shared_style_source_contents};@@ -31,7 +32,7 @@ pub(crate) struct StyloStylesheetSource {/// Stable URL exposed by the top-level `CSSStyleSheet.href`.sheet_url: StdArc<url::Url>,origin_clean: bool,- cache_key: StyleSystemSourceKey,+ cache_key: StyleSourceKey,source_id: Option<StyleSourceId>,adopted_client_id: Option<u64>,}@@ -46,11 +47,20 @@ enum StyloStylesheetSourceContents {id: crate::live_stylesheet::StylesheetId,contents_revision: u64,cascade_generation: u64,+ cascade_mutations: StdArc<+ parking_lot::Mutex<Vec<crate::live_stylesheet::LiveStylesheetCascadeMutationBatch>>,+ >,derived_state: StdArc<crate::live_stylesheet::LiveStylesheetDerivedState>,shared_initial_contents: Option<StdArc<crate::live_stylesheet::SharedStylesheetContents>>,},}+#[derive(Clone, Debug)]+pub(in crate::style_engine) enum LiveStylesheetCascadeUpdate {+ Full,+ Rules(Vec<crate::live_stylesheet::LiveStylesheetRuleMutation>),+}+#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]pub(in crate::style_engine) struct StyleSourceMetadata {pub(in crate::style_engine) dependency_summary: StyloSourceDependencySummary,@@ -73,7 +83,7 @@ impl StyloStylesheetSource {pub(crate) fn new(css_text: String, base_url: url::Url) -> Self {let shared = shared_style_source_contents(css_text, base_url);let cache_key =- StyleSystemSourceKey::from_css_fingerprint(shared.css_fingerprint(), shared.base_url());+ StyleSourceKey::from_css_fingerprint(shared.css_fingerprint(), shared.base_url());let base_url = shared.base_url_handle();Self {contents: StyloStylesheetSourceContents::Text { shared },@@ -96,13 +106,14 @@ impl StyloStylesheetSource {id: stylesheet.id(),contents_revision: stylesheet.contents_revision(),cascade_generation: stylesheet.cascade_generation(),+ cascade_mutations: stylesheet.cascade_mutation_journal(),derived_state: stylesheet.derived_state(),shared_initial_contents: stylesheet.shared_initial_contents(),},base_url: StdArc::new(base_url.clone()),sheet_url: StdArc::new(base_url),origin_clean: true,- cache_key: StyleSystemSourceKey::from_live_stylesheet(+ cache_key: StyleSourceKey::from_live_stylesheet(stylesheet.id(),stylesheet.cascade_generation(),),@@ -152,6 +163,28 @@ impl StyloStylesheetSource {}}+ /// Projects this source into an independently parsed text source.+ ///+ /// A live stylesheet is owned by the `SharedRwLock` of the retained style+ /// world that parsed it. Passing that object to another `MoliStyleEngine`+ /// would pair it with an unrelated guard. Compatibility probes that use an+ /// isolated engine therefore serialize live sources at that boundary and+ /// let the isolated engine parse its own stylesheet object.+ pub(crate) fn independent_text_projection(&self) -> Self {+ let StyloStylesheetSourceContents::Live { .. } = &self.contents else {+ return self.clone();+ };+ let mut projection = Self::new(+ self.serialized_css_text().to_string(),+ self.base_url.as_ref().clone(),+ )+ .with_source_id(self.source_id.clone())+ .with_origin_clean(self.origin_clean)+ .with_sheet_url(self.sheet_url.as_ref().clone());+ projection.adopted_client_id = self.adopted_client_id;+ projection+ }+fn processing_contents(&self) -> Option<&SharedStyleSourceContents> {match &self.contents {StyloStylesheetSourceContents::Text { shared } => Some(shared),@@ -175,6 +208,64 @@ impl StyloStylesheetSource {}}+ pub(in crate::style_engine) fn live_cascade_update_since(+ &self,+ previous: &Self,+ ) -> LiveStylesheetCascadeUpdate {+ let (+ StyloStylesheetSourceContents::Live {+ id,+ cascade_generation,+ cascade_mutations,+ ..+ },+ StyloStylesheetSourceContents::Live {+ id: previous_id,+ cascade_generation: previous_generation,+ ..+ },+ ) = (&self.contents, &previous.contents)+ else {+ return LiveStylesheetCascadeUpdate::Full;+ };+ if id != previous_id || previous_generation >= cascade_generation {+ return LiveStylesheetCascadeUpdate::Full;+ }++ let cascade_mutations = cascade_mutations.lock();+ let batches = cascade_mutations+ .iter()+ .filter(|batch| {+ batch.generation() > *previous_generation+ && batch.generation() <= *cascade_generation+ })+ .collect::<Vec<_>>();+ let expected_batch_count = cascade_generation.saturating_sub(*previous_generation);+ if batches.len() as u64 != expected_batch_count+ || batches+ .first()+ .is_none_or(|batch| batch.generation() != previous_generation.saturating_add(1))+ || batches+ .last()+ .is_none_or(|batch| batch.generation() != *cascade_generation)+ {+ return LiveStylesheetCascadeUpdate::Full;+ }++ let mut rules = Vec::new();+ for batch in batches {+ match batch.mutation() {+ crate::live_stylesheet::LiveStylesheetCascadeMutation::Full => {+ return LiveStylesheetCascadeUpdate::Full;+ }+ crate::live_stylesheet::LiveStylesheetCascadeMutation::Rules(changes) => {+ rules.extend(changes.iter().cloned());+ }+ }+ }+ LiveStylesheetCascadeUpdate::Rules(rules)+ }+pub(crate) fn shared_initial_contents(&self,) -> Option<StdArc<crate::live_stylesheet::SharedStylesheetContents>> {@@ -199,7 +290,7 @@ impl StyloStylesheetSource {self.origin_clean}- pub(in crate::style_engine) fn cache_key(&self) -> StyleSystemSourceKey {+ pub(in crate::style_engine) fn cache_key(&self) -> StyleSourceKey {self.cache_key}@@ -218,7 +309,7 @@ impl StyloStylesheetSource {*contents_revision,*cascade_generation,|| {- super::super::retained::style_source_metadata_for_stylesheet(stylesheet)+ super::super::stylesheet::style_source_metadata_for_stylesheet(stylesheet).dependency_summary},),@@ -234,6 +325,28 @@ impl StyloStylesheetSource {}}+ pub(crate) fn import_urls(&self) -> StdArc<[url::Url]> {+ match &self.contents {+ StyloStylesheetSourceContents::Text { shared } => shared.import_urls(),+ StyloStylesheetSourceContents::Live { stylesheet, .. } => {+ let guard = stylesheet.shared_lock.read();+ let mut urls = Vec::new();+ for rule in stylesheet.contents(&guard).rules(&guard) {+ let CssRule::Import(rule) = rule else {+ continue;+ };+ let Some(url) = rule.read_with(&guard).url.url() else {+ continue;+ };+ if !urls.iter().any(|existing| existing == url.as_ref()) {+ urls.push(url.as_ref().clone());+ }+ }+ urls.into()+ }+ }+ }+pub(in crate::style_engine) fn source_id(&self) -> Option<&StyleSourceId> {self.source_id.as_ref()}@@ -248,7 +361,7 @@ impl StyloStylesheetSource {})}- pub(in crate::style_engine) fn adopted_client_id(&self) -> Option<u64> {+ pub(crate) fn adopted_client_id(&self) -> Option<u64> {self.adopted_client_id}@@ -265,6 +378,24 @@ impl StyloStylesheetSource {}}+ pub(in crate::style_engine) fn has_same_stylesheet_revision(&self, other: &Self) -> bool {+ self.base_url == other.base_url+ && self.sheet_url == other.sheet_url+ && self.origin_clean == other.origin_clean+ && self.cache_key == other.cache_key+ && match (&self.contents, &other.contents) {+ (+ StyloStylesheetSourceContents::Text { shared: left },+ StyloStylesheetSourceContents::Text { shared: right },+ ) => left == right,+ (+ StyloStylesheetSourceContents::Live { .. },+ StyloStylesheetSourceContents::Live { .. },+ ) => true,+ _ => false,+ }+ }+#[cfg(test)]pub(in crate::style_engine) fn shares_source_storage_for_test(&self, other: &Self) -> bool {match (&self.contents, &other.contents) {@@ -408,7 +539,7 @@ impl OwnerStyleSheetSource {pub(in crate::style_engine) fn stylesheet_sources_cache_key(sources: &[StyloStylesheetSource],-) -> StyleSystemSourceSetKey {+) -> StyleSourceSetKey {let mut hasher = Sha256Context::new();hasher.update(sources.len().to_le_bytes());for source in sources {@@ -422,7 +553,7 @@ pub(in crate::style_engine) fn stylesheet_sources_cache_key(None => hasher.update([0]),}}- StyleSystemSourceSetKey {+ StyleSourceSetKey {len: sources.len(),fingerprint: hasher.finish(),}@@ -447,13 +578,13 @@ fn update_style_source_identity_hash(hasher.update([1]);hasher.update(owner.index().to_le_bytes());}- StyleSourceKind::DocumentAdoptedStyleSheet { index } => {+ StyleSourceKind::DocumentAdoptedStyleSheet { client_id } => {hasher.update([2]);- hasher.update(index.to_le_bytes());+ hasher.update(client_id.to_le_bytes());}- StyleSourceKind::ShadowRootAdoptedStyleSheet { index } => {+ StyleSourceKind::ShadowRootAdoptedStyleSheet { client_id } => {hasher.update([3]);- hasher.update(index.to_le_bytes());+ hasher.update(client_id.to_le_bytes());}}}diff --git a/moli-renderer-v8/src/style_engine/source_cascade.rs b/moli-renderer-v8/src/style_engine/source_cascade.rsnew file mode 100644index 000000000..06b03c53c--- /dev/null+++ b/moli-renderer-v8/src/style_engine/source_cascade.rs@@ -0,0 +1,234 @@+use std::collections::{HashMap, HashSet};++use style::{+ author_styles::AuthorStyles,+ servo_arc::Arc as ServoArc,+ shared_lock::SharedRwLock,+ stylesheets::{CustomMediaMap, DocumentStyleSheet},+ stylist::{CascadeData, Stylist},+};++use super::{+ active_stylesheets::{ActiveStylesheet, ActiveStylesheetCollection},+ shadow_scopes::ShadowScopeStyles,+ source::store::{StyloStylesheetSource, stylesheet_sources_cache_key},+ source_id::{StyleScopeId, StyleSourceId},+ source_key::StyleSourceSetKey,+ source_record::RetainedStylesheetSourceRecord,+ state::RetainedStyleSystem,+};++type SourceCascadeMaps = (+ HashMap<StyleSourceId, ServoArc<CascadeData>>,+ HashMap<StyleSourceId, StyleSourceSetKey>,+);++type InstalledSourceGroup = (Vec<StyloStylesheetSource>, Vec<DocumentStyleSheet>);++#[cfg(test)]+thread_local! {+ static SOURCE_CASCADE_REBUILD_COUNT: std::cell::Cell<usize> = const {+ std::cell::Cell::new(0)+ };+}++#[cfg(test)]+pub(crate) fn reset_source_cascade_rebuild_count_for_test() {+ SOURCE_CASCADE_REBUILD_COUNT.with(|count| count.set(0));+}++#[cfg(test)]+pub(crate) fn source_cascade_rebuild_count_for_test() -> usize {+ SOURCE_CASCADE_REBUILD_COUNT.with(std::cell::Cell::get)+}++/// Builds the per-source cascade projection used by CSSOM target queries.+///+/// The document and shadow collections remain the canonical installed-sheet+/// state. Source records are included only when CSSOM still owns a detached or+/// otherwise inactive sheet that must remain queryable.+pub(super) fn build_source_cascade_data(+ stylist: &mut Stylist,+ shared_lock: &SharedRwLock,+ document_stylesheets: &ActiveStylesheetCollection,+ shadow_scopes: &[ShadowScopeStyles],+ retained_source_records: &[RetainedStylesheetSourceRecord<'_>],+ previous: Option<(&SourceCascadeData, &SourceCascadeKeys)>,+ mut install: impl FnMut(&StyloStylesheetSource) -> ActiveStylesheet,+) -> SourceCascadeMaps {+ let mut sources_by_id =+ installed_sources_by_id(document_stylesheets, shadow_scopes, None, None);+ add_retained_source_records(+ &mut sources_by_id,+ retained_source_records,+ None,+ None,+ &mut install,+ );++ let mut cascade_data = HashMap::with_capacity(sources_by_id.len());+ let mut cascade_keys = HashMap::with_capacity(sources_by_id.len());+ for (source_id, (sources, stylesheets)) in sources_by_id {+ let key = stylesheet_sources_cache_key(&sources);+ let retained_data = previous.and_then(|(previous_data, previous_keys)| {+ (previous_keys.get(&source_id) == Some(&key))+ .then(|| previous_data.get(&source_id).cloned())+ .flatten()+ });+ let data = retained_data+ .unwrap_or_else(|| build_author_cascade_data(stylist, shared_lock, &stylesheets));+ cascade_keys.insert(source_id.clone(), key);+ cascade_data.insert(source_id, data);+ }+ (cascade_data, cascade_keys)+}++/// Reprojects only sources owned by dirty TreeScopes. Entries belonging to a+/// clean scope retain both their key and `CascadeData` allocation.+pub(super) fn update_source_cascade_data_for_scopes(+ retained: &mut RetainedStyleSystem,+ shared_lock: &SharedRwLock,+ retained_source_records: &[RetainedStylesheetSourceRecord<'_>],+ dirty_source_ids: &HashSet<StyleSourceId>,+ dirty_scopes: &HashSet<StyleScopeId>,+ mut install: impl FnMut(&StyloStylesheetSource) -> ActiveStylesheet,+) {+ if dirty_source_ids.is_empty() && dirty_scopes.is_empty() {+ return;+ }++ let previous_data = std::mem::take(&mut retained.source_cascade_data);+ let previous_keys = std::mem::take(&mut retained.source_cascade_keys);+ let mut next_data = retain_clean_entries(&previous_data, dirty_source_ids, dirty_scopes);+ let mut next_keys = retain_clean_entries(&previous_keys, dirty_source_ids, dirty_scopes);++ let mut sources_by_id = installed_sources_by_id(+ &retained.document_stylesheets,+ &retained.shadow_scopes,+ Some(dirty_source_ids),+ Some(dirty_scopes),+ );+ add_retained_source_records(+ &mut sources_by_id,+ retained_source_records,+ Some(dirty_source_ids),+ Some(dirty_scopes),+ &mut install,+ );++ for (source_id, (sources, stylesheets)) in sources_by_id {+ let key = stylesheet_sources_cache_key(&sources);+ let data = if previous_keys.get(&source_id) == Some(&key) {+ previous_data.get(&source_id).cloned()+ } else {+ None+ }+ .unwrap_or_else(|| {+ build_author_cascade_data(&mut retained.stylist, shared_lock, &stylesheets)+ });+ next_keys.insert(source_id.clone(), key);+ next_data.insert(source_id, data);+ }+ retained.source_cascade_data = next_data;+ retained.source_cascade_keys = next_keys;+}++type SourceCascadeData = HashMap<StyleSourceId, ServoArc<CascadeData>>;+type SourceCascadeKeys = HashMap<StyleSourceId, StyleSourceSetKey>;++fn installed_sources_by_id(+ document_stylesheets: &ActiveStylesheetCollection,+ shadow_scopes: &[ShadowScopeStyles],+ dirty_source_ids: Option<&HashSet<StyleSourceId>>,+ dirty_scopes: Option<&HashSet<StyleScopeId>>,+) -> HashMap<StyleSourceId, InstalledSourceGroup> {+ let mut sources_by_id = HashMap::<StyleSourceId, InstalledSourceGroup>::new();+ for entry in document_stylesheets.entries().iter().chain(+ shadow_scopes+ .iter()+ .flat_map(|scope| scope.active_stylesheets().entries()),+ ) {+ let Some(source_id) = entry.source().source_id().cloned() else {+ continue;+ };+ if !source_needs_projection(&source_id, dirty_source_ids, dirty_scopes) {+ continue;+ }+ let (sources, stylesheets) = sources_by_id.entry(source_id).or_default();+ sources.push(entry.source().clone());+ stylesheets.push(entry.stylesheet().clone());+ }+ sources_by_id+}++fn add_retained_source_records(+ sources_by_id: &mut HashMap<StyleSourceId, InstalledSourceGroup>,+ records: &[RetainedStylesheetSourceRecord<'_>],+ dirty_source_ids: Option<&HashSet<StyleSourceId>>,+ dirty_scopes: Option<&HashSet<StyleScopeId>>,+ install: &mut impl FnMut(&StyloStylesheetSource) -> ActiveStylesheet,+) {+ for record in records {+ if !source_needs_projection(record.id(), dirty_source_ids, dirty_scopes)+ || sources_by_id.contains_key(record.id())+ {+ continue;+ }+ let source = record.to_stylo_source();+ let installed = install(&source);+ sources_by_id.insert(+ record.id().clone(),+ (vec![source], vec![installed.stylesheet().clone()]),+ );+ }+}++fn retain_clean_entries<T: Clone>(+ previous: &HashMap<StyleSourceId, T>,+ dirty_source_ids: &HashSet<StyleSourceId>,+ dirty_scopes: &HashSet<StyleScopeId>,+) -> HashMap<StyleSourceId, T> {+ previous+ .iter()+ .filter(|(source_id, _)| {+ !dirty_source_ids.contains(*source_id) && !dirty_scopes.contains(&source_id.scope_id)+ })+ .map(|(source_id, value)| (source_id.clone(), value.clone()))+ .collect()+}++fn source_needs_projection(+ source_id: &StyleSourceId,+ dirty_source_ids: Option<&HashSet<StyleSourceId>>,+ dirty_scopes: Option<&HashSet<StyleScopeId>>,+) -> bool {+ match (dirty_source_ids, dirty_scopes) {+ (None, None) => true,+ (dirty_source_ids, dirty_scopes) => {+ dirty_source_ids.is_some_and(|ids| ids.contains(source_id))+ || dirty_scopes.is_some_and(|scopes| scopes.contains(&source_id.scope_id))+ }+ }+}++fn build_author_cascade_data(+ stylist: &mut Stylist,+ shared_lock: &SharedRwLock,+ stylesheets: &[DocumentStyleSheet],+) -> ServoArc<CascadeData> {+ #[cfg(test)]+ SOURCE_CASCADE_REBUILD_COUNT.with(|count| count.set(count.get().saturating_add(1)));+ let mut author_styles = AuthorStyles::<DocumentStyleSheet>::new();+ let custom_media = CustomMediaMap::default();+ let guard = shared_lock.read();+ for stylesheet in stylesheets {+ author_styles.stylesheets.append_stylesheet(+ None,+ &custom_media,+ stylesheet.clone(),+ &guard,+ );+ }+ author_styles.flush(stylist, &guard);+ author_styles.data+}diff --git a/moli-renderer-v8/src/style_engine/source_dirty.rs b/moli-renderer-v8/src/style_engine/source_dirty.rsindex d4cd95b17..343e5cd14 100644--- a/moli-renderer-v8/src/style_engine/source_dirty.rs+++ b/moli-renderer-v8/src/style_engine/source_dirty.rs@@ -18,16 +18,17 @@ pub(super) struct StyleSourceDirtyScopeRecord {reason: StyleSourceDirtyReason,source_ids: IndexSet<StyleSourceId>,scoped_roots: IndexSet<DomHandle>,- cache_write_generation_at_cleanup: Option<u64>,clear_all_fallback_reasons: IndexSet<StyloSourceInvalidationFallbackReason>,}#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]pub(super) enum StyleSourceDirtyReason {+ DocumentStyleSheets,DocumentAdoptedStyleSheets,OwnerStyleSheet,LinkedStyleSheet,ShadowRootAdoptedStyleSheets,+ CustomPropertyRegistration,InvalidationClearAllFallback,}@@ -43,7 +44,6 @@ impl StyleSourceDirtyScopes {reason: StyleSourceDirtyReason,source_ids: impl IntoIterator<Item = StyleSourceId>,roots: impl IntoIterator<Item = DomHandle>,- cache_write_generation_at_cleanup: u64,) {let scoped_roots = roots.into_iter().collect::<IndexSet<_>>();self.records.borrow_mut().push(StyleSourceDirtyScopeRecord {@@ -51,7 +51,6 @@ impl StyleSourceDirtyScopes {reason,source_ids: source_ids.into_iter().collect(),scoped_roots,- cache_write_generation_at_cleanup: Some(cache_write_generation_at_cleanup),clear_all_fallback_reasons: IndexSet::new(),});}@@ -68,7 +67,6 @@ impl StyleSourceDirtyScopes {reason: StyleSourceDirtyReason::InvalidationClearAllFallback,source_ids: IndexSet::new(),scoped_roots: IndexSet::new(),- cache_write_generation_at_cleanup: None,clear_all_fallback_reasons: reasons.into_iter().collect(),});}@@ -91,12 +89,8 @@ impl StyleSourceDirtyScopes {}impl StyleSourceDirtyScopeSnapshot {- pub(super) fn has_only_scoped_source_records(&self) -> bool {- !self.records.is_empty() && self.records.iter().all(|record| record.scope_id.is_some())- }-- pub(super) fn contains_document_scope(&self, document: DomHandle) -> bool {- self.scope_ids().contains(&StyleScopeId::Document(document))+ pub(super) fn requires_retained_style_update(&self) -> bool {+ self.records.iter().any(|record| record.scope_id.is_some())}pub(super) fn scoped_roots_vec(&self) -> Vec<DomHandle> {@@ -107,6 +101,25 @@ impl StyleSourceDirtyScopeSnapshot {self.source_ids().into_iter().collect()}+ /// Scopes whose mutation did not provide stable source identities. These+ /// are explicit compatibility fallbacks; ordinary owner/adopted-sheet+ /// mutations carry exact IDs and avoid a scope-wide source projection.+ pub(super) fn full_source_projection_scope_ids(&self) -> IndexSet<StyleScopeId> {+ self.records+ .iter()+ .filter(|record| {+ record.scope_id.is_some()+ && record.source_ids.is_empty()+ && !matches!(+ record.reason,+ StyleSourceDirtyReason::CustomPropertyRegistration+ | StyleSourceDirtyReason::InvalidationClearAllFallback+ )+ })+ .filter_map(|record| record.scope_id)+ .collect()+ }+pub(super) fn scope_ids_vec(&self) -> Vec<StyleScopeId> {self.scope_ids().into_iter().collect()}@@ -119,6 +132,34 @@ impl StyleSourceDirtyScopeSnapshot {self.records.clone()}+ pub(super) fn refreshes_document_stylesheets(&self, document: DomHandle) -> bool {+ self.records.iter().any(|record| {+ record.scope_id == Some(StyleScopeId::Document(document))+ && !matches!(+ record.reason,+ StyleSourceDirtyReason::CustomPropertyRegistration+ | StyleSourceDirtyReason::InvalidationClearAllFallback+ )+ })+ }++ pub(super) fn dirty_shadow_roots(&self) -> IndexSet<DomHandle> {+ self.records+ .iter()+ .filter_map(|record| match record.scope_id {+ Some(StyleScopeId::ShadowRoot(root)) => Some(root),+ Some(StyleScopeId::Document(_)) | None => None,+ })+ .collect()+ }++ pub(super) fn refreshes_custom_property_registrations(&self, document: DomHandle) -> bool {+ self.records.iter().any(|record| {+ record.scope_id == Some(StyleScopeId::Document(document))+ && record.reason == StyleSourceDirtyReason::CustomPropertyRegistration+ })+ }+#[cfg(test)]pub(super) fn invalidation_clear_all_fallback_reasons_vec(&self,@@ -135,19 +176,6 @@ impl StyleSourceDirtyScopeSnapshot {.collect()}- pub(super) fn cache_cleanup_covers(- &self,- roots: impl IntoIterator<Item = DomHandle>,- current_cache_write_generation: u64,- ) -> bool {- roots.into_iter().all(|root| {- self.records.iter().any(|record| {- record.cache_write_generation_at_cleanup == Some(current_cache_write_generation)- && record.scoped_roots.contains(&root)- })- })- }-fn source_ids(&self) -> IndexSet<StyleSourceId> {self.records.iter()diff --git a/moli-renderer-v8/src/style_engine/source_document.rs b/moli-renderer-v8/src/style_engine/source_document.rsindex b9fdc753c..c4127630b 100644--- a/moli-renderer-v8/src/style_engine/source_document.rs+++ b/moli-renderer-v8/src/style_engine/source_document.rs@@ -8,12 +8,12 @@ use super::{StyleSourceId, StyleViewport,document_world::DocumentStyleWorld,request::RetainedSourceDependencyRequestPlan,- retained::moli_user_agent_source_dependency_summary,source::adopted::AdoptedStyleSheetSources,source::linked::LinkedStylesheetSources,source_lifecycle::{StyleSourceDocumentContext, StyleSourceLifecycleReport},source_owner_text::OwnerStyleSheetSources,source_record::{MatchingStyleDependencySource, RetainedStylesheetSourceRecord},+ stylesheet::moli_user_agent_source_dependency_summary,};pub(super) struct DocumentStyleSourceStores<'a> {diff --git a/moli-renderer-v8/src/style_engine/source_id.rs b/moli-renderer-v8/src/style_engine/source_id.rsindex 512fb4735..1d9210d0d 100644--- a/moli-renderer-v8/src/style_engine/source_id.rs+++ b/moli-renderer-v8/src/style_engine/source_id.rs@@ -30,8 +30,8 @@ pub(super) enum StyleScopeId {pub(super) enum StyleSourceKind {OwnerStyleSheet { owner: DomHandle },LinkedStyleSheet { owner: DomHandle },- DocumentAdoptedStyleSheet { index: usize },- ShadowRootAdoptedStyleSheet { index: usize },+ DocumentAdoptedStyleSheet { client_id: u64 },+ ShadowRootAdoptedStyleSheet { client_id: u64 },}impl StyleSourceId {@@ -49,17 +49,17 @@ impl StyleSourceId {})}- pub(crate) fn document_adopted_style_sheet(document: DomHandle, index: usize) -> Self {+ pub(crate) fn document_adopted_style_sheet(document: DomHandle, client_id: u64) -> Self {Self {scope_id: StyleScopeId::Document(document),- kind: StyleSourceKind::DocumentAdoptedStyleSheet { index },+ kind: StyleSourceKind::DocumentAdoptedStyleSheet { client_id },}}- pub(crate) fn shadow_root_adopted_style_sheet(root: DomHandle, index: usize) -> Self {+ pub(crate) fn shadow_root_adopted_style_sheet(root: DomHandle, client_id: u64) -> Self {Self {scope_id: StyleScopeId::ShadowRoot(root),- kind: StyleSourceKind::ShadowRootAdoptedStyleSheet { index },+ kind: StyleSourceKind::ShadowRootAdoptedStyleSheet { client_id },}}}diff --git a/moli-renderer-v8/src/style_engine/source_key.rs b/moli-renderer-v8/src/style_engine/source_key.rsnew file mode 100644index 000000000..db029a588--- /dev/null+++ b/moli-renderer-v8/src/style_engine/source_key.rs@@ -0,0 +1,54 @@+use moli_crypto::Sha256Context;++/// Revision key for one installed stylesheet source.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub(super) struct StyleSourceKey {+ pub(super) fingerprint: [u8; 32],+}++/// Ordered revision key used only by source-local CSSOM cascade projections.+///+/// This is deliberately not part of the Document style-world identity. The+/// persistent active collections and their dirty journals decide when the+/// Document world changes.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub(super) struct StyleSourceSetKey {+ pub(super) len: usize,+ pub(super) fingerprint: [u8; 32],+}++impl StyleSourceKey {+ pub(super) fn css_fingerprint(css_text: &str) -> [u8; 32] {+ let mut hasher = Sha256Context::new();+ let css_text = css_text.as_bytes();+ hasher.update(css_text.len().to_le_bytes());+ hasher.update(css_text);+ hasher.finish()+ }++ pub(super) fn from_css_fingerprint(css_fingerprint: [u8; 32], base_url: &url::Url) -> Self {+ let mut hasher = Sha256Context::new();+ hasher.update(css_fingerprint);+ let mut base_url = base_url.clone();+ base_url.set_fragment(None);+ let base_url = base_url.as_str().as_bytes();+ hasher.update(base_url.len().to_le_bytes());+ hasher.update(base_url);+ Self {+ fingerprint: hasher.finish(),+ }+ }++ pub(super) fn from_live_stylesheet(+ stylesheet_id: crate::live_stylesheet::StylesheetId,+ cascade_generation: u64,+ ) -> Self {+ let mut hasher = Sha256Context::new();+ hasher.update(b"live-stylesheet");+ hasher.update(stylesheet_id.get().to_le_bytes());+ hasher.update(cascade_generation.to_le_bytes());+ Self {+ fingerprint: hasher.finish(),+ }+ }+}diff --git a/moli-renderer-v8/src/style_engine/source_scope_plan.rs b/moli-renderer-v8/src/style_engine/source_scope_plan.rsindex 228f3c1de..b4aaaaee0 100644--- a/moli-renderer-v8/src/style_engine/source_scope_plan.rs+++ b/moli-renderer-v8/src/style_engine/source_scope_plan.rs@@ -22,14 +22,16 @@ pub(super) struct StyleSourceScopeCleanupPlanEntry {}impl StyleSourceScopeCleanupPlan {- pub(super) fn document_adopted_stylesheets(document: DomHandle, source_count: usize) -> Self {+ pub(super) fn document_adopted_stylesheets(+ document: DomHandle,+ source_ids: impl IntoIterator<Item = StyleSourceId>,+ ) -> Self {let mut plan = Self::default();plan.add_scoped_roots(document,StyleScopeId::Document(document),StyleSourceDirtyReason::DocumentAdoptedStyleSheets,- (0..source_count)- .map(|index| StyleSourceId::document_adopted_style_sheet(document, index)),+ source_ids,[document],);plan@@ -65,7 +67,7 @@ impl StyleSourceScopeCleanupPlan {pub(super) fn shadow_root_adopted_stylesheets(host: &DomHost,root: DomHandle,- source_count: usize,+ source_ids: impl IntoIterator<Item = StyleSourceId>,) -> Self {let mut plan = Self::default();let Some(document) = owner_document_for_source_owner(host, root) else {@@ -79,8 +81,7 @@ impl StyleSourceScopeCleanupPlan {document,StyleScopeId::ShadowRoot(root),StyleSourceDirtyReason::ShadowRootAdoptedStyleSheets,- (0..source_count)- .map(|index| StyleSourceId::shadow_root_adopted_style_sheet(root, index)),+ source_ids,roots,);}diff --git a/moli-renderer-v8/src/style_engine/state.rs b/moli-renderer-v8/src/style_engine/state.rsindex 0018e244c..34231e9a0 100644--- a/moli-renderer-v8/src/style_engine/state.rs+++ b/moli-renderer-v8/src/style_engine/state.rs@@ -13,17 +13,32 @@ use style::{use crate::document_runtime::DomHandle;use super::{+ CssCustomPropertyRegistrationRecord, StyleTreeScopeVersions, StyleViewport,+ StyloStyleEnvironment,+ active_stylesheets::ActiveStylesheetCollection,+ shadow_scopes::ShadowScopeStyles,source_dirty::{StyleSourceDirtyReason, StyleSourceDirtyScopeSnapshot, StyleSourceDirtyScopes},source_id::{StyleScopeId, StyleSourceId},- system::StyleSystemCacheKey,+ source_key::StyleSourceSetKey,+ stylesheet_resources::{+ StylesheetResourceGeneration, StylesheetResourceManifest, StylesheetResourceSnapshot,+ },+ world_key::StyleWorldKey,};pub(super) struct RetainedStyleSystem {- pub(super) key: StyleSystemCacheKey,+ pub(super) stylist_identity: u64,+ pub(super) key: StyleWorldKey,pub(super) stylist: Stylist,+ pub(super) document_stylesheets: ActiveStylesheetCollection,+ pub(super) shadow_scopes: Vec<ShadowScopeStyles>,+ pub(super) stylesheet_resources: StylesheetResourceManifest,+ pub(super) stylesheet_resource_revision: u64,pub(super) user_agent_cascade_data: ServoArc<CascadeData>,pub(super) shadow_cascade_data: Vec<(DomHandle, ServoArc<CascadeData>)>,pub(super) source_cascade_data: HashMap<StyleSourceId, ServoArc<CascadeData>>,+ pub(super) source_cascade_keys: HashMap<StyleSourceId, StyleSourceSetKey>,+ pub(super) script_custom_property_registrations: Vec<CssCustomPropertyRegistrationRecord>,}#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -44,6 +59,10 @@ pub(super) struct StyleDocumentState {target_context_epoch: Cell<u64>,#[cfg(test)]retained_style_system_rebuilds: Cell<u64>,+ #[cfg(test)]+ retained_style_system_updates: Cell<u64>,+ #[cfg(test)]+ element_style_resolutions: Cell<u64>,}impl StyleDocumentState {@@ -58,6 +77,10 @@ impl StyleDocumentState {target_context_epoch: Cell::new(0),#[cfg(test)]retained_style_system_rebuilds: Cell::new(0),+ #[cfg(test)]+ retained_style_system_updates: Cell::new(0),+ #[cfg(test)]+ element_style_resolutions: Cell::new(0),}}@@ -127,15 +150,9 @@ impl StyleDocumentState {reason: StyleSourceDirtyReason,source_ids: impl IntoIterator<Item = StyleSourceId>,roots: impl IntoIterator<Item = DomHandle>,- cache_write_generation_at_cleanup: u64,) {- self.source_dirty_scopes.record_scope(- scope_id,- reason,- source_ids,- roots,- cache_write_generation_at_cleanup,- );+ self.source_dirty_scopes+ .record_scope(scope_id, reason, source_ids, roots);}pub(super) fn source_dirty_scope_snapshot(&self) -> StyleSourceDirtyScopeSnapshot {@@ -167,14 +184,51 @@ impl StyleDocumentState {.invalidation_clear_all_fallback_reasons_vec()}- pub(super) fn retained_style_system_matches(&self, key: &StyleSystemCacheKey) -> bool {+ #[cfg(test)]+ pub(super) fn retained_style_system_matches(&self, key: &StyleWorldKey) -> bool {self.retained_style_system.borrow().as_ref().is_some_and(|retained| retained.key == *key)}- pub(super) fn set_retained_style_system(&self, retained: RetainedStyleSystem) {+ pub(super) fn retained_style_system_is_current_for_observation(+ &self,+ document_url: &url::Url,+ viewport: StyleViewport,+ environment: StyloStyleEnvironment,+ quirks_mode: style::context::QuirksMode,+ tree_scope_versions: StyleTreeScopeVersions,+ ) -> bool {+ if self+ .source_dirty_scope_snapshot()+ .requires_retained_style_update()+ {+ return false;+ }+ self.retained_style_system+ .borrow()+ .as_ref()+ .is_some_and(|retained| {+ retained.key.matches_observation_environment(+ document_url,+ viewport,+ environment,+ quirks_mode,+ tree_scope_versions,+ )+ })+ }++ pub(super) fn set_retained_style_system(&self, mut retained: RetainedStyleSystem) {+ let mut retained_slot = self.retained_style_system.borrow_mut();+ retained.stylesheet_resource_revision = retained_slot.as_ref().map_or(1, |previous| {+ if previous.stylesheet_resources == retained.stylesheet_resources {+ previous.stylesheet_resource_revision+ } else {+ previous.stylesheet_resource_revision.saturating_add(1)+ }+ });self.retained_style_system_generation.set(self.retained_style_system_generation.get()@@ -183,7 +237,29 @@ impl StyleDocumentState {#[cfg(test)]self.retained_style_system_rebuilds.set(self.retained_style_system_rebuild_count().saturating_add(1));- *self.retained_style_system.borrow_mut() = Some(retained);+ *retained_slot = Some(retained);+ }++ pub(super) fn update_retained_style_system_with_result<R>(+ &self,+ update: impl FnOnce(&mut RetainedStyleSystem) -> R,+ ) -> R {+ let result = {+ let mut retained = self.retained_style_system.borrow_mut();+ let retained = retained+ .as_mut()+ .expect("retained style system should exist before an incremental update");+ update(retained)+ };+ self.retained_style_system_generation.set(+ self.retained_style_system_generation+ .get()+ .saturating_add(1),+ );+ #[cfg(test)]+ self.retained_style_system_updates+ .set(self.retained_style_system_update_count().saturating_add(1));+ result}#[cfg(test)]@@ -191,6 +267,25 @@ impl StyleDocumentState {self.retained_style_system_rebuilds.get()}+ #[cfg(test)]+ pub(super) fn retained_style_system_update_count(&self) -> u64 {+ self.retained_style_system_updates.get()+ }++ #[cfg(test)]+ pub(super) fn note_element_style_resolutions(&self, count: u64) {+ self.element_style_resolutions+ .set(self.element_style_resolutions.get().saturating_add(count));+ }++ #[cfg(not(test))]+ pub(super) fn note_element_style_resolutions(&self, _count: u64) {}++ #[cfg(test)]+ pub(super) fn element_style_resolution_count(&self) -> u64 {+ self.element_style_resolutions.get()+ }+pub(super) fn with_shadow_cascade_data<R>(&self,callback: impl FnOnce(&[(DomHandle, ServoArc<CascadeData>)]) -> R,@@ -216,4 +311,18 @@ impl StyleDocumentState {.expect("retained style system should be prepared before resolving styles");callback(retained)}++ pub(super) fn stylesheet_resource_snapshot(+ &self,+ document: DomHandle,+ ) -> Option<StylesheetResourceSnapshot> {+ self.try_with_retained_style_system(|retained| {+ retained+ .stylesheet_resources+ .snapshot(StylesheetResourceGeneration::new(+ document,+ retained.stylesheet_resource_revision,+ ))+ })+ }}diff --git a/moli-renderer-v8/src/style_engine/stylesheet.rs b/moli-renderer-v8/src/style_engine/stylesheet.rsnew file mode 100644index 000000000..340ea9f81--- /dev/null+++ b/moli-renderer-v8/src/style_engine/stylesheet.rs@@ -0,0 +1,507 @@+use std::{+ collections::HashSet,+ ptr::NonNull,+ sync::{Arc as StdArc, LazyLock},+};++use euclid::{Scale, Size2D};+use moli_selector::StyloSourceDependencySummary;+use style::{+ context::QuirksMode,+ device::{Device, servo::FontMetricsProvider},+ font_face::FontFaceRule,+ font_metrics::FontMetrics,+ media_queries::MediaList,+ properties::{ComputedValues, style_structs::Font},+ servo::media_features::PointerCapabilities,+ servo_arc::Arc as ServoArc,+ shared_lock::{Locked, SharedRwLock, ToCssWithGuard},+ stylesheets::{+ AllowImportRules, CssRule, CustomMediaMap, DocumentStyleSheet, Origin, Stylesheet,+ StylesheetInDocument, UrlExtraData, scope_rule::ImplicitScopeRoot,+ },+ stylist::{CascadeData, Stylist},+ values::{+ computed::{+ CSSPixelLength, Length,+ font::{GenericFontFamily, SingleFontFamily},+ },+ specified::font::QueryFontMetricsFlags,+ },+};+use style_traits::{CSSPixel, CssWriter, DevicePixel, ToCss};++use crate::{document_runtime::DomHandle, dom::native::DomHost};++use super::{+ StyleViewport, StyloStyleEnvironment,+ active_stylesheets::{ActiveStylesheet, ActiveStylesheetCollection},+ source::store::{StyleSourceMetadata, StyloStylesheetSource},+ source_id::{StyleSourceId, StyleSourceKind},+ ua::HTML_STYLESHEET as MOLI_UA_STYLESHEET,+ world_key::{DEFAULT_VIEWPORT_HEIGHT, DEFAULT_VIEWPORT_WIDTH},+};++static MOLI_UA_SOURCE_METADATA: LazyLock<StyleSourceMetadata> = LazyLock::new(|| {+ style_source_metadata_for_css_text_with_origin(+ MOLI_UA_STYLESHEET,+ &url::Url::parse("about:blank").expect("valid built-in stylesheet base URL"),+ Origin::UserAgent,+ )+});++static MOLI_UA_SOURCE_DEPENDENCY_SUMMARY: LazyLock<StdArc<StyloSourceDependencySummary>> =+ LazyLock::new(|| StdArc::new(MOLI_UA_SOURCE_METADATA.dependency_summary.clone()));++#[cfg(test)]+thread_local! {+ static AUTHOR_SOURCE_TEXT_PARSE_COUNT: std::cell::Cell<usize> = const {+ std::cell::Cell::new(0)+ };+}++#[cfg(test)]+pub(crate) fn reset_author_source_text_parse_count_for_test() {+ AUTHOR_SOURCE_TEXT_PARSE_COUNT.with(|count| count.set(0));+}++#[cfg(test)]+pub(crate) fn author_source_text_parse_count_for_test() -> usize {+ AUTHOR_SOURCE_TEXT_PARSE_COUNT.with(std::cell::Cell::get)+}++#[derive(Debug)]+struct HeadlessFontMetricsProvider;++pub(super) fn install_active_stylesheets(+ host: &DomHost,+ shared_lock: &SharedRwLock,+ sources: &[StyloStylesheetSource],+ quirks_mode: QuirksMode,+) -> ActiveStylesheetCollection {+ ActiveStylesheetCollection::new(+ sources+ .iter()+ .map(|source| install_active_stylesheet(host, shared_lock, source, quirks_mode))+ .collect(),+ )+}++pub(super) fn install_active_stylesheet(+ host: &DomHost,+ shared_lock: &SharedRwLock,+ source: &StyloStylesheetSource,+ quirks_mode: QuirksMode,+) -> ActiveStylesheet {+ let stylesheet = author_stylesheet_for_source(shared_lock, source, quirks_mode);+ let web_font_resources = native_font_face_rules_for_stylesheet(&stylesheet)+ .into_iter()+ .filter_map(|rule| {+ crate::css_resource_urls::stylesheet_web_font_resource(+ &rule.rule_fingerprint,+ source.base_url(),+ )+ })+ .collect::<Vec<_>>();+ ActiveStylesheet::new(+ source.clone(),+ document_stylesheet_for_source(host, source, stylesheet),+ StdArc::from(web_font_resources),+ source.import_urls(),+ )+}++pub(super) fn style_source_metadata_for_css_text(+ css_text: &str,+ base_url: &url::Url,+) -> StyleSourceMetadata {+ style_source_metadata_for_css_text_with_origin(css_text, base_url, Origin::Author)+}++pub(in crate::style_engine) fn style_source_metadata_for_stylesheet(+ stylesheet: &ServoArc<Stylesheet>,+) -> StyleSourceMetadata {+ let guard = stylesheet.shared_lock.read();+ let quirks_mode = stylesheet.contents.read_with(&guard).quirks_mode;+ let stylist = new_stylist_with_viewport_bits(+ DEFAULT_VIEWPORT_WIDTH.to_bits(),+ DEFAULT_VIEWPORT_HEIGHT.to_bits(),+ DEFAULT_VIEWPORT_WIDTH.to_bits(),+ DEFAULT_VIEWPORT_HEIGHT.to_bits(),+ StyloStyleEnvironment::default(),+ quirks_mode,+ );+ let mut cascade_data = CascadeData::new();+ let document_stylesheet = DocumentStyleSheet::new(stylesheet.clone());+ if cascade_data+ .add_stylesheet_for_moli_source_metadata(+ stylist.device(),+ quirks_mode,+ &document_stylesheet,+ 0,+ &guard,+ )+ .is_err()+ {+ return StyleSourceMetadata::default();+ }+ style_source_metadata_from_cascade_data(&cascade_data)+}++#[derive(Clone, Debug)]+pub(crate) struct StylesheetFontFaceRuleProjection {+ pub(crate) rule_identity: u64,+ pub(crate) rule_fingerprint: String,+ pub(crate) descriptor: moli_css_parse::CssFontFace,+}++#[derive(Clone, Debug, Default)]+pub(crate) struct StylesheetFontFaceProjection {+ pub(crate) all_rules: Vec<StylesheetFontFaceRuleProjection>,+ pub(crate) effective_rule_identities: HashSet<u64>,+}++#[derive(Clone, Debug)]+pub(crate) struct NativeStylesheetFontFaceRuleProjection {+ pub(crate) rule: ServoArc<Locked<FontFaceRule>>,+ pub(crate) rule_fingerprint: String,+ pub(crate) descriptor: moli_css_parse::CssFontFace,+}++#[derive(Clone, Debug, Default)]+pub(crate) struct NativeStylesheetFontFaceProjection {+ pub(crate) all_rules: Vec<NativeStylesheetFontFaceRuleProjection>,+ pub(crate) effective_rule_addresses: HashSet<usize>,+}++pub(crate) fn native_font_face_projection_for_stylesheet(+ stylesheet: &ServoArc<Stylesheet>,+ environment: StyloStyleEnvironment,+ viewport: StyleViewport,+) -> NativeStylesheetFontFaceProjection {+ let guard = stylesheet.shared_lock.read();+ let quirks_mode = stylesheet.contents.read_with(&guard).quirks_mode;+ let viewport_width = viewport.width.unwrap_or(DEFAULT_VIEWPORT_WIDTH as f64) as f32;+ let viewport_height = viewport.height.unwrap_or(DEFAULT_VIEWPORT_HEIGHT as f64) as f32;+ let screen_width = viewport.screen_width.unwrap_or(f64::from(viewport_width)) as f32;+ let screen_height = viewport.screen_height.unwrap_or(f64::from(viewport_height)) as f32;+ let stylist = new_stylist_with_viewport_bits(+ viewport_width.to_bits(),+ viewport_height.to_bits(),+ screen_width.to_bits(),+ screen_height.to_bits(),+ environment,+ quirks_mode,+ );++ let mut projection = NativeStylesheetFontFaceProjection::default();+ let contents = stylesheet.contents(&guard);+ collect_font_face_rule_projections(contents.rules(&guard), &guard, &mut projection.all_rules);++ let document_stylesheet = DocumentStyleSheet::new(stylesheet.clone());+ let custom_media = CustomMediaMap::default();+ if document_stylesheet.enabled()+ && document_stylesheet.is_effective_for_device(stylist.device(), &custom_media, &guard)+ {+ projection.effective_rule_addresses.extend(+ contents+ .effective_rules(stylist.device(), &custom_media, &guard)+ .filter_map(|rule| match rule {+ CssRule::FontFace(rule) => Some(rule.raw_ptr().as_ptr() as usize),+ _ => None,+ }),+ );+ }+ projection+}++pub(crate) fn native_font_face_rules_for_stylesheet(+ stylesheet: &ServoArc<Stylesheet>,+) -> Vec<NativeStylesheetFontFaceRuleProjection> {+ let guard = stylesheet.shared_lock.read();+ let mut rules = Vec::new();+ collect_font_face_rule_projections(+ stylesheet.contents(&guard).rules(&guard),+ &guard,+ &mut rules,+ );+ rules+}++fn collect_font_face_rule_projections(+ rules: &[CssRule],+ guard: &style::shared_lock::SharedRwLockReadGuard<'_>,+ projections: &mut Vec<NativeStylesheetFontFaceRuleProjection>,+) {+ for rule in rules {+ if let CssRule::FontFace(rule) = rule {+ let locked_rule = rule.read_with(guard);+ let Some(family) = locked_rule.descriptors.font_family.as_ref() else {+ continue;+ };+ let Some(source) = locked_rule.descriptors.src.as_ref() else {+ continue;+ };+ let mut serialized_source = String::new();+ if source+ .to_css(&mut CssWriter::new(&mut serialized_source))+ .is_ok()+ {+ projections.push(NativeStylesheetFontFaceRuleProjection {+ rule: rule.clone(),+ rule_fingerprint: locked_rule.to_css_string(guard),+ descriptor: moli_css_parse::CssFontFace {+ family: family.name.to_string(),+ source: serialized_source,+ },+ });+ }+ continue;+ }+ collect_font_face_rule_projections(rule.children(guard), guard, projections);+ }+}++pub(super) fn moli_user_agent_source_dependency_summary() -> StdArc<StyloSourceDependencySummary> {+ StdArc::clone(&MOLI_UA_SOURCE_DEPENDENCY_SUMMARY)+}++fn style_source_metadata_for_css_text_with_origin(+ css_text: &str,+ base_url: &url::Url,+ origin: Origin,+) -> StyleSourceMetadata {+ let shared_lock = SharedRwLock::new();+ let stylesheet = DocumentStyleSheet::new(ServoArc::new(parse_stylesheet(+ &shared_lock,+ base_url,+ css_text,+ origin,+ QuirksMode::NoQuirks,+ )));+ let guard = shared_lock.read();+ let stylist = new_stylist_with_viewport_bits(+ DEFAULT_VIEWPORT_WIDTH.to_bits(),+ DEFAULT_VIEWPORT_HEIGHT.to_bits(),+ DEFAULT_VIEWPORT_WIDTH.to_bits(),+ DEFAULT_VIEWPORT_HEIGHT.to_bits(),+ StyloStyleEnvironment::default(),+ QuirksMode::NoQuirks,+ );+ let mut cascade_data = CascadeData::new();+ if cascade_data+ .add_stylesheet_for_moli_source_metadata(+ stylist.device(),+ QuirksMode::NoQuirks,+ &stylesheet,+ 0,+ &guard,+ )+ .is_err()+ {+ return StyleSourceMetadata::default();+ }+ style_source_metadata_from_cascade_data(&cascade_data)+}++fn style_source_metadata_from_cascade_data(cascade_data: &CascadeData) -> StyleSourceMetadata {+ StyleSourceMetadata {+ dependency_summary: StyloSourceDependencySummary::from_cascade_data(cascade_data),+ }+}++pub(super) fn new_stylist_with_viewport_bits(+ viewport_width_bits: u32,+ viewport_height_bits: u32,+ screen_width_bits: u32,+ screen_height_bits: u32,+ environment: StyloStyleEnvironment,+ quirks_mode: QuirksMode,+) -> Stylist {+ Stylist::new(+ new_style_device_with_viewport_bits(+ viewport_width_bits,+ viewport_height_bits,+ screen_width_bits,+ screen_height_bits,+ environment,+ quirks_mode,+ ),+ quirks_mode,+ )+}++pub(super) fn new_style_device_with_viewport_bits(+ viewport_width_bits: u32,+ viewport_height_bits: u32,+ screen_width_bits: u32,+ screen_height_bits: u32,+ environment: StyloStyleEnvironment,+ quirks_mode: QuirksMode,+) -> Device {+ let width = f32::from_bits(viewport_width_bits);+ let height = f32::from_bits(viewport_height_bits);+ let screen_width = f32::from_bits(screen_width_bits);+ let screen_height = f32::from_bits(screen_height_bits);+ let initial_style = ComputedValues::initial_values_with_font_override(Font::initial_values());+ let mut device = Device::new(+ environment.stylo_media_type(),+ quirks_mode,+ Size2D::<f32, CSSPixel>::new(width, height),+ Size2D::<f32, DevicePixel>::new(screen_width, screen_height),+ Scale::<f32, CSSPixel, DevicePixel>::new(1.0),+ Box::new(HeadlessFontMetricsProvider),+ initial_style,+ environment.stylo_prefers_color_scheme(),+ PointerCapabilities::default(),+ PointerCapabilities::default(),+ );+ device.set_media_feature_preferences(environment.stylo_media_feature_preferences());+ device+}++fn document_stylesheet_for_source(+ host: &DomHost,+ source: &StyloStylesheetSource,+ stylesheet: ServoArc<Stylesheet>,+) -> DocumentStyleSheet {+ implicit_scope_root_for_source(host, source.source_id())+ .map(|root| DocumentStyleSheet::with_implicit_scope_root(stylesheet.clone(), root))+ .unwrap_or_else(|| DocumentStyleSheet::new(stylesheet))+}++fn implicit_scope_root_for_source(+ host: &DomHost,+ source_id: Option<&StyleSourceId>,+) -> Option<ImplicitScopeRoot> {+ let source_id = source_id?;+ match &source_id.kind {+ StyleSourceKind::OwnerStyleSheet { owner }+ | StyleSourceKind::LinkedStyleSheet { owner } => {+ implicit_scope_root_for_stylesheet_owner(host, *owner)+ }+ StyleSourceKind::DocumentAdoptedStyleSheet { .. }+ | StyleSourceKind::ShadowRootAdoptedStyleSheet { .. } => {+ Some(ImplicitScopeRoot::Constructed)+ }+ }+}++fn implicit_scope_root_for_stylesheet_owner(+ host: &DomHost,+ owner: DomHandle,+) -> Option<ImplicitScopeRoot> {+ let parent = host.node(owner)?.parent_node()?;+ if host.is_shadow_root(parent) {+ return host+ .shadow_root_host(parent)+ .and_then(|host_element| opaque_element_for_handle(host, host_element))+ .map(ImplicitScopeRoot::ShadowHost);+ }+ host.node(parent)?.as_element()?;+ let opaque_parent = opaque_element_for_handle(host, parent)?;+ if host.containing_shadow_root(parent).is_some() {+ Some(ImplicitScopeRoot::InShadowTree(opaque_parent))+ } else {+ Some(ImplicitScopeRoot::InLightTree(opaque_parent))+ }+}++fn opaque_element_for_handle(+ host: &DomHost,+ handle: DomHandle,+) -> Option<selectors::OpaqueElement> {+ let node = host.node(handle)?;+ node.as_element()?;+ Some(selectors::OpaqueElement::from_non_null_ptr(+ NonNull::new(node as *const crate::dom::native::Node as *mut ())+ .expect("DOM node pointers are never null"),+ ))+}++pub(super) fn append_stylesheet_to_stylist(+ stylist: &mut Stylist,+ shared_lock: &SharedRwLock,+ css_text: &str,+ base_url: &url::Url,+ origin: Origin,+ quirks_mode: QuirksMode,+) {+ let stylesheet = parse_stylesheet(shared_lock, base_url, css_text, origin, quirks_mode);+ let guard = shared_lock.read();+ stylist.append_stylesheet(DocumentStyleSheet::new(ServoArc::new(stylesheet)), &guard);+}++fn author_stylesheet_for_source(+ shared_lock: &SharedRwLock,+ source: &StyloStylesheetSource,+ quirks_mode: QuirksMode,+) -> ServoArc<Stylesheet> {+ if let Some(stylesheet) = source.parsed_stylesheet() {+ return stylesheet;+ }+ #[cfg(test)]+ AUTHOR_SOURCE_TEXT_PARSE_COUNT.with(|count| count.set(count.get() + 1));+ let css_text = source+ .input_css_text()+ .expect("stylesheet without parsed contents must remain text-backed");+ ServoArc::new(parse_stylesheet(+ shared_lock,+ source.base_url(),+ css_text,+ Origin::Author,+ quirks_mode,+ ))+}++fn parse_stylesheet(+ shared_lock: &SharedRwLock,+ base_url: &url::Url,+ css_text: &str,+ origin: Origin,+ quirks_mode: QuirksMode,+) -> Stylesheet {+ let media = ServoArc::new(shared_lock.wrap(MediaList::empty()));+ Stylesheet::from_str(+ css_text,+ UrlExtraData::from(base_url.clone()),+ origin,+ media,+ shared_lock.clone(),+ None,+ None,+ quirks_mode,+ AllowImportRules::No,+ )+}++impl FontMetricsProvider for HeadlessFontMetricsProvider {+ fn query_font_metrics(+ &self,+ _vertical: bool,+ font: &Font,+ base_size: CSSPixelLength,+ _flags: QueryFontMetricsFlags,+ ) -> FontMetrics {+ let mut metrics = FontMetrics::default();+ if font_family_list_starts_with_ahem(font) {+ metrics.zero_advance_measure = Some(base_size);+ }+ metrics+ }++ fn base_size_for_generic(&self, _generic: GenericFontFamily) -> Length {+ Length::new(16.0)+ }+}++fn font_family_list_starts_with_ahem(font: &Font) -> bool {+ font.clone_font_family()+ .families+ .iter()+ .next()+ .is_some_and(|family| match family {+ SingleFontFamily::FamilyName(name) => name.name.as_ref().eq_ignore_ascii_case("Ahem"),+ SingleFontFamily::Generic(_) => false,+ })+}diff --git a/moli-renderer-v8/src/style_engine/stylesheet_resources.rs b/moli-renderer-v8/src/style_engine/stylesheet_resources.rsnew file mode 100644index 000000000..f24554501--- /dev/null+++ b/moli-renderer-v8/src/style_engine/stylesheet_resources.rs@@ -0,0 +1,137 @@+use std::{collections::BTreeMap, sync::Arc};++use crate::{css_resource_urls::StylesheetLoadBlockingResource, document_runtime::DomHandle};++use super::{active_stylesheets::ActiveStylesheetCollection, shadow_scopes::ShadowScopeStyles};++#[cfg(test)]+thread_local! {+ static STYLESHEET_RESOURCE_MANIFEST_BUILD_COUNT: std::cell::Cell<usize> = const {+ std::cell::Cell::new(0)+ };+}++#[cfg(test)]+pub(crate) fn reset_stylesheet_resource_manifest_build_count_for_test() {+ STYLESHEET_RESOURCE_MANIFEST_BUILD_COUNT.with(|count| count.set(0));+}++#[cfg(test)]+pub(crate) fn stylesheet_resource_manifest_build_count_for_test() -> usize {+ STYLESHEET_RESOURCE_MANIFEST_BUILD_COUNT.with(std::cell::Cell::get)+}++/// Identity of one typed stylesheet resource set published by a Document.+///+/// The revision advances only when the font/import manifest changes, not for+/// unrelated style-world flushes. Keeping the Document in the type prevents a+/// layout-owned sidecar from treating equal revisions from two iframe worlds+/// as interchangeable.+#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]+pub(crate) struct StylesheetResourceGeneration {+ document: DomHandle,+ revision: u64,+}++impl StylesheetResourceGeneration {+ pub(super) const fn new(document: DomHandle, revision: u64) -> Self {+ Self { document, revision }+ }+}++/// Owned, typed resource projection from one current retained style world.+#[derive(Clone, Debug)]+pub(crate) struct StylesheetResourceSnapshot {+ generation: StylesheetResourceGeneration,+ web_fonts: Arc<[StylesheetLoadBlockingResource]>,+ imports: Arc<[url::Url]>,+}++impl StylesheetResourceSnapshot {+ pub(super) fn new(+ generation: StylesheetResourceGeneration,+ web_fonts: Arc<[StylesheetLoadBlockingResource]>,+ imports: Arc<[url::Url]>,+ ) -> Self {+ Self {+ generation,+ web_fonts,+ imports,+ }+ }++ pub(crate) const fn generation(&self) -> StylesheetResourceGeneration {+ self.generation+ }++ pub(crate) fn web_fonts(&self) -> &[StylesheetLoadBlockingResource] {+ self.web_fonts.as_ref()+ }++ pub(crate) fn imports(&self) -> &[url::Url] {+ self.imports.as_ref()+ }+}++/// Resource metadata retained beside the exact parsed stylesheet collections.+/// It contains no layout, paint, or network state.+#[derive(PartialEq)]+pub(super) struct StylesheetResourceManifest {+ web_fonts: Arc<[StylesheetLoadBlockingResource]>,+ imports: Arc<[url::Url]>,+}++impl StylesheetResourceManifest {+ pub(super) fn from_active_stylesheets(+ document_stylesheets: &ActiveStylesheetCollection,+ shadow_scopes: &[ShadowScopeStyles],+ ) -> Self {+ #[cfg(test)]+ STYLESHEET_RESOURCE_MANIFEST_BUILD_COUNT.with(|count| count.set(count.get() + 1));+ let mut web_fonts = BTreeMap::new();+ let mut imports = BTreeMap::new();+ collect_resources(document_stylesheets, &mut web_fonts, &mut imports);+ for scope in shadow_scopes {+ collect_resources(scope.active_stylesheets(), &mut web_fonts, &mut imports);+ }+ Self {+ web_fonts: web_fonts.into_values().collect::<Vec<_>>().into(),+ imports: imports.into_values().collect::<Vec<_>>().into(),+ }+ }++ pub(super) fn snapshot(+ &self,+ generation: StylesheetResourceGeneration,+ ) -> StylesheetResourceSnapshot {+ StylesheetResourceSnapshot::new(+ generation,+ Arc::clone(&self.web_fonts),+ Arc::clone(&self.imports),+ )+ }+}++fn collect_resources(+ stylesheets: &ActiveStylesheetCollection,+ web_fonts: &mut BTreeMap<String, StylesheetLoadBlockingResource>,+ imports: &mut BTreeMap<String, url::Url>,+) {+ for stylesheet in stylesheets.entries() {+ for resource in stylesheet.web_font_resources() {+ let Some(font) = resource.web_font() else {+ continue;+ };+ web_fonts+ .entry(font.slot().to_owned())+ .or_insert_with(|| resource.clone());+ }+ for import in stylesheet.import_urls() {+ let mut identity = import.clone();+ identity.set_fragment(None);+ imports+ .entry(identity.as_str().to_owned())+ .or_insert_with(|| import.clone());+ }+ }+}diff --git a/moli-renderer-v8/src/style_engine/system.rs b/moli-renderer-v8/src/style_engine/system.rsdeleted file mode 100644index f1b0b3f39..000000000--- a/moli-renderer-v8/src/style_engine/system.rs+++ /dev/null@@ -1,517 +0,0 @@-use moli_crypto::Sha256Context;--use crate::{document_runtime::DomHandle, dom::native::DomHost};--use moli_selector::StyloDomStyleAdapter;-use style::context::QuirksMode;--use super::{- StyleViewport, StyloComputedStyleInputs, StyloStyleEnvironment,- cleanup::StyleCacheCleanup,- retained::build_retained_style_system,- source::store::{StyloStylesheetSource, stylesheet_sources_cache_key},- source_dirty::StyleSourceDirtyScopeSnapshot,- source_document::DocumentStyleSourceStores,- source_id::StyleSourceId,- source_lifecycle::{- StyleSourceDocumentContext, StyleSourceLifecycleOwnerDetailTrace,- StyleSourceLifecycleOwnerDetailTraceSink, StyleSourceLifecycleReport,- StyleSourceLifecycleSnapshot, StyleSourceLifecycleSnapshotSink,- },- state::{RetainedStyleSystem, StyleDocumentState},-};--pub(super) const DEFAULT_VIEWPORT_WIDTH: f32 = 1024.0;-pub(super) const DEFAULT_VIEWPORT_HEIGHT: f32 = 768.0;--#[derive(Clone, Debug, PartialEq, Eq, Hash)]-pub(super) struct StyleSystemCacheKey {- pub(super) document_url: url::Url,- pub(super) viewport_width_bits: u32,- pub(super) viewport_height_bits: u32,- pub(super) screen_width_bits: u32,- pub(super) screen_height_bits: u32,- pub(super) environment: StyloStyleEnvironment,- pub(super) quirks_mode: QuirksMode,- pub(super) script_custom_property_registrations: StyleSystemScriptCustomPropertyKey,- pub(super) document_stylesheet_sources: StyleSystemSourceSetKey,- pub(super) shadow_stylesheet_sources: Vec<(DomHandle, StyleSystemSourceSetKey)>,-}--#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub(super) struct StyleSystemSourceSetKey {- pub(super) len: usize,- pub(super) fingerprint: [u8; 32],-}--#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub(super) struct StyleSystemSourceKey {- pub(super) fingerprint: [u8; 32],-}--#[derive(Clone, Debug, PartialEq, Eq, Hash)]-pub(super) struct StyleSystemScriptCustomPropertyKey {- len: usize,- fingerprint: [u8; 32],-}--#[derive(Clone, Debug, PartialEq, Eq)]-pub(super) struct StyleSourceInputTrace {- pub(super) document_stylesheet_source_count: usize,- pub(super) document_source_ids: Vec<Option<StyleSourceId>>,- pub(super) shadow_stylesheet_sources: Vec<StyleSourceInputShadowRootTrace>,- pub(super) script_custom_property_registration_count: usize,- pub(super) script_custom_property_base_url: url::Url,-}--#[derive(Clone, Debug, PartialEq, Eq)]-pub(super) struct StyleSourceInputShadowRootTrace {- pub(super) root: DomHandle,- pub(super) source_count: usize,- pub(super) source_ids: Vec<Option<StyleSourceId>>,-}--#[derive(Clone, Debug, PartialEq, Eq)]-pub(super) struct StyleSystemCacheKeyMismatchTrace {- pub(super) document_url_changed: bool,- pub(super) previous_document_url: url::Url,- pub(super) next_document_url: url::Url,- pub(super) viewport_changed: bool,- pub(super) previous_viewport_width_bits: u32,- pub(super) next_viewport_width_bits: u32,- pub(super) previous_viewport_height_bits: u32,- pub(super) next_viewport_height_bits: u32,- pub(super) screen_changed: bool,- pub(super) previous_screen_width_bits: u32,- pub(super) next_screen_width_bits: u32,- pub(super) previous_screen_height_bits: u32,- pub(super) next_screen_height_bits: u32,- pub(super) environment_changed: bool,- pub(super) quirks_mode_changed: bool,- pub(super) custom_property_registrations_changed: bool,- pub(super) previous_custom_property_registrations: StyleSystemScriptCustomPropertyKey,- pub(super) next_custom_property_registrations: StyleSystemScriptCustomPropertyKey,- pub(super) document_stylesheet_sources_changed: bool,- pub(super) previous_document_stylesheet_sources: StyleSystemSourceSetKey,- pub(super) next_document_stylesheet_sources: StyleSystemSourceSetKey,- pub(super) shadow_root_list_changed: bool,- pub(super) previous_shadow_roots: Vec<DomHandle>,- pub(super) next_shadow_roots: Vec<DomHandle>,- pub(super) added_shadow_roots: Vec<DomHandle>,- pub(super) removed_shadow_roots: Vec<DomHandle>,- pub(super) shadow_stylesheet_sources_changed: bool,- pub(super) previous_shadow_stylesheet_sources: Vec<(DomHandle, StyleSystemSourceSetKey)>,- pub(super) next_shadow_stylesheet_sources: Vec<(DomHandle, StyleSystemSourceSetKey)>,- pub(super) changed_shadow_source_roots: Vec<DomHandle>,-}--impl StyleSystemCacheKey {- pub(super) fn new(- document_url: &url::Url,- inputs: &StyloComputedStyleInputs,- viewport: impl Into<StyleViewport>,- ) -> Self {- let viewport = viewport.into();- let mut document_url = document_url.clone();- document_url.set_fragment(None);- let viewport_width_bits = style_dimension_bits(viewport.width, DEFAULT_VIEWPORT_WIDTH);- let viewport_height_bits = style_dimension_bits(viewport.height, DEFAULT_VIEWPORT_HEIGHT);- Self {- document_url,- viewport_width_bits,- viewport_height_bits,- screen_width_bits: style_dimension_bits(- viewport.screen_width,- f32::from_bits(viewport_width_bits),- ),- screen_height_bits: style_dimension_bits(- viewport.screen_height,- f32::from_bits(viewport_height_bits),- ),- environment: inputs.environment,- quirks_mode: inputs.quirks_mode,- script_custom_property_registrations: script_custom_property_registrations_cache_key(- inputs,- ),- document_stylesheet_sources: stylesheet_sources_cache_key(- &inputs.document_stylesheet_sources,- ),- shadow_stylesheet_sources: inputs- .shadow_stylesheet_sources- .iter()- .map(|(root, sources)| (*root, stylesheet_sources_cache_key(sources)))- .collect(),- }- }-- pub(super) fn mismatch_trace(&self, next: &Self) -> StyleSystemCacheKeyMismatchTrace {- let previous_shadow_roots = shadow_roots_for_trace(&self.shadow_stylesheet_sources);- let next_shadow_roots = shadow_roots_for_trace(&next.shadow_stylesheet_sources);- StyleSystemCacheKeyMismatchTrace {- document_url_changed: self.document_url != next.document_url,- previous_document_url: self.document_url.clone(),- next_document_url: next.document_url.clone(),- viewport_changed: self.viewport_width_bits != next.viewport_width_bits- || self.viewport_height_bits != next.viewport_height_bits,- previous_viewport_width_bits: self.viewport_width_bits,- next_viewport_width_bits: next.viewport_width_bits,- previous_viewport_height_bits: self.viewport_height_bits,- next_viewport_height_bits: next.viewport_height_bits,- screen_changed: self.screen_width_bits != next.screen_width_bits- || self.screen_height_bits != next.screen_height_bits,- previous_screen_width_bits: self.screen_width_bits,- next_screen_width_bits: next.screen_width_bits,- previous_screen_height_bits: self.screen_height_bits,- next_screen_height_bits: next.screen_height_bits,- environment_changed: self.environment != next.environment,- quirks_mode_changed: self.quirks_mode != next.quirks_mode,- custom_property_registrations_changed: self.script_custom_property_registrations- != next.script_custom_property_registrations,- previous_custom_property_registrations: self- .script_custom_property_registrations- .clone(),- next_custom_property_registrations: next.script_custom_property_registrations.clone(),- document_stylesheet_sources_changed: self.document_stylesheet_sources- != next.document_stylesheet_sources,- previous_document_stylesheet_sources: self.document_stylesheet_sources,- next_document_stylesheet_sources: next.document_stylesheet_sources,- shadow_root_list_changed: previous_shadow_roots != next_shadow_roots,- added_shadow_roots: shadow_roots_added_for_trace(- &previous_shadow_roots,- &next_shadow_roots,- ),- removed_shadow_roots: shadow_roots_added_for_trace(- &next_shadow_roots,- &previous_shadow_roots,- ),- previous_shadow_roots,- next_shadow_roots,- shadow_stylesheet_sources_changed: self.shadow_stylesheet_sources- != next.shadow_stylesheet_sources,- previous_shadow_stylesheet_sources: self.shadow_stylesheet_sources.clone(),- next_shadow_stylesheet_sources: next.shadow_stylesheet_sources.clone(),- changed_shadow_source_roots: changed_shadow_source_roots_for_trace(- &self.shadow_stylesheet_sources,- &next.shadow_stylesheet_sources,- ),- }- }-}--impl StyleSystemCacheKeyMismatchTrace {- fn is_only_scoped_source_change(&self, roots: &[DomHandle], has_document_scope: bool) -> bool {- !self.document_url_changed- && !self.viewport_changed- && !self.screen_changed- && !self.environment_changed- && !self.quirks_mode_changed- && !self.custom_property_registrations_changed- && (self.document_stylesheet_sources_changed- || self.shadow_root_list_changed- || self.shadow_stylesheet_sources_changed)- && (!self.document_stylesheet_sources_changed || has_document_scope)- && (!self.shadow_stylesheet_sources_changed- || self.shadow_source_scope_changed_roots_covered_by(roots))- && self.shadow_root_list_change_covered_by(roots)- }-- fn shadow_source_scope_changed_roots_covered_by(&self, roots: &[DomHandle]) -> bool {- let mut changed_root_count = 0;- for root in self- .changed_shadow_source_roots- .iter()- .chain(self.added_shadow_roots.iter())- .chain(self.removed_shadow_roots.iter())- {- changed_root_count += 1;- if !roots.contains(root) {- return false;- }- }- changed_root_count > 0- }-- fn shadow_root_list_change_covered_by(&self, roots: &[DomHandle]) -> bool {- if !self.shadow_root_list_changed {- return true;- }- let mut changed_root_count = 0;- for root in self- .added_shadow_roots- .iter()- .chain(self.removed_shadow_roots.iter())- {- changed_root_count += 1;- if !roots.contains(root) {- return false;- }- }- changed_root_count > 0- }-}--fn shadow_roots_for_trace(- shadow_sources: &[(DomHandle, StyleSystemSourceSetKey)],-) -> Vec<DomHandle> {- shadow_sources.iter().map(|(root, _)| *root).collect()-}--fn shadow_roots_added_for_trace(previous: &[DomHandle], next: &[DomHandle]) -> Vec<DomHandle> {- next.iter()- .copied()- .filter(|root| !previous.contains(root))- .collect()-}--fn changed_shadow_source_roots_for_trace(- previous: &[(DomHandle, StyleSystemSourceSetKey)],- next: &[(DomHandle, StyleSystemSourceSetKey)],-) -> Vec<DomHandle> {- next.iter()- .filter_map(|(root, next_key)| {- previous- .iter()- .find(|(previous_root, _)| previous_root == root)- .and_then(|(_, previous_key)| (previous_key != next_key).then_some(*root))- })- .collect()-}--fn script_custom_property_registrations_cache_key(- inputs: &StyloComputedStyleInputs,-) -> StyleSystemScriptCustomPropertyKey {- let mut hasher = Sha256Context::new();- let mut base_url = inputs.script_custom_property_base_url.clone();- base_url.set_fragment(None);- hasher.update(base_url.as_str().len().to_le_bytes());- hasher.update(base_url.as_str().as_bytes());- hasher.update(- inputs- .script_custom_property_registrations- .len()- .to_le_bytes(),- );- for registration in &inputs.script_custom_property_registrations {- update_string_hash(&mut hasher, ®istration.name);- update_string_hash(&mut hasher, ®istration.syntax);- hasher.update([registration.inherits as u8]);- match registration.initial_value.as_deref() {- Some(initial_value) => {- hasher.update([1]);- update_string_hash(&mut hasher, initial_value);- }- None => hasher.update([0]),- }- }- StyleSystemScriptCustomPropertyKey {- len: inputs.script_custom_property_registrations.len(),- fingerprint: hasher.finish(),- }-}--fn update_string_hash(hasher: &mut Sha256Context, value: &str) {- hasher.update(value.len().to_le_bytes());- hasher.update(value.as_bytes());-}--impl StyleSystemSourceKey {- pub(super) fn css_fingerprint(css_text: &str) -> [u8; 32] {- let mut hasher = Sha256Context::new();- let css_text = css_text.as_bytes();- hasher.update(css_text.len().to_le_bytes());- hasher.update(css_text);- hasher.finish()- }-- pub(super) fn from_css_fingerprint(css_fingerprint: [u8; 32], base_url: &url::Url) -> Self {- let mut hasher = Sha256Context::new();- hasher.update(css_fingerprint);- let mut base_url = base_url.clone();- base_url.set_fragment(None);- let base_url = base_url.as_str().as_bytes();- hasher.update(base_url.len().to_le_bytes());- hasher.update(base_url);- Self {- fingerprint: hasher.finish(),- }- }-- pub(super) fn from_live_stylesheet(- stylesheet_id: crate::live_stylesheet::StylesheetId,- cascade_generation: u64,- ) -> Self {- let mut hasher = Sha256Context::new();- hasher.update(b"live-stylesheet");- hasher.update(stylesheet_id.get().to_le_bytes());- hasher.update(cascade_generation.to_le_bytes());- Self {- fingerprint: hasher.finish(),- }- }-}--pub(super) fn ensure_retained_style_system(- host: &DomHost,- dom_adapter: &StyloDomStyleAdapter,- document_state: &StyleDocumentState,- source_stores: &DocumentStyleSourceStores<'_>,- document_context: StyleSourceDocumentContext<'_>,- retained_document: DomHandle,- cache_cleanup: StyleCacheCleanup<'_>,- key: &StyleSystemCacheKey,- inputs: &StyloComputedStyleInputs,-) {- if document_state.retained_style_system_matches(key) {- return;- }- let trace_enabled = moli_trace::style_invalidation_trace_enabled();- let key_mismatch_trace =- document_state.try_with_retained_style_system(|retained| retained.key.mismatch_trace(key));- let trace_documents = trace_enabled.then(|| vec![retained_document]);-- let source_dirty_scope = document_state.source_dirty_scope_snapshot();- let scoped_roots_vec = source_dirty_scope.scoped_roots_vec();- if source_dirty_scope.has_only_scoped_source_records()- && key_mismatch_trace.as_ref().is_some_and(|trace| {- trace.is_only_scoped_source_change(- &scoped_roots_vec,- source_dirty_scope.contains_document_scope(retained_document),- )- })- {- if !source_dirty_scope.cache_cleanup_covers(- scoped_roots_vec.iter().copied(),- cache_cleanup.computed_style_cache_write_generation(),- ) {- cache_cleanup.clear_for_scoped_retained_style_system_rebuild(- host,- scoped_roots_vec.iter().copied(),- );- }- document_state.clear_source_dirty_scopes();- } else {- cache_cleanup.clear_for_retained_style_system_rebuild(host);- document_state.clear_source_dirty_scopes();- }-- let source_lifecycle = source_stores.source_lifecycle_report(host, document_context);- let retained_source_records =- source_stores.retained_source_records_for_lifecycle(host, &source_lifecycle);- let shared_lock = dom_adapter.shared_lock().clone();- let retained = build_retained_style_system(- host,- key.clone(),- inputs,- &shared_lock,- &retained_source_records,- );- if trace_enabled {- trace_retained_style_system_rebuild(- inputs,- &source_lifecycle,- &source_dirty_scope,- document_state.source_set_generation(),- &retained,- key_mismatch_trace.as_ref(),- trace_documents.as_deref().unwrap_or_default(),- );- }- document_state.set_retained_style_system(retained);-}--fn trace_retained_style_system_rebuild(- inputs: &StyloComputedStyleInputs,- source_lifecycle: &StyleSourceLifecycleReport,- source_dirty_scope: &StyleSourceDirtyScopeSnapshot,- source_set_generation: u64,- retained: &RetainedStyleSystem,- key_mismatch: Option<&StyleSystemCacheKeyMismatchTrace>,- document_context_documents: &[DomHandle],-) {- let mut lifecycle_snapshot = RetainedStyleSystemRebuildLifecycleSnapshot::default();- source_lifecycle.record_snapshot_into(&mut lifecycle_snapshot);- source_lifecycle.record_owner_detail_trace_into(&mut lifecycle_snapshot);- let source_input = style_source_input_trace(inputs);- tracing::info!(- document_url = %retained.key.document_url,- document_stylesheet_input_count = inputs.document_stylesheet_sources.len(),- shadow_stylesheet_input_count = inputs.shadow_stylesheet_sources.len(),- retained_shadow_cascade_count = retained.shadow_cascade_data.len(),- retained_source_cascade_data_count = retained.source_cascade_data.len(),- document_context_documents = ?document_context_documents,- source_set_generation = source_set_generation,- source_dirty_ids = ?source_dirty_scope.source_ids_vec(),- source_dirty_scope_ids = ?source_dirty_scope.scope_ids_vec(),- source_dirty_roots = ?source_dirty_scope.scoped_roots_vec(),- source_dirty_reasons = ?source_dirty_scope.reasons_vec(),- source_dirty_records = ?source_dirty_scope.records_vec(),- source_input = ?source_input,- key_mismatch = ?key_mismatch,- source_lifecycle = ?lifecycle_snapshot.snapshot,- source_lifecycle_owner_details = ?lifecycle_snapshot.owner_details,- "retained style system rebuild summary"- );-}--fn style_source_input_trace(inputs: &StyloComputedStyleInputs) -> StyleSourceInputTrace {- StyleSourceInputTrace {- document_stylesheet_source_count: inputs.document_stylesheet_sources.len(),- document_source_ids: style_source_ids_for_trace(&inputs.document_stylesheet_sources),- shadow_stylesheet_sources: inputs- .shadow_stylesheet_sources- .iter()- .map(|(root, sources)| StyleSourceInputShadowRootTrace {- root: *root,- source_count: sources.len(),- source_ids: style_source_ids_for_trace(sources),- })- .collect(),- script_custom_property_registration_count: inputs- .script_custom_property_registrations- .len(),- script_custom_property_base_url: inputs.script_custom_property_base_url.clone(),- }-}--fn style_source_ids_for_trace(sources: &[StyloStylesheetSource]) -> Vec<Option<StyleSourceId>> {- sources- .iter()- .map(|source| source.source_id().cloned())- .collect()-}--#[cfg(test)]-pub(super) fn style_source_input_trace_for_test(- inputs: &StyloComputedStyleInputs,-) -> StyleSourceInputTrace {- style_source_input_trace(inputs)-}--#[derive(Default)]-struct RetainedStyleSystemRebuildLifecycleSnapshot {- snapshot: StyleSourceLifecycleSnapshot,- owner_details: Vec<StyleSourceLifecycleOwnerDetailTrace>,-}--impl StyleSourceLifecycleSnapshotSink for RetainedStyleSystemRebuildLifecycleSnapshot {- fn record_source_lifecycle_snapshot(&mut self, snapshot: StyleSourceLifecycleSnapshot) {- self.snapshot = snapshot;- }-}--impl StyleSourceLifecycleOwnerDetailTraceSink for RetainedStyleSystemRebuildLifecycleSnapshot {- fn record_source_lifecycle_owner_detail_trace(- &mut self,- trace: StyleSourceLifecycleOwnerDetailTrace,- ) {- self.owner_details.push(trace);- }-}--fn style_dimension_bits(value: Option<f64>, fallback: f32) -> u32 {- value- .filter(|value| value.is_finite() && *value >= 0.0)- .map(|value| value as f32)- .unwrap_or(fallback)- .to_bits()-}diff --git a/moli-renderer-v8/src/style_engine/tests/char_child.rs b/moli-renderer-v8/src/style_engine/tests/char_child.rsindex b467926dd..7bcbb217a 100644--- a/moli-renderer-v8/src/style_engine/tests/char_child.rs+++ b/moli-renderer-v8/src/style_engine/tests/char_child.rs@@ -16,15 +16,14 @@ fn character_data_without_structural_selector_preserves_cache_entries() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new(".parent + .target { color: red; }".into(),document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [parent, target] {assert!(engine@@ -76,15 +75,14 @@ fn character_data_structural_sibling_dependency_invalidates_following_siblings()let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new(".parent:empty + .target { color: red; }".into(),document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [parent, target] {assert!(engine@@ -137,15 +135,14 @@ fn character_data_has_empty_dependency_invalidates_ancestor_subjects() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new(".container:has(.child:empty) .target { color: red; }".into(),document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [child, target] {assert!(engine@@ -198,12 +195,8 @@ fn child_list_has_empty_dependency_invalidates_ancestor_subjects() {"#subject { display: block; } #subject:has(:empty) { display: none; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert_eq!(engine.computed_style_property_value(@@ -275,12 +268,8 @@ fn child_list_type_sibling_invalidation_clears_next_sibling_without_keyed_dependlet document_url = url::Url::parse("https://example.test/").unwrap();let source =StyloStylesheetSource::new("div + .target { color: red; }".into(), document_url.clone());- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, unrelated] {assert!(@@ -341,12 +330,8 @@ fn child_list_universal_sibling_invalidation_keeps_later_sibling_cache() {let document_url = url::Url::parse("https://example.test/").unwrap();let source =StyloStylesheetSource::new("* + .target { color: red; }".into(), document_url.clone());- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, unrelated] {assert!(@@ -411,12 +396,8 @@ fn child_list_universal_sibling_removal_keeps_later_sibling_cache() {let document_url = url::Url::parse("https://example.test/").unwrap();let source =StyloStylesheetSource::new("* + .target { color: red; }".into(), document_url.clone());- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, unrelated] {assert!(@@ -498,12 +479,8 @@ fn retained_stylo_invalidator_uses_batch_snapshot_for_outer_dependency() {"div .scope:where(.marker *) .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [scoped_target, loose_target] {assert!(@@ -592,12 +569,8 @@ fn retained_stylo_invalidator_uses_attribute_value_snapshot_for_outer_dependency"div .scope:where([data-state=\"old\"] *) .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [scoped_target, loose_target] {assert!(@@ -684,12 +657,8 @@ fn retained_stylo_invalidator_uses_focus_state_snapshot_for_outer_dependency() {"div .scope:where(:focus *) .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [scoped_target, loose_target] {assert!(@@ -763,12 +732,8 @@ fn retained_stylo_invalidator_uses_target_state_snapshot_for_outer_dependency()"div .scope:where(:target *) .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [scoped_target, loose_target] {assert!(@@ -832,12 +797,8 @@ fn retained_stylo_child_list_insertion_preserves_broken_next_sibling_target() {".previous + .target { color: red; } .marker ~ .later { color: green; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, later, unrelated] {assert!(@@ -909,12 +870,8 @@ fn retained_stylo_child_list_insertion_uses_element_sibling_relation_across_text".marker + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, unrelated] {assert!(@@ -982,12 +939,8 @@ fn retained_stylo_child_list_removal_uses_mutation_time_removed_snapshot() {".marker + .target { color: red; } .other + .unrelated { color: blue; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, unrelated] {assert!(@@ -1054,12 +1007,8 @@ fn retained_stylo_child_list_removal_preserves_new_previous_sibling_match() {".marker + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, unrelated] {assert!(@@ -1132,12 +1081,8 @@ fn retained_stylo_child_list_removal_uses_element_sibling_relation_across_text()".marker + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, unrelated] {assert!(@@ -1210,12 +1155,8 @@ fn retained_stylo_child_list_removal_uses_previous_element_sibling_across_text()".marker + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, unrelated] {assert!(@@ -1286,12 +1227,8 @@ fn retained_stylo_child_list_multi_removal_uses_removed_element_sibling_relation".spacer + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, unrelated] {assert!(@@ -1367,12 +1304,8 @@ fn retained_stylo_child_list_multi_removal_preserves_new_previous_sibling_match(".marker + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, unrelated] {assert!(diff --git a/moli-renderer-v8/src/style_engine/tests/dependency.rs b/moli-renderer-v8/src/style_engine/tests/dependency.rsindex e09b1caf7..0450df364 100644--- a/moli-renderer-v8/src/style_engine/tests/dependency.rs+++ b/moli-renderer-v8/src/style_engine/tests/dependency.rs@@ -162,7 +162,7 @@ fn missing_retained_style_system_reaches_cleanup_application_table() {let host = test_host();let mut engine = MoliStyleEngine::new();let root = host.document_handle();- engine.set_document_adopted_style_sheet_sources_with_host(&host, root, Vec::new());+ engine.set_document_adopted_style_sheet_sources(root, Vec::new());let source_id = StyleSourceId::document_adopted_style_sheet(root, 0);let mut target_query = PendingStyleInvalidationTargetQueries::retained_source(source_id.clone(),@@ -288,10 +288,10 @@ fn missing_retained_cascade_data_reaches_cleanup_application_table() {let host = test_host();let mut engine = MoliStyleEngine::new();let root = host.document_handle();- engine.set_document_adopted_style_sheet_sources_with_host(&host, root, Vec::new());+ engine.set_document_adopted_style_sheet_sources(root, Vec::new());let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();- let key = StyleSystemCacheKey::new(&document_url, &inputs, None);+ let inputs = FullStyleWorldSnapshot::default();+ let key = StyleWorldKey::new(&document_url, &inputs, None);engine.ensure_retained_style_system_for_document(&host, root, key, &inputs);let source_id = StyleSourceId::document_adopted_style_sheet(root, 0);@@ -534,7 +534,7 @@ fn media_state_change_without_snapshot_uses_retained_query() {.with_source_id(Some(StyleSourceId::document_adopted_style_sheet(document, 0,)));- engine.set_document_adopted_style_sheet_sources_with_host(&host, document, vec![source]);+ engine.set_document_adopted_style_sheet_sources(document, vec![source]);let media = crate::protocol_types::EmulatedMediaOverrides::default();let source_scope = super::scope::source_scope_for_element_state_change(@@ -1440,14 +1440,10 @@ fn source_dependency_request_translation_preserves_context_fallback_kind_with_relet mut engine = MoliStyleEngine::new();let source = StyloStylesheetSource::new(style_text.into(), base_url.clone()).with_source_id(Some(source_id));- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);- let key = StyleSystemCacheKey::new(&base_url, &inputs, None);+ let key = StyleWorldKey::new(&base_url, &inputs, None);engine.ensure_retained_style_system_for_document(&host, document, key, &inputs);let application = engine@@ -1659,7 +1655,7 @@ fn retained_unavailable_uses_exact_safety_roots_without_broadening_context_fallb);let mut engine = MoliStyleEngine::new();- engine.set_document_adopted_style_sheet_sources_with_host(&host, document, Vec::new());+ engine.set_document_adopted_style_sheet_sources(document, Vec::new());let application = retained_source_invalidation_outcome_for_document_for_test(&engine,&host,@@ -1831,7 +1827,7 @@ fn user_agent_structural_boundary_fallback_coexists_with_author_source_target()let user_agent_source = super::source_record::MatchingStyleDependencySource::user_agent(&host,document,- super::retained::moli_user_agent_source_dependency_summary(),+ super::stylesheet::moli_user_agent_source_dependency_summary(),&source_scope,).expect("document UA source should participate in document scope");@@ -1899,7 +1895,7 @@ fn user_agent_structural_metadata_skips_unrelated_boundary_type() {super::source_record::MatchingStyleDependencySource::user_agent(&host,document,- super::retained::moli_user_agent_source_dependency_summary(),+ super::stylesheet::moli_user_agent_source_dependency_summary(),&source_scope,).expect("document UA source should participate in document scope"),@@ -2449,8 +2445,8 @@ fn retained_style_system_cache_hit_preserves_computed_and_retained_generations()let host = test_host();let document = host.document_handle();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();- let key = StyleSystemCacheKey::new(&document_url, &inputs, None);+ let inputs = FullStyleWorldSnapshot::default();+ let key = StyleWorldKey::new(&document_url, &inputs, None);engine.ensure_retained_style_system_for_document(&host,@@ -2477,7 +2473,7 @@ fn retained_style_system_cache_hit_preserves_computed_and_retained_generations()}#[test]-fn full_retained_rebuild_clears_computed_cache_until_generation_split() {+fn viewport_change_updates_the_persistent_style_world_in_place() {let mut host = test_host();let document = host.document_handle();let target = host.create_element("main");@@ -2487,33 +2483,47 @@ fn full_retained_rebuild_clears_computed_cache_until_generation_split() {let engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();- let initial_key = StyleSystemCacheKey::new(&document_url, &inputs, None);- let viewport_key = StyleSystemCacheKey::new(- &document_url,- &inputs,- StyleViewport::from_width(Some(640.0)),- );+ let inputs = FullStyleWorldSnapshot {+ document_stylesheet_sources: vec![StyloStylesheetSource::new(+ "main { color: rgb(1, 2, 3); }\n\+ aside { color: rgb(7, 8, 9); }\n\+ @media (max-width: 700px) { main { color: rgb(4, 5, 6); } }"+ .to_owned(),+ document_url.clone(),+ )],+ ..Default::default()+ };+ let initial_viewport = StyleViewport::from_width(Some(800.0));+ let next_viewport = StyleViewport::from_width(Some(640.0));+ let initial_key = StyleWorldKey::new(&document_url, &inputs, initial_viewport);+ let viewport_key = StyleWorldKey::new(&document_url, &inputs, next_viewport);let mismatch = initial_key.mismatch_trace(&viewport_key);assert!(mismatch.viewport_changed);- assert!(!mismatch.document_stylesheet_sources_changed);- assert!(!mismatch.shadow_stylesheet_sources_changed);- for handle in [target, sibling] {- assert!(- engine- .computed_style_property_value(- &host,- &document_url,- handle,- "display",- None,- &inputs,- None,- )- .is_some()- );- }+ assert_eq!(+ engine.computed_style_property_value(+ &host,+ &document_url,+ target,+ "color",+ None,+ &inputs,+ initial_viewport,+ ),+ Some("rgb(1, 2, 3)".to_owned())+ );+ assert_eq!(+ engine.computed_style_property_value(+ &host,+ &document_url,+ sibling,+ "color",+ None,+ &inputs,+ initial_viewport,+ ),+ Some("rgb(7, 8, 9)".to_owned())+ );assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(document),2@@ -2524,31 +2534,56 @@ fn full_retained_rebuild_clears_computed_cache_until_generation_split() {engine.source_set_generation_for_document_for_test(document);let retained_generation_after_cached_reads =engine.retained_style_system_generation_for_document_for_test(document);+ let retained_identity_after_cached_reads =+ engine.retained_stylist_identity_for_document_for_test(document);+ let retained_rebuilds_after_cached_reads =+ engine.retained_style_system_rebuild_count_for_document_for_test(document);+ let retained_updates_after_cached_reads =+ engine.retained_style_system_update_count_for_document_for_test(document);engine.ensure_retained_style_system_for_document(&host, document, viewport_key, &inputs);assert_eq!(engine.source_set_generation_for_document_for_test(document),source_set_generation_after_cached_reads,- "non-source retained rebuild must not advance source-set generation"+ "a device update must not advance source-set generation");- assert!(- engine.computed_cache_generation_for_document_for_test(document)- > computed_generation_after_cached_reads,- "non-source key mismatch should keep full rebuild as a generation boundary"+ assert_eq!(+ engine.computed_cache_generation_for_document_for_test(document),+ computed_generation_after_cached_reads,+ "an in-place device update must not create a full-cache generation boundary");assert!(engine.retained_style_system_generation_for_document_for_test(document)> retained_generation_after_cached_reads,- "full retained rebuild should advance retained style-system generation"+ "the observation generation must record the in-place device update");assert_eq!(- engine.computed_style_cache_entry_count_for_document_for_test(document),- 0,- "computed entries remain keyed by the old generation until generation splitting exists"+ engine.retained_stylist_identity_for_document_for_test(document),+ retained_identity_after_cached_reads,+ "viewport changes must retain the Document Stylist"+ );+ assert_eq!(+ engine.retained_style_system_rebuild_count_for_document_for_test(document),+ retained_rebuilds_after_cached_reads+ );+ assert_eq!(+ engine.retained_style_system_update_count_for_document_for_test(document),+ retained_updates_after_cached_reads + 1+ );+ assert_eq!(+ engine.computed_style_property_value(+ &host,+ &document_url,+ target,+ "color",+ None,+ &inputs,+ next_viewport,+ ),+ Some("rgb(4, 5, 6)".to_owned()),+ "the retained world must recascade media-query-dependent values");- assert!(!engine.computed_style_cache_contains_handle_for_document_for_test(document, target));- assert!(!engine.computed_style_cache_contains_handle_for_document_for_test(document, sibling));}#[test]fn stylesheet_source_clones_share_css_text_and_base_url() {@@ -2572,7 +2607,7 @@ fn source_scope_fallback_roots_preserve_unrelated_document_cache() {let engine = MoliStyleEngine::new();let active_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -2642,7 +2677,7 @@ fn source_scope_fallback_roots_preserve_active_document_cache_for_detached_documlet engine = MoliStyleEngine::new();let active_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -2712,7 +2747,7 @@ fn unsupported_state_change_without_snapshot_uses_source_scope_fallback() {let mut engine = MoliStyleEngine::new();let active_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [active, detached] {assert!(engine@@ -2809,7 +2844,7 @@ fn cache_key_source_matching_skips_inactive_owner_sources() {let disconnected_style_id =StyleSourceId::owner_style_sheet(&host, disconnected_style).expect("disconnected style id");- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(StyloStylesheetSource::new(@@ -2820,7 +2855,7 @@ fn cache_key_source_matching_skips_inactive_owner_sources() {engine.ensure_retained_style_system_for_document(&host,host.document_handle(),- StyleSystemCacheKey::new(&document_url, &inputs, None),+ StyleWorldKey::new(&document_url, &inputs, None),&inputs,);engine.with_retained_style_system_for_document_for_test(host.document_handle(), |retained| {diff --git a/moli-renderer-v8/src/style_engine/tests/invalidator.rs b/moli-renderer-v8/src/style_engine/tests/invalidator.rsindex 9d8b1d692..35cba75e4 100644--- a/moli-renderer-v8/src/style_engine/tests/invalidator.rs+++ b/moli-renderer-v8/src/style_engine/tests/invalidator.rs@@ -121,8 +121,8 @@ fn retained_system_mutations_without_computed_cache_still_queue_work() {"section:has(span) { color: red; }".into(),);let document_url = host.document_url().expect("test document url").clone();- let inputs = StyloComputedStyleInputs::default();- let key = StyleSystemCacheKey::new(&document_url, &inputs, None);+ let inputs = FullStyleWorldSnapshot::default();+ let key = StyleWorldKey::new(&document_url, &inputs, None);engine.ensure_retained_style_system_for_document(&host, host.document_handle(), key, &inputs);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(document),@@ -185,7 +185,7 @@ fn has_selector_child_list_invalidation_uses_target_queries_without_rebuilding_s"body:has(span) .subject { color: red; }".into(),);let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -285,7 +285,7 @@ fn has_selector_child_list_invalidation_collects_inserted_subtree_dependency_key".subject:has(.descendant) { color: rgb(1, 2, 3); }".into(),);let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();let initial = engine.computed_style_property_value(&host, &document_url, subject, "color", None, &inputs, None).expect("subject color should compute before insertion");@@ -340,12 +340,8 @@ fn has_selector_child_list_invalidation_matches_inserted_heading_pseudo_class()"#ancestor:has(:heading(1)) ~ #subject { color: rgb(1, 2, 3); }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);let initial = engine.computed_style_property_value(&host, &document_url, subject, "color", None, &inputs, None)@@ -407,12 +403,8 @@ fn has_selector_child_list_invalidation_matches_inserted_adjacent_heading_pseudolet mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();let source = StyloStylesheetSource::new(style_text.into(), document_url.clone());- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);let initial = engine.computed_style_property_value(&host, &document_url, target, "color", None, &inputs, None)@@ -496,7 +488,7 @@ fn has_selector_child_list_insertion_ignores_unrelated_element_type() {"body:has(span) .subject { color: red; }".into(),);let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [outside, subject] {assert!(engine@@ -550,7 +542,7 @@ fn stylo_tree_invalidator_wrapper_collects_sibling_roots() {let engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(StyloStylesheetSource::new(".marker + .target { color: red; }".into(),@@ -560,7 +552,7 @@ fn stylo_tree_invalidator_wrapper_collects_sibling_roots() {document, 0,))),);- let key = StyleSystemCacheKey::new(&document_url, &inputs, None);+ let key = StyleWorldKey::new(&document_url, &inputs, None);engine.ensure_retained_style_system_for_document(&host, host.document_handle(), key, &inputs);let (roots, requires_fallback) = collect_source_invalidation_roots_for_test(@@ -590,7 +582,7 @@ fn stylo_tree_invalidator_wrapper_handles_normal_dependency_chains() {let engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(StyloStylesheetSource::new(".scope :is(.marker) + .target { color: red; }".into(),@@ -600,7 +592,7 @@ fn stylo_tree_invalidator_wrapper_handles_normal_dependency_chains() {document, 0,))),);- let key = StyleSystemCacheKey::new(&document_url, &inputs, None);+ let key = StyleWorldKey::new(&document_url, &inputs, None);engine.ensure_retained_style_system_for_document(&host, host.document_handle(), key, &inputs);let (roots, requires_fallback) = collect_source_invalidation_roots_for_test(@@ -633,7 +625,7 @@ fn stylo_tree_invalidator_wrapper_handles_scope_dependency_chains() {let engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(StyloStylesheetSource::new(":scope .marker + .target { color: red; }".into(),@@ -643,7 +635,7 @@ fn stylo_tree_invalidator_wrapper_handles_scope_dependency_chains() {document, 0,))),);- let key = StyleSystemCacheKey::new(&document_url, &inputs, None);+ let key = StyleWorldKey::new(&document_url, &inputs, None);engine.ensure_retained_style_system_for_document(&host, host.document_handle(), key, &inputs);let (roots, requires_fallback) = collect_source_invalidation_roots_for_test(@@ -673,7 +665,7 @@ fn stylo_tree_invalidator_wrapper_accepts_empty_scope_dependency_result() {let engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(StyloStylesheetSource::new(":scope .marker + .target { color: red; }".into(),@@ -683,7 +675,7 @@ fn stylo_tree_invalidator_wrapper_accepts_empty_scope_dependency_result() {document, 0,))),);- let key = StyleSystemCacheKey::new(&document_url, &inputs, None);+ let key = StyleWorldKey::new(&document_url, &inputs, None);engine.ensure_retained_style_system_for_document(&host, host.document_handle(), key, &inputs);let (roots, requires_fallback) = collect_source_invalidation_roots_for_test(@@ -755,7 +747,7 @@ fn stylo_style_resolution_records_relative_selector_flags() {".anchor:has(.marker) { color: red; }".into(),document_url.clone(),);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert!(@@ -801,7 +793,7 @@ fn detached_subtree_invalidation_clears_relative_selector_flags() {".anchor:has(.marker) { color: red; }".into(),document_url.clone(),);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert!(@@ -875,12 +867,8 @@ fn retained_stylo_invalidator_narrows_sibling_cache_invalidation() {".marker + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert!(@@ -948,12 +936,8 @@ fn retained_stylo_invalidator_narrows_class_attribute_cache_invalidation() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();let source = StyloStylesheetSource::new(".active { color: red; }".into(), document_url.clone());- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, unrelated] {@@ -1014,12 +998,8 @@ fn retained_stylo_invalidator_accepts_empty_normal_sibling_result() {".marker + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert!(@@ -1076,12 +1056,8 @@ fn retained_stylo_invalidator_accepts_empty_scope_sibling_result() {":scope .marker + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert!(@@ -1184,12 +1160,8 @@ fn retained_stylo_invalidator_keeps_self_dependency_inheritance_safe() {let document_url = url::Url::parse("https://example.test/").unwrap();let source =StyloStylesheetSource::new(".marker { color: blue; }".into(), document_url.clone());- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [outside, parent, child, unrelated] {assert!(@@ -1263,17 +1235,13 @@ fn retained_stylo_invalidator_ignores_unrelated_shadow_cascade_data() {);let shadow_source =StyloStylesheetSource::new(".shadow-only { color: blue; }".into(), document_url.clone());- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![document_source.clone()],- );+ engine.set_document_adopted_style_sheet_sources(document, vec![document_source.clone()]);engine.set_shadow_root_adopted_style_sheet_sources_with_host(&host,shadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(document_source);inputs.shadow_stylesheet_sources@@ -1348,17 +1316,13 @@ fn retained_stylo_invalidator_ignores_out_of_scope_shadow_cascade_dependency() {);let shadow_source =StyloStylesheetSource::new(".marker { color: blue; }".into(), document_url.clone());- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![document_source.clone()],- );+ engine.set_document_adopted_style_sheet_sources(document, vec![document_source.clone()]);engine.set_shadow_root_adopted_style_sheet_sources_with_host(&host,shadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(document_source);inputs.shadow_stylesheet_sources@@ -1428,7 +1392,7 @@ fn retained_stylo_invalidator_falls_back_for_in_scope_shadow_cascade_dependency(shadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((shadow_root, vec![shadow_source]));@@ -1507,7 +1471,7 @@ fn retained_stylo_invalidator_narrows_shadow_tree_sibling_dependency() {shadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((shadow_root, vec![shadow_source]));@@ -1578,7 +1542,7 @@ fn retained_stylo_invalidator_treats_shadow_host_as_shadow_scope() {shadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((shadow_root, vec![shadow_source]));@@ -1654,7 +1618,7 @@ fn retained_stylo_invalidator_narrows_shadow_host_descendant_dependency() {shadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((shadow_root, vec![shadow_source]));@@ -1731,7 +1695,7 @@ fn retained_stylo_invalidator_uses_shadow_relative_dependency() {shadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((shadow_root, vec![shadow_source]));@@ -1804,7 +1768,7 @@ fn retained_stylo_invalidator_clears_shadow_host_for_shadow_tree_has_dependency(shadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((shadow_root, vec![shadow_source]));@@ -1910,7 +1874,7 @@ fn retained_stylo_invalidator_clears_shadow_subject_for_host_context_inside_has_shadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((shadow_root, vec![shadow_source]));@@ -1993,7 +1957,7 @@ fn retained_stylo_invalidator_keeps_shadow_host_self_dependency_conservative() {shadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((shadow_root, vec![shadow_source]));@@ -2062,12 +2026,8 @@ fn retained_stylo_invalidator_ignores_unrelated_relative_selector_fallback() {".marker + .target { color: red; } section:has(*) { display: block; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, unrelated] {@@ -2134,12 +2094,8 @@ fn retained_stylo_invalidator_uses_snapshot_roots_for_has_class_dependency() {.with_source_id(Some(StyleSourceId::document_adopted_style_sheet(document, 0,)));- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [subject, unrelated] {@@ -2217,12 +2173,8 @@ fn retained_stylo_invalidator_accepts_empty_snapshot_relative_result_for_has_cla.with_source_id(Some(StyleSourceId::document_adopted_style_sheet(document, 0,)));- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [subject, unrelated] {@@ -2329,12 +2281,8 @@ fn target_query_drain_uses_selector_wrapper_fallback_without_retained_system() {".marker + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, unrelated] {@@ -2398,12 +2346,8 @@ fn retained_stylo_invalidator_narrows_focus_sibling_cache_invalidation() {".focusable:focus + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source_text.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source_text.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source_text);for handle in [previous, target, unrelated] {assert!(@@ -2461,12 +2405,8 @@ fn retained_stylo_invalidator_narrows_checked_sibling_cache_invalidation() {".toggle:checked + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source_text.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source_text.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source_text);for handle in [previous, target, unrelated] {assert!(@@ -2528,12 +2468,8 @@ fn retained_stylo_invalidator_clears_defined_state_sibling_cache() {"#source:defined + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source_text.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source_text.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source_text);for handle in [source, target, unrelated] {assert!(@@ -2599,12 +2535,8 @@ fn retained_stylo_invalidator_clears_has_defined_ancestor_subject_cache() {"#subject:has(:defined) { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source_text.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source_text.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source_text);for handle in [subject, source, unrelated] {assert!(@@ -2676,12 +2608,8 @@ fn retained_stylo_invalidator_uses_old_state_snapshots_for_radio_peer_batch() {.into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source_text.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source_text.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source_text);for handle in [first_target, second_target, unrelated] {assert!(@@ -2765,12 +2693,8 @@ fn retained_stylo_invalidator_uses_old_state_snapshot_for_range_sibling_invalida"#range:out-of-range + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source_text.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source_text.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source_text);for handle in [previous, target, unrelated] {assert!(@@ -2843,12 +2767,8 @@ fn retained_stylo_invalidator_treats_readonly_as_range_state_change() {"#range:in-range + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source_text.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source_text.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source_text);for handle in [target, unrelated] {assert!(@@ -2918,12 +2838,8 @@ fn retained_stylo_invalidator_treats_readonly_as_validity_candidate_change() {.into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source_text.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source_text.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source_text);assert_eq!(engine.computed_style_property_value(@@ -3001,12 +2917,8 @@ fn value_state_change_keeps_unrelated_sibling_cache_entries() {".unrelated + .target { color: blue; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source_text.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source_text.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source_text);for handle in [target, unrelated] {assert!(@@ -3090,12 +3002,8 @@ fn retained_stylo_invalidator_uses_state_snapshots_for_range_batches() {.into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source_text.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source_text.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source_text);for handle in [first_target, second_target, unrelated] {assert!(@@ -3188,12 +3096,8 @@ fn retained_stylo_invalidator_uses_snapshots_for_mixed_attribute_state_batches().into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source_text.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source_text.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source_text);for handle in [attr_target, state_target, unrelated] {assert!(@@ -3278,12 +3182,8 @@ fn retained_stylo_invalidator_narrows_target_sibling_cache_invalidation() {"#current:target + .target { color: green; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source_text.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source_text.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source_text);for handle in [previous, target, unrelated] {assert!(@@ -3385,12 +3285,8 @@ fn retained_stylo_invalidator_uses_snapshots_for_mixed_attribute_focus_batches().into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [attr_scoped_target,@@ -3541,12 +3437,8 @@ fn retained_stylo_invalidator_uses_snapshots_for_mixed_attribute_target_batches(.into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [attr_scoped_target,@@ -3649,12 +3541,8 @@ fn retained_stylo_invalidator_narrows_child_list_inserted_sibling_invalidation()".marker + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, unrelated] {assert!(@@ -3720,12 +3608,8 @@ fn retained_stylo_invalidator_keeps_ua_structural_boundary_when_author_source_halet document_url = url::Url::parse("https://example.test/").unwrap();let source =StyloStylesheetSource::new(".unrelated { color: red; }".into(), document_url.clone());- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [first, second, unrelated] {assert!(@@ -3834,7 +3718,7 @@ fn retained_stylo_invalidator_uses_user_agent_attribute_dependencies() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [dialog, unrelated] {assert!(engine@@ -3928,12 +3812,8 @@ fn retained_stylo_invalidator_clears_relative_previous_sibling_for_middle_insert"#subject:has(+ #old-next) { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [subject, unrelated] {assert!(@@ -4011,12 +3891,8 @@ fn retained_stylo_invalidator_refreshes_has_side_effect_siblings() {.into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert_eq!(engine.computed_style_property_value(@@ -4174,12 +4050,8 @@ fn retained_stylo_invalidator_clears_previous_sibling_for_inserted_last_child_ch"span:last-child { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [previous, unrelated] {assert!(@@ -4246,12 +4118,8 @@ fn retained_stylo_invalidator_merges_inserted_last_child_batches() {"span:last-child { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [previous, unrelated] {assert!(@@ -4335,12 +4203,8 @@ fn retained_stylo_invalidator_defers_large_child_list_batches_until_drain() {.into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert_eq!(engine.computed_style_property_value(@@ -4429,12 +4293,8 @@ fn retained_stylo_invalidator_clears_previous_sibling_for_removed_last_child_cha"span:last-child { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [previous, unrelated] {assert!(@@ -4504,12 +4364,8 @@ fn retained_stylo_invalidator_narrows_child_list_removed_sibling_invalidation()".marker + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, unrelated] {assert!(@@ -4579,12 +4435,8 @@ fn retained_stylo_invalidator_narrows_child_list_replacement_sibling_invalidatio".marker + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [target, unrelated] {assert!(@@ -4661,7 +4513,7 @@ fn retained_stylo_invalidator_narrows_assigned_node_slotted_dependency() {document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [outside, assigned, unrelated_assigned] {assert!(engine@@ -4738,7 +4590,7 @@ fn retained_stylo_invalidator_accepts_empty_slotted_result() {shadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((shadow_root, vec![shadow_source]));@@ -4807,12 +4659,8 @@ fn retained_stylo_invalidator_narrows_part_dependency() {".host::part(label) { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [outside, part, unrelated_shadow_child] {assert!(@@ -4929,12 +4777,8 @@ fn retained_stylo_invalidator_accepts_empty_part_result() {".host::part(label) { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [outside, part] {assert!(@@ -5012,12 +4856,8 @@ fn retained_stylo_invalidator_refreshes_nth_child_of_selector_list_on_class_chan.with_source_id(Some(StyleSourceId::document_adopted_style_sheet(document, 0,)));- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert_eq!(engine.computed_style_property_value(@@ -5124,12 +4964,8 @@ fn retained_stylo_invalidator_custom_state_snapshot_avoids_source_fallback() {.with_source_id(Some(StyleSourceId::document_adopted_style_sheet(document, 0,)));- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert_eq!(engine.computed_style_property_value(@@ -5286,7 +5122,7 @@ fn custom_state_batch_invalidation_builds_queries_for_each_changed_state() {"x-stateful:state(--active), x-stateful:state(--enabled) { color: red; }".into(),);let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -5416,12 +5252,8 @@ fn retained_stylo_invalidator_refreshes_nested_is_sibling_has_on_child_removal().with_source_id(Some(StyleSourceId::document_adopted_style_sheet(document, 0,)));- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert_eq!(engine.computed_style_property_value(@@ -5520,12 +5352,8 @@ fn retained_stylo_invalidator_refreshes_nested_is_sibling_has_on_middle_insertio.with_source_id(Some(StyleSourceId::document_adopted_style_sheet(document, 0,)));- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert_eq!(engine.computed_style_property_value(@@ -5603,12 +5431,8 @@ fn retained_stylo_invalidator_refreshes_has_any_link_on_href_insertion() {.with_source_id(Some(StyleSourceId::document_adopted_style_sheet(document, 0,)));- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert_eq!(engine.computed_style_property_value(@@ -5691,12 +5515,8 @@ fn retained_stylo_invalidator_refreshes_has_not_any_link_on_plain_child_insertio.with_source_id(Some(StyleSourceId::document_adopted_style_sheet(document, 0,)));- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert_eq!(engine.computed_style_property_value(diff --git a/moli-renderer-v8/src/style_engine/tests/lifecycle.rs b/moli-renderer-v8/src/style_engine/tests/lifecycle.rsindex bf9701b0f..f4f330c8d 100644--- a/moli-renderer-v8/src/style_engine/tests/lifecycle.rs+++ b/moli-renderer-v8/src/style_engine/tests/lifecycle.rs@@ -293,7 +293,7 @@ fn active_document_light_tree_mutation_matches_related_shadow_sources() {);let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [descendant_target, sibling_target] {assert!(engine@@ -343,8 +343,7 @@ fn author_stylesheet_sources_are_owned_by_style_engine() {let adopted_url = url::Url::parse("https://example.test/adopted.css").unwrap();let shadow_url = url::Url::parse("https://example.test/shadow.css").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new("body { color: red; }".into(),@@ -506,11 +505,11 @@ fn retained_sources_are_scoped_to_document_worlds() {&linked_url,));- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();engine.ensure_retained_style_system_for_document(&host,host.document_handle(),- StyleSystemCacheKey::new(&document_url, &inputs, None),+ StyleWorldKey::new(&document_url, &inputs, None),&inputs,);engine.with_retained_style_system_for_document_for_test(host.document_handle(), |retained| {@@ -547,7 +546,7 @@ fn retained_sources_are_scoped_to_document_worlds() {engine.ensure_retained_style_system_for_document(&host,host.document_handle(),- StyleSystemCacheKey::new(&document_url, &inputs, None),+ StyleWorldKey::new(&document_url, &inputs, None),&inputs,);engine.with_retained_style_system_for_document_for_test(host.document_handle(), |retained| {@@ -560,7 +559,7 @@ fn retained_sources_are_scoped_to_document_worlds() {engine.ensure_retained_style_system_for_document(&host,detached_document,- StyleSystemCacheKey::new(&document_url, &inputs, None),+ StyleWorldKey::new(&document_url, &inputs, None),&inputs,);engine.with_retained_style_system_for_document_for_test(detached_document, |retained| {@@ -879,27 +878,21 @@ fn source_lifecycle_snapshot_distinguishes_trackable_and_retained_sources() {let missing_document = NativeNodeId::new(90_011);let empty_detached_document = host.create_detached_html_document();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new(".document-adopted { color: orange; }".into(),url::Url::parse("https://example.test/document-adopted.css").unwrap(),)],);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(missing_document,vec![StyloStylesheetSource::new(".missing-document-adopted { color: pink; }".into(),url::Url::parse("https://example.test/missing-document-adopted.css").unwrap(),)],);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- empty_detached_document,- Vec::new(),- );+ engine.set_document_adopted_style_sheet_sources(empty_detached_document, Vec::new());let connected_shadow_host = host.create_element("article");assert!(host.append_child(document, connected_shadow_host));@@ -932,6 +925,10 @@ fn source_lifecycle_snapshot_distinguishes_trackable_and_retained_sources() {url::Url::parse("https://example.test/inactive-shadow-adopted.css").unwrap(),)],);+ let document_adopted_source_ids =+ engine.document_adopted_style_sheet_source_ids_for_test(document);+ let connected_shadow_adopted_source_ids =+ engine.shadow_root_adopted_style_sheet_source_ids_for_test(&host, connected_shadow_root);let document_context = StyleSourceDocumentContext::for_root_document(document);let root_report =@@ -1001,7 +998,8 @@ fn source_lifecycle_snapshot_distinguishes_trackable_and_retained_sources() {assert_eq!(root_report.record_for_source_id_for_test(&StyleSourceId::document_adopted_style_sheet(- document, 1,+ document,+ u64::MAX,)).map(|record| record.availability().clone()),Some(StyleSourceLifecycleAvailability::AvailableWithoutSource {@@ -1020,8 +1018,8 @@ fn source_lifecycle_snapshot_distinguishes_trackable_and_retained_sources() {.expect("connected owner stylesheet id"),StyleSourceId::linked_style_sheet(&host, connected_link).expect("connected linked stylesheet id"),- StyleSourceId::document_adopted_style_sheet(document, 0),- StyleSourceId::shadow_root_adopted_style_sheet(connected_shadow_root, 0),+ document_adopted_source_ids[0].clone(),+ connected_shadow_adopted_source_ids[0].clone(),]));let detached_retained_source_ids = engine@@ -1109,16 +1107,14 @@ fn source_lifecycle_context_distinguishes_child_and_detached_documents_in_outcomlet document = host.document_handle();let document_context =OwnedStyleSourceDocumentContext::new(document).with_child_documents([child_document]);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(child_document,vec![StyloStylesheetSource::new(".child { color: green; }".into(),url::Url::parse("https://example.test/child.css").unwrap(),)],);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(detached_document,vec![StyloStylesheetSource::new(".detached { color: blue; }".into(),@@ -1169,8 +1165,16 @@ fn source_lifecycle_context_distinguishes_child_and_detached_documents_in_outcomSome(StyleSourceDocumentKind::Detached));- let child_source = StyleSourceId::document_adopted_style_sheet(child_document, 0);- let detached_source = StyleSourceId::document_adopted_style_sheet(detached_document, 0);+ let child_source = engine+ .document_adopted_style_sheet_source_ids_for_test(child_document)+ .into_iter()+ .next()+ .expect("child document should retain an adopted stylesheet source");+ let detached_source = engine+ .document_adopted_style_sheet_source_ids_for_test(detached_document)+ .into_iter()+ .next()+ .expect("detached document should retain an adopted stylesheet source");let child_target_queries = vec![PendingStyleInvalidationTargetQueries::retained_source(child_source,indexmap::IndexSet::from([RetainedStyleInvalidationQuery::universal(child_document)]),@@ -1294,24 +1298,21 @@ fn source_lifecycle_owner_detail_trace_records_owner_document_kind_and_availabil".disconnected { color: red; }".into(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(child_document,vec![StyloStylesheetSource::new(".child { color: blue; }".into(),url::Url::parse("https://example.test/child.css").unwrap(),)],);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(detached_document,vec![StyloStylesheetSource::new(".detached { color: purple; }".into(),url::Url::parse("https://example.test/detached.css").unwrap(),)],);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(missing_document,vec![StyloStylesheetSource::new(".missing { color: orange; }".into(),@@ -1385,10 +1386,7 @@ fn source_lifecycle_owner_detail_trace_records_owner_document_kind_and_availabilassert_eq!(child_detail.availability(),&StyleSourceLifecycleAvailability::RetainedSources {- source_ids: vec![StyleSourceId::document_adopted_style_sheet(- child_document,- 0,- )],+ source_ids: engine.document_adopted_style_sheet_source_ids_for_test(child_document),});@@ -1477,8 +1475,7 @@ fn source_lifecycle_report_for_source_ids_only_records_requested_tracked_owners();let adopted_base_url = url::Url::parse("https://example.test/adopted.css").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new(@@ -1488,8 +1485,9 @@ fn source_lifecycle_report_for_source_ids_only_records_requested_tracked_owners(StyloStylesheetSource::new(".adopted-b { color: orange; }".into(), adopted_base_url),],);- let requested_adopted_source_id = StyleSourceId::document_adopted_style_sheet(document, 0);- let unrequested_adopted_source_id = StyleSourceId::document_adopted_style_sheet(document, 1);+ let adopted_source_ids = engine.document_adopted_style_sheet_source_ids_for_test(document);+ let requested_adopted_source_id = adopted_source_ids[0].clone();+ let unrequested_adopted_source_id = adopted_source_ids[1].clone();let adopted_report = {let document_world = engine.world_for_document(document);let source_stores = document_world.borrow_source_stores();@@ -1787,14 +1785,24 @@ fn linked_source_store_lifecycle_records_drive_retained_record_construction() {.into_iter().map(|record| record.id().clone()).collect::<HashSet<_>>();+ let document_adopted_source_id = adopted_sources+ .document_source_ids(document)+ .into_iter()+ .next()+ .expect("document adopted source id");+ let shadow_adopted_source_id = adopted_sources+ .shadow_root_source_ids(shadow_root)+ .into_iter()+ .next()+ .expect("shadow adopted source id");assert_eq!(retained_record_ids,HashSet::from([StyleSourceId::owner_style_sheet(&host, style).expect("owner source id"),StyleSourceId::linked_style_sheet(&host, link).expect("linked source id"),- StyleSourceId::document_adopted_style_sheet(document, 0),- StyleSourceId::shadow_root_adopted_style_sheet(shadow_root, 0),+ document_adopted_source_id,+ shadow_adopted_source_id,]));}@@ -1908,6 +1916,32 @@ fn reconnecting_inline_owner_creates_a_new_processing_source_identity() {);}+#[test]+fn disconnecting_inline_owner_retires_source_and_advances_document_generation() {+ let mut host = test_host();+ let document = host.document_handle();+ let style = host.create_element("style");+ assert!(host.set_text_content(style, "body { color: green; }"));+ assert!(host.append_child(document, style));++ let mut engine = MoliStyleEngine::new();+ engine.set_owner_style_sheet_text_with_host(&host, style, "body { color: green; }".to_owned());+ let generation = engine.source_set_generation_for_document_for_test(document);+ assert!(engine.owner_style_sheet_processing_source(style).is_some());++ let removal = host.remove_child_effects(document, style);+ engine.apply_stylesheet_owner_changes_with_host(&host, removal.stylesheet_owners().changes());++ assert!(+ engine.owner_style_sheet_processing_source(style).is_none(),+ "a disconnected owner must not remain installed in its old Document world"+ );+ assert!(+ engine.source_set_generation_for_document_for_test(document) > generation,+ "retiring the owner must make retained style and resource manifests observably dirty"+ );+}+#[test]fn linked_owner_binding_changes_only_on_explicit_install() {let mut host = test_host();@@ -2101,15 +2135,14 @@ fn source_lifecycle_target_result_reports_missing_adopted_source_id() {let host = test_host();let mut engine = MoliStyleEngine::new();let document = host.document_handle();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new(".existing { color: green; }".into(),url::Url::parse("https://example.test/existing.css").unwrap(),)],);- let missing_source_id = StyleSourceId::document_adopted_style_sheet(document, 1);+ let missing_source_id = StyleSourceId::document_adopted_style_sheet(document, u64::MAX);let target_query = PendingStyleInvalidationTargetQueries::retained_source(missing_source_id,indexmap::IndexSet::from([RetainedStyleInvalidationQuery::universal(document)]),@@ -2151,8 +2184,7 @@ fn missing_document_adopted_sources_remain_trackable_without_retained_source() {let source_url = url::Url::parse("https://example.test/missing-document.css").unwrap();let source_id = StyleSourceId::document_adopted_style_sheet(missing_document, 0);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(missing_document,vec![StyloStylesheetSource::new("body:has(.marker) .target { color: green; }".into(),@@ -2181,11 +2213,11 @@ fn missing_document_adopted_sources_remain_trackable_without_retained_source() {"missing document adopted sources should not participate in dependency matching");- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();engine.ensure_retained_style_system_for_document(&host,host.document_handle(),- StyleSystemCacheKey::new(&document_url, &inputs, None),+ StyleWorldKey::new(&document_url, &inputs, None),&inputs,);engine.with_retained_style_system_for_document_for_test(host.document_handle(), |retained| {@@ -2213,7 +2245,7 @@ fn unchanged_stylesheet_source_syncs_do_not_advance_generation() {let shadow_url = url::Url::parse("https://example.test/shadow.css").unwrap();let linked_url = url::Url::parse("https://cdn.example.test/app.css").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(&host, document, Vec::new());+ engine.set_document_adopted_style_sheet_sources(document, Vec::new());engine.set_shadow_root_adopted_style_sheet_sources_with_host(&host, shadow_root, Vec::new());assert_eq!(engine.computed_cache_generation_for_document_for_test(active_document),@@ -2228,25 +2260,17 @@ fn unchanged_stylesheet_source_syncs_do_not_advance_generation() {);let document_source = StyloStylesheetSource::new("body { color: red; }".into(), document_url);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![document_source.clone()],- );+ engine.set_document_adopted_style_sheet_sources(document, vec![document_source.clone()]);let after_document_source = engine.computed_cache_generation_for_document_for_test(document);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![document_source],- );+ engine.set_document_adopted_style_sheet_sources(document, vec![document_source]);assert_eq!(engine.computed_cache_generation_for_document_for_test(document),after_document_source);- engine.set_document_adopted_style_sheet_sources_with_host(&host, document, Vec::new());+ engine.set_document_adopted_style_sheet_sources(document, Vec::new());let after_document_clear = engine.computed_cache_generation_for_document_for_test(document);assert_eq!(after_document_clear, after_document_source);- engine.set_document_adopted_style_sheet_sources_with_host(&host, document, Vec::new());+ engine.set_document_adopted_style_sheet_sources(document, Vec::new());assert_eq!(engine.computed_cache_generation_for_document_for_test(document),after_document_clear@@ -2326,8 +2350,7 @@ fn empty_adopted_sources_are_not_retained_but_shadow_roots_remain_trackable() {let shadow_url = url::Url::parse("https://example.test/shadow.css").unwrap();assert!(host.append_child(document, shadow_host));- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new("body { color: red; }".into(),@@ -2355,7 +2378,7 @@ fn empty_adopted_sources_are_not_retained_but_shadow_roots_remain_trackable() {));- engine.set_document_adopted_style_sheet_sources_with_host(&host, document, Vec::new());+ engine.set_document_adopted_style_sheet_sources(document, Vec::new());engine.set_shadow_root_adopted_style_sheet_sources_with_host(&host, shadow_root, Vec::new());assert_eq!(@@ -2581,7 +2604,7 @@ fn attribute_mutation_without_source_dependency_skips_style_invalidation() {"the retained source has no dependency on data-state");let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -2640,7 +2663,7 @@ fn attribute_mutation_with_source_dependency_still_invalidates_style() {"the retained source must report its script async dependency");let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(diff --git a/moli-renderer-v8/src/style_engine/tests/outcome.rs b/moli-renderer-v8/src/style_engine/tests/outcome.rsindex be55c77f3..6a2a6bbac 100644--- a/moli-renderer-v8/src/style_engine/tests/outcome.rs+++ b/moli-renderer-v8/src/style_engine/tests/outcome.rs@@ -74,7 +74,7 @@ macro_rules! moli_invalidation_result {}#[test]-fn stylesheet_invalidation_advances_generation() {+fn document_stylesheet_dirty_mark_advances_only_the_source_generation() {let mut engine = MoliStyleEngine::new();let host = test_host();let document = host.document_handle();@@ -83,10 +83,14 @@ fn stylesheet_invalidation_advances_generation() {engine.computed_cache_generation_for_document_for_test(document),0);- engine.invalidate_author_stylesheet_set_for_document_with_host(&host, document);+ engine.mark_document_stylesheet_set_dirty(document);assert_eq!(engine.computed_cache_generation_for_document_for_test(document),+ 0+ );+ assert_eq!(+ engine.source_set_generation_for_document_for_test(document),1);}@@ -737,7 +741,7 @@ fn mixed_cleanup_clears_shadow_cascade_data_only_for_source_fallback_roots() {let engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((exact_shadow_root,vec![StyloStylesheetSource::new(@@ -759,7 +763,7 @@ fn mixed_cleanup_clears_shadow_cascade_data_only_for_source_fallback_roots() {document_url.clone(),)],));- let key = StyleSystemCacheKey::new(&document_url, &inputs, None);+ let key = StyleWorldKey::new(&document_url, &inputs, None);engine.ensure_retained_style_system_for_document(&host, document, key, &inputs);let (exact_cascade_data, fallback_cascade_data, structural_cascade_data) = engine@@ -1613,7 +1617,7 @@ fn target_query_drain_clear_all_when_retained_fallback_has_no_roots() {let engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [active, detached] {assert!(engine@@ -1669,7 +1673,10 @@ fn target_query_drain_clear_all_when_retained_fallback_has_no_roots() {engine.computed_style_cache_entry_count_for_document_for_test(detached_document),1);- assert!(!engine.dom_adapter.has_element_data(active));+ assert!(+ element_style_is_dirty_for_test(&engine, &host, active),+ "scoped fallback should retain the last computed values and mark them dirty"+ );assert!(engine.dom_adapter.has_element_data(detached));assert!(engine.target_context_epoch_for_document_for_test(document) > target_epoch);}@@ -1747,14 +1754,14 @@ fn subtree_fallback_cleanup_clears_only_affected_shadow_cascade_data() {":host { color: rgb(4, 5, 6); }".into(),document_url.clone(),);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((first_shadow_root, vec![first_source]));inputs.shadow_stylesheet_sources.push((second_shadow_root, vec![second_source]));- let key = StyleSystemCacheKey::new(&document_url, &inputs, None);+ let key = StyleWorldKey::new(&document_url, &inputs, None);engine.ensure_retained_style_system_for_document(&host, document, key, &inputs);let (first_cascade_data, second_cascade_data) = engine@@ -1856,7 +1863,7 @@ fn detached_document_rootless_source_fallback_clears_only_source_document_world(let engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [active, detached] {assert!(engine@@ -1906,7 +1913,10 @@ fn detached_document_rootless_source_fallback_clears_only_source_document_world(0);assert!(engine.dom_adapter.has_element_data(active));- assert!(!engine.dom_adapter.has_element_data(detached));+ assert!(+ element_style_is_dirty_for_test(&engine, &host, detached),+ "scoped fallback should retain the last computed values and mark them dirty"+ );}fn ensure_adapter_element_data(@@ -1921,3 +1931,16 @@ fn ensure_adapter_element_data(}});}++fn element_style_is_dirty_for_test(+ engine: &MoliStyleEngine,+ host: &crate::dom::native::DomHost,+ handle: crate::document_runtime::DomHandle,+) -> bool {+ engine.dom_adapter.with_bound_host(host, |adapter| {+ let element = adapter.element(host, handle).expect("element");+ element+ .borrow_data()+ .is_some_and(|data| !data.hint.is_empty())+ })+}diff --git a/moli-renderer-v8/src/style_engine/tests/registered_properties.rs b/moli-renderer-v8/src/style_engine/tests/registered_properties.rsindex 391d54c52..8b9aa7816 100644--- a/moli-renderer-v8/src/style_engine/tests/registered_properties.rs+++ b/moli-renderer-v8/src/style_engine/tests/registered_properties.rs@@ -6,15 +6,13 @@ fn test_url() -> url::Url {fn register_custom_property(engine: &mut MoliStyleEngine,- host: &DomHost,document: DomHandle,name: &str,syntax: &str,initial_value: &str,) {engine- .register_css_custom_property_for_document_with_host(- host,+ .register_css_custom_property_for_document(document,CssCustomPropertyRegistration {name: name.to_owned(),@@ -43,7 +41,7 @@ fn computed_value(property: &str,document_sources: &[StyloStylesheetSource],) -> String {- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.extend(document_sources.iter().cloned());@@ -51,8 +49,7 @@ fn computed_value(.owner_document_handle(target).unwrap_or_else(|| host.document_handle());inputs.script_custom_property_registrations =- engine.script_css_custom_property_registrations_for_document(document);- inputs.script_custom_property_base_url = test_url();+ engine.script_css_custom_property_registration_records_for_document(document);engine.computed_style_property_value(host, &test_url(), target, property, None, &inputs, None).unwrap_or_default()@@ -60,19 +57,27 @@ fn computed_value(#[test]fn css_register_property_does_not_advance_source_set_generation() {- let host = test_host();+ let mut host = test_host();let document = host.document_handle();+ let target = host.create_element("div");+ assert!(host.append_child(document, target));let mut engine = MoliStyleEngine::new();+ assert_eq!(+ computed_value(&engine, &host, target, "display", &[]),+ "block"+ );let source_set_generation = engine.source_set_generation_for_document_for_test(document);let computed_generation = engine.computed_cache_generation_for_document_for_test(document);+ let stylist_identity = engine.retained_stylist_identity_for_document_for_test(document);+ let rebuilds = engine.retained_style_system_rebuild_count_for_document_for_test(document);+ let updates = engine.retained_style_system_update_count_for_document_for_test(document);register_custom_property(&mut engine,- &host,document,"--registered-color","<color>",- "red",+ "rgb(1, 2, 3)",);assert_eq!(@@ -80,9 +85,69 @@ fn css_register_property_does_not_advance_source_set_generation() {source_set_generation,"CSS.registerProperty changes author style semantics but not the stylesheet source set");+ assert_eq!(+ engine.computed_cache_generation_for_document_for_test(document),+ computed_generation,+ "CSS.registerProperty only marks the document dirty until the next observation"+ );+ assert_eq!(+ engine.source_dirty_scope_reasons_for_document_for_test(document),+ vec![StyleSourceDirtyReason::CustomPropertyRegistration]+ );++ assert_eq!(+ computed_value(&engine, &host, target, "--registered-color", &[]),+ "rgb(1, 2, 3)"+ );+ assert_eq!(+ engine.retained_stylist_identity_for_document_for_test(document),+ stylist_identity,+ "registerProperty must update the existing document Stylist"+ );+ assert_eq!(+ engine.retained_style_system_rebuild_count_for_document_for_test(document),+ rebuilds+ );+ assert_eq!(+ engine.retained_style_system_update_count_for_document_for_test(document),+ updates + 1+ );assert!(- engine.computed_cache_generation_for_document_for_test(document) > computed_generation,- "CSS.registerProperty still invalidates computed style state"+ engine+ .source_dirty_scope_reasons_for_document_for_test(document)+ .is_empty(),+ "the observation must consume the registration dirty marker"+ );+}++#[test]+fn registered_custom_properties_keep_their_registration_time_base_urls() {+ let mut host = test_host();+ let document = host.document_handle();+ let target = host.create_element("div");+ assert!(host.append_child(document, target));+ let mut engine = MoliStyleEngine::new();++ for (name, base_url) in [+ ("--first-image", "https://example.test/first/"),+ ("--second-image", "https://example.test/second/"),+ ] {+ engine+ .register_css_custom_property_for_document(+ document,+ registration(name, "<image>", "url(icon.svg)"),+ url::Url::parse(base_url).unwrap(),+ )+ .expect("custom property registration should succeed");+ }++ assert_eq!(+ computed_value(&engine, &host, target, "--first-image", &[]),+ r#"url("https://example.test/first/icon.svg")"#+ );+ assert_eq!(+ computed_value(&engine, &host, target, "--second-image", &[]),+ r#"url("https://example.test/second/icon.svg")"#);}@@ -97,7 +162,6 @@ fn invalid_registered_property_value_substitutes_registered_initial_value() {let mut engine = MoliStyleEngine::new();register_custom_property(&mut engine,- &host,document,"--registered-length","<length>",@@ -130,16 +194,14 @@ fn custom_property_registry_is_scoped_to_document_world() {let mut engine = MoliStyleEngine::new();engine- .register_css_custom_property_for_document_with_host(- &host,+ .register_css_custom_property_for_document(active_document,registration("--active-only", "<length>", "1px"),test_url(),).expect("active document registration should succeed");engine- .register_css_custom_property_for_document_with_host(- &host,+ .register_css_custom_property_for_document(detached_document,registration("--detached-only", "<color>", "red"),test_url(),@@ -194,7 +256,6 @@ fn registered_invalid_color_value_substitutes_initial_value_into_normal_propertylet mut engine = MoliStyleEngine::new();register_custom_property(&mut engine,- &host,document,"--registered-color","<color>",@@ -228,14 +289,7 @@ fn registered_length_lh_units_resolve_after_line_height() {assert!(host.append_child(document, target));let mut engine = MoliStyleEngine::new();- register_custom_property(- &mut engine,- &host,- document,- "--registered-lh",- "<length>",- "0px",- );+ register_custom_property(&mut engine, document, "--registered-lh", "<length>", "0px");let sources = vec![StyloStylesheetSource::new("#target {font-size: 10px;@@ -267,7 +321,6 @@ fn registered_color_values_resolve_currentcolor() {let mut engine = MoliStyleEngine::new();register_custom_property(&mut engine,- &host,document,"--registered-color","<color>",@@ -303,7 +356,6 @@ fn registered_color_functions_resolve_currentcolor() {let mut engine = MoliStyleEngine::new();register_custom_property(&mut engine,- &host,document,"--registered-color","<color>",@@ -337,7 +389,6 @@ fn registered_color_values_resolve_tree_counting_math() {let mut engine = MoliStyleEngine::new();register_custom_property(&mut engine,- &host,document,"--registered-color","<color>",diff --git a/moli-renderer-v8/src/style_engine/tests/slotted_focus.rs b/moli-renderer-v8/src/style_engine/tests/slotted_focus.rsindex 970a4d28f..39e44bef9 100644--- a/moli-renderer-v8/src/style_engine/tests/slotted_focus.rs+++ b/moli-renderer-v8/src/style_engine/tests/slotted_focus.rs@@ -28,7 +28,7 @@ fn slotted_dependency_invalidation_targets_assigned_nodes() {document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [outside, assigned] {assert!(engine@@ -102,7 +102,7 @@ fn slotted_dependency_change_clears_assigned_descendant_cache_via_subtree_cleanushadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((shadow_root, vec![shadow_source]));@@ -211,7 +211,7 @@ fn slotted_relative_anchor_invalidation_preserves_unmatched_assigned_node() {shadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((shadow_root, vec![shadow_source]));@@ -300,7 +300,7 @@ fn manual_slot_assignment_invalidation_uses_assigned_node_snapshot() {shadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((shadow_root, vec![shadow_source]));@@ -389,7 +389,7 @@ fn shadow_slot_insertion_uses_retargeted_assignment_snapshots() {shadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((shadow_root, vec![shadow_source]));@@ -468,7 +468,7 @@ fn slotted_dependency_invalidation_treats_assigned_node_as_shadow_scope() {document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [outside, assigned] {assert!(engine@@ -528,15 +528,14 @@ fn part_dependency_invalidation_targets_shadow_tree() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new(".host::part(label) { color: red; }".into(),document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [outside, part] {assert!(engine@@ -608,12 +607,8 @@ fn part_relative_anchor_invalidation_preserves_unmatched_part() {".host:has(.marker)::part(label) { color: rgb(1, 2, 3); }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [outside, part, unmatched_part] {@@ -682,12 +677,8 @@ fn document_part_rule_styles_shadow_part() {".host::part(label) { color: rgb(1, 2, 3); }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert_eq!(@@ -731,12 +722,8 @@ fn document_part_rule_styles_after_part_lang_and_invalidates() {.into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert_eq!(@@ -850,12 +837,8 @@ fn document_part_rule_styles_after_part_dir_and_invalidates() {.into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert_eq!(@@ -970,12 +953,8 @@ fn document_part_rule_styles_exported_nested_shadow_part() {".outer::part(public) { color: rgb(4, 5, 6); }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);assert_eq!(@@ -1017,7 +996,7 @@ fn shadow_part_rule_does_not_style_local_part_from_same_shadow_scope() {shadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((shadow_root, vec![shadow_source]));@@ -1066,7 +1045,7 @@ fn manual_slot_assignment_noop_preserves_cache_entries() {shadow_root,vec![shadow_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((shadow_root, vec![shadow_source]));@@ -1135,12 +1114,8 @@ fn attribute_relative_dependency_invalidates_outer_sibling_target() {".ancestor:has(.marker) + .target { color: red; }".into(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![source.clone()],- );- let mut inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![source.clone()]);+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(source);for handle in [outside, ancestor, target, unrelated] {assert!(@@ -1200,15 +1175,14 @@ fn unrelated_attribute_mutation_ignores_unmatched_has_selector_dependency() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new(".container:has(.marker) .target { color: red; }".into(),document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [unrelated, target] {assert!(engine@@ -1258,7 +1232,7 @@ fn style_attribute_mutation_keeps_local_subtree_fallback_without_dependency() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -1317,15 +1291,14 @@ fn attribute_sibling_invalidation_is_per_effect() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new(".marker + .target { color: red; }".into(),document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -1403,8 +1376,7 @@ fn focus_invalidation_keeps_unrelated_sibling_cache_entries() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new(".focusable:focus { color: red; }@@ -1413,7 +1385,7 @@ fn focus_invalidation_keeps_unrelated_sibling_cache_entries() {document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -1456,15 +1428,14 @@ fn focus_within_invalidation_preserves_unrelated_sibling_cache_entries() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new(".container:focus-within { color: red; }".into(),document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [previous, parent] {assert!(engine@@ -1514,15 +1485,14 @@ fn focus_sibling_invalidation_preserves_previous_sibling_cache() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new(".focusable:focus + .target { color: red; }".into(),document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [previous, target] {assert!(engine@@ -1571,8 +1541,7 @@ fn focus_invalidation_ignores_unmatched_has_selector_dependency() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new(".focusable:focus { color: red; }@@ -1581,7 +1550,7 @@ fn focus_invalidation_ignores_unmatched_has_selector_dependency() {document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [source, target] {assert!(engine@@ -1628,15 +1597,14 @@ fn focus_invalidation_uses_has_focus_relative_dependency() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new(".container:has(:focus) .target { color: blue; }".into(),document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -1678,15 +1646,14 @@ fn target_invalidation_keeps_pending_work_kind() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new("#current:target + .target { color: green; }".into(),document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -1727,8 +1694,7 @@ fn target_invalidation_ignores_unmatched_has_selector_dependency() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new("#current:target { color: red; }@@ -1737,7 +1703,7 @@ fn target_invalidation_ignores_unmatched_has_selector_dependency() {document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [source, target] {assert!(engine@@ -1785,15 +1751,14 @@ fn target_invalidation_uses_has_target_relative_dependency() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new(".container:has(:target) .target { color: blue; }".into(),document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -1837,15 +1802,14 @@ fn target_sibling_invalidation_preserves_previous_sibling_cache() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new("#current:target + .target { color: green; }".into(),document_url.clone(),)],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [previous, target] {assert!(engine@@ -1933,7 +1897,7 @@ fn attribute_relative_dependency_uses_impacted_shadow_stylesheet_scope() {);let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [outside, shadow_target] {assert!(enginediff --git a/moli-renderer-v8/src/style_engine/tests/subtree_cache.rs b/moli-renderer-v8/src/style_engine/tests/subtree_cache.rsindex 7d5a2c66d..0c685aa4f 100644--- a/moli-renderer-v8/src/style_engine/tests/subtree_cache.rs+++ b/moli-renderer-v8/src/style_engine/tests/subtree_cache.rs@@ -1,5 +1,157 @@use super::*;+fn assert_only_source_document_is_dirty(+ engine: &MoliStyleEngine,+ dirty_document: DomHandle,+ clean_document: DomHandle,+) {+ assert!(+ !engine+ .source_dirty_scope_reasons_for_document_for_test(dirty_document)+ .is_empty(),+ "the source owner document must carry pending style work"+ );+ assert!(+ engine+ .source_dirty_scope_reasons_for_document_for_test(clean_document)+ .is_empty(),+ "an unrelated document must remain clean"+ );+}++#[test]+fn computed_style_is_published_on_canonical_element_data_and_reused() {+ let mut host = test_host();+ let document = host.document_handle();+ let style = host.create_element("style");+ let target = host.create_element("div");+ assert!(host.set_attribute(target, "class", "target"));+ assert!(host.append_child(document, style));+ assert!(host.append_child(document, target));++ let mut engine = MoliStyleEngine::new();+ engine.set_owner_style_sheet_text_with_host(+ &host,+ style,+ ".target { color: rgb(1, 2, 3); }".into(),+ );+ let document_url = url::Url::parse("https://example.test/").unwrap();+ let inputs = FullStyleWorldSnapshot::default();++ let first = computed_style_snapshot_for_test(&engine, &host, &document_url, target, &inputs);+ let retained_first = retained_primary_style_for_test(&engine, &host, target)+ .expect("the target's computed style must live on canonical ElementData");+ assert!(ServoArc::ptr_eq(&first.computed_values(), &retained_first));+ let publication_generation =+ engine.computed_style_publication_generation_for_document_for_test(document);++ let second = computed_style_snapshot_for_test(&engine, &host, &document_url, target, &inputs);+ let retained_second = retained_primary_style_for_test(&engine, &host, target)+ .expect("a clean read must retain canonical ElementData");+ assert!(ServoArc::ptr_eq(+ &first.computed_values(),+ &second.computed_values()+ ));+ assert!(ServoArc::ptr_eq(&retained_first, &retained_second));+ assert_eq!(+ engine.computed_style_publication_generation_for_document_for_test(document),+ publication_generation,+ "reading clean canonical style must not republish a cache entry"+ );+}++#[test]+fn scoped_invalidation_marks_canonical_style_dirty_and_preserves_clean_elements() {+ let mut host = test_host();+ let document = host.document_handle();+ let style = host.create_element("style");+ let parent = host.create_element("section");+ let target = host.create_element("li");+ assert!(host.set_attribute(target, "style", "color: rgb(1, 2, 3)"));+ assert!(host.append_child(document, style));+ assert!(host.append_child(document, parent));+ assert!(host.append_child(parent, target));++ let mut engine = MoliStyleEngine::new();+ engine.set_owner_style_sheet_text_with_host(+ &host,+ style,+ "li { display: list-item; } li::marker { color: rgb(7, 8, 9); }".into(),+ );+ let document_url = url::Url::parse("https://example.test/").unwrap();+ let inputs = FullStyleWorldSnapshot::default();+ let parent_before =+ computed_style_snapshot_for_test(&engine, &host, &document_url, parent, &inputs)+ .computed_values();+ let target_before =+ computed_style_snapshot_for_test(&engine, &host, &document_url, target, &inputs)+ .computed_values();+ assert_eq!(+ engine.computed_style_property_value(+ &host,+ &document_url,+ target,+ "color",+ None,+ &inputs,+ None,+ ),+ Some("rgb(1, 2, 3)".into())+ );+ assert!(+ engine+ .computed_style_property_value(+ &host,+ &document_url,+ target,+ "color",+ Some("marker"),+ &inputs,+ None,+ )+ .is_some()+ );+ assert_eq!(+ engine.computed_style_cache_entry_count_for_handle_for_document_for_test(document, target),+ 2,+ "the publication index should contain primary and pseudo entries"+ );++ assert!(host.set_attribute(target, "style", "color: rgb(4, 5, 6)"));+ engine.invalidate_inline_style_subtree(&host, target);++ let retained_dirty_target = retained_primary_style_for_test(&engine, &host, target)+ .expect("dirty ElementData should retain its last published values");+ assert!(ServoArc::ptr_eq(&target_before, &retained_dirty_target));+ assert!(element_style_is_dirty_for_test(&engine, &host, target));+ let retained_parent = retained_primary_style_for_test(&engine, &host, parent)+ .expect("the unaffected parent must retain its computed style");+ assert!(ServoArc::ptr_eq(&parent_before, &retained_parent));+ assert!(!element_style_is_dirty_for_test(&engine, &host, parent));+ assert_eq!(+ engine.computed_style_cache_entry_count_for_handle_for_document_for_test(document, target),+ 0,+ "dirtying an element must evict both its publication marker and pseudo sidecar"+ );++ assert_eq!(+ engine.computed_style_property_value(+ &host,+ &document_url,+ target,+ "color",+ None,+ &inputs,+ None,+ ),+ Some("rgb(4, 5, 6)".into())+ );+ let target_after = retained_primary_style_for_test(&engine, &host, target)+ .expect("the recomputed style must be republished on ElementData");+ assert!(!ServoArc::ptr_eq(&target_before, &target_after));+ assert!(!element_style_is_dirty_for_test(&engine, &host, target));+}+#[test]fn inherited_ancestor_change_clears_descendant_cache_via_subtree_cleanup() {let mut host = test_host();@@ -20,7 +172,7 @@ fn inherited_ancestor_change_clears_descendant_cache_via_subtree_cleanup() {".theme { color: rgb(1, 2, 3); }".into(),);let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [descendant, unrelated] {assert!(engine@@ -82,7 +234,7 @@ fn custom_property_ancestor_change_clears_descendant_cache_via_subtree_cleanup()".theme { --accent: rgb(1, 2, 3); } span { color: var(--accent, black); }".into(),);let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [descendant, unrelated] {assert!(engine@@ -145,7 +297,7 @@ fn non_inherited_exact_change_still_clears_descendant_cache_via_subtree_cleanup(".theme { background-color: rgb(1, 2, 3); }".into(),);let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [descendant, unrelated] {assert!(engine@@ -211,7 +363,7 @@ fn shadow_host_inherited_change_clears_shadow_descendant_cache_via_subtree_clean".theme { color: rgb(1, 2, 3); }".into(),);let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [shadow_child, unrelated] {assert!(engine@@ -274,7 +426,7 @@ fn lazy_pseudo_inherited_change_clears_pseudo_cache_via_subtree_cleanup() {.into(),);let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -369,7 +521,7 @@ fn lazy_pseudo_custom_property_change_clears_pseudo_cache_via_subtree_cleanup().into(),);let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -466,7 +618,7 @@ fn source_local_fallback_roots_preserve_unrelated_document_cache_for_shadow_sourlet engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [outside, shadow_child, sibling_shadow_child] {assert!(engine@@ -538,7 +690,9 @@ fn shadow_adopted_stylesheet_rebuild_uses_scoped_dirty_roots() {shadow_root,vec![first_source.clone()],);- let mut first_inputs = StyloComputedStyleInputs::default();+ let first_source_ids =+ engine.shadow_root_adopted_style_sheet_source_ids_for_test(&host, shadow_root);+ let mut first_inputs = FullStyleWorldSnapshot::default();first_inputs.shadow_stylesheet_sources.push((shadow_root, vec![first_source]));@@ -588,6 +742,8 @@ fn shadow_adopted_stylesheet_rebuild_uses_scoped_dirty_roots() {shadow_root,vec![second_source.clone()],);+ let second_source_ids =+ engine.shadow_root_adopted_style_sheet_source_ids_for_test(&host, shadow_root);assert_eq!(engine.computed_cache_generation_for_document_for_test(document),@@ -606,13 +762,15 @@ fn shadow_adopted_stylesheet_rebuild_uses_scoped_dirty_roots() {engine.source_set_generation_for_document_for_test(document);assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, outside));assert!(- !engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child)+ engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child));- let second_source_id = StyleSourceId::shadow_root_adopted_style_sheet(shadow_root, 0);assert_eq!(engine.source_dirty_scope_source_ids_for_document_for_test(document),- vec![second_source_id]+ first_source_ids+ .into_iter()+ .chain(second_source_ids)+ .collect::<Vec<_>>());assert_eq!(engine.source_dirty_scope_ids_for_document_for_test(document),@@ -626,7 +784,7 @@ fn shadow_adopted_stylesheet_rebuild_uses_scoped_dirty_roots() {engine.source_dirty_scope_roots_for_document_for_test(document),vec![shadow_root, shadow_host]);- let mut second_inputs = StyloComputedStyleInputs::default();+ let mut second_inputs = FullStyleWorldSnapshot::default();second_inputs.shadow_stylesheet_sources.push((shadow_root, vec![second_source]));@@ -684,7 +842,7 @@ fn shadow_adopted_stylesheet_addition_rebuild_uses_scoped_dirty_roots() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let first_inputs = StyloComputedStyleInputs::default();+ let first_inputs = FullStyleWorldSnapshot::default();assert!(engine@@ -728,6 +886,7 @@ fn shadow_adopted_stylesheet_addition_rebuild_uses_scoped_dirty_roots() {shadow_root,vec![source.clone()],);+ let source_ids = engine.shadow_root_adopted_style_sheet_source_ids_for_test(&host, shadow_root);assert_eq!(engine.computed_cache_generation_for_document_for_test(document),@@ -735,13 +894,12 @@ fn shadow_adopted_stylesheet_addition_rebuild_uses_scoped_dirty_roots() {);assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, outside));assert!(- !engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child)+ engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child));- let source_id = StyleSourceId::shadow_root_adopted_style_sheet(shadow_root, 0);assert_eq!(engine.source_dirty_scope_source_ids_for_document_for_test(document),- vec![source_id]+ source_ids);assert_eq!(engine.source_dirty_scope_ids_for_document_for_test(document),@@ -755,7 +913,7 @@ fn shadow_adopted_stylesheet_addition_rebuild_uses_scoped_dirty_roots() {engine.source_dirty_scope_roots_for_document_for_test(document),vec![shadow_root, shadow_host]);- let mut second_inputs = StyloComputedStyleInputs::default();+ let mut second_inputs = FullStyleWorldSnapshot::default();second_inputs.shadow_stylesheet_sources.push((shadow_root, vec![source]));@@ -812,7 +970,8 @@ fn shadow_adopted_stylesheet_removal_rebuild_uses_scoped_dirty_roots() {shadow_root,vec![source.clone()],);- let mut first_inputs = StyloComputedStyleInputs::default();+ let source_ids = engine.shadow_root_adopted_style_sheet_source_ids_for_test(&host, shadow_root);+ let mut first_inputs = FullStyleWorldSnapshot::default();first_inputs.shadow_stylesheet_sources.push((shadow_root, vec![source]));@@ -857,13 +1016,12 @@ fn shadow_adopted_stylesheet_removal_rebuild_uses_scoped_dirty_roots() {);assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, outside));assert!(- !engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child)+ engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child));- let source_id = StyleSourceId::shadow_root_adopted_style_sheet(shadow_root, 0);assert_eq!(engine.source_dirty_scope_source_ids_for_document_for_test(document),- vec![source_id]+ source_ids);assert_eq!(engine.source_dirty_scope_ids_for_document_for_test(document),@@ -877,7 +1035,7 @@ fn shadow_adopted_stylesheet_removal_rebuild_uses_scoped_dirty_roots() {engine.source_dirty_scope_roots_for_document_for_test(document),vec![shadow_root, shadow_host]);- let second_inputs = StyloComputedStyleInputs::default();+ let second_inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -940,13 +1098,15 @@ fn shadow_adopted_stylesheet_dirty_scopes_keep_explicit_shadow_roots() {document_url,)],);+ let expected_source_ids = engine+ .shadow_root_adopted_style_sheet_source_ids_for_test(&host, first_root)+ .into_iter()+ .chain(engine.shadow_root_adopted_style_sheet_source_ids_for_test(&host, second_root))+ .collect::<Vec<_>>();assert_eq!(engine.source_dirty_scope_source_ids_for_document_for_test(document),- vec![- StyleSourceId::shadow_root_adopted_style_sheet(first_root, 0),- StyleSourceId::shadow_root_adopted_style_sheet(second_root, 0),- ]+ expected_source_ids);assert_eq!(engine.source_dirty_scope_ids_for_document_for_test(document),@@ -966,7 +1126,7 @@ fn shadow_adopted_stylesheet_dirty_scopes_keep_explicit_shadow_roots() {}#[test]-fn shadow_source_rebuild_full_clears_on_uncovered_shadow_root_order_change() {+fn shadow_scope_reorder_updates_the_retained_world_in_place() {let mut host = test_host();let document = host.document_handle();let outside = host.create_element("main");@@ -1006,7 +1166,7 @@ fn shadow_source_rebuild_full_clears_on_uncovered_shadow_root_order_change() {second_root,vec![second_source.clone()],);- let mut first_inputs = StyloComputedStyleInputs::default();+ let mut first_inputs = FullStyleWorldSnapshot::default();first_inputs.shadow_stylesheet_sources.push((first_root, vec![first_source]));@@ -1045,6 +1205,8 @@ fn shadow_source_rebuild_full_clears_on_uncovered_shadow_root_order_change() {);let generation_after_first_build =engine.computed_cache_generation_for_document_for_test(document);+ let stylist_identity = engine.retained_stylist_identity_for_document_for_test(document);+ let rebuilds = engine.retained_style_system_rebuild_count_for_document_for_test(document);let changed_source = StyloStylesheetSource::new("span { color: rgb(7, 8, 9); }".to_owned(),@@ -1062,10 +1224,10 @@ fn shadow_source_rebuild_full_clears_on_uncovered_shadow_root_order_change() {);assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, outside));assert!(- !engine.computed_style_cache_contains_handle_for_document_for_test(document, first_child)+ engine.computed_style_cache_contains_handle_for_document_for_test(document, first_child));- let mut second_inputs = StyloComputedStyleInputs::default();+ let mut second_inputs = FullStyleWorldSnapshot::default();second_inputs.shadow_stylesheet_sources.push((second_root, vec![second_source]));@@ -1085,18 +1247,26 @@ fn shadow_source_rebuild_full_clears_on_uncovered_shadow_root_order_change() {Some("rgb(7, 8, 9)".into()));- assert!(- engine.computed_cache_generation_for_document_for_test(document)- > generation_after_first_build,- "shadow root list reordering is not proven source-local by dirty roots"+ assert_eq!(+ engine.computed_cache_generation_for_document_for_test(document),+ generation_after_first_build,+ "TreeScope order is metadata, not a reason to replace the document style world");assert!(- !engine.computed_style_cache_contains_handle_for_document_for_test(document, outside),- "full rebuild should clear unrelated computed entries when list reordering is not covered"+ engine.computed_style_cache_contains_handle_for_document_for_test(document, outside),+ "a ShadowRoot update must preserve unrelated document styles");assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, first_child));+ assert_eq!(+ engine.retained_stylist_identity_for_document_for_test(document),+ stylist_identity+ );+ assert_eq!(+ engine.retained_style_system_rebuild_count_for_document_for_test(document),+ rebuilds+ );}#[test]@@ -1114,12 +1284,9 @@ fn document_adopted_stylesheet_rebuild_uses_scoped_dirty_root() {"section { color: rgb(1, 2, 3); }".to_owned(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![first_source.clone()],- );- let mut first_inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![first_source.clone()]);+ let first_source_ids = engine.document_adopted_style_sheet_source_ids_for_test(document);+ let mut first_inputs = FullStyleWorldSnapshot::default();first_inputs.document_stylesheet_sources.push(first_source);assert!(@@ -1158,11 +1325,8 @@ fn document_adopted_stylesheet_rebuild_uses_scoped_dirty_root() {"section { color: rgb(4, 5, 6); }".to_owned(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![second_source.clone()],- );+ engine.set_document_adopted_style_sheet_sources(document, vec![second_source.clone()]);+ let second_source_ids = engine.document_adopted_style_sheet_source_ids_for_test(document);assert_eq!(engine.computed_cache_generation_for_document_for_test(document),@@ -1170,13 +1334,16 @@ fn document_adopted_stylesheet_rebuild_uses_scoped_dirty_root() {);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(document),- 0+ 2,+ "a source mutation must delay invalidation until the next observation");- let second_source_id = StyleSourceId::document_adopted_style_sheet(document, 0);assert_eq!(engine.source_dirty_scope_source_ids_for_document_for_test(document),- vec![second_source_id]+ first_source_ids+ .into_iter()+ .chain(second_source_ids)+ .collect::<Vec<_>>());assert_eq!(engine.source_dirty_scope_ids_for_document_for_test(document),@@ -1190,7 +1357,7 @@ fn document_adopted_stylesheet_rebuild_uses_scoped_dirty_root() {engine.source_dirty_scope_roots_for_document_for_test(document),vec![document]);- let mut second_inputs = StyloComputedStyleInputs::default();+ let mut second_inputs = FullStyleWorldSnapshot::default();second_inputs.document_stylesheet_sources.push(second_source);@@ -1220,7 +1387,7 @@ fn document_adopted_stylesheet_rebuild_uses_scoped_dirty_root() {}#[test]-fn document_source_scoped_rebuild_clears_same_document_shadow_cascade_data() {+fn document_source_update_preserves_shadow_scope_cascade_data() {let mut host = test_host();let document = host.document_handle();let active_shadow_host = host.create_element("section");@@ -1250,11 +1417,7 @@ fn document_source_scoped_rebuild_clears_same_document_shadow_cascade_data() {StyloStylesheetSource::new(":host { display: block; }".to_owned(), document_url.clone());let detached_shadow_source =StyloStylesheetSource::new(":host { display: flex; }".to_owned(), document_url.clone());- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![first_document_source.clone()],- );+ engine.set_document_adopted_style_sheet_sources(document, vec![first_document_source.clone()]);engine.set_shadow_root_adopted_style_sheet_sources_with_host(&host,active_shadow_root,@@ -1266,21 +1429,21 @@ fn document_source_scoped_rebuild_clears_same_document_shadow_cascade_data() {vec![detached_shadow_source.clone()],);- let mut active_inputs = StyloComputedStyleInputs::default();+ let mut active_inputs = FullStyleWorldSnapshot::default();active_inputs.document_stylesheet_sources.push(first_document_source);active_inputs.shadow_stylesheet_sources.push((active_shadow_root, vec![active_shadow_source]));- let active_key = StyleSystemCacheKey::new(&document_url, &active_inputs, None);+ let active_key = StyleWorldKey::new(&document_url, &active_inputs, None);engine.ensure_retained_style_system_for_document(&host, document, active_key, &active_inputs);- let mut detached_inputs = StyloComputedStyleInputs::default();+ let mut detached_inputs = FullStyleWorldSnapshot::default();detached_inputs.shadow_stylesheet_sources.push((detached_shadow_root, vec![detached_shadow_source]));- let detached_key = StyleSystemCacheKey::new(&document_url, &detached_inputs, None);+ let detached_key = StyleWorldKey::new(&document_url, &detached_inputs, None);engine.ensure_retained_style_system_for_document(&host,detached_document,@@ -1313,7 +1476,7 @@ fn document_source_scoped_rebuild_clears_same_document_shadow_cascade_data() {.set_shadow_cascade_data_for_document_for_test(document,active_shadow_root,- active_cascade_data,+ active_cascade_data.clone(),);engine.dom_adapter@@ -1333,14 +1496,10 @@ fn document_source_scoped_rebuild_clears_same_document_shadow_cascade_data() {.has_shadow_cascade_data_for_test(detached_shadow_root));- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![second_document_source],- );+ engine.set_document_adopted_style_sheet_sources(document, vec![second_document_source.clone()]);assert!(- !engine+ engine.dom_adapter.has_shadow_cascade_data_for_test(active_shadow_root));@@ -1349,10 +1508,31 @@ fn document_source_scoped_rebuild_clears_same_document_shadow_cascade_data() {.dom_adapter.has_shadow_cascade_data_for_test(detached_shadow_root));++ active_inputs.document_stylesheet_sources.clear();+ active_inputs+ .document_stylesheet_sources+ .push(second_document_source);+ let active_key = StyleWorldKey::new(&document_url, &active_inputs, None);+ engine.ensure_retained_style_system_for_document(&host, document, active_key, &active_inputs);+ let active_cascade_data_after =+ engine.with_retained_style_system_for_document_for_test(document, |retained| {+ retained+ .shadow_cascade_data+ .iter()+ .find(|(root, _)| *root == active_shadow_root)+ .expect("active retained system should keep the active shadow root")+ .1+ .clone()+ });+ assert!(ServoArc::ptr_eq(+ &active_cascade_data,+ &active_cascade_data_after+ ));}#[test]-fn clear_all_fallback_record_prevents_scoped_retained_rebuild() {+fn clear_all_fallback_clears_element_styles_without_replacing_the_style_world() {let mut host = test_host();let document = host.document_handle();let outside = host.create_element("main");@@ -1366,12 +1546,8 @@ fn clear_all_fallback_record_prevents_scoped_retained_rebuild() {"section { color: rgb(1, 2, 3); }".to_owned(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![first_source.clone()],- );- let mut first_inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(document, vec![first_source.clone()]);+ let mut first_inputs = FullStyleWorldSnapshot::default();first_inputs.document_stylesheet_sources.push(first_source);assert!(@@ -1401,16 +1577,15 @@ fn clear_all_fallback_record_prevents_scoped_retained_rebuild() {);let generation_after_first_build =engine.computed_cache_generation_for_document_for_test(document);+ let stylist_identity = engine.retained_stylist_identity_for_document_for_test(document);+ let rebuilds = engine.retained_style_system_rebuild_count_for_document_for_test(document);+ let updates = engine.retained_style_system_update_count_for_document_for_test(document);let second_source = StyloStylesheetSource::new("section { color: rgb(4, 5, 6); }".to_owned(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- document,- vec![second_source.clone()],- );+ engine.set_document_adopted_style_sheet_sources(document, vec![second_source.clone()]);let outcome = StyleInvalidationOutcome::retained_clear_all_for_test([StyloSourceInvalidationFallbackReason::FullSelector,]);@@ -1428,7 +1603,7 @@ fn clear_all_fallback_record_prevents_scoped_retained_rebuild() {]);- let mut second_inputs = StyloComputedStyleInputs::default();+ let mut second_inputs = FullStyleWorldSnapshot::default();second_inputs.document_stylesheet_sources.push(second_source);@@ -1445,10 +1620,22 @@ fn clear_all_fallback_record_prevents_scoped_retained_rebuild() {Some("rgb(4, 5, 6)".into()));- assert!(- engine.computed_cache_generation_for_document_for_test(document)- > generation_after_first_build,- "mixed clear-all fallback diagnostics should force full retained rebuild"+ assert_eq!(+ engine.computed_cache_generation_for_document_for_test(document),+ generation_after_first_build,+ "a clear-all element fallback must not replace the document style world"+ );+ assert_eq!(+ engine.retained_stylist_identity_for_document_for_test(document),+ stylist_identity+ );+ assert_eq!(+ engine.retained_style_system_rebuild_count_for_document_for_test(document),+ rebuilds+ );+ assert_eq!(+ engine.retained_style_system_update_count_for_document_for_test(document),+ updates + 1);assert!(engine@@ -1481,7 +1668,7 @@ fn owner_stylesheet_rebuild_uses_document_dirty_root() {.owner_style_sheet_source_with_host(&host, style).expect("document owner stylesheet source").with_source_id(Some(first_source_id));- let mut first_inputs = StyloComputedStyleInputs::default();+ let mut first_inputs = FullStyleWorldSnapshot::default();first_inputs.document_stylesheet_sources.push(first_source);assert!(@@ -1528,7 +1715,8 @@ fn owner_stylesheet_rebuild_uses_document_dirty_root() {);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(document),- 0+ 2,+ "an owner stylesheet mutation must wait for the next observation");let second_source_id = StyleSourceId::owner_style_sheet(&host, style)@@ -1553,7 +1741,7 @@ fn owner_stylesheet_rebuild_uses_document_dirty_root() {.owner_style_sheet_source_with_host(&host, style).expect("document owner stylesheet source").with_source_id(Some(second_source_id));- let mut second_inputs = StyloComputedStyleInputs::default();+ let mut second_inputs = FullStyleWorldSnapshot::default();second_inputs.document_stylesheet_sources.push(second_source);@@ -1620,7 +1808,7 @@ fn repeated_owner_stylesheet_changes_reuse_applied_document_cleanup() {vec![first_source_id.clone(), second_source_id.clone()]);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();for (owner, source_id) in [(first_style, first_source_id),(second_style, second_source_id),@@ -1680,7 +1868,7 @@ fn shadow_owner_stylesheet_rebuild_uses_scoped_dirty_roots() {.owner_style_sheet_source_with_host(&host, shadow_style).expect("shadow owner stylesheet source").with_source_id(Some(first_source_id));- let mut first_inputs = StyloComputedStyleInputs::default();+ let mut first_inputs = FullStyleWorldSnapshot::default();first_inputs.shadow_stylesheet_sources.push((shadow_root, vec![first_source]));@@ -1729,7 +1917,7 @@ fn shadow_owner_stylesheet_rebuild_uses_scoped_dirty_roots() {);assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, outside));assert!(- !engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child)+ engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child));let second_source_id = StyleSourceId::owner_style_sheet(&host, shadow_style)@@ -1754,7 +1942,7 @@ fn shadow_owner_stylesheet_rebuild_uses_scoped_dirty_roots() {.owner_style_sheet_source_with_host(&host, shadow_style).expect("shadow owner stylesheet source").with_source_id(Some(second_source_id));- let mut second_inputs = StyloComputedStyleInputs::default();+ let mut second_inputs = FullStyleWorldSnapshot::default();second_inputs.shadow_stylesheet_sources.push((shadow_root, vec![second_source]));@@ -1823,7 +2011,7 @@ fn mixed_document_and_shadow_source_rebuild_uses_document_dirty_root() {.owner_style_sheet_source_with_host(&host, shadow_style).expect("shadow owner stylesheet source").with_source_id(Some(first_shadow_source_id));- let mut first_inputs = StyloComputedStyleInputs::default();+ let mut first_inputs = FullStyleWorldSnapshot::default();first_inputs.document_stylesheet_sources.push(first_document_source);@@ -1879,7 +2067,8 @@ fn mixed_document_and_shadow_source_rebuild_uses_document_dirty_root() {);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(document),- 0+ 2,+ "batched document and shadow mutations must wait for one observation");let second_document_source_id = StyleSourceId::owner_style_sheet(&host, document_style).expect("document owner stylesheet source id");@@ -1912,7 +2101,7 @@ fn mixed_document_and_shadow_source_rebuild_uses_document_dirty_root() {.owner_style_sheet_source_with_host(&host, shadow_style).expect("shadow owner stylesheet source").with_source_id(Some(second_shadow_source_id));- let mut second_inputs = StyloComputedStyleInputs::default();+ let mut second_inputs = FullStyleWorldSnapshot::default();second_inputs.document_stylesheet_sources.push(second_document_source);@@ -1967,7 +2156,7 @@ fn inline_style_subtree_invalidation_uses_root_document_world() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [active, detached] {assert!(engine@@ -2027,14 +2216,10 @@ fn detached_document_mutation_pending_work_uses_owner_document_world() {".active { color: rgb(1, 2, 3); }".to_owned(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- detached_document,- vec![source.clone()],- );- let mut detached_inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(detached_document, vec![source.clone()]);+ let mut detached_inputs = FullStyleWorldSnapshot::default();detached_inputs.document_stylesheet_sources.push(source);- let active_inputs = StyloComputedStyleInputs::default();+ let active_inputs = FullStyleWorldSnapshot::default();assert!(engine@@ -2141,14 +2326,10 @@ fn detached_document_focus_change_pending_work_uses_owner_document_world() {"section:focus { color: rgb(1, 2, 3); }".to_owned(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- detached_document,- vec![source.clone()],- );- let mut detached_inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(detached_document, vec![source.clone()]);+ let mut detached_inputs = FullStyleWorldSnapshot::default();detached_inputs.document_stylesheet_sources.push(source);- let active_inputs = StyloComputedStyleInputs::default();+ let active_inputs = FullStyleWorldSnapshot::default();assert!(engine@@ -2207,14 +2388,10 @@ fn detached_document_target_change_pending_work_uses_owner_document_world() {"section:target { color: rgb(1, 2, 3); }".to_owned(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- detached_document,- vec![source.clone()],- );- let mut detached_inputs = StyloComputedStyleInputs::default();+ engine.set_document_adopted_style_sheet_sources(detached_document, vec![source.clone()]);+ let mut detached_inputs = FullStyleWorldSnapshot::default();detached_inputs.document_stylesheet_sources.push(source);- let active_inputs = StyloComputedStyleInputs::default();+ let active_inputs = FullStyleWorldSnapshot::default();assert!(engine@@ -2302,11 +2479,7 @@ fn detached_document_adopted_stylesheet_change_uses_document_world() {".target { color: rgb(1, 2, 3); }".to_owned(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- detached_document,- vec![first_source.clone()],- );+ engine.set_document_adopted_style_sheet_sources(detached_document, vec![first_source.clone()]);assert_eq!(engine.adopted_style_sheet_source_owner_counts_for_document_for_test(document),(0, 0)@@ -2328,11 +2501,11 @@ fn detached_document_adopted_stylesheet_change_uses_document_world() {.len(),1);- let mut first_detached_inputs = StyloComputedStyleInputs::default();+ let mut first_detached_inputs = FullStyleWorldSnapshot::default();first_detached_inputs.document_stylesheet_sources.push(first_source);- let active_inputs = StyloComputedStyleInputs::default();+ let active_inputs = FullStyleWorldSnapshot::default();assert!(host.set_attribute(detached, "class", "target"));assert!(@@ -2373,11 +2546,7 @@ fn detached_document_adopted_stylesheet_change_uses_document_world() {".target { color: rgb(4, 5, 6); }".to_owned(),document_url.clone(),);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- detached_document,- vec![second_source.clone()],- );+ engine.set_document_adopted_style_sheet_sources(detached_document, vec![second_source.clone()]);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(document),@@ -2385,17 +2554,19 @@ fn detached_document_adopted_stylesheet_change_uses_document_world() {);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(detached_document),- 0+ 1,+ "the owner document keeps its published style until observation");assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, active));assert!(- !engine.computed_style_cache_contains_handle_for_document_for_test(+ engine.computed_style_cache_contains_handle_for_document_for_test(detached_document,detached));+ assert_only_source_document_is_dirty(&engine, detached_document, document);- let mut second_detached_inputs = StyloComputedStyleInputs::default();+ let mut second_detached_inputs = FullStyleWorldSnapshot::default();second_detached_inputs.document_stylesheet_sources.push(second_source);@@ -2441,7 +2612,7 @@ fn detached_document_owner_stylesheet_change_uses_owner_document_world() {detached_style,".target { color: rgb(1, 2, 3); }".to_owned(),);- let mut detached_inputs = StyloComputedStyleInputs::default();+ let mut detached_inputs = FullStyleWorldSnapshot::default();let detached_source = engine.owner_style_sheet_source_with_host(&host, detached_style).expect("detached owner style source");@@ -2452,7 +2623,7 @@ fn detached_document_owner_stylesheet_change_uses_owner_document_world() {detached_inputs.document_stylesheet_sources.push(detached_source);- let active_inputs = StyloComputedStyleInputs::default();+ let active_inputs = FullStyleWorldSnapshot::default();assert!(engine@@ -2492,15 +2663,17 @@ fn detached_document_owner_stylesheet_change_uses_owner_document_world() {);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(detached_document),- 0+ 1,+ "the detached owner document invalidates at observation time");assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, active));assert!(- !engine.computed_style_cache_contains_handle_for_document_for_test(+ engine.computed_style_cache_contains_handle_for_document_for_test(detached_document,detached));+ assert_only_source_document_is_dirty(&engine, detached_document, document);}#[test]@@ -2512,7 +2685,7 @@ fn ownerless_owner_stylesheet_change_does_not_use_active_document_world() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine@@ -2658,7 +2831,7 @@ fn linked_stylesheet_sources_are_document_world_local() {}#[test]-fn removed_linked_stylesheet_owner_lifecycle_clears_owner_document_world() {+fn removed_linked_stylesheet_owner_lifecycle_marks_owner_document_dirty() {let mut host = test_host();let document = host.document_handle();let active = host.create_element("main");@@ -2682,7 +2855,7 @@ fn removed_linked_stylesheet_owner_lifecycle_clears_owner_document_world() {(1, 1));- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -2713,7 +2886,8 @@ fn removed_linked_stylesheet_owner_lifecycle_clears_owner_document_world() {);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(document),- 0+ 1,+ "removing a stylesheet owner delays style invalidation until observation");}@@ -2742,7 +2916,7 @@ fn linked_stylesheet_owner_lifecycle_uses_final_remove_in_same_batch() {(1, 1));- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -2775,12 +2949,13 @@ fn linked_stylesheet_owner_lifecycle_uses_final_remove_in_same_batch() {);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(document),- 0+ 1,+ "the final owner lifecycle state is applied at the observation boundary");}#[test]-fn inactive_linked_stylesheet_owner_lifecycle_clears_owner_document_world() {+fn inactive_linked_stylesheet_owner_lifecycle_marks_owner_document_dirty() {let mut host = test_host();let document = host.document_handle();let active = host.create_element("main");@@ -2804,7 +2979,7 @@ fn inactive_linked_stylesheet_owner_lifecycle_clears_owner_document_world() {(1, 1));- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -2835,7 +3010,8 @@ fn inactive_linked_stylesheet_owner_lifecycle_clears_owner_document_world() {);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(document),- 0+ 1,+ "disabling a stylesheet owner delays style invalidation until observation");}@@ -2851,7 +3027,7 @@ fn first_unknown_owner_linked_stylesheet_url_record_preserves_document_worlds()let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -2931,7 +3107,7 @@ fn no_client_linked_stylesheet_url_update_preserves_document_worlds() {StyloStylesheetSource::new("main { color: green; }".into(), linked_url.clone()),);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -2996,7 +3172,7 @@ fn explicit_linked_stylesheet_install_uses_captured_url_not_live_href() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -3029,9 +3205,10 @@ fn explicit_linked_stylesheet_install_uses_captured_url_not_live_href() {);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(document),- 0+ 1,+ "installing an explicit source only marks the owner world dirty");- assert!(!engine.computed_style_cache_contains_handle_for_document_for_test(document, active));+ assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, active));}#[test]@@ -3069,11 +3246,11 @@ fn ownerless_dom_link_url_update_does_not_register_owner_document_world() {engine.linked_stylesheet_owner_registry_counts_for_document_for_test(detached_document),(0, 0));- let mut detached_inputs = StyloComputedStyleInputs::default();+ let mut detached_inputs = FullStyleWorldSnapshot::default();detached_inputs.document_stylesheet_sources.push(first_source);- let active_inputs = StyloComputedStyleInputs::default();+ let active_inputs = FullStyleWorldSnapshot::default();assert!(engine@@ -3142,7 +3319,7 @@ fn ownerless_stylesheet_network_result_does_not_discover_dom_link_owner() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();let stale_url = url::Url::parse("https://example.test/stale.css").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine@@ -3301,11 +3478,11 @@ fn detached_document_linked_stylesheet_install_uses_owner_document_world() {".target { color: rgb(1, 2, 3); }".to_owned(),linked_url.clone(),);- let mut detached_inputs = StyloComputedStyleInputs::default();+ let mut detached_inputs = FullStyleWorldSnapshot::default();detached_inputs.document_stylesheet_sources.push(linked_source.clone());- let active_inputs = StyloComputedStyleInputs::default();+ let active_inputs = FullStyleWorldSnapshot::default();assert!(engine@@ -3346,15 +3523,17 @@ fn detached_document_linked_stylesheet_install_uses_owner_document_world() {);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(detached_document),- 0+ 1,+ "the detached owner world invalidates on its next observation");assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, active));assert!(- !engine.computed_style_cache_contains_handle_for_document_for_test(+ engine.computed_style_cache_contains_handle_for_document_for_test(detached_document,detached));+ assert_only_source_document_is_dirty(&engine, detached_document, document);}#[test]@@ -3385,11 +3564,11 @@ fn detached_document_linked_stylesheet_source_change_uses_link_owner_document_wofirst_source.clone(),&[detached_link],);- let mut detached_inputs = StyloComputedStyleInputs::default();+ let mut detached_inputs = FullStyleWorldSnapshot::default();detached_inputs.document_stylesheet_sources.push(first_source);- let active_inputs = StyloComputedStyleInputs::default();+ let active_inputs = FullStyleWorldSnapshot::default();assert!(engine@@ -3434,15 +3613,17 @@ fn detached_document_linked_stylesheet_source_change_uses_link_owner_document_wo);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(detached_document),- 0+ 1,+ "the detached linked-source world invalidates at observation time");assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, active));assert!(- !engine.computed_style_cache_contains_handle_for_document_for_test(+ engine.computed_style_cache_contains_handle_for_document_for_test(detached_document,detached));+ assert_only_source_document_is_dirty(&engine, detached_document, document);}#[test]@@ -3476,7 +3657,7 @@ fn linked_stylesheet_source_rebuild_uses_document_dirty_root() {.stylesheet_source_for_url_for_document_for_test(document, &linked_url).expect("document linked source").with_source_id(Some(first_source_id));- let mut first_inputs = StyloComputedStyleInputs::default();+ let mut first_inputs = FullStyleWorldSnapshot::default();first_inputs.document_stylesheet_sources.push(first_source);assert!(@@ -3527,7 +3708,8 @@ fn linked_stylesheet_source_rebuild_uses_document_dirty_root() {);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(document),- 0+ 2,+ "a linked stylesheet revision must wait for the next observation");let second_source_id =@@ -3552,7 +3734,7 @@ fn linked_stylesheet_source_rebuild_uses_document_dirty_root() {.stylesheet_source_for_url_for_document_for_test(document, &linked_url).expect("document linked source").with_source_id(Some(second_source_id));- let mut second_inputs = StyloComputedStyleInputs::default();+ let mut second_inputs = FullStyleWorldSnapshot::default();second_inputs.document_stylesheet_sources.push(second_source);@@ -3617,7 +3799,7 @@ fn shadow_linked_stylesheet_source_rebuild_uses_scoped_dirty_roots() {.stylesheet_source_for_url_for_document_for_test(document, &linked_url).expect("shadow linked source").with_source_id(Some(first_source_id));- let mut first_inputs = StyloComputedStyleInputs::default();+ let mut first_inputs = FullStyleWorldSnapshot::default();first_inputs.shadow_stylesheet_sources.push((shadow_root, vec![first_source]));@@ -3670,7 +3852,7 @@ fn shadow_linked_stylesheet_source_rebuild_uses_scoped_dirty_roots() {);assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, outside));assert!(- !engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child)+ engine.computed_style_cache_contains_handle_for_document_for_test(document, shadow_child));let second_source_id =@@ -3695,7 +3877,7 @@ fn shadow_linked_stylesheet_source_rebuild_uses_scoped_dirty_roots() {.stylesheet_source_for_url_for_document_for_test(document, &linked_url).expect("shadow linked source").with_source_id(Some(second_source_id));- let mut second_inputs = StyloComputedStyleInputs::default();+ let mut second_inputs = FullStyleWorldSnapshot::default();second_inputs.shadow_stylesheet_sources.push((shadow_root, vec![second_source]));@@ -3760,9 +3942,9 @@ fn linked_stylesheet_final_url_update_uses_current_owner_document_after_owner_mofirst_source.clone(),);- let mut active_inputs = StyloComputedStyleInputs::default();+ let mut active_inputs = FullStyleWorldSnapshot::default();active_inputs.document_stylesheet_sources.push(first_source);- let detached_inputs = StyloComputedStyleInputs::default();+ let detached_inputs = FullStyleWorldSnapshot::default();assert_eq!(engine.computed_style_property_value(@@ -3803,19 +3985,21 @@ fn linked_stylesheet_final_url_update_uses_current_owner_document_after_owner_moassert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(document),- 0+ 1,+ "the current owner document invalidates at observation time");assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(detached_document),1);- assert!(!engine.computed_style_cache_contains_handle_for_document_for_test(document, active));+ assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, active));assert!(engine.computed_style_cache_contains_handle_for_document_for_test(detached_document,detached));+ assert_only_source_document_is_dirty(&engine, document, detached_document);}#[test]@@ -3846,11 +4030,11 @@ fn detached_document_url_source_change_uses_explicit_source_owner_document_worldfirst_source.clone(),&[detached_link],);- let mut detached_inputs = StyloComputedStyleInputs::default();+ let mut detached_inputs = FullStyleWorldSnapshot::default();detached_inputs.document_stylesheet_sources.push(first_source);- let active_inputs = StyloComputedStyleInputs::default();+ let active_inputs = FullStyleWorldSnapshot::default();assert!(engine@@ -3895,15 +4079,17 @@ fn detached_document_url_source_change_uses_explicit_source_owner_document_world);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(detached_document),- 0+ 1,+ "the explicit owner document invalidates at observation time");assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, active));assert!(- !engine.computed_style_cache_contains_handle_for_document_for_test(+ engine.computed_style_cache_contains_handle_for_document_for_test(detached_document,detached));+ assert_only_source_document_is_dirty(&engine, detached_document, document);}#[test]@@ -3934,8 +4120,8 @@ fn detached_document_url_source_explicit_owner_change_uses_owner_document_world();assert!(host.set_attribute(detached_link, "href", "linked.css"));- let active_inputs = StyloComputedStyleInputs::default();- let mut detached_inputs = StyloComputedStyleInputs::default();+ let active_inputs = FullStyleWorldSnapshot::default();+ let mut detached_inputs = FullStyleWorldSnapshot::default();detached_inputs.document_stylesheet_sources.push(source.clone());@@ -3979,15 +4165,17 @@ fn detached_document_url_source_explicit_owner_change_uses_owner_document_world();assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(detached_document),- 0+ 1,+ "capturing the explicit owner only marks that world dirty");assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, active));assert!(- !engine.computed_style_cache_contains_handle_for_document_for_test(+ engine.computed_style_cache_contains_handle_for_document_for_test(detached_document,detached));+ assert_only_source_document_is_dirty(&engine, detached_document, document);}#[test]@@ -4003,7 +4191,7 @@ fn explicit_linked_source_install_does_not_rederive_missing_live_href() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();let stale_url = url::Url::parse("https://example.test/stale.css").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine@@ -4045,9 +4233,10 @@ fn explicit_linked_source_install_does_not_rederive_missing_live_href() {);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(document),- 0+ 1,+ "the installed source is applied at the next observation");- assert!(!engine.computed_style_cache_contains_handle_for_document_for_test(document, target));+ assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, target));}#[test]@@ -4065,7 +4254,7 @@ fn explicit_linked_source_install_is_not_rejected_by_live_disabled_state() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();let linked_url = url::Url::parse("https://example.test/linked.css").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine@@ -4097,9 +4286,10 @@ fn explicit_linked_source_install_is_not_rejected_by_live_disabled_state() {assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(document),- 0+ 1,+ "the installed disabled source is applied at the next observation");- assert!(!engine.computed_style_cache_contains_handle_for_document_for_test(document, target));+ assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, target));}#[test]@@ -4131,11 +4321,11 @@ fn ownerless_final_url_source_update_preserves_document_worlds() {first_source.clone(),&[detached_link],);- let mut detached_inputs = StyloComputedStyleInputs::default();+ let mut detached_inputs = FullStyleWorldSnapshot::default();detached_inputs.document_stylesheet_sources.push(first_source);- let active_inputs = StyloComputedStyleInputs::default();+ let active_inputs = FullStyleWorldSnapshot::default();assert!(engine@@ -4234,7 +4424,7 @@ fn detached_document_inline_style_metadata_uses_owner_document_world() {detached,"background-image",None,- &StyloComputedStyleInputs::default(),+ &FullStyleWorldSnapshot::default(),None,),Some("url(\"https://detached.test/cssom/icon.png\")".into())@@ -4290,7 +4480,7 @@ fn inline_style_metadata_moves_to_current_owner_document_world() {target,"background-image",None,- &StyloComputedStyleInputs::default(),+ &FullStyleWorldSnapshot::default(),None,),Some("url(\"https://example.test/cssom/icon.png\")".into())@@ -4330,11 +4520,11 @@ fn detached_shadow_adopted_stylesheet_change_uses_owner_document_world() {detached_shadow_sources[0].serialized_css_text().as_ref(),".target { color: rgb(1, 2, 3); }");- let mut detached_inputs = StyloComputedStyleInputs::default();+ let mut detached_inputs = FullStyleWorldSnapshot::default();detached_inputs.shadow_stylesheet_sources.push((detached_shadow_root, detached_shadow_sources));- let active_inputs = StyloComputedStyleInputs::default();+ let active_inputs = FullStyleWorldSnapshot::default();assert!(engine@@ -4376,15 +4566,17 @@ fn detached_shadow_adopted_stylesheet_change_uses_owner_document_world() {);assert_eq!(engine.computed_style_cache_entry_count_for_document_for_test(detached_document),- 0+ 1,+ "the detached shadow world invalidates at observation time");assert!(engine.computed_style_cache_contains_handle_for_document_for_test(document, active));assert!(- !engine.computed_style_cache_contains_handle_for_document_for_test(+ engine.computed_style_cache_contains_handle_for_document_for_test(detached_document,detached));+ assert_only_source_document_is_dirty(&engine, detached_document, document);}#[test]@@ -4431,8 +4623,7 @@ fn matching_dependency_sources_have_explicit_source_and_scope_ids() {&[linked_style],);- engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ engine.set_document_adopted_style_sheet_sources(document,vec![StyloStylesheetSource::new(@@ -4481,26 +4672,17 @@ fn matching_dependency_sources_have_explicit_source_and_scope_ids() {owner: shadow_style,},};- let document_adopted_a_id = StyleSourceId {- scope_id: StyleScopeId::Document(document),- kind: StyleSourceKind::DocumentAdoptedStyleSheet { index: 0 },- };- let document_adopted_b_id = StyleSourceId {- scope_id: StyleScopeId::Document(document),- kind: StyleSourceKind::DocumentAdoptedStyleSheet { index: 1 },- };- let shadow_adopted_id = StyleSourceId {- scope_id: StyleScopeId::ShadowRoot(shadow_root),- kind: StyleSourceKind::ShadowRootAdoptedStyleSheet { index: 0 },- };+ let document_adopted_ids = engine.document_adopted_style_sheet_source_ids_for_test(document);+ let shadow_adopted_ids =+ engine.shadow_root_adopted_style_sheet_source_ids_for_test(&host, shadow_root);for id in [document_style_id,linked_style_id,shadow_style_id.clone(),- document_adopted_a_id,- document_adopted_b_id,- shadow_adopted_id,+ document_adopted_ids[0].clone(),+ document_adopted_ids[1].clone(),+ shadow_adopted_ids[0].clone(),] {assert!(sources.iter().any(|(source_id, _)| source_id == &id),@@ -4517,17 +4699,17 @@ fn matching_dependency_sources_have_explicit_source_and_scope_ids() {assert!(!shadow_fallback_roots.contains(&document));}#[test]-fn style_system_cache_key_ignores_document_fragment() {+fn style_world_identity_ignores_document_fragment() {let old_url = url::Url::parse("https://example.test/page.html#old").unwrap();let new_url = url::Url::parse("https://example.test/page.html#new").unwrap();- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(StyloStylesheetSource::new(".probe { color: green; }".to_owned(),old_url.clone(),));- let mut next_inputs = StyloComputedStyleInputs::default();+ let mut next_inputs = FullStyleWorldSnapshot::default();next_inputs.document_stylesheet_sources.push(StyloStylesheetSource::new(@@ -4536,37 +4718,37 @@ fn style_system_cache_key_ignores_document_fragment() {));assert_eq!(- StyleSystemCacheKey::new(&old_url, &inputs, None),- StyleSystemCacheKey::new(&new_url, &next_inputs, None)+ StyleWorldKey::new(&old_url, &inputs, None),+ StyleWorldKey::new(&new_url, &next_inputs, None));}#[test]-fn style_system_cache_key_changes_when_screen_size_changes() {+fn style_world_identity_changes_when_screen_size_changes() {let document_url = url::Url::parse("https://example.test/page.html").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();let viewport =StyleViewport::new(Some(800.0), Some(600.0)).with_screen_size(Some(1920.0), Some(1080.0));let next_viewport =StyleViewport::new(Some(800.0), Some(600.0)).with_screen_size(Some(1366.0), Some(768.0));assert_ne!(- StyleSystemCacheKey::new(&document_url, &inputs, viewport),- StyleSystemCacheKey::new(&document_url, &inputs, next_viewport)+ StyleWorldKey::new(&document_url, &inputs, viewport),+ StyleWorldKey::new(&document_url, &inputs, next_viewport));}#[test]-fn style_system_cache_key_changes_when_stylesheet_text_changes() {+fn style_world_identity_does_not_hash_stylesheet_text() {let document_url = url::Url::parse("https://example.test/page.html").unwrap();- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(StyloStylesheetSource::new(".probe { color: green; }".to_owned(),document_url.clone(),));- let mut next_inputs = StyloComputedStyleInputs::default();+ let mut next_inputs = FullStyleWorldSnapshot::default();next_inputs.document_stylesheet_sources.push(StyloStylesheetSource::new(@@ -4574,24 +4756,24 @@ fn style_system_cache_key_changes_when_stylesheet_text_changes() {document_url.clone(),));- assert_ne!(- StyleSystemCacheKey::new(&document_url, &inputs, None),- StyleSystemCacheKey::new(&document_url, &next_inputs, None)+ assert_eq!(+ StyleWorldKey::new(&document_url, &inputs, None),+ StyleWorldKey::new(&document_url, &next_inputs, None));}#[test]-fn style_system_cache_key_changes_when_stylesheet_base_url_changes() {+fn style_world_identity_does_not_hash_stylesheet_base_urls() {let document_url = url::Url::parse("https://example.test/page.html").unwrap();let old_base = url::Url::parse("https://example.test/assets/app.css").unwrap();let next_base = url::Url::parse("https://cdn.example.test/assets/app.css").unwrap();- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(StyloStylesheetSource::new(".probe { background-image: url(icon.png); }".to_owned(),old_base,));- let mut next_inputs = StyloComputedStyleInputs::default();+ let mut next_inputs = FullStyleWorldSnapshot::default();next_inputs.document_stylesheet_sources.push(StyloStylesheetSource::new(@@ -4599,55 +4781,31 @@ fn style_system_cache_key_changes_when_stylesheet_base_url_changes() {next_base,));- assert_ne!(- StyleSystemCacheKey::new(&document_url, &inputs, None),- StyleSystemCacheKey::new(&document_url, &next_inputs, None)+ assert_eq!(+ StyleWorldKey::new(&document_url, &inputs, None),+ StyleWorldKey::new(&document_url, &next_inputs, None));}#[test]-fn style_system_cache_key_changes_when_document_quirks_mode_changes() {+fn style_world_identity_changes_when_document_quirks_mode_changes() {let document_url = url::Url::parse("https://example.test/page.html").unwrap();- let standards_inputs = StyloComputedStyleInputs::default();- let quirks_inputs = StyloComputedStyleInputs {+ let standards_inputs = FullStyleWorldSnapshot::default();+ let quirks_inputs = FullStyleWorldSnapshot {quirks_mode: style::context::QuirksMode::Quirks,..Default::default()};assert_ne!(- StyleSystemCacheKey::new(&document_url, &standards_inputs, None),- StyleSystemCacheKey::new(&document_url, &quirks_inputs, None)+ StyleWorldKey::new(&document_url, &standards_inputs, None),+ StyleWorldKey::new(&document_url, &quirks_inputs, None));}#[test]-fn style_system_cache_key_mismatch_trace_records_changed_dimensions() {+fn style_world_identity_mismatch_trace_records_changed_dimensions() {let previous_url = url::Url::parse("https://example.test/old.html").unwrap();let next_url = url::Url::parse("https://example.test/new.html").unwrap();- let shadow_root = NativeNodeId::new(10);- let removed_shadow_root = NativeNodeId::new(11);- let added_shadow_root = NativeNodeId::new(12);-- let mut previous_inputs = StyloComputedStyleInputs::default();- previous_inputs- .document_stylesheet_sources- .push(StyloStylesheetSource::new(- ".probe { color: rgb(1, 2, 3); }".to_owned(),- previous_url.clone(),- ));- previous_inputs.shadow_stylesheet_sources.push((- shadow_root,- vec![StyloStylesheetSource::new(- "#target { color: rgb(4, 5, 6); }".to_owned(),- previous_url.clone(),- )],- ));- previous_inputs.shadow_stylesheet_sources.push((- removed_shadow_root,- vec![StyloStylesheetSource::new(- "#removed { color: rgb(7, 8, 9); }".to_owned(),- previous_url.clone(),- )],- ));+ let previous_inputs = FullStyleWorldSnapshot::default();let mut next_inputs = previous_inputs.clone();next_inputs.environment = StyloStyleEnvironment::from_emulated_media(@@ -4657,41 +4815,12 @@ fn style_system_cache_key_mismatch_trace_records_changed_dimensions() {},);next_inputs.quirks_mode = style::context::QuirksMode::Quirks;- next_inputs- .script_custom_property_registrations- .push(CssCustomPropertyRegistration {- name: "--accent".to_owned(),- syntax: "<color>".to_owned(),- inherits: false,- initial_value: Some("red".to_owned()),- });- next_inputs.document_stylesheet_sources = vec![StyloStylesheetSource::new(- ".probe { color: rgb(10, 11, 12); }".to_owned(),- next_url.clone(),- )];- next_inputs.shadow_stylesheet_sources = vec![- (- shadow_root,- vec![StyloStylesheetSource::new(- "#target { color: rgb(13, 14, 15); }".to_owned(),- next_url.clone(),- )],- ),- (- added_shadow_root,- vec![StyloStylesheetSource::new(- "#added { color: rgb(16, 17, 18); }".to_owned(),- next_url.clone(),- )],- ),- ];-- let previous_key = StyleSystemCacheKey::new(+ let previous_key = StyleWorldKey::new(&previous_url,&previous_inputs,StyleViewport::new(Some(800.0), Some(600.0)).with_screen_size(Some(1920.0), Some(1080.0)),);- let next_key = StyleSystemCacheKey::new(+ let next_key = StyleWorldKey::new(&next_url,&next_inputs,StyleViewport::new(Some(1024.0), Some(768.0)).with_screen_size(Some(1366.0), Some(768.0)),@@ -4706,25 +4835,6 @@ fn style_system_cache_key_mismatch_trace_records_changed_dimensions() {assert!(trace.screen_changed);assert!(trace.environment_changed);assert!(trace.quirks_mode_changed);- assert!(trace.custom_property_registrations_changed);- assert!(trace.document_stylesheet_sources_changed);- assert_eq!(trace.previous_document_stylesheet_sources.len, 1);- assert_eq!(trace.next_document_stylesheet_sources.len, 1);- assert!(trace.shadow_root_list_changed);- assert_eq!(- trace.previous_shadow_roots,- vec![shadow_root, removed_shadow_root]- );- assert_eq!(- trace.next_shadow_roots,- vec![shadow_root, added_shadow_root]- );- assert_eq!(trace.added_shadow_roots, vec![added_shadow_root]);- assert_eq!(trace.removed_shadow_roots, vec![removed_shadow_root]);- assert!(trace.shadow_stylesheet_sources_changed);- assert_eq!(trace.changed_shadow_source_roots, vec![shadow_root]);- assert_eq!(trace.previous_shadow_stylesheet_sources.len(), 2);- assert_eq!(trace.next_shadow_stylesheet_sources.len(), 2);}#[test]@@ -4769,7 +4879,7 @@ fn retained_style_system_source_input_trace_records_source_ids_and_shadow_roots(let document_url = url::Url::parse("https://example.test/source-input.html").unwrap();let document_source_id = StyleSourceId::document_adopted_style_sheet(document, 0);let shadow_source_id = StyleSourceId::shadow_root_adopted_style_sheet(shadow_root, 1);- let mut inputs = StyloComputedStyleInputs {+ let mut inputs = FullStyleWorldSnapshot {document_stylesheet_sources: vec![StyloStylesheetSource::new("body { color: rgb(1, 2, 3); }".to_owned(),@@ -4781,7 +4891,6 @@ fn retained_style_system_source_input_trace_records_source_ids_and_shadow_roots(document_url.clone(),),],- script_custom_property_base_url: document_url.clone(),..Default::default()};inputs.shadow_stylesheet_sources.push((@@ -4796,14 +4905,17 @@ fn retained_style_system_source_input_trace_records_source_ids_and_shadow_roots());inputs.script_custom_property_registrations- .push(CssCustomPropertyRegistration {- name: "--accent".to_owned(),- syntax: "<color>".to_owned(),- inherits: true,- initial_value: Some("blue".to_owned()),+ .push(CssCustomPropertyRegistrationRecord {+ registration: CssCustomPropertyRegistration {+ name: "--accent".to_owned(),+ syntax: "<color>".to_owned(),+ inherits: true,+ initial_value: Some("blue".to_owned()),+ },+ base_url: document_url.clone(),});- let trace = super::super::system::style_source_input_trace_for_test(&inputs);+ let trace = super::super::world_trace::style_source_input_trace_for_test(&inputs);assert_eq!(trace.document_stylesheet_source_count, 2);assert_eq!(@@ -4818,7 +4930,7 @@ fn retained_style_system_source_input_trace_records_source_ids_and_shadow_roots(vec![Some(shadow_source_id)]);assert_eq!(trace.script_custom_property_registration_count, 1);- assert_eq!(trace.script_custom_property_base_url, document_url);+ assert_eq!(trace.script_custom_property_base_urls, [document_url]);}#[test]@@ -4832,7 +4944,7 @@ fn quirks_mode_stylesheet_sources_match_ids_case_insensitively() {assert!(host.append_child(document, target));let document_url = url::Url::parse("https://example.test/page.html").unwrap();- let mut standards_inputs = StyloComputedStyleInputs::default();+ let mut standards_inputs = FullStyleWorldSnapshot::default();standards_inputs.document_stylesheet_sources.push(StyloStylesheetSource::new(@@ -4870,27 +4982,101 @@ fn quirks_mode_stylesheet_sources_match_ids_case_insensitively() {assert_eq!(quirks_background, "rgb(0, 128, 0)");}#[test]-fn stylesheet_invalidation_clears_retained_style_system() {- let host = test_host();+fn document_stylesheet_fallback_updates_the_persistent_world_in_place() {+ let mut host = test_host();let document = host.document_handle();+ let target = host.create_element("div");+ assert!(host.set_attribute(target, "class", "target"));+ assert!(host.append_child(document, target));let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();- let key = StyleSystemCacheKey::new(&document_url, &inputs, None);-- engine.ensure_retained_style_system_for_document(- &host,- host.document_handle(),- key.clone(),- &inputs,- );+ let mut first_inputs = FullStyleWorldSnapshot::default();+ first_inputs+ .document_stylesheet_sources+ .push(StyloStylesheetSource::new(+ ".target { color: rgb(1, 2, 3); }".into(),+ document_url.clone(),+ ));+ let first_key = StyleWorldKey::new_for_observation(+ &document_url,+ &first_inputs,+ StyleViewport::default(),+ StyleTreeScopeVersions::current(&host, Some(document)),+ );- assert!(engine.retained_style_system_matches_for_document_for_test(document, &key));+ assert_eq!(+ engine.computed_style_property_value(+ &host,+ &document_url,+ target,+ "color",+ None,+ &first_inputs,+ None,+ ),+ Some("rgb(1, 2, 3)".into())+ );+ assert!(engine.retained_style_system_matches_for_document_for_test(document, &first_key));+ let stylist_identity = engine.retained_stylist_identity_for_document_for_test(document);+ let rebuilds = engine.retained_style_system_rebuild_count_for_document_for_test(document);+ let updates = engine.retained_style_system_update_count_for_document_for_test(document);+ let cache_entries = engine.computed_style_cache_entry_count_for_document_for_test(document);- engine.invalidate_author_stylesheet_set_for_document_with_host(&host, document);+ engine.mark_document_stylesheet_set_dirty(document);- assert!(engine.retained_style_system_is_none_for_document_for_test(document));- assert!(engine.computed_style_cache_entry_count_for_document_for_test(document) == 0);+ assert!(engine.retained_style_system_matches_for_document_for_test(document, &first_key));+ assert_eq!(+ engine.retained_stylist_identity_for_document_for_test(document),+ stylist_identity,+ "marking a source set dirty must not eagerly replace the Stylist"+ );+ assert_eq!(+ engine.computed_style_cache_entry_count_for_document_for_test(document),+ cache_entries,+ "the last published style remains readable until the next observation"+ );+ assert_eq!(+ engine.source_dirty_scope_reasons_for_document_for_test(document),+ vec![StyleSourceDirtyReason::DocumentStyleSheets]+ );++ let mut second_inputs = FullStyleWorldSnapshot::default();+ second_inputs+ .document_stylesheet_sources+ .push(StyloStylesheetSource::new(+ ".target { color: rgb(4, 5, 6); }".into(),+ document_url.clone(),+ ));+ assert_eq!(+ engine.computed_style_property_value(+ &host,+ &document_url,+ target,+ "color",+ None,+ &second_inputs,+ None,+ ),+ Some("rgb(4, 5, 6)".into())+ );+ assert_eq!(+ engine.retained_stylist_identity_for_document_for_test(document),+ stylist_identity,+ "a full-document source fallback must still update the Stylist in place"+ );+ assert_eq!(+ engine.retained_style_system_rebuild_count_for_document_for_test(document),+ rebuilds+ );+ assert_eq!(+ engine.retained_style_system_update_count_for_document_for_test(document),+ updates + 1+ );+ assert!(+ engine+ .source_dirty_scope_reasons_for_document_for_test(document)+ .is_empty()+ );}#[test]fn style_subtree_invalidation_retains_style_system() {@@ -4900,8 +5086,8 @@ fn style_subtree_invalidation_retains_style_system() {assert!(host.append_child(document, target));let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();- let key = StyleSystemCacheKey::new(&document_url, &inputs, None);+ let inputs = FullStyleWorldSnapshot::default();+ let key = StyleWorldKey::new(&document_url, &inputs, None);engine.ensure_retained_style_system_for_document(&host,@@ -4932,14 +5118,14 @@ fn retained_style_system_keeps_cascade_data_for_empty_shadow_scopes() {let engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/empty-scopes.html").unwrap();- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((open_root, Vec::new()));inputs.shadow_stylesheet_sources.push((closed_root, Vec::new()));- let key = StyleSystemCacheKey::new(&document_url, &inputs, None);+ let key = StyleWorldKey::new(&document_url, &inputs, None);engine.ensure_retained_style_system_for_document(&host, document, key, &inputs);engine.with_retained_style_system_for_document_for_test(document, |retained| {@@ -4952,6 +5138,625 @@ fn retained_style_system_keeps_cascade_data_for_empty_shadow_scopes() {});}+#[test]+fn document_stylesheet_change_updates_the_retained_system_in_place() {+ reset_author_source_text_parse_count_for_test();+ let mut host = test_host();+ let document = host.document_handle();+ let target = host.create_element("div");+ let inherited_child = host.create_element("span");+ let unrelated = host.create_element("p");+ assert!(host.set_attribute(target, "class", "target"));+ assert!(host.set_attribute(unrelated, "class", "unrelated"));+ assert!(host.append_child(target, inherited_child));+ assert!(host.append_child(document, target));+ assert!(host.append_child(document, unrelated));++ let engine = MoliStyleEngine::new();+ let document_url = url::Url::parse("https://example.test/incremental.html").unwrap();+ let source_id = StyleSourceId::document_adopted_style_sheet(document, 41);+ let unrelated_source_id = StyleSourceId::document_adopted_style_sheet(document, 42);+ let unrelated_source = StyloStylesheetSource::new(+ ".unrelated { background-color: rgb(7, 8, 9); }".into(),+ document_url.clone(),+ )+ .with_source_id(Some(unrelated_source_id));+ let mut first_inputs = FullStyleWorldSnapshot::default();+ first_inputs.document_stylesheet_sources.push(+ StyloStylesheetSource::new(+ ".target { color: rgb(1, 2, 3); }".into(),+ document_url.clone(),+ )+ .with_source_id(Some(source_id.clone())),+ );+ first_inputs+ .document_stylesheet_sources+ .push(unrelated_source.clone());+ assert_eq!(+ engine.computed_style_property_value(+ &host,+ &document_url,+ target,+ "color",+ None,+ &first_inputs,+ None,+ ),+ Some("rgb(1, 2, 3)".into())+ );+ assert_eq!(+ engine.computed_style_property_value(+ &host,+ &document_url,+ unrelated,+ "background-color",+ None,+ &first_inputs,+ None,+ ),+ Some("rgb(7, 8, 9)".into())+ );+ assert_eq!(+ engine.computed_style_property_value(+ &host,+ &document_url,+ inherited_child,+ "color",+ None,+ &first_inputs,+ None,+ ),+ Some("rgb(1, 2, 3)".into())+ );+ let target_style_before = retained_primary_style_for_test(&engine, &host, target)+ .expect("target style should be retained");+ let unrelated_style_before = retained_primary_style_for_test(&engine, &host, unrelated)+ .expect("unrelated style should be retained");+ let inherited_style_before = retained_primary_style_for_test(&engine, &host, inherited_child)+ .expect("inherited child style should be retained");+ assert_eq!(author_source_text_parse_count_for_test(), 2);+ let stylist_identity = engine.retained_stylist_identity_for_document_for_test(document);+ let stylist_flushes = engine.retained_stylist_flush_count_for_document_for_test(document);+ let element_resolutions = engine.element_style_resolution_count_for_document_for_test(document);+ assert_eq!(+ engine.retained_style_system_rebuild_count_for_document_for_test(document),+ 1+ );+ assert_eq!(+ engine.retained_style_system_update_count_for_document_for_test(document),+ 0+ );++ let mut second_inputs = FullStyleWorldSnapshot::default();+ second_inputs.document_stylesheet_sources.push(+ StyloStylesheetSource::new(+ ".target { color: rgb(4, 5, 6); }".into(),+ document_url.clone(),+ )+ .with_source_id(Some(source_id)),+ );+ second_inputs+ .document_stylesheet_sources+ .push(unrelated_source);+ assert_eq!(+ engine.computed_style_property_value(+ &host,+ &document_url,+ target,+ "color",+ None,+ &second_inputs,+ None,+ ),+ Some("rgb(4, 5, 6)".into())+ );+ assert_eq!(author_source_text_parse_count_for_test(), 3);+ let target_style_after = retained_primary_style_for_test(&engine, &host, target)+ .expect("target style should be recomputed");+ let unrelated_style_after = retained_primary_style_for_test(&engine, &host, unrelated)+ .expect("unrelated style should remain retained");+ assert!(!ServoArc::ptr_eq(&target_style_before, &target_style_after));+ assert!(+ ServoArc::ptr_eq(&unrelated_style_before, &unrelated_style_after),+ "Stylo stylesheet invalidation must preserve an unrelated source's canonical style"+ );+ assert!(element_style_is_dirty_for_test(+ &engine,+ &host,+ inherited_child+ ));+ assert_eq!(+ engine.computed_style_property_value(+ &host,+ &document_url,+ inherited_child,+ "color",+ None,+ &second_inputs,+ None,+ ),+ Some("rgb(4, 5, 6)".into()),+ "a matched ancestor invalidation must propagate to demanded inherited descendants"+ );+ let inherited_style_after = retained_primary_style_for_test(&engine, &host, inherited_child)+ .expect("inherited child should be recomputed on demand");+ assert!(!ServoArc::ptr_eq(+ &inherited_style_before,+ &inherited_style_after+ ));+ assert_eq!(+ engine.retained_stylist_identity_for_document_for_test(document),+ stylist_identity,+ "a stylesheet revision must preserve the exact Stylist identity"+ );+ assert_eq!(+ engine.retained_stylist_flush_count_for_document_for_test(document),+ stylist_flushes + 1,+ "one stylesheet revision must flush the document Stylist once"+ );+ assert!(+ engine.element_style_resolution_count_for_document_for_test(document) > element_resolutions,+ "reading the invalidated target must perform a new element style resolution"+ );+ assert_eq!(+ engine.retained_style_system_rebuild_count_for_document_for_test(document),+ 1,+ "a stylesheet revision must not replace the document Stylist"+ );+ assert_eq!(+ engine.retained_style_system_update_count_for_document_for_test(document),+ 1+ );+ let flushes_after_revision =+ engine.retained_stylist_flush_count_for_document_for_test(document);+ let resolutions_after_revision =+ engine.element_style_resolution_count_for_document_for_test(document);++ assert_eq!(+ engine.computed_style_property_value(+ &host,+ &document_url,+ target,+ "color",+ None,+ &second_inputs,+ None,+ ),+ Some("rgb(4, 5, 6)".into())+ );+ assert_eq!(author_source_text_parse_count_for_test(), 3);+ assert_eq!(+ engine.retained_style_system_update_count_for_document_for_test(document),+ 1,+ "a clean read must not flush the retained style world again"+ );+ assert_eq!(+ engine.retained_stylist_flush_count_for_document_for_test(document),+ flushes_after_revision,+ "a clean read must not flush Stylo"+ );+ assert_eq!(+ engine.element_style_resolution_count_for_document_for_test(document),+ resolutions_after_revision,+ "a clean read must reuse the canonical ElementData style"+ );+}++#[test]+fn retained_stylesheet_resource_manifest_advances_only_when_resources_change() {+ reset_author_source_text_parse_count_for_test();+ reset_stylesheet_resource_manifest_build_count_for_test();+ let host = test_host();+ let document = host.document_handle();+ let mut engine = MoliStyleEngine::new();+ let document_url = url::Url::parse("https://example.test/resources.html").unwrap();+ let source_id = StyleSourceId::document_adopted_style_sheet(document, 71);+ let first_source = StyloStylesheetSource::new(+ "@import url(theme-a.css); @font-face { font-family: First; src: url(font-a.woff2); font-weight: 700; }".into(),+ document_url.clone(),+ )+ .with_source_id(Some(source_id.clone()));+ engine.set_document_adopted_style_sheet_sources(document, vec![first_source.clone()]);+ let first_inputs = FullStyleWorldSnapshot {+ document_stylesheet_sources: vec![first_source],+ ..Default::default()+ };+ let first_key = StyleWorldKey::new(&document_url, &first_inputs, None);+ engine.ensure_retained_style_system_for_document(&host, document, first_key, &first_inputs);++ let first = engine+ .stylesheet_resource_snapshot_for_document(document)+ .expect("the retained style world must publish its resource manifest");+ assert_eq!(first.web_fonts().len(), 1);+ assert_eq!(+ first.imports(),+ [url::Url::parse("https://example.test/theme-a.css").unwrap()]+ );+ assert_eq!(+ first.web_fonts()[0].request_url().as_str(),+ "https://example.test/font-a.woff2"+ );+ assert_eq!(author_source_text_parse_count_for_test(), 1);+ assert_eq!(stylesheet_resource_manifest_build_count_for_test(), 1);++ let clean = engine+ .stylesheet_resource_snapshot_for_document(document)+ .expect("a clean world must retain its resource manifest");+ assert_eq!(clean.generation(), first.generation());+ assert_eq!(author_source_text_parse_count_for_test(), 1);+ assert_eq!(stylesheet_resource_manifest_build_count_for_test(), 1);++ let viewport = StyleViewport::from_width(Some(640.0));+ let viewport_key = StyleWorldKey::new(&document_url, &first_inputs, viewport);+ engine.ensure_retained_style_system_for_document(&host, document, viewport_key, &first_inputs);+ let after_viewport_change = engine+ .stylesheet_resource_snapshot_for_document(document)+ .expect("a device update must retain its resource manifest");+ assert_eq!(+ after_viewport_change.generation(),+ first.generation(),+ "device-only style updates must not advance the resource revision"+ );+ assert_eq!(+ stylesheet_resource_manifest_build_count_for_test(),+ 1,+ "a device-only update must not rebuild the typed resource projection"+ );++ let same_resources_source = StyloStylesheetSource::new(+ "@import url(theme-a.css); @font-face { font-family: First; src: url(font-a.woff2); font-weight: 700; } body { color: green; }".into(),+ document_url.clone(),+ )+ .with_source_id(Some(source_id.clone()));+ engine.set_document_adopted_style_sheet_sources(document, vec![same_resources_source.clone()]);+ let same_resources_inputs = FullStyleWorldSnapshot {+ document_stylesheet_sources: vec![same_resources_source],+ ..Default::default()+ };+ let same_resources_key = StyleWorldKey::new(&document_url, &same_resources_inputs, viewport);+ engine.ensure_retained_style_system_for_document(+ &host,+ document,+ same_resources_key,+ &same_resources_inputs,+ );+ let after_non_resource_change = engine+ .stylesheet_resource_snapshot_for_document(document)+ .expect("a non-resource rule update must retain its resource manifest");+ assert_eq!(+ after_non_resource_change.generation(),+ first.generation(),+ "ordinary declaration changes must not restart resource reconciliation"+ );+ assert_eq!(author_source_text_parse_count_for_test(), 2);+ assert_eq!(stylesheet_resource_manifest_build_count_for_test(), 2);++ let second_source = StyloStylesheetSource::new(+ "@import url(theme-b.css); @font-face { font-family: Second; src: url(font-b.woff2); font-style: italic; }".into(),+ document_url.clone(),+ )+ .with_source_id(Some(source_id));+ engine.set_document_adopted_style_sheet_sources(document, vec![second_source.clone()]);+ let second_inputs = FullStyleWorldSnapshot {+ document_stylesheet_sources: vec![second_source],+ ..Default::default()+ };+ let second_key = StyleWorldKey::new(&document_url, &second_inputs, viewport);+ engine.ensure_retained_style_system_for_document(&host, document, second_key, &second_inputs);++ let second = engine+ .stylesheet_resource_snapshot_for_document(document)+ .expect("the revised world must publish its new resource manifest");+ assert_ne!(second.generation(), first.generation());+ assert_eq!(second.web_fonts().len(), 1);+ assert_eq!(+ second.imports(),+ [url::Url::parse("https://example.test/theme-b.css").unwrap()]+ );+ assert_eq!(+ second.web_fonts()[0].request_url().as_str(),+ "https://example.test/font-b.woff2"+ );+ assert_eq!(+ author_source_text_parse_count_for_test(),+ 3,+ "each stylesheet revision must be parsed once for both cascade and resources"+ );+ assert_eq!(stylesheet_resource_manifest_build_count_for_test(), 3);+}++#[test]+fn document_stylesheet_append_and_reorder_reuse_parsed_sheets() {+ reset_author_source_text_parse_count_for_test();+ let mut host = test_host();+ let document = host.document_handle();+ let target = host.create_element("div");+ assert!(host.set_attribute(target, "class", "target"));+ assert!(host.append_child(document, target));++ let engine = MoliStyleEngine::new();+ let document_url = url::Url::parse("https://example.test/ordered-sheets.html").unwrap();+ let first_source = StyloStylesheetSource::new(+ ".target { color: rgb(1, 2, 3); }".into(),+ document_url.clone(),+ )+ .with_source_id(Some(StyleSourceId::document_adopted_style_sheet(+ document, 61,+ )));+ let second_source = StyloStylesheetSource::new(+ ".target { color: rgb(4, 5, 6); }".into(),+ document_url.clone(),+ )+ .with_source_id(Some(StyleSourceId::document_adopted_style_sheet(+ document, 62,+ )));++ let mut first_inputs = FullStyleWorldSnapshot::default();+ first_inputs+ .document_stylesheet_sources+ .push(first_source.clone());+ assert_eq!(+ engine.computed_style_property_value(+ &host,+ &document_url,+ target,+ "color",+ None,+ &first_inputs,+ None,+ ),+ Some("rgb(1, 2, 3)".into())+ );+ assert_eq!(author_source_text_parse_count_for_test(), 1);++ let appended_inputs = FullStyleWorldSnapshot {+ document_stylesheet_sources: vec![first_source.clone(), second_source.clone()],+ ..Default::default()+ };+ assert_eq!(+ engine.computed_style_property_value(+ &host,+ &document_url,+ target,+ "color",+ None,+ &appended_inputs,+ None,+ ),+ Some("rgb(4, 5, 6)".into())+ );+ assert_eq!(+ author_source_text_parse_count_for_test(),+ 2,+ "appending one sheet must not reparse the existing sheet"+ );++ let reordered_inputs = FullStyleWorldSnapshot {+ document_stylesheet_sources: vec![second_source, first_source],+ ..Default::default()+ };+ assert_eq!(+ engine.computed_style_property_value(+ &host,+ &document_url,+ target,+ "color",+ None,+ &reordered_inputs,+ None,+ ),+ Some("rgb(1, 2, 3)".into())+ );+ assert_eq!(+ author_source_text_parse_count_for_test(),+ 2,+ "reordering sheets must reuse both parsed stylesheet objects"+ );+ assert_eq!(+ engine.retained_style_system_rebuild_count_for_document_for_test(document),+ 1+ );+ assert_eq!(+ engine.retained_style_system_update_count_for_document_for_test(document),+ 2+ );+}++#[test]+fn incremental_document_stylesheet_updates_match_a_fresh_style_world_oracle() {+ let mut host = test_host();+ let document = host.document_handle();+ let target = host.create_element("section");+ let child = host.create_element("span");+ let unrelated = host.create_element("aside");+ assert!(host.set_attribute(target, "class", "target"));+ assert!(host.set_attribute(unrelated, "class", "unrelated"));+ assert!(host.append_child(target, child));+ assert!(host.append_child(document, target));+ assert!(host.append_child(document, unrelated));++ let document_url = url::Url::parse("https://example.test/oracle.html").unwrap();+ let first_id = StyleSourceId::document_adopted_style_sheet(document, 81);+ let second_id = StyleSourceId::document_adopted_style_sheet(document, 82);+ let source = |css: &str, id: StyleSourceId| {+ StyloStylesheetSource::new(css.into(), document_url.clone()).with_source_id(Some(id))+ };+ let first = source(+ ".target { color: rgb(1, 2, 3); background-color: rgb(4, 5, 6); }",+ first_id.clone(),+ );+ let first_revision = source(+ ".target { color: rgb(7, 8, 9); background-color: rgb(10, 11, 12); }",+ first_id,+ );+ let second = source(+ ".target { color: rgb(13, 14, 15); } .unrelated { color: rgb(16, 17, 18); }",+ second_id,+ );+ let sequences = [+ vec![first.clone()],+ vec![first.clone(), second.clone()],+ vec![first_revision.clone(), second.clone()],+ vec![second.clone(), first_revision.clone()],+ vec![first_revision],+ Vec::new(),+ ];++ let mut incremental = MoliStyleEngine::new();+ for sources in sequences {+ incremental.set_document_adopted_style_sheet_sources(document, sources.clone());+ let inputs = FullStyleWorldSnapshot {+ document_stylesheet_sources: sources,+ ..Default::default()+ };+ let oracle = MoliStyleEngine::new();+ for (element, property) in [+ (target, "color"),+ (target, "background-color"),+ (child, "color"),+ (unrelated, "color"),+ ] {+ assert_eq!(+ incremental.computed_style_property_value(+ &host,+ &document_url,+ element,+ property,+ None,+ &inputs,+ None,+ ),+ oracle.computed_style_property_value(+ &host,+ &document_url,+ element,+ property,+ None,+ &inputs,+ None,+ ),+ "incremental and fresh worlds diverged for {element:?} {property}"+ );+ }+ }++ assert_eq!(+ incremental.retained_style_system_rebuild_count_for_document_for_test(document),+ 1,+ "the oracle sequence must keep one persistent document Stylist"+ );+ assert_eq!(+ incremental.retained_style_system_update_count_for_document_for_test(document),+ 5+ );+}++#[test]+fn one_shadow_stylesheet_change_preserves_the_other_scope_cascade_data() {+ reset_author_source_text_parse_count_for_test();+ let mut host = test_host();+ let document = host.document_handle();+ let first_host = host.create_element("section");+ let second_host = host.create_element("article");+ assert!(host.append_child(document, first_host));+ assert!(host.append_child(document, second_host));+ let first_root = host+ .attach_shadow_root(first_host, "open")+ .expect("first host should accept a shadow root");+ let second_root = host+ .attach_shadow_root(second_host, "open")+ .expect("second host should accept a shadow root");++ let engine = MoliStyleEngine::new();+ let document_url = url::Url::parse("https://example.test/shadow-incremental.html").unwrap();+ let first_source_id = StyleSourceId::shadow_root_adopted_style_sheet(first_root, 51);+ let second_source_id = StyleSourceId::shadow_root_adopted_style_sheet(second_root, 52);+ let first_source = StyloStylesheetSource::new(+ ":host { color: rgb(1, 2, 3); }".into(),+ document_url.clone(),+ )+ .with_source_id(Some(first_source_id.clone()));+ let second_source = StyloStylesheetSource::new(+ ":host { color: rgb(4, 5, 6); }".into(),+ document_url.clone(),+ )+ .with_source_id(Some(second_source_id));+ let mut first_inputs = FullStyleWorldSnapshot::default();+ first_inputs+ .shadow_stylesheet_sources+ .push((first_root, vec![first_source]));+ first_inputs+ .shadow_stylesheet_sources+ .push((second_root, vec![second_source.clone()]));+ let first_key = StyleWorldKey::new(&document_url, &first_inputs, None);+ engine.ensure_retained_style_system_for_document(&host, document, first_key, &first_inputs);++ let initial_data =+ engine.with_retained_style_system_for_document_for_test(document, |retained| {+ retained+ .shadow_cascade_data+ .iter()+ .map(|(root, data)| (*root, data.clone()))+ .collect::<Vec<_>>()+ });+ let stylist_identity = engine.retained_stylist_identity_for_document_for_test(document);+ let first_scope_flushes = engine+ .retained_shadow_scope_flush_count_for_document_for_test(document, first_root)+ .expect("first scope should be retained");+ let second_scope_flushes = engine+ .retained_shadow_scope_flush_count_for_document_for_test(document, second_root)+ .expect("second scope should be retained");+ assert_eq!(author_source_text_parse_count_for_test(), 2);++ let revised_first_source = StyloStylesheetSource::new(+ ":host { color: rgb(7, 8, 9); }".into(),+ document_url.clone(),+ )+ .with_source_id(Some(first_source_id));+ let mut second_inputs = FullStyleWorldSnapshot::default();+ second_inputs+ .shadow_stylesheet_sources+ .push((first_root, vec![revised_first_source]));+ second_inputs+ .shadow_stylesheet_sources+ .push((second_root, vec![second_source]));+ let second_key = StyleWorldKey::new(&document_url, &second_inputs, None);+ engine.ensure_retained_style_system_for_document(&host, document, second_key, &second_inputs);++ engine.with_retained_style_system_for_document_for_test(document, |retained| {+ let current_data = retained+ .shadow_cascade_data+ .iter()+ .map(|(root, data)| (*root, data))+ .collect::<Vec<_>>();+ assert!(!ServoArc::ptr_eq(&initial_data[0].1, current_data[0].1));+ assert!(ServoArc::ptr_eq(&initial_data[1].1, current_data[1].1));+ });+ assert_eq!(+ engine.retained_stylist_identity_for_document_for_test(document),+ stylist_identity+ );+ assert_eq!(+ engine.retained_shadow_scope_flush_count_for_document_for_test(document, first_root),+ Some(first_scope_flushes + 1),+ "the dirty ShadowRoot must flush exactly once"+ );+ assert_eq!(+ engine.retained_shadow_scope_flush_count_for_document_for_test(document, second_root),+ Some(second_scope_flushes),+ "an unrelated ShadowRoot must not flush"+ );+ assert_eq!(author_source_text_parse_count_for_test(), 3);+ assert_eq!(+ engine.retained_style_system_rebuild_count_for_document_for_test(document),+ 1+ );+ assert_eq!(+ engine.retained_style_system_update_count_for_document_for_test(document),+ 1+ );+}+#[test]fn style_subtree_invalidation_clears_only_affected_shadow_cascade_data() {let mut host = test_host();@@ -4987,14 +5792,14 @@ fn style_subtree_invalidation_clears_only_affected_shadow_cascade_data() {second_shadow_root,vec![second_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((first_shadow_root, vec![first_source]));inputs.shadow_stylesheet_sources.push((second_shadow_root, vec![second_source]));- let key = StyleSystemCacheKey::new(&document_url, &inputs, None);+ let key = StyleWorldKey::new(&document_url, &inputs, None);engine.ensure_retained_style_system_for_document(&host, document, key, &inputs);let (first_cascade_data, second_cascade_data) = engine@@ -5079,14 +5884,14 @@ fn detached_subtree_invalidation_clears_only_affected_shadow_cascade_data() {second_shadow_root,vec![second_source.clone()],);- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.shadow_stylesheet_sources.push((first_shadow_root, vec![first_source]));inputs.shadow_stylesheet_sources.push((second_shadow_root, vec![second_source]));- let key = StyleSystemCacheKey::new(&document_url, &inputs, None);+ let key = StyleWorldKey::new(&document_url, &inputs, None);engine.ensure_retained_style_system_for_document(&host, document, key, &inputs);let (first_cascade_data, second_cascade_data) = engine@@ -5144,7 +5949,7 @@ fn detached_subtree_invalidation_clears_only_affected_shadow_cascade_data() {}#[test]-fn document_stylesheet_cleanup_preserves_other_document_shadow_cascade_data() {+fn document_stylesheet_dirty_mark_isolated_to_its_document_world() {let mut host = test_host();let document = host.document_handle();let active_shadow_host = host.create_element("section");@@ -5181,18 +5986,18 @@ fn document_stylesheet_cleanup_preserves_other_document_shadow_cascade_data() {vec![detached_source.clone()],);- let mut active_inputs = StyloComputedStyleInputs::default();+ let mut active_inputs = FullStyleWorldSnapshot::default();active_inputs.shadow_stylesheet_sources.push((active_shadow_root, vec![active_source]));- let active_key = StyleSystemCacheKey::new(&document_url, &active_inputs, None);+ let active_key = StyleWorldKey::new(&document_url, &active_inputs, None);engine.ensure_retained_style_system_for_document(&host, document, active_key, &active_inputs);- let mut detached_inputs = StyloComputedStyleInputs::default();+ let mut detached_inputs = FullStyleWorldSnapshot::default();detached_inputs.shadow_stylesheet_sources.push((detached_shadow_root, vec![detached_source]));- let detached_key = StyleSystemCacheKey::new(&document_url, &detached_inputs, None);+ let detached_key = StyleWorldKey::new(&document_url, &detached_inputs, None);engine.ensure_retained_style_system_for_document(&host,detached_document,@@ -5243,7 +6048,7 @@ fn document_stylesheet_cleanup_preserves_other_document_shadow_cascade_data() {2);- engine.invalidate_author_stylesheet_set_for_document_with_host(&host, detached_document);+ engine.mark_document_stylesheet_set_dirty(detached_document);assert!(engine@@ -5251,16 +6056,17 @@ fn document_stylesheet_cleanup_preserves_other_document_shadow_cascade_data() {.has_shadow_cascade_data_for_test(active_shadow_root));assert!(- !engine+ engine.dom_adapter.has_shadow_cascade_data_for_test(detached_shadow_root));assert!(engine.dom_adapter.has_element_data(active_shadow_host));- assert!(!engine.dom_adapter.has_element_data(detached_shadow_host));+ assert!(engine.dom_adapter.has_element_data(detached_shadow_host));assert_eq!(engine.dom_adapter.shadow_cascade_document_count_for_test(),- 1+ 2);+ assert_only_source_document_is_dirty(&engine, detached_document, document);}#[test]@@ -5297,7 +6103,7 @@ fn document_replacement_cleanup_preserves_unreplaced_document_world_and_shared_s&[active_link, detached_link],);- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [active, detached] {assert!(engine@@ -5332,43 +6138,6 @@ fn document_replacement_cleanup_preserves_unreplaced_document_world_and_shared_s);assert!(engine.dom_adapter.has_element_data(active));assert!(engine.dom_adapter.has_element_data(detached));- let input_cache_key = StyloDocumentComputedStyleInputCacheKey::new(- None,- &[],- &document_url,- StyleViewport::default(),- StyloStyleEnvironment::default(),- &document_url,- );- let prepared_inputs = || {- std::rc::Rc::new(StyloPreparedComputedStyleInputs::new(- &document_url,- std::rc::Rc::new(StyloComputedStyleInputs::default()),- StyleViewport::default(),- ))- };- let document_inputs = prepared_inputs();- let detached_document_inputs = prepared_inputs();- engine.cache_document_prepared_style_inputs(- document,- input_cache_key.clone(),- std::rc::Rc::clone(&document_inputs),- );- engine.cache_document_prepared_style_inputs(- detached_document,- input_cache_key.clone(),- std::rc::Rc::clone(&detached_document_inputs),- );- assert!(- engine- .cached_document_prepared_style_inputs(document, &input_cache_key)- .is_some()- );- assert!(- engine- .cached_document_prepared_style_inputs(detached_document, &input_cache_key)- .is_some()- );let document_source_set_generation =engine.source_set_generation_for_document_for_test(document);let detached_source_set_generation =@@ -5386,19 +6155,6 @@ fn document_replacement_cleanup_preserves_unreplaced_document_world_and_shared_sengine.computed_style_cache_entry_count_for_document_for_test(detached_document),1);- assert!(- engine- .cached_document_prepared_style_inputs(document, &input_cache_key)- .is_none(),- "document replacement must clear prepared inputs for the replaced document"- );- let retained_detached_inputs = engine- .cached_document_prepared_style_inputs(detached_document, &input_cache_key)- .expect("document replacement must preserve other document input caches");- assert!(std::rc::Rc::ptr_eq(- &retained_detached_inputs,- &detached_document_inputs- ));assert_eq!(engine.linked_stylesheet_owner_registry_counts_for_document_for_test(document),(0, 0)@@ -5443,8 +6199,8 @@ fn detached_retained_rebuild_preserves_active_document_adapter_element_data() {let engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();- let active_key = StyleSystemCacheKey::new(&document_url, &inputs, None);+ let inputs = FullStyleWorldSnapshot::default();+ let active_key = StyleWorldKey::new(&document_url, &inputs, None);engine.ensure_retained_style_system_for_document(&host, document, active_key, &inputs);ensure_adapter_element_data(&engine, &host, active);assert!(engine.dom_adapter.has_element_data(active));@@ -5453,11 +6209,11 @@ fn detached_retained_rebuild_preserves_active_document_adapter_element_data() {"section { color: rgb(1, 2, 3); }".into(),document_url.clone(),);- let mut first_detached_inputs = StyloComputedStyleInputs::default();+ let mut first_detached_inputs = FullStyleWorldSnapshot::default();first_detached_inputs.document_stylesheet_sources.push(detached_source);- let first_detached_key = StyleSystemCacheKey::new(&document_url, &first_detached_inputs, None);+ let first_detached_key = StyleWorldKey::new(&document_url, &first_detached_inputs, None);engine.ensure_retained_style_system_for_document(&host,detached_document,@@ -5469,11 +6225,11 @@ fn detached_retained_rebuild_preserves_active_document_adapter_element_data() {"section { color: rgb(4, 5, 6); }".into(),document_url.clone(),);- let mut next_detached_inputs = StyloComputedStyleInputs::default();+ let mut next_detached_inputs = FullStyleWorldSnapshot::default();next_detached_inputs.document_stylesheet_sources.push(next_detached_source);- let next_detached_key = StyleSystemCacheKey::new(&document_url, &next_detached_inputs, None);+ let next_detached_key = StyleWorldKey::new(&document_url, &next_detached_inputs, None);engine.ensure_retained_style_system_for_document(&host,detached_document,@@ -5499,3 +6255,51 @@ fn ensure_adapter_element_data(}});}++fn computed_style_snapshot_for_test(+ engine: &MoliStyleEngine,+ host: &crate::dom::native::DomHost,+ document_url: &url::Url,+ handle: crate::document_runtime::DomHandle,+ inputs: &FullStyleWorldSnapshot,+) -> StyloComputedStyleSnapshot {+ let document = host+ .owner_document_handle(handle)+ .expect("test element should have an owner document");+ engine+ .computed_style_snapshot_after_style_update_with_document_context(+ host,+ document_url,+ handle,+ inputs,+ StyleSourceDocumentContext::for_root_document(document),+ document,+ StyleViewport::default(),+ )+ .expect("test element should have computed style")+}++fn retained_primary_style_for_test(+ engine: &MoliStyleEngine,+ host: &crate::dom::native::DomHost,+ handle: crate::document_runtime::DomHandle,+) -> Option<ServoArc<style::properties::ComputedValues>> {+ engine.dom_adapter.with_bound_host(host, |adapter| {+ let element = adapter.element(host, handle)?;+ let data = element.borrow_data()?;+ data.has_styles().then(|| data.styles.primary().clone())+ })+}++fn element_style_is_dirty_for_test(+ engine: &MoliStyleEngine,+ host: &crate::dom::native::DomHost,+ handle: crate::document_runtime::DomHandle,+) -> bool {+ engine.dom_adapter.with_bound_host(host, |adapter| {+ let element = adapter.element(host, handle).expect("test element");+ element+ .borrow_data()+ .is_some_and(|data| !data.hint.is_empty())+ })+}diff --git a/moli-renderer-v8/src/style_engine/tests/subtree_context.rs b/moli-renderer-v8/src/style_engine/tests/subtree_context.rsindex b1cd5ed4a..daf5fed3c 100644--- a/moli-renderer-v8/src/style_engine/tests/subtree_context.rs+++ b/moli-renderer-v8/src/style_engine/tests/subtree_context.rs@@ -24,7 +24,7 @@ fn lang_selector_does_not_match_more_specific_range() {);let source_id = StyleSourceId::owner_style_sheet(&host, style).expect("owner source id");let document_url = url::Url::parse("https://example.test/").unwrap();- let mut inputs = StyloComputedStyleInputs::default();+ let mut inputs = FullStyleWorldSnapshot::default();inputs.document_stylesheet_sources.push(engine.owner_style_sheet_source_with_host(&host, style)@@ -69,7 +69,7 @@ fn standalone_subtree_context_invalidation_preserves_unrelated_cache_entries() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -137,7 +137,7 @@ fn pending_mutation_invalidations_drain_before_computed_style_read() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();assert!(engine.computed_style_property_value(@@ -221,7 +221,7 @@ fn pending_mutation_invalidations_keep_separate_work_items_until_drain() {let mut engine = MoliStyleEngine::new();let document_url = url::Url::parse("https://example.test/").unwrap();- let inputs = StyloComputedStyleInputs::default();+ let inputs = FullStyleWorldSnapshot::default();for handle in [outside, first_target, second_target] {assert!(engine@@ -297,8 +297,8 @@ fn pending_attribute_mutation_invalidations_merge_for_batch_drain() {".first { color: red; } .second { color: blue; }".into(),);let document_url = host.document_url().expect("test document url").clone();- let inputs = StyloComputedStyleInputs::default();- let key = StyleSystemCacheKey::new(&document_url, &inputs, None);+ let inputs = FullStyleWorldSnapshot::default();+ let key = StyleWorldKey::new(&document_url, &inputs, None);engine.ensure_retained_style_system_for_document(&host, host.document_handle(), key, &inputs);let media = crate::protocol_types::EmulatedMediaOverrides::default();@@ -508,11 +508,7 @@ fn source_metadata_uses_explicitly_installed_linked_stylesheet_owners() {url::Url::parse("https://example.test/has.css").unwrap(),);let detached_document = host.create_detached_html_document();- engine.set_document_adopted_style_sheet_sources_with_host(- &host,- detached_document,- vec![has_source],- );+ engine.set_document_adopted_style_sheet_sources(detached_document, vec![has_source]);let linked_url = url::Url::parse("https://example.test/app.css").unwrap();engine.record_stylesheet_source_for_url_for_document_for_test(@@ -864,8 +860,7 @@ fn source_metadata_matches_detached_document_styles_without_matching_active_disc"body:has(.marker) .target { color: green; }".into(),);let mut adopted_engine = MoliStyleEngine::new();- adopted_engine.set_document_adopted_style_sheet_sources_with_host(- &host,+ adopted_engine.set_document_adopted_style_sheet_sources(detached_document,vec![StyloStylesheetSource::new("body:has(.marker) .target { color: green; }".into(),diff --git a/moli-renderer-v8/src/style_engine/world_environment.rs b/moli-renderer-v8/src/style_engine/world_environment.rsnew file mode 100644index 000000000..9b26c751f--- /dev/null+++ b/moli-renderer-v8/src/style_engine/world_environment.rs@@ -0,0 +1,233 @@+use style::{+ device::servo::ServoMediaFeaturePreferences, media_queries::MediaType,+ queries::values::PrefersColorScheme, servo::media_features::PrefersContrast,+ values::specified::color::ForcedColors,+};++use crate::{document_runtime::DomHandle, dom::native::DomHost};++/// Cheap, Document-local identity of the connected ShadowRoot universe+/// sampled for one style observation. The actual root vector is cloned only+/// when this version no longer matches the retained Document world.+#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]+pub(crate) struct StyleTreeScopeVersions {+ document_tree_scopes: u64,+}++impl StyleTreeScopeVersions {+ pub(crate) fn current(host: &DomHost, document: Option<DomHandle>) -> Self {+ Self {+ document_tree_scopes: document+ .map(|document| host.document_tree_scope_version(document))+ .unwrap_or(0),+ }+ }+}++#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub(crate) struct StyleViewport {+ pub(crate) width: Option<f64>,+ pub(crate) height: Option<f64>,+ pub(crate) screen_width: Option<f64>,+ pub(crate) screen_height: Option<f64>,+}++impl StyleViewport {+ pub(crate) const fn new(width: Option<f64>, height: Option<f64>) -> Self {+ Self {+ width,+ height,+ screen_width: None,+ screen_height: None,+ }+ }++ pub(crate) const fn from_width(width: Option<f64>) -> Self {+ Self {+ width,+ height: None,+ screen_width: None,+ screen_height: None,+ }+ }++ pub(crate) const fn with_screen_size(+ self,+ screen_width: Option<f64>,+ screen_height: Option<f64>,+ ) -> Self {+ Self {+ screen_width,+ screen_height,+ ..self+ }+ }++ pub(crate) fn from_viewport_surface(surface: crate::protocol_types::ViewportSurface) -> Self {+ Self::new(+ Some(f64::from(surface.inner_width)),+ Some(f64::from(surface.inner_height)),+ )+ .with_screen_size(+ Some(f64::from(surface.screen_width)),+ Some(f64::from(surface.screen_height)),+ )+ }+}++impl From<Option<f64>> for StyleViewport {+ fn from(width: Option<f64>) -> Self {+ Self::from_width(width)+ }+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]+pub(crate) struct StyloStyleEnvironment {+ media_type: StyloStyleMediaType,+ color_scheme: StyloStyleColorScheme,+ reduced_motion: StyloStyleReducedPreference,+ reduced_data: StyloStyleReducedPreference,+ reduced_transparency: StyloStyleReducedPreference,+ contrast: StyloStyleContrastPreference,+ forced_colors: StyloStyleForcedColors,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]+enum StyloStyleMediaType {+ #[default]+ Screen,+ Print,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]+enum StyloStyleColorScheme {+ #[default]+ Light,+ Dark,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]+enum StyloStyleReducedPreference {+ #[default]+ NoPreference,+ Reduce,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]+enum StyloStyleContrastPreference {+ More,+ Less,+ Custom,+ #[default]+ NoPreference,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]+enum StyloStyleForcedColors {+ #[default]+ None,+ Active,+}++impl StyloStyleEnvironment {+ pub(crate) fn from_emulated_media(+ overrides: &crate::protocol_types::EmulatedMediaOverrides,+ ) -> Self {+ Self {+ media_type: if overrides.media.as_deref() == Some("print") {+ StyloStyleMediaType::Print+ } else {+ StyloStyleMediaType::Screen+ },+ color_scheme: if overrides.color_scheme.as_deref() == Some("dark") {+ StyloStyleColorScheme::Dark+ } else {+ StyloStyleColorScheme::Light+ },+ reduced_motion: match overrides.reduced_motion.as_deref() {+ Some("reduce") => StyloStyleReducedPreference::Reduce,+ Some("no-preference") | None => StyloStyleReducedPreference::NoPreference,+ Some(_) => StyloStyleReducedPreference::NoPreference,+ },+ reduced_data: StyloStyleReducedPreference::NoPreference,+ reduced_transparency: StyloStyleReducedPreference::NoPreference,+ contrast: match overrides.contrast.as_deref() {+ Some("more") => StyloStyleContrastPreference::More,+ Some("less") => StyloStyleContrastPreference::Less,+ Some("custom") => StyloStyleContrastPreference::Custom,+ Some("no-preference") | None => StyloStyleContrastPreference::NoPreference,+ Some(_) => StyloStyleContrastPreference::NoPreference,+ },+ forced_colors: match overrides.forced_colors.as_deref() {+ Some("active") => StyloStyleForcedColors::Active,+ Some("none") | None => StyloStyleForcedColors::None,+ Some(_) => StyloStyleForcedColors::None,+ },+ }+ }++ pub(super) fn stylo_media_type(self) -> MediaType {+ match self.media_type {+ StyloStyleMediaType::Screen => MediaType::screen(),+ StyloStyleMediaType::Print => MediaType::print(),+ }+ }++ pub(super) fn stylo_prefers_color_scheme(self) -> PrefersColorScheme {+ match self.color_scheme {+ StyloStyleColorScheme::Light => PrefersColorScheme::Light,+ StyloStyleColorScheme::Dark => PrefersColorScheme::Dark,+ }+ }++ pub(super) fn stylo_media_feature_preferences(self) -> ServoMediaFeaturePreferences {+ ServoMediaFeaturePreferences {+ prefers_reduced_motion: self.reduced_motion.prefers_reduced(),+ prefers_reduced_data: self.reduced_data.prefers_reduced(),+ prefers_reduced_transparency: self.reduced_transparency.prefers_reduced(),+ prefers_contrast: match self.contrast {+ StyloStyleContrastPreference::More => PrefersContrast::More,+ StyloStyleContrastPreference::Less => PrefersContrast::Less,+ StyloStyleContrastPreference::Custom => PrefersContrast::Custom,+ StyloStyleContrastPreference::NoPreference => PrefersContrast::NoPreference,+ },+ forced_colors: match self.forced_colors {+ StyloStyleForcedColors::None => ForcedColors::None,+ StyloStyleForcedColors::Active => ForcedColors::Active,+ },+ }+ }+}++impl StyloStyleReducedPreference {+ fn prefers_reduced(self) -> bool {+ matches!(self, Self::Reduce)+ }+}++#[derive(Clone, Debug)]+pub(crate) struct StyleWorldEnvironment {+ pub(super) document_url: url::Url,+ pub(super) viewport: StyleViewport,+ pub(super) media: StyloStyleEnvironment,+ pub(super) quirks_mode: style::context::QuirksMode,+ pub(super) tree_scope_versions: StyleTreeScopeVersions,+}++impl StyleWorldEnvironment {+ pub(crate) fn new(+ document_url: url::Url,+ viewport: StyleViewport,+ media: StyloStyleEnvironment,+ quirks_mode: style::context::QuirksMode,+ tree_scope_versions: StyleTreeScopeVersions,+ ) -> Self {+ Self {+ document_url,+ viewport,+ media,+ quirks_mode,+ tree_scope_versions,+ }+ }+}diff --git a/moli-renderer-v8/src/style_engine/world_key.rs b/moli-renderer-v8/src/style_engine/world_key.rsnew file mode 100644index 000000000..b7934ba92--- /dev/null+++ b/moli-renderer-v8/src/style_engine/world_key.rs@@ -0,0 +1,216 @@+use style::context::QuirksMode;++use super::{+ FullStyleWorldSnapshot, StyleTreeScopeVersions, StyleViewport, StyleWorldEnvironment,+ StyloStyleEnvironment,+};++pub(super) const DEFAULT_VIEWPORT_WIDTH: f32 = 1024.0;+pub(super) const DEFAULT_VIEWPORT_HEIGHT: f32 = 768.0;++/// Stable identity of a retained Document style world.+///+/// Stylesheet contents intentionally do not participate. Persistent active+/// collections and dirty records update those incrementally; hashing complete+/// source vectors here would reintroduce the snapshot model.+#[derive(Clone, Debug, PartialEq, Eq, Hash)]+pub(super) struct StyleWorldKey {+ pub(super) document_url: url::Url,+ pub(super) viewport_width_bits: u32,+ pub(super) viewport_height_bits: u32,+ pub(super) screen_width_bits: u32,+ pub(super) screen_height_bits: u32,+ pub(super) environment: StyloStyleEnvironment,+ pub(super) quirks_mode: QuirksMode,+ pub(super) tree_scope_versions: Option<StyleTreeScopeVersions>,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub(super) struct StyleWorldKeyMismatchTrace {+ pub(super) document_url_changed: bool,+ pub(super) previous_document_url: url::Url,+ pub(super) next_document_url: url::Url,+ pub(super) viewport_changed: bool,+ pub(super) previous_viewport_width_bits: u32,+ pub(super) next_viewport_width_bits: u32,+ pub(super) previous_viewport_height_bits: u32,+ pub(super) next_viewport_height_bits: u32,+ pub(super) screen_changed: bool,+ pub(super) previous_screen_width_bits: u32,+ pub(super) next_screen_width_bits: u32,+ pub(super) previous_screen_height_bits: u32,+ pub(super) next_screen_height_bits: u32,+ pub(super) environment_changed: bool,+ pub(super) quirks_mode_changed: bool,+ pub(super) tree_scope_versions_changed: bool,+ pub(super) previous_tree_scope_versions: Option<StyleTreeScopeVersions>,+ pub(super) next_tree_scope_versions: Option<StyleTreeScopeVersions>,+}++impl StyleWorldKey {+ #[cfg(test)]+ pub(super) fn new(+ document_url: &url::Url,+ inputs: &FullStyleWorldSnapshot,+ viewport: impl Into<StyleViewport>,+ ) -> Self {+ Self::build(document_url, inputs, viewport.into(), None)+ }++ pub(super) fn new_for_observation(+ document_url: &url::Url,+ inputs: &FullStyleWorldSnapshot,+ viewport: StyleViewport,+ tree_scope_versions: StyleTreeScopeVersions,+ ) -> Self {+ Self::build(document_url, inputs, viewport, Some(tree_scope_versions))+ }++ fn build(+ document_url: &url::Url,+ inputs: &FullStyleWorldSnapshot,+ viewport: StyleViewport,+ tree_scope_versions: Option<StyleTreeScopeVersions>,+ ) -> Self {+ let mut document_url = document_url.clone();+ document_url.set_fragment(None);+ let viewport_width_bits = style_dimension_bits(viewport.width, DEFAULT_VIEWPORT_WIDTH);+ let viewport_height_bits = style_dimension_bits(viewport.height, DEFAULT_VIEWPORT_HEIGHT);+ Self {+ document_url,+ viewport_width_bits,+ viewport_height_bits,+ screen_width_bits: style_dimension_bits(+ viewport.screen_width,+ f32::from_bits(viewport_width_bits),+ ),+ screen_height_bits: style_dimension_bits(+ viewport.screen_height,+ f32::from_bits(viewport_height_bits),+ ),+ environment: inputs.environment,+ quirks_mode: inputs.quirks_mode,+ tree_scope_versions,+ }+ }++ pub(super) fn updated_for_observation(&self, environment: &StyleWorldEnvironment) -> Self {+ let mut next = self.clone();+ let mut document_url = environment.document_url.clone();+ document_url.set_fragment(None);+ let viewport_width_bits =+ style_dimension_bits(environment.viewport.width, DEFAULT_VIEWPORT_WIDTH);+ let viewport_height_bits =+ style_dimension_bits(environment.viewport.height, DEFAULT_VIEWPORT_HEIGHT);+ next.document_url = document_url;+ next.viewport_width_bits = viewport_width_bits;+ next.viewport_height_bits = viewport_height_bits;+ next.screen_width_bits = style_dimension_bits(+ environment.viewport.screen_width,+ f32::from_bits(viewport_width_bits),+ );+ next.screen_height_bits = style_dimension_bits(+ environment.viewport.screen_height,+ f32::from_bits(viewport_height_bits),+ );+ next.environment = environment.media;+ next.quirks_mode = environment.quirks_mode;+ next.tree_scope_versions = Some(environment.tree_scope_versions);+ next+ }++ pub(super) fn mismatch_trace(&self, next: &Self) -> StyleWorldKeyMismatchTrace {+ StyleWorldKeyMismatchTrace {+ document_url_changed: self.document_url != next.document_url,+ previous_document_url: self.document_url.clone(),+ next_document_url: next.document_url.clone(),+ viewport_changed: self.viewport_width_bits != next.viewport_width_bits+ || self.viewport_height_bits != next.viewport_height_bits,+ previous_viewport_width_bits: self.viewport_width_bits,+ next_viewport_width_bits: next.viewport_width_bits,+ previous_viewport_height_bits: self.viewport_height_bits,+ next_viewport_height_bits: next.viewport_height_bits,+ screen_changed: self.screen_width_bits != next.screen_width_bits+ || self.screen_height_bits != next.screen_height_bits,+ previous_screen_width_bits: self.screen_width_bits,+ next_screen_width_bits: next.screen_width_bits,+ previous_screen_height_bits: self.screen_height_bits,+ next_screen_height_bits: next.screen_height_bits,+ environment_changed: self.environment != next.environment,+ quirks_mode_changed: self.quirks_mode != next.quirks_mode,+ tree_scope_versions_changed: self.tree_scope_versions != next.tree_scope_versions,+ previous_tree_scope_versions: self.tree_scope_versions,+ next_tree_scope_versions: next.tree_scope_versions,+ }+ }++ pub(super) fn matches_observation_environment(+ &self,+ document_url: &url::Url,+ viewport: StyleViewport,+ environment: StyloStyleEnvironment,+ quirks_mode: QuirksMode,+ tree_scope_versions: StyleTreeScopeVersions,+ ) -> bool {+ let mut document_url = document_url.clone();+ document_url.set_fragment(None);+ let viewport_width_bits = style_dimension_bits(viewport.width, DEFAULT_VIEWPORT_WIDTH);+ let viewport_height_bits = style_dimension_bits(viewport.height, DEFAULT_VIEWPORT_HEIGHT);+ self.document_url == document_url+ && self.viewport_width_bits == viewport_width_bits+ && self.viewport_height_bits == viewport_height_bits+ && self.screen_width_bits+ == style_dimension_bits(viewport.screen_width, f32::from_bits(viewport_width_bits))+ && self.screen_height_bits+ == style_dimension_bits(+ viewport.screen_height,+ f32::from_bits(viewport_height_bits),+ )+ && self.environment == environment+ && self.quirks_mode == quirks_mode+ && self.tree_scope_versions == Some(tree_scope_versions)+ }++ pub(super) fn requires_replacement_for_observation(+ &self,+ document_url: &url::Url,+ quirks_mode: QuirksMode,+ ) -> bool {+ let mut document_url = document_url.clone();+ document_url.set_fragment(None);+ self.document_url != document_url || self.quirks_mode != quirks_mode+ }++ pub(super) fn device_differs_from_observation(+ &self,+ viewport: StyleViewport,+ environment: StyloStyleEnvironment,+ ) -> bool {+ let viewport_width_bits = style_dimension_bits(viewport.width, DEFAULT_VIEWPORT_WIDTH);+ let viewport_height_bits = style_dimension_bits(viewport.height, DEFAULT_VIEWPORT_HEIGHT);+ self.viewport_width_bits != viewport_width_bits+ || self.viewport_height_bits != viewport_height_bits+ || self.screen_width_bits+ != style_dimension_bits(viewport.screen_width, f32::from_bits(viewport_width_bits))+ || self.screen_height_bits+ != style_dimension_bits(+ viewport.screen_height,+ f32::from_bits(viewport_height_bits),+ )+ || self.environment != environment+ }+}++impl StyleWorldKeyMismatchTrace {+ pub(super) fn requires_style_system_replacement(&self) -> bool {+ self.document_url_changed || self.quirks_mode_changed+ }+}++fn style_dimension_bits(value: Option<f64>, fallback: f32) -> u32 {+ value+ .filter(|value| value.is_finite() && *value >= 0.0)+ .map(|value| value as f32)+ .unwrap_or(fallback)+ .to_bits()+}diff --git a/moli-renderer-v8/src/style_engine/world_lifecycle.rs b/moli-renderer-v8/src/style_engine/world_lifecycle.rsnew file mode 100644index 000000000..37bb7d9ff--- /dev/null+++ b/moli-renderer-v8/src/style_engine/world_lifecycle.rs@@ -0,0 +1,366 @@+//! Planning and application of on-demand updates to retained Document worlds.++use crate::{document_runtime::DomHandle, dom::native::DomHost};++use moli_selector::StyloDomStyleAdapter;+use style::context::QuirksMode;++use super::{+ FullStyleWorldSnapshot, StyleTreeScopeVersions, StyleViewport, StyleWorldEnvironment,+ StyloStyleEnvironment,+ cleanup::StyleCacheCleanup,+ retained::{+ RetainedStyleInvalidations, build_retained_style_system,+ retained_style_system_matches_full_snapshot, update_retained_style_system,+ update_retained_style_system_incrementally,+ },+ source_document::DocumentStyleSourceStores,+ source_lifecycle::StyleSourceDocumentContext,+ state::StyleDocumentState,+ world_key::StyleWorldKey,+ world_trace::{RetainedStyleSystemChangeKind, trace_retained_style_system_change},+ world_update::{+ IncrementalStyleWorldUpdate, IncrementalStyleWorldUpdatePlan, StyleWorldUpdatePlan,+ },+};++pub(super) fn retained_style_world_update_plan(+ host: &DomHost,+ document_state: &StyleDocumentState,+ document: DomHandle,+ document_url: &url::Url,+ viewport: StyleViewport,+ environment: StyloStyleEnvironment,+ quirks_mode: QuirksMode,+ tree_scope_versions: StyleTreeScopeVersions,+) -> StyleWorldUpdatePlan {+ let source_dirty_scope = document_state.source_dirty_scope_snapshot();+ let Some((replace_world, device_changed, tree_scopes_changed, retained_shadow_roots)) =+ document_state.try_with_retained_style_system(|retained| {+ (+ retained+ .key+ .requires_replacement_for_observation(document_url, quirks_mode),+ retained+ .key+ .device_differs_from_observation(viewport, environment),+ retained.key.tree_scope_versions != Some(tree_scope_versions),+ retained+ .shadow_scopes+ .iter()+ .map(|scope| scope.root())+ .collect::<Vec<_>>(),+ )+ })+ else {+ return StyleWorldUpdatePlan::Full;+ };+ if replace_world {+ return StyleWorldUpdatePlan::Full;+ }++ let connected_shadow_roots = tree_scopes_changed.then(|| {+ let mut roots = host+ .snapshot_connected_shadow_roots()+ .into_iter()+ .filter(|root| host.owner_document_handle(*root) == Some(document))+ .collect::<Vec<_>>();+ roots.sort_by_key(|root| root.index());+ roots+ });+ let mut shadow_stylesheet_roots = source_dirty_scope.dirty_shadow_roots();+ if let Some(connected_roots) = connected_shadow_roots.as_ref() {+ shadow_stylesheet_roots.extend(+ connected_roots+ .iter()+ .copied()+ .filter(|root| !retained_shadow_roots.contains(root)),+ );+ }++ // The bridge currently models <style media> and <link media> by active-list+ // membership instead of installing their MediaList on the Stylo sheet.+ // A device change therefore has to refresh those ordered lists. This is+ // still scope-local and parse-free for unchanged installations.+ if device_changed {+ shadow_stylesheet_roots.extend(+ connected_shadow_roots+ .as_deref()+ .unwrap_or(&retained_shadow_roots)+ .iter()+ .copied(),+ );+ }++ StyleWorldUpdatePlan::Incremental(IncrementalStyleWorldUpdatePlan::new(+ source_dirty_scope.refreshes_document_stylesheets(document) || device_changed,+ shadow_stylesheet_roots.into_iter().collect(),+ connected_shadow_roots,+ source_dirty_scope.refreshes_custom_property_registrations(document),+ ))+}++pub(super) fn ensure_retained_style_system(+ host: &DomHost,+ dom_adapter: &StyloDomStyleAdapter,+ document_state: &StyleDocumentState,+ source_stores: &DocumentStyleSourceStores<'_>,+ document_context: StyleSourceDocumentContext<'_>,+ retained_document: DomHandle,+ cache_cleanup: StyleCacheCleanup<'_>,+ key: &StyleWorldKey,+ inputs: &FullStyleWorldSnapshot,+) {+ let source_dirty_scope = document_state.source_dirty_scope_snapshot();+ if document_state+ .try_with_retained_style_system(|retained| {+ retained_style_system_matches_full_snapshot(retained, key, inputs)+ })+ .unwrap_or(false)+ {+ if source_dirty_scope.requires_retained_style_update() {+ document_state.clear_source_dirty_scopes();+ }+ return;+ }+ let trace_enabled = moli_trace::style_invalidation_trace_enabled();+ let key_mismatch_trace =+ document_state.try_with_retained_style_system(|retained| retained.key.mismatch_trace(key));+ let trace_documents = trace_enabled.then(|| vec![retained_document]);++ let source_lifecycle = source_stores.source_lifecycle_report(host, document_context);+ let retained_source_records =+ source_stores.retained_source_records_for_lifecycle(host, &source_lifecycle);+ let shared_lock = dom_adapter.shared_lock().clone();+ let custom_property_history_is_append_only = document_state+ .try_with_retained_style_system(|retained| {+ retained.script_custom_property_registrations.len()+ <= inputs.script_custom_property_registrations.len()+ && retained.script_custom_property_registrations+ == inputs.script_custom_property_registrations+ [..retained.script_custom_property_registrations.len()]+ })+ .unwrap_or(true);+ let can_update_in_place = key_mismatch_trace+ .as_ref()+ .is_some_and(|trace| !trace.requires_style_system_replacement())+ && custom_property_history_is_append_only;+ if can_update_in_place {+ let invalidations = document_state.update_retained_style_system_with_result(|retained| {+ update_retained_style_system(+ retained,+ host,+ key.clone(),+ inputs,+ &shared_lock,+ &retained_source_records,+ )+ });+ apply_retained_stylesheet_invalidations(+ host,+ dom_adapter,+ retained_document,+ &cache_cleanup,+ invalidations,+ );+ document_state.clear_source_dirty_scopes();+ if trace_enabled {+ document_state.with_retained_style_system(|retained| {+ trace_retained_style_system_change(+ inputs,+ &source_lifecycle,+ &source_dirty_scope,+ document_state.source_set_generation(),+ retained,+ RetainedStyleSystemChangeKind::IncrementalUpdate,+ custom_property_history_is_append_only,+ key_mismatch_trace.as_ref(),+ trace_documents.as_deref().unwrap_or_default(),+ );+ });+ }+ return;+ }++ // Replacing the document style world is the exceptional path. Incremental+ // updates above must preserve canonical ElementData so Stylo can apply the+ // invalidation set returned by flush().+ cache_cleanup.clear_for_retained_style_system_rebuild();+ document_state.clear_source_dirty_scopes();++ let retained = build_retained_style_system(+ host,+ key.clone(),+ inputs,+ &shared_lock,+ &retained_source_records,+ );+ if trace_enabled {+ trace_retained_style_system_change(+ inputs,+ &source_lifecycle,+ &source_dirty_scope,+ document_state.source_set_generation(),+ &retained,+ if key_mismatch_trace.is_some() {+ RetainedStyleSystemChangeKind::Replacement+ } else {+ RetainedStyleSystemChangeKind::InitialBuild+ },+ custom_property_history_is_append_only,+ key_mismatch_trace.as_ref(),+ trace_documents.as_deref().unwrap_or_default(),+ );+ }+ document_state.set_retained_style_system(retained);+}++pub(super) fn ensure_retained_style_system_incrementally(+ host: &DomHost,+ dom_adapter: &StyloDomStyleAdapter,+ document_state: &StyleDocumentState,+ source_stores: &DocumentStyleSourceStores<'_>,+ document_context: StyleSourceDocumentContext<'_>,+ retained_document: DomHandle,+ cache_cleanup: StyleCacheCleanup<'_>,+ environment: &StyleWorldEnvironment,+ update: &IncrementalStyleWorldUpdate,+) {+ let source_dirty_scope = document_state.source_dirty_scope_snapshot();+ let Some((next_key, device_changed)) =+ document_state.try_with_retained_style_system(|retained| {+ (+ retained.key.updated_for_observation(environment),+ retained+ .key+ .device_differs_from_observation(environment.viewport, environment.media),+ )+ })+ else {+ // Planning guarantees an initial observation is full. Keep this guard+ // explicit so a stale or incorrectly reused plan cannot create a+ // partial Document world.+ debug_assert!(false, "incremental style update requires a retained world");+ return;+ };++ let dirty_source_ids = source_dirty_scope+ .source_ids_vec()+ .into_iter()+ .collect::<std::collections::HashSet<_>>();+ let full_source_projection_scopes = source_dirty_scope+ .full_source_projection_scope_ids()+ .into_iter()+ .collect::<std::collections::HashSet<_>>();+ let source_lifecycle = if device_changed || !full_source_projection_scopes.is_empty() {+ source_stores.source_lifecycle_report(host, document_context)+ } else {+ source_stores.source_lifecycle_report_for_source_ids(+ host,+ document_context,+ dirty_source_ids.iter().cloned(),+ )+ };+ let retained_source_records =+ source_stores.retained_source_records_for_lifecycle(host, &source_lifecycle);+ let shared_lock = dom_adapter.shared_lock().clone();+ let invalidations = document_state.update_retained_style_system_with_result(|retained| {+ update_retained_style_system_incrementally(+ retained,+ host,+ retained_document,+ next_key,+ update,+ &shared_lock,+ &retained_source_records,+ &dirty_source_ids,+ &full_source_projection_scopes,+ )+ });+ apply_retained_stylesheet_invalidations(+ host,+ dom_adapter,+ retained_document,+ &cache_cleanup,+ invalidations,+ );+ document_state.clear_source_dirty_scopes();++ if moli_trace::style_invalidation_trace_enabled() {+ tracing::info!(+ retained_document = ?retained_document,+ document_scope_materialized = update.document_stylesheet_sources.is_some(),+ shadow_scopes_materialized = ?update+ .shadow_stylesheet_sources+ .iter()+ .map(|(root, _)| *root)+ .collect::<Vec<_>>(),+ tree_scope_membership_materialized = update.connected_shadow_roots.is_some(),+ custom_properties_materialized = update+ .script_custom_property_registrations+ .is_some(),+ source_dirty_ids = ?source_dirty_scope.source_ids_vec(),+ source_dirty_scope_ids = ?source_dirty_scope.scope_ids_vec(),+ source_dirty_reasons = ?source_dirty_scope.reasons_vec(),+ "incremental retained style world update"+ );+ }+}++fn apply_retained_stylesheet_invalidations(+ host: &DomHost,+ dom_adapter: &StyloDomStyleAdapter,+ document: DomHandle,+ cache_cleanup: &StyleCacheCleanup<'_>,+ invalidations: RetainedStyleInvalidations,+) {+ let RetainedStyleInvalidations {+ document: document_invalidations,+ document_scope_fallback,+ shadow_scopes,+ shadow_scope_fallbacks,+ removed_shadow_scopes,+ } = invalidations;+ if let Some(invalidations) = document_invalidations {+ // HTML documents normally have one document element. The native DOM+ // also permits fragment-like test documents with several top-level+ // elements, and every one of those roots belongs to the document+ // stylesheet scope.+ let mut roots = host+ .child_handles(document)+ .filter(|handle| {+ host.node(*handle)+ .is_some_and(|node| node.as_element().is_some())+ })+ .collect::<Vec<_>>();+ if roots.is_empty()+ && let Some(root) = host.document_element_handle_for_document(document)+ {+ roots.push(root);+ }+ dom_adapter.process_stylesheet_invalidations(host, &roots, &invalidations);+ }+ for (shadow_root, invalidations) in shadow_scopes {+ let mut roots = host+ .child_handles(shadow_root)+ .filter(|handle| {+ host.node(*handle)+ .is_some_and(|node| node.as_element().is_some())+ })+ .collect::<Vec<_>>();+ if let Some(shadow_host) = host.shadow_root_host(shadow_root) {+ roots.push(shadow_host);+ }+ dom_adapter.process_stylesheet_invalidations(host, &roots, &invalidations);+ }+ cache_cleanup.invalidate_stylesheet_dirty_subtrees(host);+ if document_scope_fallback {+ cache_cleanup.invalidate_subtrees(host, [document]);+ }+ for shadow_root in shadow_scope_fallbacks {+ let mut roots = vec![shadow_root];+ roots.extend(host.shadow_root_host(shadow_root));+ cache_cleanup.invalidate_subtrees(host, roots);+ }+ cache_cleanup.invalidate_subtrees(host, removed_shadow_scopes);+}diff --git a/moli-renderer-v8/src/style_engine/world_trace.rs b/moli-renderer-v8/src/style_engine/world_trace.rsnew file mode 100644index 000000000..b376d252e--- /dev/null+++ b/moli-renderer-v8/src/style_engine/world_trace.rs@@ -0,0 +1,136 @@+use crate::document_runtime::DomHandle;++use super::{+ FullStyleWorldSnapshot,+ source::store::StyloStylesheetSource,+ source_dirty::StyleSourceDirtyScopeSnapshot,+ source_id::StyleSourceId,+ source_lifecycle::{+ StyleSourceLifecycleOwnerDetailTrace, StyleSourceLifecycleOwnerDetailTraceSink,+ StyleSourceLifecycleReport, StyleSourceLifecycleSnapshot, StyleSourceLifecycleSnapshotSink,+ },+ state::RetainedStyleSystem,+ world_key::StyleWorldKeyMismatchTrace,+};++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(super) enum RetainedStyleSystemChangeKind {+ InitialBuild,+ IncrementalUpdate,+ Replacement,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub(super) struct StyleSourceInputTrace {+ pub(super) document_stylesheet_source_count: usize,+ pub(super) document_source_ids: Vec<Option<StyleSourceId>>,+ pub(super) shadow_stylesheet_sources: Vec<StyleSourceInputShadowRootTrace>,+ pub(super) script_custom_property_registration_count: usize,+ pub(super) script_custom_property_base_urls: Vec<url::Url>,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub(super) struct StyleSourceInputShadowRootTrace {+ pub(super) root: DomHandle,+ pub(super) source_count: usize,+ pub(super) source_ids: Vec<Option<StyleSourceId>>,+}++pub(super) fn trace_retained_style_system_change(+ inputs: &FullStyleWorldSnapshot,+ source_lifecycle: &StyleSourceLifecycleReport,+ source_dirty_scope: &StyleSourceDirtyScopeSnapshot,+ source_set_generation: u64,+ retained: &RetainedStyleSystem,+ change_kind: RetainedStyleSystemChangeKind,+ custom_property_history_is_append_only: bool,+ key_mismatch: Option<&StyleWorldKeyMismatchTrace>,+ document_context_documents: &[DomHandle],+) {+ let mut lifecycle_snapshot = RetainedStyleSystemRebuildLifecycleSnapshot::default();+ source_lifecycle.record_snapshot_into(&mut lifecycle_snapshot);+ source_lifecycle.record_owner_detail_trace_into(&mut lifecycle_snapshot);+ let source_input = style_source_input_trace(inputs);+ tracing::info!(+ change_kind = ?change_kind,+ stylist_identity = retained.stylist_identity,+ stylist_flush_count = retained.stylist.num_rebuilds(),+ custom_property_history_is_append_only,+ document_url = %retained.key.document_url,+ document_stylesheet_input_count = inputs.document_stylesheet_sources.len(),+ shadow_stylesheet_input_count = inputs.shadow_stylesheet_sources.len(),+ retained_shadow_cascade_count = retained.shadow_cascade_data.len(),+ retained_source_cascade_data_count = retained.source_cascade_data.len(),+ document_context_documents = ?document_context_documents,+ source_set_generation,+ source_dirty_ids = ?source_dirty_scope.source_ids_vec(),+ source_dirty_scope_ids = ?source_dirty_scope.scope_ids_vec(),+ source_dirty_roots = ?source_dirty_scope.scoped_roots_vec(),+ source_dirty_reasons = ?source_dirty_scope.reasons_vec(),+ source_dirty_records = ?source_dirty_scope.records_vec(),+ source_input = ?source_input,+ key_mismatch = ?key_mismatch,+ source_lifecycle = ?lifecycle_snapshot.snapshot,+ source_lifecycle_owner_details = ?lifecycle_snapshot.owner_details,+ "retained style system change summary"+ );+}++fn style_source_input_trace(inputs: &FullStyleWorldSnapshot) -> StyleSourceInputTrace {+ StyleSourceInputTrace {+ document_stylesheet_source_count: inputs.document_stylesheet_sources.len(),+ document_source_ids: style_source_ids_for_trace(&inputs.document_stylesheet_sources),+ shadow_stylesheet_sources: inputs+ .shadow_stylesheet_sources+ .iter()+ .map(|(root, sources)| StyleSourceInputShadowRootTrace {+ root: *root,+ source_count: sources.len(),+ source_ids: style_source_ids_for_trace(sources),+ })+ .collect(),+ script_custom_property_registration_count: inputs+ .script_custom_property_registrations+ .len(),+ script_custom_property_base_urls: inputs+ .script_custom_property_registrations+ .iter()+ .map(|record| record.base_url.clone())+ .collect(),+ }+}++fn style_source_ids_for_trace(sources: &[StyloStylesheetSource]) -> Vec<Option<StyleSourceId>> {+ sources+ .iter()+ .map(|source| source.source_id().cloned())+ .collect()+}++#[cfg(test)]+pub(super) fn style_source_input_trace_for_test(+ inputs: &FullStyleWorldSnapshot,+) -> StyleSourceInputTrace {+ style_source_input_trace(inputs)+}++#[derive(Default)]+struct RetainedStyleSystemRebuildLifecycleSnapshot {+ snapshot: StyleSourceLifecycleSnapshot,+ owner_details: Vec<StyleSourceLifecycleOwnerDetailTrace>,+}++impl StyleSourceLifecycleSnapshotSink for RetainedStyleSystemRebuildLifecycleSnapshot {+ fn record_source_lifecycle_snapshot(&mut self, snapshot: StyleSourceLifecycleSnapshot) {+ self.snapshot = snapshot;+ }+}++impl StyleSourceLifecycleOwnerDetailTraceSink for RetainedStyleSystemRebuildLifecycleSnapshot {+ fn record_source_lifecycle_owner_detail_trace(+ &mut self,+ trace: StyleSourceLifecycleOwnerDetailTrace,+ ) {+ self.owner_details.push(trace);+ }+}diff --git a/moli-renderer-v8/src/style_engine/world_update.rs b/moli-renderer-v8/src/style_engine/world_update.rsnew file mode 100644index 000000000..79e935202--- /dev/null+++ b/moli-renderer-v8/src/style_engine/world_update.rs@@ -0,0 +1,183 @@+use std::rc::Rc;++use style::context::QuirksMode;++use crate::document_runtime::DomHandle;++use super::{+ CssCustomPropertyRegistrationRecord, StyleWorldEnvironment, StyloStyleEnvironment,+ StyloStylesheetSource,+};++/// Complete source projection used to construct a fresh Document style world.+///+/// Normal observations use `IncrementalStyleWorldUpdate`; this full snapshot+/// is reserved for the first observation, true world replacement, isolated+/// provenance queries, and the full-rebuild test oracle.+#[derive(Clone, Debug)]+pub(crate) struct FullStyleWorldSnapshot {+ pub(crate) document_stylesheet_sources: Vec<StyloStylesheetSource>,+ pub(crate) shadow_stylesheet_sources: Vec<(DomHandle, Vec<StyloStylesheetSource>)>,+ pub(crate) script_custom_property_registrations: Vec<CssCustomPropertyRegistrationRecord>,+ pub(crate) environment: StyloStyleEnvironment,+ pub(crate) quirks_mode: QuirksMode,+}++impl FullStyleWorldSnapshot {+ /// Makes a snapshot safe to consume under a different Stylo+ /// `SharedRwLock`. Text sources already have no lock-bound rule tree;+ /// live sources are converted to independently parsed text projections.+ pub(crate) fn independent_style_engine_projection(&self) -> Self {+ let project_sources = |sources: &[StyloStylesheetSource]| {+ sources+ .iter()+ .map(StyloStylesheetSource::independent_text_projection)+ .collect()+ };+ Self {+ document_stylesheet_sources: project_sources(&self.document_stylesheet_sources),+ shadow_stylesheet_sources: self+ .shadow_stylesheet_sources+ .iter()+ .map(|(root, sources)| (*root, project_sources(sources)))+ .collect(),+ script_custom_property_registrations: self.script_custom_property_registrations.clone(),+ environment: self.environment,+ quirks_mode: self.quirks_mode,+ }+ }+}++impl Default for FullStyleWorldSnapshot {+ fn default() -> Self {+ Self {+ document_stylesheet_sources: Vec::new(),+ shadow_stylesheet_sources: Vec::new(),+ script_custom_property_registrations: Vec::new(),+ environment: StyloStyleEnvironment::default(),+ quirks_mode: QuirksMode::NoQuirks,+ }+ }+}++/// Work that must be materialized before observing a retained Document style+/// world.+///+/// A full update is reserved for the first observation and true world+/// replacement. Incremental updates name the exact stylesheet scopes whose+/// ordered active collections must be refreshed. Device-only updates carry no+/// stylesheet vectors.+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) enum StyleWorldUpdatePlan {+ Full,+ Incremental(IncrementalStyleWorldUpdatePlan),+}++#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub(crate) struct IncrementalStyleWorldUpdatePlan {+ document_stylesheets: bool,+ shadow_stylesheet_roots: Vec<DomHandle>,+ connected_shadow_roots: Option<Vec<DomHandle>>,+ custom_property_registrations: bool,+}++impl IncrementalStyleWorldUpdatePlan {+ pub(super) fn new(+ document_stylesheets: bool,+ shadow_stylesheet_roots: Vec<DomHandle>,+ connected_shadow_roots: Option<Vec<DomHandle>>,+ custom_property_registrations: bool,+ ) -> Self {+ Self {+ document_stylesheets,+ shadow_stylesheet_roots,+ connected_shadow_roots,+ custom_property_registrations,+ }+ }++ pub(crate) fn refreshes_document_stylesheets(&self) -> bool {+ self.document_stylesheets+ }++ pub(crate) fn shadow_stylesheet_roots(&self) -> &[DomHandle] {+ &self.shadow_stylesheet_roots+ }++ pub(crate) fn connected_shadow_roots(&self) -> Option<&[DomHandle]> {+ self.connected_shadow_roots.as_deref()+ }++ pub(crate) fn refreshes_custom_property_registrations(&self) -> bool {+ self.custom_property_registrations+ }+}++#[derive(Clone, Debug)]+pub(crate) struct IncrementalStyleWorldUpdate {+ pub(super) document_stylesheet_sources: Option<Vec<StyloStylesheetSource>>,+ pub(super) shadow_stylesheet_sources: Vec<(DomHandle, Vec<StyloStylesheetSource>)>,+ pub(super) connected_shadow_roots: Option<Vec<DomHandle>>,+ pub(super) script_custom_property_registrations:+ Option<Vec<CssCustomPropertyRegistrationRecord>>,+}++impl IncrementalStyleWorldUpdate {+ pub(crate) fn new(+ document_stylesheet_sources: Option<Vec<StyloStylesheetSource>>,+ shadow_stylesheet_sources: Vec<(DomHandle, Vec<StyloStylesheetSource>)>,+ connected_shadow_roots: Option<Vec<DomHandle>>,+ script_custom_property_registrations: Option<Vec<CssCustomPropertyRegistrationRecord>>,+ ) -> Self {+ Self {+ document_stylesheet_sources,+ shadow_stylesheet_sources,+ connected_shadow_roots,+ script_custom_property_registrations,+ }+ }+}++#[derive(Clone, Debug)]+pub(crate) enum StyleWorldUpdate {+ Full(Rc<FullStyleWorldSnapshot>),+ Incremental(IncrementalStyleWorldUpdate),+}++/// An observation-local update batch. It contains only data requested by the+/// retained world's dirty plan and never outlives the synchronous observation.+#[derive(Clone, Debug)]+pub(crate) struct PreparedStyleWorldUpdate {+ environment: StyleWorldEnvironment,+ update: StyleWorldUpdate,+}++impl PreparedStyleWorldUpdate {+ pub(crate) fn full(+ environment: StyleWorldEnvironment,+ inputs: Rc<FullStyleWorldSnapshot>,+ ) -> Self {+ Self {+ environment,+ update: StyleWorldUpdate::Full(inputs),+ }+ }++ pub(crate) fn incremental(+ environment: StyleWorldEnvironment,+ update: IncrementalStyleWorldUpdate,+ ) -> Self {+ Self {+ environment,+ update: StyleWorldUpdate::Incremental(update),+ }+ }++ pub(super) fn environment(&self) -> &StyleWorldEnvironment {+ &self.environment+ }++ pub(super) fn update(&self) -> &StyleWorldUpdate {+ &self.update+ }+}diff --git a/moli-renderer-v8/src/stylesheet_runtime/settlement.rs b/moli-renderer-v8/src/stylesheet_runtime/settlement.rsindex 1332136f3..d83e2474f 100644--- a/moli-renderer-v8/src/stylesheet_runtime/settlement.rs+++ b/moli-renderer-v8/src/stylesheet_runtime/settlement.rs@@ -137,7 +137,7 @@ impl DocumentRuntime {if request_url.scheme() != "data" {linked_stylesheet_import_urls.extend(import_urls);}- for resource in crate::css_resource_urls::stylesheet_load_blocking_resources(+ for resource in crate::css_resource_urls::stylesheet_load_blocking_font_resources(&stylesheet_text,&stylesheet_base_url,optional_resource_fetch_mask,diff --git a/moli-selector/src/stylo/style_traversal.rs b/moli-selector/src/stylo/style_traversal.rsindex 33933e329..222f8725c 100644--- a/moli-selector/src/stylo/style_traversal.rs+++ b/moli-selector/src/stylo/style_traversal.rs@@ -22,6 +22,7 @@ use style::{context::{QuirksMode, SharedStyleContext},data::{ElementDataMut, ElementDataRef, ElementDataWrapper},dom::{LayoutIterator, NodeInfo, OpaqueNode, TDocument, TElement, TNode, TShadowRoot},+ invalidation::{element::restyle_hints::RestyleHint, stylesheets::StylesheetInvalidationSet},properties::{PropertyDeclarationBlock, longhands::display::computed_value::T as Display},selector_parser::{AttrValue as SelectorAttrValue, Lang, PseudoElement, SelectorImpl},servo_arc::{Arc, ArcBorrow},@@ -168,6 +169,12 @@ impl StyloDomStyleAdapter {self.state.clear_element_style_values(handle);}+ /// Retains the element's last published computed values while marking+ /// them unavailable for the next style observation.+ pub fn mark_element_style_dirty(&self, handle: NodeId) -> bool {+ self.state.mark_element_style_dirty(handle)+ }+pub fn clear_element_data_for_document(&self, document: NodeId) {self.state.clear_element_data_for_document(document);}@@ -194,6 +201,28 @@ impl StyloDomStyleAdapter {.element_style_value_handles_for_document(document)}+ pub fn dirty_element_style_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {+ self.state+ .dirty_element_style_handles_for_document(document)+ }++ pub fn process_stylesheet_invalidations(+ &self,+ host: &DomHost,+ roots: &[NodeId],+ invalidations: &StylesheetInvalidationSet,+ ) -> bool {+ self.with_bound_host(host, |binding| {+ let mut changed = false;+ for root in roots.iter().filter_map(|root| binding.element(host, *root)) {+ // Every root belongs to an independent Document/ShadowRoot+ // scope and must be processed even after an earlier match.+ changed |= invalidations.process_style(root, None);+ }+ changed+ })+ }+pub fn element_selector_flag_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {self.state.element_selector_flag_handles_for_document(document)@@ -328,6 +357,11 @@ impl<'binding> StyleDomHostBinding<'binding> {.element_style_value_handles_for_document(document)}+ pub fn dirty_element_style_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {+ self.state+ .dirty_element_style_handles_for_document(document)+ }+pub fn element_selector_flag_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {self.state.element_selector_flag_handles_for_document(document)@@ -500,6 +534,33 @@ impl StyloElementDataStore {});}+ fn mark_style_dirty(&self, handle: NodeId) -> bool {+ let data = {+ let documents = self.documents.borrow();+ self.document_for_handle(handle)+ .and_then(|document| documents.get(&document))+ .and_then(|bucket| bucket.data.get(&handle))+ .map(|data| &**data as *const ElementDataWrapper)+ .or_else(|| {+ documents+ .values()+ .find_map(|bucket| bucket.data.get(&handle))+ .map(|data| &**data as *const ElementDataWrapper)+ })+ };+ let Some(data) = data else {+ return false;+ };+ // SAFETY: ElementDataWrapper is heap-allocated behind a Box and the+ // adapter's side-table contract forbids removing this entry while the+ // returned Stylo borrow is alive.+ unsafe { &*data }+ .borrow_mut()+ .hint+ .insert(RestyleHint::RESTYLE_SELF | RestyleHint::RESTYLE_PSEUDOS);+ true+ }+fn clear_data_for_document(&self, document: NodeId) {let orphaned_handles = {let mut documents = self.documents.borrow_mut();@@ -710,6 +771,22 @@ impl StyloElementDataStore {handles.into_iter().collect()}+ fn dirty_style_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {+ self.documents+ .borrow()+ .get(&document)+ .map(|bucket| {+ bucket+ .data+ .iter()+ .filter_map(|(handle, data)| {+ (!data.borrow().hint.is_empty()).then_some(*handle)+ })+ .collect()+ })+ .unwrap_or_default()+ }+fn selector_flag_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {self.documents.borrow()@@ -1267,6 +1344,11 @@ impl StyleDomState {self.element_data.clear_style_values(handle);}+ fn mark_element_style_dirty(&self, handle: NodeId) -> bool {+ self.note_owner_document_if_bound(handle);+ self.element_data.mark_style_dirty(handle)+ }+fn clear_element_data_for_document(&self, document: NodeId) {self.element_data.clear_data_for_document(document);}@@ -1298,6 +1380,10 @@ impl StyleDomState {self.element_data.style_value_handles_for_document(document)}+ fn dirty_element_style_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {+ self.element_data.dirty_style_handles_for_document(document)+ }+fn element_selector_flag_handles_for_document(&self, document: NodeId) -> Vec<NodeId> {self.element_data.selector_flag_handles_for_document(document)