Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(css): avoid reparsing incomplete inline styles

ldm083e0afd1a1a9
diff --git a/moli-dom/src/native/element/control_state.rs b/moli-dom/src/native/element/control_state.rs
index 12a3509a4..02bcb64ca 100644
--- a/moli-dom/src/native/element/control_state.rs
+++ b/moli-dom/src/native/element/control_state.rs
@@ -147,6 +147,7 @@ pub struct ElementControlState {
select_explicit_none: bool,
indeterminate: bool,
script: Option<Box<ScriptElementState>>,
+ style_children_parsing: bool,
link_created_by_parser: bool,
link_explicitly_enabled: bool,
selection_start: Option<u32>,
@@ -629,6 +630,18 @@ impl ElementControlState {
true
}
+ pub fn style_children_parsing(&self) -> bool {
+ self.style_children_parsing
+ }
+
+ pub fn note_parser_created_style(&mut self) {
+ self.style_children_parsing = true;
+ }
+
+ pub fn finish_parsing_style_children(&mut self) -> bool {
+ std::mem::take(&mut self.style_children_parsing)
+ }
+
pub fn finish_parsing_link_children(&mut self) -> bool {
if !self.link_created_by_parser {
return false;
diff --git a/moli-dom/src/native/element/mod.rs b/moli-dom/src/native/element/mod.rs
index b6f26f59f..feb2b416f 100644
--- a/moli-dom/src/native/element/mod.rs
+++ b/moli-dom/src/native/element/mod.rs
@@ -139,6 +139,15 @@ impl Element {
{
rare_data.control_state_mut().note_parser_created_link();
}
+ if creation_source == ElementCreationSource::Parser
+ && local_name == "style"
+ && matches!(
+ namespace.as_str(),
+ "http://www.w3.org/1999/xhtml" | "http://www.w3.org/2000/svg"
+ )
+ {
+ rare_data.control_state_mut().note_parser_created_style();
+ }
Self {
local_name: LocalName::from(local_name),
namespace: Namespace::from(namespace),
@@ -777,6 +786,17 @@ impl Element {
self.control_state_mut().finish_parsing_link_children()
}
+ pub fn style_children_parsing(&self) -> bool {
+ self.control_state().style_children_parsing()
+ }
+
+ pub fn finish_parsing_style_children(&mut self) -> bool {
+ if !self.style_children_parsing() {
+ return false;
+ }
+ self.control_state_mut().finish_parsing_style_children()
+ }
+
pub fn parser_associated_form_owner(&self) -> Option<NativeNodeId> {
self.rare_data.parser_associated_form_owner()
}
diff --git a/moli-dom/src/native/host/document.rs b/moli-dom/src/native/host/document.rs
index 61bafdaba..ea6f1c9d7 100644
--- a/moli-dom/src/native/host/document.rs
+++ b/moli-dom/src/native/host/document.rs
@@ -1286,6 +1286,64 @@ impl DomHost {
Some(self.child_handles(handle).collect())
}
+ pub fn create_element_without_attributes_for_document(
+ &mut self,
+ document_handle: DomHandle,
+ local_name: String,
+ namespace: String,
+ prefix: Option<String>,
+ ) -> DomHandle {
+ self.allocate_element_for_document(document_handle, local_name, namespace, prefix, false)
+ }
+
+ pub(super) fn allocate_element_for_document(
+ &mut self,
+ document_handle: DomHandle,
+ local_name: String,
+ namespace: String,
+ prefix: Option<String>,
+ parser_created: bool,
+ ) -> DomHandle {
+ let is_template = namespace == "http://www.w3.org/1999/xhtml" && local_name == "template";
+ let is_child_browsing_context_host_candidate =
+ is_html_frame_owner_candidate(&local_name, &namespace);
+ let element = if parser_created {
+ Element::new_parser_created(local_name, namespace, prefix, Vec::new())
+ } else {
+ Element::new(local_name, namespace, prefix, Vec::new())
+ };
+ let node_id = self.dom.create_node(
+ NodeData::Element(element),
+ Some(document_handle),
+ false,
+ false,
+ );
+ if let Some(node) = self.node_mut(node_id) {
+ node.set_parser_created(parser_created);
+ }
+ self.record_element_query_index_candidate(node_id);
+ if is_child_browsing_context_host_candidate {
+ let mut candidates = self.child_browsing_context_host_candidates.borrow_mut();
+ if !candidates.contains(&node_id) {
+ candidates.push(node_id);
+ }
+ }
+
+ if is_template {
+ let template_contents = self
+ .dom
+ .create_template_contents_fragment_for_document(document_handle);
+ if let Some(element) = self
+ .node_mut(node_id)
+ .and_then(|node| node.data_mut().as_element_mut())
+ {
+ element.set_template_contents(Some(template_contents));
+ }
+ }
+
+ node_id
+ }
+
pub fn create_element(&mut self, local_name: &str) -> DomHandle {
let handle = self.dom.create_element(local_name);
self.record_element_query_index_candidate(handle);
diff --git a/moli-dom/src/native/host/mutation/effects/stylesheet.rs b/moli-dom/src/native/host/mutation/effects/stylesheet.rs
index 8926d6fec..40066b5c9 100644
--- a/moli-dom/src/native/host/mutation/effects/stylesheet.rs
+++ b/moli-dom/src/native/host/mutation/effects/stylesheet.rs
@@ -53,6 +53,8 @@ pub enum DomStylesheetOwnerChangeKind {
local_name: String,
},
Contents,
+ /// The parser has finished constructing this style element's children.
+ ParsingFinished,
OwnerDocumentChanged,
TreeConnectionChanged {
connected: bool,
@@ -190,6 +192,18 @@ impl DomMutationEffects {
});
}
+ pub(in crate::native::host::mutation) fn mark_stylesheet_owner_parsing_finished(
+ &mut self,
+ owner: DomHandle,
+ current_tree_scope: Option<DomHandle>,
+ ) {
+ self.mark_stylesheet_owner_change(DomStylesheetOwnerChange {
+ owner,
+ kind: DomStylesheetOwnerChangeKind::ParsingFinished,
+ tree_scopes: DomStylesheetOwnerTreeScopes::current(current_tree_scope),
+ });
+ }
+
pub(super) fn mark_stylesheet_owner_change(&mut self, change: DomStylesheetOwnerChange) {
self.changed = true;
self.stylesheet_owners.push(change);
diff --git a/moli-dom/src/native/host/mutation/state.rs b/moli-dom/src/native/host/mutation/state.rs
index 1d2608cda..0e0a5a69f 100644
--- a/moli-dom/src/native/host/mutation/state.rs
+++ b/moli-dom/src/native/host/mutation/state.rs
@@ -892,6 +892,28 @@ impl DomHost {
did_change
}
+ /// Finish a parser-created style at its closing tag or EOF. Report the
+ /// lifecycle transition without producing child or text mutation records.
+ pub fn finish_parsing_style_children_effects(
+ &mut self,
+ handle: DomHandle,
+ ) -> DomMutationEffects {
+ let did_change = self
+ .node_mut(handle)
+ .and_then(|node| node.data_mut().as_element_mut())
+ .is_some_and(Element::finish_parsing_style_children);
+ if !did_change {
+ return DomMutationEffects::default();
+ }
+ self.record_mutation(MutationScope::LocalState);
+ let mut effects = DomMutationEffects::changed();
+ effects.mark_stylesheet_owner_parsing_finished(
+ handle,
+ self.dom.stylesheet_candidate_tree_scope_for_node(handle),
+ );
+ effects
+ }
+
pub fn set_cryptographic_nonce(&mut self, handle: DomHandle, nonce: Option<String>) -> bool {
let did_change = {
let Some(element) = self
diff --git a/moli-dom/src/native/host/mutation/tree.rs b/moli-dom/src/native/host/mutation/tree.rs
index bd360d3fa..b68ffa680 100644
--- a/moli-dom/src/native/host/mutation/tree.rs
+++ b/moli-dom/src/native/host/mutation/tree.rs
@@ -877,7 +877,9 @@ impl DomHost {
effects: &mut DomMutationEffects,
parent: DomHandle,
) {
- if self.is_inline_style_sheet_owner(parent) {
+ if self.is_inline_style_sheet_owner(parent)
+ && !self.is_style_element_parsing_children(parent)
+ {
effects.mark_stylesheet_owner_contents_change(
parent,
self.dom.stylesheet_candidate_tree_scope_for_node(parent),
diff --git a/moli-dom/src/native/host/parser.rs b/moli-dom/src/native/host/parser.rs
index 872635976..5802f548d 100644
--- a/moli-dom/src/native/host/parser.rs
+++ b/moli-dom/src/native/host/parser.rs
@@ -58,44 +58,7 @@ impl DomHost {
namespace: String,
prefix: Option<String>,
) -> DomHandle {
- let is_template = namespace == "http://www.w3.org/1999/xhtml" && local_name == "template";
- let is_child_browsing_context_host_candidate =
- is_html_frame_owner_candidate(&local_name, &namespace);
- let node_id = self.dom.create_node(
- NodeData::Element(Element::new_parser_created(
- local_name,
- namespace,
- prefix,
- Vec::new(),
- )),
- Some(document_handle),
- false,
- false,
- );
- if let Some(node) = self.node_mut(node_id) {
- node.set_parser_created(true);
- }
- self.record_element_query_index_candidate(node_id);
- if is_child_browsing_context_host_candidate {
- let mut candidates = self.child_browsing_context_host_candidates.borrow_mut();
- if !candidates.contains(&node_id) {
- candidates.push(node_id);
- }
- }
-
- if is_template {
- let template_contents = self
- .dom
- .create_template_contents_fragment_for_document(document_handle);
- if let Some(element) = self
- .node_mut(node_id)
- .and_then(|node| node.data_mut().as_element_mut())
- {
- element.set_template_contents(Some(template_contents));
- }
- }
-
- node_id
+ self.allocate_element_for_document(document_handle, local_name, namespace, prefix, true)
}
pub fn parser_template_contents_handle(&self, node_id: DomHandle) -> Option<DomHandle> {
diff --git a/moli-dom/src/native/host/stylesheet_candidates.rs b/moli-dom/src/native/host/stylesheet_candidates.rs
index 9a78dfdc4..ec394895c 100644
--- a/moli-dom/src/native/host/stylesheet_candidates.rs
+++ b/moli-dom/src/native/host/stylesheet_candidates.rs
@@ -304,6 +304,12 @@ impl DomHost {
.is_some_and(Element::is_inline_style_element)
}
+ pub fn is_style_element_parsing_children(&self, handle: DomHandle) -> bool {
+ self.node(handle)
+ .and_then(Node::as_element)
+ .is_some_and(Element::style_children_parsing)
+ }
+
pub fn stylesheet_candidate_handles_for_tree_scope(
&self,
tree_scope: DomHandle,
diff --git a/moli-parser/src/live_target.rs b/moli-parser/src/live_target.rs
index 8ca5aff17..08f64f80c 100644
--- a/moli-parser/src/live_target.rs
+++ b/moli-parser/src/live_target.rs
@@ -561,8 +561,9 @@ impl ParserDomMutation {
pub trait ParserDomMutationConsumer {
fn apply_parser_dom_mutation(&mut self, mutation: ParserDomMutation);
- fn create_parser_element_without_attributes(
+ fn create_element_for_document_without_attributes(
&mut self,
+ document_handle: NativeNodeId,
local_name: String,
namespace: String,
prefix: Option<String>,
@@ -628,6 +629,10 @@ pub trait ParserDomMutationConsumer {
fn finish_parsing_link_children(&mut self, node_id: NativeNodeId);
+ /// Finish constructing a style element's source and process the resulting
+ /// stylesheet lifecycle effects. This does not mutate its child nodes.
+ fn finish_parsing_style_children(&mut self, node_id: NativeNodeId);
+
fn attach_declarative_shadow_for_parser(
&mut self,
host_id: NativeNodeId,
@@ -642,6 +647,8 @@ pub trait ParserDomMutationConsumer {
struct ParserDomMutationSink {
data: NonNull<()>,
apply: unsafe fn(NonNull<()>, ParserDomMutation),
+ create_element_for_document_without_attributes:
+ unsafe fn(NonNull<()>, NativeNodeId, String, String, Option<String>) -> NativeNodeId,
create_parser_element_for_document_without_attributes:
unsafe fn(NonNull<()>, NativeNodeId, String, String, Option<String>) -> NativeNodeId,
add_attrs_if_missing_for_parser: unsafe fn(NonNull<()>, NativeNodeId, Vec<NativeAttribute>),
@@ -659,6 +666,7 @@ struct ParserDomMutationSink {
mark_script_already_started_for_parser: unsafe fn(NonNull<()>, NativeNodeId),
finish_parsing_script_children: unsafe fn(NonNull<()>, NativeNodeId),
finish_parsing_link_children: unsafe fn(NonNull<()>, NativeNodeId),
+ finish_parsing_style_children: unsafe fn(NonNull<()>, NativeNodeId),
attach_declarative_shadow_for_parser:
unsafe fn(NonNull<()>, NativeNodeId, NativeNodeId, Vec<NativeAttribute>) -> bool,
associate_parser_form_owner: unsafe fn(NonNull<()>, NativeNodeId, NativeNodeId) -> bool,
@@ -674,6 +682,24 @@ impl ParserDomMutationSink {
// pointed-to consumer to remain live and exclusive for the pump step.
unsafe { data.cast::<T>().as_mut() }.apply_parser_dom_mutation(mutation);
}
+ unsafe fn create_element_for_document_without_attributes_impl<
+ T: ParserDomMutationConsumer,
+ >(
+ data: NonNull<()>,
+ document_handle: NativeNodeId,
+ local_name: String,
+ namespace: String,
+ prefix: Option<String>,
+ ) -> NativeNodeId {
+ // SAFETY: ParserDomMutationSink::from_consumer_unchecked requires the
+ // pointed-to consumer to remain live and exclusive for the pump step.
+ unsafe { data.cast::<T>().as_mut() }.create_element_for_document_without_attributes(
+ document_handle,
+ local_name,
+ namespace,
+ prefix,
+ )
+ }
unsafe fn create_parser_element_for_document_without_attributes_impl<
T: ParserDomMutationConsumer,
>(
@@ -817,6 +843,14 @@ impl ParserDomMutationSink {
// pointed-to consumer to remain live and exclusive for the pump step.
unsafe { data.cast::<T>().as_mut() }.finish_parsing_link_children(node_id);
}
+ unsafe fn finish_parsing_style_children_impl<T: ParserDomMutationConsumer>(
+ data: NonNull<()>,
+ node_id: NativeNodeId,
+ ) {
+ // SAFETY: ParserDomMutationSink::from_consumer_unchecked requires the
+ // pointed-to consumer to remain live and exclusive for the pump step.
+ unsafe { data.cast::<T>().as_mut() }.finish_parsing_style_children(node_id);
+ }
unsafe fn attach_declarative_shadow_for_parser_impl<T: ParserDomMutationConsumer>(
data: NonNull<()>,
host_id: NativeNodeId,
@@ -844,6 +878,8 @@ impl ParserDomMutationSink {
Self {
data: NonNull::from(consumer).cast(),
apply: apply_impl::<T>,
+ create_element_for_document_without_attributes:
+ create_element_for_document_without_attributes_impl::<T>,
create_parser_element_for_document_without_attributes:
create_parser_element_for_document_without_attributes_impl::<T>,
add_attrs_if_missing_for_parser: add_attrs_if_missing_for_parser_impl::<T>,
@@ -859,6 +895,7 @@ impl ParserDomMutationSink {
mark_script_already_started_for_parser: mark_script_already_started_for_parser_impl::<T>,
finish_parsing_script_children: finish_parsing_script_children_impl::<T>,
finish_parsing_link_children: finish_parsing_link_children_impl::<T>,
+ finish_parsing_style_children: finish_parsing_style_children_impl::<T>,
attach_declarative_shadow_for_parser: attach_declarative_shadow_for_parser_impl::<T>,
associate_parser_form_owner: associate_parser_form_owner_impl::<T>,
}
@@ -870,6 +907,26 @@ impl ParserDomMutationSink {
unsafe { (self.apply)(self.data, mutation) };
}
+ fn create_element_for_document_without_attributes(
+ self,
+ document_handle: NativeNodeId,
+ local_name: String,
+ namespace: String,
+ prefix: Option<String>,
+ ) -> NativeNodeId {
+ // SAFETY: construction ties the raw pointer and callback to the same
+ // consumer remains live for the current runtime-DOM sink step.
+ unsafe {
+ (self.create_element_for_document_without_attributes)(
+ self.data,
+ document_handle,
+ local_name,
+ namespace,
+ prefix,
+ )
+ }
+ }
+
fn create_parser_element_for_document_without_attributes(
self,
document_handle: NativeNodeId,
@@ -981,6 +1038,12 @@ impl ParserDomMutationSink {
unsafe { (self.finish_parsing_link_children)(self.data, node_id) };
}
+ fn finish_parsing_style_children(self, node_id: NativeNodeId) {
+ // SAFETY: construction ties the raw pointer and callback to the same
+ // consumer remains live for the current runtime-DOM sink step.
+ unsafe { (self.finish_parsing_style_children)(self.data, node_id) };
+ }
+
fn attach_declarative_shadow_for_parser(
self,
host_id: NativeNodeId,
@@ -1404,16 +1467,20 @@ impl ParserDomMutationConsumer for TestMutationEffectCollector<'_> {
self.effects.merge(effects);
}
- fn create_parser_element_without_attributes(
+ fn create_element_for_document_without_attributes(
&mut self,
+ document_handle: NativeNodeId,
local_name: String,
namespace: String,
prefix: Option<String>,
) -> NativeNodeId {
- // SAFETY: tests keep the borrowed DomHost pointer alive and route the
- // parser pump through this collector for the duration of the step.
- unsafe { &mut *self.host }
- .create_parser_element_without_attributes(local_name, namespace, prefix)
+ // SAFETY: tests keep the DomHost alive and exclusive for this parser step.
+ unsafe { &mut *self.host }.create_element_without_attributes_for_document(
+ document_handle,
+ local_name,
+ namespace,
+ prefix,
+ )
}
fn create_parser_element_for_document_without_attributes(
@@ -1547,6 +1614,13 @@ impl ParserDomMutationConsumer for TestMutationEffectCollector<'_> {
let _ = unsafe { &mut *self.host }.finish_parsing_link_children(node_id);
}
+ fn finish_parsing_style_children(&mut self, node_id: NativeNodeId) {
+ // SAFETY: tests keep the borrowed DomHost pointer alive and route the
+ // parser pump through this collector for the duration of the step.
+ let effects = unsafe { &mut *self.host }.finish_parsing_style_children_effects(node_id);
+ self.consume_parser_mutation_effects(effects);
+ }
+
fn attach_declarative_shadow_for_parser(
&mut self,
host_id: NativeNodeId,
@@ -1775,16 +1849,20 @@ impl ParserDomMutationConsumer for TestReadTrackingCollector<'_> {
self.effects.merge(effects);
}
- fn create_parser_element_without_attributes(
+ fn create_element_for_document_without_attributes(
&mut self,
+ document_handle: NativeNodeId,
local_name: String,
namespace: String,
prefix: Option<String>,
) -> NativeNodeId {
- // SAFETY: tests keep the borrowed DomHost pointer alive and route the
- // parser pump through this collector for the duration of the step.
- unsafe { &mut *self.host }
- .create_parser_element_without_attributes(local_name, namespace, prefix)
+ // SAFETY: tests keep the DomHost alive and exclusive for this parser step.
+ unsafe { &mut *self.host }.create_element_without_attributes_for_document(
+ document_handle,
+ local_name,
+ namespace,
+ prefix,
+ )
}
fn create_parser_element_for_document_without_attributes(
@@ -1918,6 +1996,13 @@ impl ParserDomMutationConsumer for TestReadTrackingCollector<'_> {
let _ = unsafe { &mut *self.host }.finish_parsing_link_children(node_id);
}
+ fn finish_parsing_style_children(&mut self, node_id: NativeNodeId) {
+ // SAFETY: tests keep the borrowed DomHost pointer alive and route the
+ // parser pump through this collector for the duration of the step.
+ let effects = unsafe { &mut *self.host }.finish_parsing_style_children_effects(node_id);
+ self.consume_parser_mutation_effects(effects);
+ }
+
fn attach_declarative_shadow_for_parser(
&mut self,
host_id: NativeNodeId,
@@ -2589,7 +2674,18 @@ impl ParserStreamHtmlTreeSinkTarget {
.iter()
.rposition(|candidate| candidate.node_id == node_id)
{
- self.open_parser_elements.remove(index);
+ let element = self.open_parser_elements.remove(index);
+ if element.name.local.as_ref() == "style"
+ && matches!(
+ element.name.ns.as_ref(),
+ "http://www.w3.org/1999/xhtml" | "http://www.w3.org/2000/svg"
+ )
+ {
+ // Like Blink's StyleElement::FinishParsingChildren, process
+ // the complete source, not every growing tokenizer prefix.
+ self.finish_parsing_style_children(node_id);
+ self.note_blocking_stylesheet_pause_if_needed(node_id);
+ }
}
if self.read_is_html_element_named(node_id, "link") {
let _ = self.capture_parser_blocking_stylesheet(node_id);
@@ -2649,21 +2745,6 @@ impl ParserStreamHtmlTreeSinkTarget {
svg_script.then_some(node_id)
}
- pub(super) fn create_parser_element_without_attributes(
- &mut self,
- local_name: String,
- namespace: String,
- prefix: Option<String>,
- ) -> NativeNodeId {
- let document_handle = self.parser_owner_document_node_id();
- self.create_parser_element_without_attributes_for_document(
- document_handle,
- local_name,
- namespace,
- prefix,
- )
- }
-
fn create_parser_element_without_attributes_for_document(
&mut self,
document_handle: NativeNodeId,
@@ -2691,6 +2772,28 @@ impl ParserStreamHtmlTreeSinkTarget {
}
}
+ /// Build generated DOM without entering the tokenizer's construction lifecycle.
+ pub(super) fn create_element_without_attributes(
+ &mut self,
+ local_name: String,
+ namespace: String,
+ prefix: Option<String>,
+ ) -> NativeNodeId {
+ let document = self.parser_owner_document_node_id();
+ if let Some(owner) = &self.runtime_dom_sinks {
+ owner
+ .dom_mutation_sink()
+ .create_element_for_document_without_attributes(
+ document, local_name, namespace, prefix,
+ )
+ } else {
+ self.dom_host_mut()
+ .create_element_without_attributes_for_document(
+ document, local_name, namespace, prefix,
+ )
+ }
+ }
+
pub(super) fn add_attrs_if_missing_for_parser(
&mut self,
node_id: NativeNodeId,
@@ -2864,6 +2967,19 @@ impl ParserStreamHtmlTreeSinkTarget {
}
}
+ /// Complete a parser-created style after the tree builder closes it.
+ fn finish_parsing_style_children(&mut self, node_id: NativeNodeId) {
+ if let Some(owner) = &self.runtime_dom_sinks {
+ owner
+ .dom_mutation_sink()
+ .finish_parsing_style_children(node_id);
+ } else {
+ let _ = self
+ .dom_host_mut()
+ .finish_parsing_style_children_effects(node_id);
+ }
+ }
+
fn attach_declarative_shadow_for_dom_host(
&mut self,
host_id: NativeNodeId,
@@ -3479,9 +3595,6 @@ impl ParserStreamHtmlTreeSinkTarget {
if self.read_is_html_element_named(node_id, "template") {
self.open_template_element_depth = self.open_template_element_depth.saturating_sub(1);
}
- if self.read_is_html_element_named(node_id, "style") {
- self.note_blocking_stylesheet_pause_if_needed(node_id);
- }
self.note_parser_element_popped(node_id);
}
@@ -3949,7 +4062,8 @@ fn parser_stream_runtime_dom_sinks_routes_parser_state_writes_through_sink() {
script = target.with_runtime_dom_consumer_for_test(&mut collector, |target| {
target.push_parse_error("state write through sink".to_owned());
target.set_html_quirks_mode(QuirksMode::Quirks);
- let script = target.create_parser_element_without_attributes(
+ let script = target.create_parser_element_without_attributes_for_document(
+ document,
"script".to_owned(),
"http://www.w3.org/1999/xhtml".to_owned(),
None,
diff --git a/moli-parser/src/stream.rs b/moli-parser/src/stream.rs
index 7cee4c146..2aca656fc 100644
--- a/moli-parser/src/stream.rs
+++ b/moli-parser/src/stream.rs
@@ -1027,15 +1027,20 @@ mod tests {
self.effects.merge(effects);
}
- fn create_parser_element_without_attributes(
+ fn create_element_for_document_without_attributes(
&mut self,
+ document_handle: NativeNodeId,
local_name: String,
namespace: String,
prefix: Option<String>,
) -> NativeNodeId {
// SAFETY: the test keeps the DomHost alive for this parser pump step.
- unsafe { &mut *self.host }
- .create_parser_element_without_attributes(local_name, namespace, prefix)
+ unsafe { &mut *self.host }.create_element_without_attributes_for_document(
+ document_handle,
+ local_name,
+ namespace,
+ prefix,
+ )
}
fn create_parser_element_for_document_without_attributes(
@@ -1174,6 +1179,12 @@ mod tests {
let _ = unsafe { &mut *self.host }.finish_parsing_link_children(node_id);
}
+ fn finish_parsing_style_children(&mut self, node_id: NativeNodeId) {
+ // SAFETY: the test keeps the DomHost alive for this parser pump step.
+ let effects = unsafe { &mut *self.host }.finish_parsing_style_children_effects(node_id);
+ self.effects.merge(effects);
+ }
+
fn attach_declarative_shadow_for_parser(
&mut self,
host_id: NativeNodeId,
@@ -2472,6 +2483,59 @@ mod tests {
);
}
+ #[test]
+ fn parser_style_reports_parsing_finished_only_after_its_closing_tag() {
+ use moli_dom::native::DomStylesheetOwnerChangeKind;
+
+ for prefix in ["<!doctype html><head>", "<!doctype html><body><svg>"] {
+ let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
+ Url::parse("https://example.test/style-stream").unwrap(),
+ );
+ let mut host = stream.take_parser_stream_dom_host();
+ host.set_mutation_observer_records_enabled(true);
+ let mut effects = DomMutationEffects::default();
+ let mut consumer = TestMutationEffectCollector {
+ host: &mut host,
+ effects: &mut effects,
+ interrupt_when_body_text_is: None,
+ };
+ stream.pump_parser_step_with_runtime_dom_consumer_without_element_creation(
+ &format!("{prefix}<style id=sheet>"),
+ &mut consumer,
+ );
+ let style = host.elements_by_tag_name(host.document_handle(), "style", true)[0];
+ *consumer.effects = DomMutationEffects::default();
+ // Separate feeds and line breaks both split tokenizer text. Neither
+ // may publish growing stylesheet prefixes to the renderer.
+ let chunk = ".rule { color: red; }\n".repeat(64);
+ for _ in 0..8 {
+ stream.pump_parser_step_with_runtime_dom_consumer_without_element_creation(
+ &chunk,
+ &mut consumer,
+ );
+ assert!(consumer.effects.stylesheet_owners().changes().is_empty());
+ assert!(!consumer.effects.observer_records().records().is_empty());
+ *consumer.effects = DomMutationEffects::default();
+ }
+ stream.pump_parser_step_with_runtime_dom_consumer_without_element_creation(
+ "</style>",
+ &mut consumer,
+ );
+ let changes = consumer.effects.stylesheet_owners().changes();
+ assert_eq!(changes.len(), 1);
+ assert_eq!(changes[0].owner(), style);
+ assert!(matches!(
+ changes[0].kind(),
+ DomStylesheetOwnerChangeKind::ParsingFinished
+ ));
+ assert!(consumer.effects.observer_records().records().is_empty());
+ assert!(!host.is_style_element_parsing_children(style));
+ assert_eq!(host.text_content(style).unwrap(), chunk.repeat(8));
+ stream.restore_parser_stream_dom_host(host);
+ stream.finish();
+ }
+ }
+
#[test]
fn parser_stream_reports_style_import_blocker_on_runtime_dom_sinks() {
let stream = DocumentStream::new_scripting_enabled_parser_stream_for_testing(
diff --git a/moli-parser/src/xml.rs b/moli-parser/src/xml.rs
index 7f2c0cdac..bc553283d 100644
--- a/moli-parser/src/xml.rs
+++ b/moli-parser/src/xml.rs
@@ -555,6 +555,16 @@ impl<'host> XmlTreeSinkBase for XmlDocumentSink<'host> {
left == right
}
+ fn pop(&self, node: &Self::Handle) {
+ // This inert sink has no renderer consumer. Complete parser state here
+ // so a later document handoff can prepare the finished stylesheet.
+ let _ = self
+ .target
+ .borrow_mut()
+ .dom_host
+ .finish_parsing_style_children_effects(node.node_id);
+ }
+
fn set_quirks_mode(&self, mode: XmlQuirksMode) {
self.quirks_mode.set(mode);
}
@@ -649,6 +659,41 @@ mod tests {
assert_eq!(child_attributes[0].value(), "urn:nested");
}
+ #[test]
+ fn xml_parser_finishes_styles_in_owned_and_borrowed_documents() {
+ let url = Url::parse("https://example.test/style.xml").unwrap();
+ for namespace in ["http://www.w3.org/1999/xhtml", "http://www.w3.org/2000/svg"] {
+ for ending in [
+ "/>",
+ "><![CDATA[body { color: red; }]]></style>",
+ ">body { color: red; }",
+ ] {
+ let source = format!("<style xmlns='{namespace}'{ending}");
+ let parsed = XmlParser.parse(url.clone(), source.clone());
+ let style = document_element(&parsed);
+ assert!(
+ !parsed
+ .node(style)
+ .and_then(Node::as_element)
+ .unwrap()
+ .style_children_parsing(),
+ "owned XML parse must finish style children: {source}"
+ );
+
+ let mut host = DomHost::from_dom(NativeDom::new_html(url.clone()));
+ let document = host.create_detached_xml_document();
+ XmlParser
+ .parse_inert_tree_into_document(&mut host, document, &source)
+ .unwrap();
+ let style = host.child_handles(document).next().unwrap();
+ assert!(
+ !host.is_style_element_parsing_children(style),
+ "borrowed XML parse must finish style children: {source}"
+ );
+ }
+ }
+ }
+
#[test]
fn xml_parser_populates_an_existing_xml_document_with_exact_node_owners() {
let parser = XmlParser;
diff --git a/moli-parser/src/xml_stream.rs b/moli-parser/src/xml_stream.rs
index ff57d39b3..7d15c73df 100644
--- a/moli-parser/src/xml_stream.rs
+++ b/moli-parser/src/xml_stream.rs
@@ -1093,6 +1093,19 @@ mod tests {
.expect("viewer document element");
assert_eq!(document_element.local_name(), "html");
assert_eq!(document_element.namespace(), "http://www.w3.org/1999/xhtml");
+ let style = element_by_id(&document, "xml-viewer-style").expect("viewer stylesheet");
+ assert!(
+ !document.node(style).unwrap().flags().parser_created(),
+ "generated viewer nodes must use ordinary DOM construction"
+ );
+ assert!(
+ !document
+ .node(style)
+ .and_then(Node::as_element)
+ .unwrap()
+ .style_children_parsing(),
+ "the generated viewer stylesheet must finish construction before publication"
+ );
let source_container = element_by_id(&document, "webkit-xml-viewer-source-xml")
.expect("viewer source container");
assert_eq!(
diff --git a/moli-parser/src/xml_tree_viewer.rs b/moli-parser/src/xml_tree_viewer.rs
index 4f296d351..52a67c77c 100644
--- a/moli-parser/src/xml_tree_viewer.rs
+++ b/moli-parser/src/xml_tree_viewer.rs
@@ -152,7 +152,7 @@ fn materialize_transformed_viewer_node(
.clone();
let materialized = match data {
NodeData::Element(element) => {
- let handle = target.create_parser_element_without_attributes(
+ let handle = target.create_element_without_attributes(
element.local_name().to_owned(),
element.namespace().to_owned(),
element.prefix().map(str::to_owned),
diff --git a/moli-renderer-v8/src/document_runtime/document_write.rs b/moli-renderer-v8/src/document_runtime/document_write.rs
index e9b8a4b0a..03cc1daca 100644
--- a/moli-renderer-v8/src/document_runtime/document_write.rs
+++ b/moli-renderer-v8/src/document_runtime/document_write.rs
@@ -48,19 +48,10 @@ struct DocumentWriteParserMutationOwner<'a, 'scope, 'pin> {
#[derive(Clone, Copy)]
enum DocumentWriteParserMutationTarget {
LiveDocument,
- DetachedFragment { owner_document: DomHandle },
+ DetachedFragment,
}
impl DocumentWriteParserMutationOwner<'_, '_, '_> {
- fn owner_document_handle(&self) -> DomHandle {
- match self.target {
- DocumentWriteParserMutationTarget::LiveDocument => self.runtime.document_handle(),
- DocumentWriteParserMutationTarget::DetachedFragment { owner_document } => {
- owner_document
- }
- }
- }
-
fn targets_live_document(&self) -> bool {
matches!(self.target, DocumentWriteParserMutationTarget::LiveDocument)
}
@@ -194,15 +185,15 @@ impl ParserDomMutationConsumer for DocumentWriteParserMutationOwner<'_, '_, '_>
);
}
- fn create_parser_element_without_attributes(
+ fn create_element_for_document_without_attributes(
&mut self,
+ document_handle: DomHandle,
local_name: String,
namespace: String,
prefix: Option<String>,
) -> DomHandle {
- let document_handle = self.owner_document_handle();
self.runtime
- .create_parser_element_for_document_without_attributes_in_live_dom_host(
+ .create_element_for_document_without_attributes_in_live_dom_host(
document_handle,
local_name,
namespace,
@@ -322,6 +313,14 @@ impl ParserDomMutationConsumer for DocumentWriteParserMutationOwner<'_, '_, '_>
.finish_parsing_link_children(node_id);
}
+ fn finish_parsing_style_children(&mut self, node_id: DomHandle) {
+ let effects = self
+ .runtime
+ .dom_host_mut()
+ .finish_parsing_style_children_effects(node_id);
+ self.consume_parser_mutation_effects(effects);
+ }
+
fn attach_declarative_shadow_for_parser(
&mut self,
host_id: DomHandle,
@@ -578,9 +577,7 @@ impl DocumentRuntime {
runtime,
scope,
host_ptr,
- target: DocumentWriteParserMutationTarget::DetachedFragment {
- owner_document: document_handle,
- },
+ target: DocumentWriteParserMutationTarget::DetachedFragment,
};
parser.parse_fragment_into_live_dom(
mutation_owner.runtime.document_url().clone(),
diff --git a/moli-renderer-v8/src/document_runtime/dom_facade.rs b/moli-renderer-v8/src/document_runtime/dom_facade.rs
index ab71b42c4..8b6ba3c3f 100644
--- a/moli-renderer-v8/src/document_runtime/dom_facade.rs
+++ b/moli-renderer-v8/src/document_runtime/dom_facade.rs
@@ -268,14 +268,20 @@ impl DocumentRuntime {
.text_content(node_id)
}
- pub(crate) fn create_parser_element_without_attributes_in_live_dom_host(
+ pub(crate) fn create_element_for_document_without_attributes_in_live_dom_host(
&mut self,
+ document_handle: DomHandle,
local_name: String,
namespace: String,
prefix: Option<String>,
) -> DomHandle {
self.dom_host_mut_for_active_parser_step()
- .create_parser_element_without_attributes(local_name, namespace, prefix)
+ .create_element_without_attributes_for_document(
+ document_handle,
+ local_name,
+ namespace,
+ prefix,
+ )
}
pub(crate) fn create_parser_element_for_document_without_attributes_in_live_dom_host(
diff --git a/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs b/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs
index 59d8f110f..02a53a085 100644
--- a/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs
+++ b/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs
@@ -44,7 +44,7 @@ impl DocumentRuntime {
return DocumentWriteScriptRunOutcome::Complete;
}
unsafe { &mut *host_ptr }
- .sync_owner_style_sheet_texts_for_document_tree_scopes(self.document_handle());
+ .install_prepared_style_sheets_for_document(self.document_handle());
let Some(wrapper) = unsafe { &mut *host_ptr }
.native_bridge_mut()
diff --git a/moli-renderer-v8/src/document_runtime/security_policy.rs b/moli-renderer-v8/src/document_runtime/security_policy.rs
index 138ac01ee..9f7b3ee29 100644
--- a/moli-renderer-v8/src/document_runtime/security_policy.rs
+++ b/moli-renderer-v8/src/document_runtime/security_policy.rs
@@ -248,7 +248,8 @@ impl DocumentRuntime {
DomStylesheetOwnerChangeKind::Registered
| DomStylesheetOwnerChangeKind::OwnerDocumentChanged
| DomStylesheetOwnerChangeKind::TreeConnectionChanged { connected: true } => true,
- DomStylesheetOwnerChangeKind::Contents => is_inline_style,
+ DomStylesheetOwnerChangeKind::Contents
+ | DomStylesheetOwnerChangeKind::ParsingFinished => is_inline_style,
DomStylesheetOwnerChangeKind::Attribute {
namespace,
local_name,
@@ -311,6 +312,9 @@ impl DocumentRuntime {
for owner in stylesheet_owners {
if self.dom_host.is_inline_style_sheet_owner(owner) {
+ if self.dom_host.is_style_element_parsing_children(owner) {
+ continue;
+ }
self.apply_inline_style_element_csp_check(scope, host_ptr, owner);
} else {
self.apply_link_style_element_csp_check(scope, host_ptr, owner);
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs
index 9244a3da0..4b8652caa 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs
@@ -5,7 +5,7 @@ use crate::{
custom_elements,
document_runtime::DomHandle,
document_script_scheduler::FrameDocumentClassicScriptSchedulerWork,
- dom::native::{Attribute, DomMutationEffects, Node},
+ dom::native::{Attribute, DomMutationEffects, DomStylesheetOwnerChange, Node},
frame_owner_model::{
DocumentId, FrameClassicDocumentScriptExecutionStart,
FrameDocumentClassicCompletionFinishAction, FrameDocumentClassicParserResumeApplication,
@@ -70,9 +70,11 @@ struct ChildParserMutationEffects {
}
impl ParserMutationEffectsOwner for ChildParserMutationEffects {
- type Prepared = ();
+ type Prepared = Vec<DomStylesheetOwnerChange>;
- fn prepare_parser_mutation_effects(&mut self, _effects: &DomMutationEffects) {}
+ fn prepare_parser_mutation_effects(&mut self, effects: &DomMutationEffects) -> Self::Prepared {
+ effects.stylesheet_owners().changes().to_vec()
+ }
fn ensure_parser_reaction_queue(&mut self, host_ptr: *mut JsContextHost) {
if !self.reaction_queue_active {
@@ -85,9 +87,14 @@ impl ParserMutationEffectsOwner for ChildParserMutationEffects {
&mut self,
scope: &mut v8::PinScope<'_, '_>,
host_ptr: *mut JsContextHost,
- _prepared: (),
+ prepared: Self::Prepared,
) {
unsafe { &mut *host_ptr }.sync_child_browsing_context_subtree(scope, self.document_handle);
+ crate::native_bridge::document::apply_stylesheet_owner_css_projections(
+ scope,
+ unsafe { &*host_ptr },
+ &prepared,
+ );
}
}
@@ -335,15 +342,21 @@ impl ParserDomMutationConsumer for ChildFrameLiveParserOwner<'_, '_, '_> {
self.consume_parser_mutation_effects(effects);
}
- fn create_parser_element_without_attributes(
+ fn create_element_for_document_without_attributes(
&mut self,
+ document_handle: DomHandle,
local_name: String,
namespace: String,
prefix: Option<String>,
) -> DomHandle {
self.host
.dom_host_mut()
- .create_parser_element_without_attributes(local_name, namespace, prefix)
+ .create_element_without_attributes_for_document(
+ document_handle,
+ local_name,
+ namespace,
+ prefix,
+ )
}
fn create_parser_element_for_document_without_attributes(
@@ -467,6 +480,17 @@ impl ParserDomMutationConsumer for ChildFrameLiveParserOwner<'_, '_, '_> {
.finish_parsing_link_children(node_id);
}
+ fn finish_parsing_style_children(&mut self, node_id: DomHandle) {
+ if !self.targets_current_document() {
+ return;
+ }
+ let effects = self
+ .host
+ .dom_host_mut()
+ .finish_parsing_style_children_effects(node_id);
+ self.consume_parser_mutation_effects(effects);
+ }
+
fn attach_declarative_shadow_for_parser(
&mut self,
host_id: DomHandle,
@@ -1019,7 +1043,7 @@ impl JsContextHost {
let _ = self
.dom_host_mut()
.update_document_target_from_url(document_handle);
- self.sync_owner_style_sheet_texts_for_document_tree_scopes(document_handle);
+ self.install_prepared_style_sheets_for_document(document_handle);
self.dom_host_mut()
.mark_subtree_connected_preserving_owner_document(document_handle);
let document_url = self.document_url_for_handle(document_handle);
diff --git a/moli-renderer-v8/src/native_bridge/context_host/core.rs b/moli-renderer-v8/src/native_bridge/context_host/core.rs
index 6fa074614..4cf33aed5 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/core.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs
@@ -474,7 +474,7 @@ impl JsContextHost {
#[cfg(test)]
style_observation_environment_resolutions: Cell::new(0),
};
- host.sync_owner_style_sheet_texts_for_document_tree_scopes(host.document_handle());
+ host.initialize_style_element_sources_for_document(host.document_handle());
host
}
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.rs
index e3e97d8e9..b9c728120 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
@@ -884,15 +884,13 @@ impl JsContextHost {
.adopted_style_sheet_sources_for_document(document)
}
- pub(crate) fn sync_owner_style_sheet_text(&mut self, owner: DomHandle) {
- let css_text = self.dom_host().text_content(owner).unwrap_or_default();
+ /// Initialize sources when taking ownership of an already constructed DOM.
+ /// Ordinary reads and synchronization only install lifecycle-prepared sources.
+ pub(crate) fn initialize_style_element_sources_for_document(&mut self, document: DomHandle) {
let dom_host = self.dom_host() as *const _;
- self.style_engine.sync_owner_style_sheet_text_with_host(
- unsafe { &*dom_host },
- owner,
- css_text,
- );
- self.install_owner_live_stylesheet(owner);
+ self.style_engine
+ .initialize_style_element_sources_with_host(unsafe { &*dom_host }, document);
+ self.install_prepared_style_sheets_for_document(document);
}
pub(crate) fn apply_stylesheet_owner_changes(&mut self, changes: &[DomStylesheetOwnerChange]) {
@@ -904,19 +902,7 @@ impl JsContextHost {
let mut linked_attribute_owners = Vec::new();
for change in changes {
let owner = change.owner();
- let source_was_processed = match change.kind() {
- DomStylesheetOwnerChangeKind::Registered
- | DomStylesheetOwnerChangeKind::Contents => {
- unsafe { &*dom_host }.is_connected(owner)
- }
- DomStylesheetOwnerChangeKind::OwnerDocumentChanged => true,
- DomStylesheetOwnerChangeKind::TreeConnectionChanged { connected } => *connected,
- DomStylesheetOwnerChangeKind::Unregistered
- | DomStylesheetOwnerChangeKind::Attribute { .. } => false,
- };
- if unsafe { &*dom_host }.is_inline_style_sheet_owner(owner)
- && source_was_processed
- && !owners.contains(&owner)
+ if unsafe { &*dom_host }.is_inline_style_sheet_owner(owner) && !owners.contains(&owner)
{
owners.push(owner);
}
@@ -956,10 +942,7 @@ impl JsContextHost {
}
}
- pub(crate) fn sync_owner_style_sheet_texts_for_document_tree_scopes(
- &mut self,
- document: DomHandle,
- ) {
+ pub(crate) fn install_prepared_style_sheets_for_document(&mut self, document: DomHandle) {
let owners = {
let host = self.dom_host();
let mut owners = Vec::new();
@@ -977,7 +960,7 @@ impl JsContextHost {
owners
};
for owner in owners {
- self.sync_owner_style_sheet_text(owner);
+ self.install_owner_live_stylesheet(owner);
}
}
@@ -987,7 +970,7 @@ impl JsContextHost {
runtime.take_style_source_document_sync_pending()
};
if pending {
- self.sync_owner_style_sheet_texts_for_document_tree_scopes(self.document_handle());
+ self.install_prepared_style_sheets_for_document(self.document_handle());
}
}
@@ -1042,11 +1025,6 @@ impl JsContextHost {
owner,
stylesheet_id,
) {
- self.style_engine
- .mark_owner_live_stylesheet_cssom_authoritative_with_host(
- unsafe { &*dom_host },
- owner,
- );
let canceled_load_event_bindings =
unsafe { &mut *self.runtime }.invalidate_style_related_state(owner);
for binding in canceled_load_event_bindings {
diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups.rs b/moli-renderer-v8/src/native_bridge/context_host/popups.rs
index d1d9f16db..973d8435e 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs
@@ -2664,7 +2664,7 @@ impl JsContextHost {
self.dom_host_mut()
.set_document_fallback_base_url_for_handle(document_handle, Some(base_url));
}
- self.sync_owner_style_sheet_texts_for_document_tree_scopes(document_handle);
+ self.initialize_style_element_sources_for_document(document_handle);
self.dom_host_mut()
.mark_subtree_connected_preserving_owner_document(document_handle);
self.lightweight_popup_document_handles
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.rs
index 0fabe2ebd..b938623d9 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
@@ -275,6 +275,7 @@ fn owner_change_projects_css(host: &JsContextHost, change: &DomStylesheetOwnerCh
DomStylesheetOwnerChangeKind::Registered
| DomStylesheetOwnerChangeKind::Unregistered
| DomStylesheetOwnerChangeKind::Contents
+ | DomStylesheetOwnerChangeKind::ParsingFinished
| DomStylesheetOwnerChangeKind::OwnerDocumentChanged
| DomStylesheetOwnerChangeKind::TreeConnectionChanged { .. } => true,
}
diff --git a/moli-renderer-v8/src/native_bridge/document/detached_objects/builders/documents.rs b/moli-renderer-v8/src/native_bridge/document/detached_objects/builders/documents.rs
index a52958314..918c7053d 100644
--- a/moli-renderer-v8/src/native_bridge/document/detached_objects/builders/documents.rs
+++ b/moli-renderer-v8/src/native_bridge/document/detached_objects/builders/documents.rs
@@ -180,8 +180,7 @@ fn import_detached_document_children_from_host_with_reaction_policy<'s>(
adopt_attached_imported_node_as_detached(scope, document, imported_object, document)?;
}
}
- unsafe { &mut *runtime_ptr }
- .sync_owner_style_sheet_texts_for_document_tree_scopes(document_handle);
+ unsafe { &mut *runtime_ptr }.initialize_style_element_sources_for_document(document_handle);
Some(())
}
diff --git a/moli-renderer-v8/src/native_bridge/element/stylesheets/sheet.rs b/moli-renderer-v8/src/native_bridge/element/stylesheets/sheet.rs
index c95f9ed3f..dc2446403 100644
--- a/moli-renderer-v8/src/native_bridge/element/stylesheets/sheet.rs
+++ b/moli-renderer-v8/src/native_bridge/element/stylesheets/sheet.rs
@@ -150,13 +150,6 @@ pub(crate) fn style_sheet_for_element<'s>(
if !owner_is_connected {
return None;
}
- if is_style && detached_owner && runtime.owner_style_sheet_source(handle).is_none() {
- // DOMParser/createHTMLDocument trees do not pass through the active
- // document's initial owner lifecycle. Install their source lazily into
- // the existing owner-document style world instead of creating a
- // text-only CSSStyleSheet shell.
- runtime.sync_owner_style_sheet_text(handle);
- }
if is_style && runtime.owner_style_sheet_source(handle).is_none() {
return None;
}
diff --git a/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs b/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs
index 6c1173217..4e2815d55 100644
--- a/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs
@@ -202,16 +202,20 @@ impl ParserDomMutationConsumer for PhaseOneParserOwner<'_> {
.apply_parser_dom_mutation_to_live_dom_host_in_default_context(mutation);
}
- fn create_parser_element_without_attributes(
+ fn create_element_for_document_without_attributes(
&mut self,
+ document_handle: NativeNodeId,
local_name: String,
namespace: String,
prefix: Option<String>,
) -> NativeNodeId {
self.vm
.document_runtime
- .create_parser_element_without_attributes_in_live_dom_host(
- local_name, namespace, prefix,
+ .create_element_for_document_without_attributes_in_live_dom_host(
+ document_handle,
+ local_name,
+ namespace,
+ prefix,
)
}
@@ -346,6 +350,15 @@ impl ParserDomMutationConsumer for PhaseOneParserOwner<'_> {
.finish_parsing_link_children(node_id);
}
+ fn finish_parsing_style_children(&mut self, node_id: NativeNodeId) {
+ let effects = self
+ .vm
+ .document_runtime
+ .dom_host_mut()
+ .finish_parsing_style_children_effects(node_id);
+ self.consume_parser_mutation_effects(effects);
+ }
+
fn attach_declarative_shadow_for_parser(
&mut self,
host_id: NativeNodeId,
diff --git a/moli-renderer-v8/src/runtime/tests.rs b/moli-renderer-v8/src/runtime/tests.rs
index 5393c3203..98a3fa506 100644
--- a/moli-renderer-v8/src/runtime/tests.rs
+++ b/moli-renderer-v8/src/runtime/tests.rs
@@ -1784,10 +1784,13 @@ async fn streaming_unstyled_xml_converts_live_document_before_domcontentloaded()
"globalThis.__xmlViewerDcl = null;",
"document.addEventListener('DOMContentLoaded', () => {",
" const source = document.getElementById('source');",
+ " const style = document.getElementById('xml-viewer-style');",
" globalThis.__xmlViewerDcl = [",
" document.documentElement.localName,",
" source && source.parentNode && source.parentNode.id,",
- " source && source.textContent",
+ " source && source.textContent,",
+ " !!(style && style.sheet),",
+ " getComputedStyle(source.parentNode).display",
" ];",
"});",
)
@@ -1843,7 +1846,7 @@ async fn streaming_unstyled_xml_converts_live_document_before_domcontentloaded()
assert_eq!(
renderer_json_value(reply),
Some(serde_json::json!(
- r#"["html","http://www.w3.org/1999/xhtml",["html","webkit-xml-viewer-source-xml","xml-ready"]]"#
+ r#"["html","http://www.w3.org/1999/xhtml",["html","webkit-xml-viewer-source-xml","xml-ready",true,"none"]]"#
))
);
page.close_async()
diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rs
index 43acc3f4c..1b5c48276 100644
--- a/moli-renderer-v8/src/script_vm.rs
+++ b/moli-renderer-v8/src/script_vm.rs
@@ -2419,7 +2419,7 @@ impl ScriptVm {
let document = self.document_runtime.document_handle();
self._context_host
.borrow_mut()
- .sync_owner_style_sheet_texts_for_document_tree_scopes(document);
+ .install_prepared_style_sheets_for_document(document);
}
pub(super) fn computed_style_property_values_for_document_snapshot(
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.rs
index 08d2bdb92..a4e161d53 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
@@ -2351,6 +2351,195 @@ fn document_point_queries_use_real_paint_order_geometry() {
);
}
+#[test]
+fn style_source_sync_consumes_prepared_sources_and_preserves_cssom() {
+ let mut vm = new_parsed_test_vm(
+ "https://style-source-lifecycle.test/",
+ "<!doctype html><body></body>",
+ );
+ vm.eval(
+ r#"
+document.open();
+document.write('<!doctype html><head><style id=sheet>body { color: red; }');
+globalThis.pendingStyle = document.getElementById('sheet');
+"#,
+ )
+ .unwrap();
+
+ vm.sync_live_document_style_sources();
+ assert_eq!(
+ vm.eval("JSON.stringify([pendingStyle.sheet === null, document.styleSheets.length])")
+ .unwrap(),
+ "[true,0]",
+ "rendering synchronization must not create a source for an unfinished style",
+ );
+
+ vm.eval(
+ r#"
+document.write('</style></head><body>');
+globalThis.preparedSheet = pendingStyle.sheet;
+preparedSheet.insertRule('.added { color: blue; }', preparedSheet.cssRules.length);
+"#,
+ )
+ .unwrap();
+ vm.sync_live_document_style_sources();
+ assert_eq!(
+ vm.eval(
+ "JSON.stringify([pendingStyle.sheet === preparedSheet, preparedSheet.cssRules.length])"
+ )
+ .unwrap(),
+ "[true,2]",
+ "synchronization must preserve the prepared stylesheet and CSSOM edits",
+ );
+ assert_eq!(
+ vm.eval(
+ r#"
+pendingStyle.textContent = 'body { color: green; }';
+document.close();
+JSON.stringify([pendingStyle.sheet !== preparedSheet,
+ pendingStyle.sheet.cssRules.length, getComputedStyle(document.body).color]);
+"#,
+ )
+ .unwrap(),
+ r#"[true,1,"rgb(0, 128, 0)"]"#,
+ "a real DOM content change must still replace the stylesheet",
+ );
+}
+
+#[test]
+fn parser_style_waits_for_complete_source_in_main_and_child_documents() {
+ let mut vm = new_parsed_test_vm(
+ "https://parser-style-completion.test/",
+ "<!doctype html><body></body>",
+ );
+ let result = vm
+ .eval(
+ r#"
+(() => {
+ function exercise(w) {
+ const d = w.document;
+ d.open();
+ d.write('<!doctype html><head><style id=sheet>\n');
+ const style = d.getElementById('sheet');
+ const pending = () => [style.sheet === null, d.styleSheets.length];
+ const before = [pending()];
+ d.write('body { color: rgb(1, 2, 3); }\n');
+ before.push(pending());
+ d.write('.second { color: green; }\n');
+ style.type = 'text/css';
+ before.push(pending());
+ const clone = d.head.appendChild(style.cloneNode(true));
+ const cloneRules = clone.sheet.cssRules.length;
+ clone.remove();
+ d.write('</style></head><body>');
+ const sheet = style.sheet;
+ const complete = [sheet.cssRules.length, d.styleSheets.length,
+ w.getComputedStyle(d.body).color];
+ sheet.insertRule('.kept { color: blue; }', sheet.cssRules.length);
+ d.write('<p>unrelated parser work</p>');
+ const preserved = sheet === style.sheet && sheet.cssRules.length === 3;
+ style.firstChild.appendData('.third { color: black; }');
+ const changed = Array.from(style.sheet.cssRules, r => r.selectorText);
+ style.textContent = 'body { color: rgb(4, 5, 6); }';
+ const dynamicColor = w.getComputedStyle(d.body).color;
+ d.close();
+ return {before, cloneRules, complete, preserved, changed, dynamicColor};
+ }
+ const main = exercise(window);
+ const frame = document.body.appendChild(document.createElement('iframe'));
+ const child = exercise(frame.contentWindow);
+ return JSON.stringify([main, child]);
+})()
+"#,
+ )
+ .expect("parser style completion should preserve CSSOM and dynamic text updates");
+ let expected = serde_json::json!({
+ "before": [[true, 0], [true, 0], [true, 0]],
+ "cloneRules": 2,
+ "complete": [2, 1, "rgb(1, 2, 3)"],
+ "preserved": true,
+ "changed": ["body", ".second", ".third"],
+ "dynamicColor": "rgb(4, 5, 6)"
+ });
+ assert_eq!(
+ serde_json::from_str::<serde_json::Value>(&result).unwrap(),
+ serde_json::json!([expected, expected]),
+ );
+}
+
+#[test]
+fn parser_style_finishes_at_eof_in_main_and_child_documents() {
+ let mut vm = new_parsed_test_vm(
+ "https://parser-style-eof.test/",
+ "<!doctype html><body></body>",
+ );
+ let result = vm
+ .eval(
+ r#"
+(() => {
+ function exercise(w) {
+ const d = w.document;
+ d.open();
+ d.write('<!doctype html><body><style id=sheet>\nbody { color: rgb(7, 8, 9); }\n');
+ const style = d.getElementById('sheet');
+ const pending = style.sheet === null && d.styleSheets.length === 0;
+ d.close();
+ return [pending, style.sheet.cssRules.length, d.styleSheets.length,
+ w.getComputedStyle(d.body).color];
+ }
+ const main = exercise(window);
+ const frame = document.body.appendChild(document.createElement('iframe'));
+ const child = exercise(frame.contentWindow);
+ return JSON.stringify([main, child]);
+})()
+"#,
+ )
+ .expect("EOF should publish the complete unterminated style source");
+ let expected = serde_json::json!([true, 1, 1, "rgb(7, 8, 9)"]);
+ assert_eq!(
+ serde_json::from_str::<serde_json::Value>(&result).unwrap(),
+ serde_json::json!([expected, expected]),
+ );
+}
+
+#[test]
+fn parser_style_finishes_in_svg_and_detached_fragments() {
+ let mut vm = new_parsed_test_vm(
+ "https://parser-svg-style-completion.test/",
+ "<!doctype html><body></body>",
+ );
+ let result = vm.eval(r#"
+(() => {
+ document.open();
+ document.write('<!doctype html><body><svg><style id=sheet>\n');
+ const style = document.getElementById('sheet');
+ document.write('body { color: rgb(1, 2, 3); }\n');
+ const pending = style.sheet === null && document.styleSheets.length === 0;
+ document.write('</style><style id=empty /></svg>');
+ const complete = [style.sheet.cssRules.length,
+ document.getElementById('empty').sheet.cssRules.length];
+ document.close();
+ const fragment = document.createElement('div');
+ fragment.innerHTML = '<style>body { color: rgb(4, 5, 6); }\n</style>';
+ document.body.appendChild(fragment);
+ const fragmentRules = fragment.firstChild.sheet.cssRules.length;
+ const parsed = new DOMParser().parseFromString(
+ '<html xmlns="http://www.w3.org/1999/xhtml"><head><style>body {color:red}</style></head></html>',
+ 'application/xhtml+xml');
+ return JSON.stringify({pending, complete, fragmentRules,
+ color:getComputedStyle(document.body).color,
+ xmlRules:parsed.querySelector('style').sheet.cssRules.length});
+})()
+"#).expect("SVG, fragments and XML should all finish parser-created styles");
+ assert_eq!(
+ serde_json::from_str::<serde_json::Value>(&result).unwrap(),
+ serde_json::json!({
+ "pending": true, "complete": [1, 0], "fragmentRules": 1,
+ "color": "rgb(4, 5, 6)", "xmlRules": 1
+ }),
+ );
+}
+
#[test]
fn parser_coalesced_style_text_updates_main_and_child_hit_tests() {
let mut vm = new_rendered_test_vm(
diff --git a/moli-renderer-v8/src/style_engine/source/mod.rs b/moli-renderer-v8/src/style_engine/source/mod.rs
index 77dfad212..4131e2ae8 100644
--- a/moli-renderer-v8/src/style_engine/source/mod.rs
+++ b/moli-renderer-v8/src/style_engine/source/mod.rs
@@ -6,6 +6,7 @@ pub(super) mod inline;
pub(super) mod linked;
mod shared_cache;
pub(super) mod store;
+mod style_element;
use crate::{
document_runtime::DomHandle,
@@ -160,6 +161,7 @@ impl MoliStyleEngine {
.tracks_document(document)
}
+ #[cfg(test)]
pub(crate) fn set_owner_style_sheet_text_with_host(
&mut self,
host: &DomHost,
@@ -170,46 +172,7 @@ impl MoliStyleEngine {
self.set_owner_style_sheet_source_with_parser_base(host, owner, css_text, parser_base);
}
- pub(crate) fn sync_owner_style_sheet_text_with_host(
- &mut self,
- host: &DomHost,
- owner: DomHandle,
- css_text: String,
- ) {
- if self.owner_document_world(host, owner).is_some_and(|world| {
- world
- .owner_style_sheet_sources
- .borrow()
- .cssom_source_is_authoritative(owner)
- }) {
- return;
- }
- self.set_owner_style_sheet_text_with_host(host, owner, css_text);
- }
-
- fn process_owner_style_sheet_text_with_host(
- &mut self,
- host: &DomHost,
- owner: DomHandle,
- css_text: String,
- ) {
- let Some(document) = owner_document_for_source_owner(host, owner) else {
- return;
- };
- let previous_linked_documents = self.linked_stylesheet_owner_documents(owner);
- self.remove_linked_stylesheet_owner_from_documents(host, owner, previous_linked_documents);
- let previous_documents = self.move_owner_style_sheet_source_to_document(document, owner);
- let parser_base = stylesheet_source_base_url(host, owner);
- self.world_for_document(document)
- .owner_style_sheet_sources
- .borrow_mut()
- .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.mark_document_stylesheet_set_dirty(previous_document);
- }
- }
-
+ #[cfg(test)]
fn set_owner_style_sheet_source_with_parser_base(
&mut self,
host: &DomHost,
@@ -300,21 +263,6 @@ impl MoliStyleEngine {
refreshed
}
- pub(crate) fn mark_owner_live_stylesheet_cssom_authoritative_with_host(
- &mut self,
- host: &DomHost,
- owner: DomHandle,
- ) -> bool {
- let Some(world) = self.owner_document_world(host, owner) else {
- return false;
- };
- world
- .owner_style_sheet_sources
- .borrow_mut()
- .mark_cssom_authoritative(owner);
- true
- }
-
pub(crate) fn owner_live_stylesheet_with_host(
&self,
host: &DomHost,
@@ -506,45 +454,7 @@ impl MoliStyleEngine {
for change in changes {
let owner = change.owner();
if host.is_inline_style_sheet_owner(owner) {
- let should_sync = match change.kind() {
- DomStylesheetOwnerChangeKind::Registered
- | DomStylesheetOwnerChangeKind::Contents => host.is_connected(owner),
- DomStylesheetOwnerChangeKind::OwnerDocumentChanged => true,
- DomStylesheetOwnerChangeKind::TreeConnectionChanged { connected } => *connected,
- DomStylesheetOwnerChangeKind::Unregistered
- | DomStylesheetOwnerChangeKind::Attribute { .. } => false,
- };
- if should_sync {
- self.process_owner_style_sheet_text_with_host(
- host,
- owner,
- host.text_content(owner).unwrap_or_default(),
- );
- } else if matches!(
- change.kind(),
- DomStylesheetOwnerChangeKind::Attribute {
- namespace: None,
- local_name,
- } if local_name == "type"
- ) {
- // The type attribute changes whether the already-parsed
- // owner source participates in its TreeScope. The source
- // text and identity stay stable, but retained worlds must
- // refresh their active stylesheet projection immediately.
- self.invalidate_owner_stylesheet_set_for_owner_with_host(host, owner);
- } else if matches!(
- change.kind(),
- 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,
- owner,
- previous_documents,
- );
- }
+ self.apply_style_element_change_with_host(host, change);
continue;
}
if !host.is_html_element_named(owner, "link") {
diff --git a/moli-renderer-v8/src/style_engine/source/store.rs b/moli-renderer-v8/src/style_engine/source/store.rs
index 041fb9961..823ce883e 100644
--- a/moli-renderer-v8/src/style_engine/source/store.rs
+++ b/moli-renderer-v8/src/style_engine/source/store.rs
@@ -546,6 +546,7 @@ impl OwnerStyleSheetSource {
Self { owner, source }
}
+ #[cfg(test)]
pub(in crate::style_engine) fn matches_processing_input(
&self,
css_text: &str,
diff --git a/moli-renderer-v8/src/style_engine/source/style_element.rs b/moli-renderer-v8/src/style_engine/source/style_element.rs
new file mode 100644
index 000000000..450b19458
--- /dev/null
+++ b/moli-renderer-v8/src/style_engine/source/style_element.rs
@@ -0,0 +1,109 @@
+use super::{
+ DomHandle, DomHost, DomStylesheetOwnerChange, DomStylesheetOwnerChangeKind, MoliStyleEngine,
+ owner_document_for_source_owner, stylesheet_source_base_url,
+};
+use crate::dom::native::Node;
+
+impl MoliStyleEngine {
+ /// Adopt style elements built before this style engine observed their DOM
+ /// lifecycle. Existing sources, including CSSOM edits, remain authoritative.
+ pub(crate) fn initialize_style_element_sources_with_host(
+ &mut self,
+ host: &DomHost,
+ document: DomHandle,
+ ) {
+ for (_, owners) in host
+ .stylesheet_candidate_tree_scope_snapshots_for_document(document)
+ .iter()
+ {
+ for &owner in owners.iter() {
+ if host.is_inline_style_sheet_owner(owner)
+ && self.owner_style_sheet_processing_source(owner).is_none()
+ {
+ self.process_style_element_with_host(host, owner);
+ }
+ }
+ }
+ }
+
+ pub(super) fn apply_style_element_change_with_host(
+ &mut self,
+ host: &DomHost,
+ change: &DomStylesheetOwnerChange,
+ ) {
+ let owner = change.owner();
+ match change.kind() {
+ DomStylesheetOwnerChangeKind::Registered
+ | DomStylesheetOwnerChangeKind::Contents
+ | DomStylesheetOwnerChangeKind::ParsingFinished => {
+ if style_element_has_document_root(host, owner) {
+ self.process_style_element_with_host(host, owner);
+ }
+ }
+ DomStylesheetOwnerChangeKind::OwnerDocumentChanged
+ | DomStylesheetOwnerChangeKind::TreeConnectionChanged { connected: true } => {
+ self.process_style_element_with_host(host, owner);
+ }
+ DomStylesheetOwnerChangeKind::Unregistered
+ | DomStylesheetOwnerChangeKind::TreeConnectionChanged { connected: false } => {
+ self.remove_owner_style_sheet_source(owner);
+ let documents = self.linked_stylesheet_owner_documents(owner);
+ self.remove_linked_stylesheet_owner_from_documents(host, owner, documents);
+ }
+ DomStylesheetOwnerChangeKind::Attribute {
+ namespace: None,
+ local_name,
+ } if local_name == "type" => {
+ // Type changes eligibility, not the prepared source or CSSOM identity.
+ self.invalidate_owner_stylesheet_set_for_owner_with_host(host, owner);
+ }
+ DomStylesheetOwnerChangeKind::Attribute { .. } => {}
+ }
+ }
+
+ /// The only production path that prepares an owner source from DOM text.
+ /// Parsing state is enforced here, before a source can become visible to
+ /// stylesheet installation, CSSOM reads, or rendering synchronization.
+ fn process_style_element_with_host(&mut self, host: &DomHost, owner: DomHandle) {
+ if host.is_style_element_parsing_children(owner) {
+ return;
+ }
+ let Some(document) = owner_document_for_source_owner(host, owner) else {
+ return;
+ };
+ let css_text = host.text_content(owner).unwrap_or_default();
+ let parser_base = stylesheet_source_base_url(host, owner);
+ let previous_linked_documents = self.linked_stylesheet_owner_documents(owner);
+ self.remove_linked_stylesheet_owner_from_documents(host, owner, previous_linked_documents);
+ let previous_documents = self.move_owner_style_sheet_source_to_document(document, owner);
+ self.world_for_document(document)
+ .owner_style_sheet_sources
+ .borrow_mut()
+ .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.mark_document_stylesheet_set_dirty(previous_document);
+ }
+ }
+}
+
+fn style_element_has_document_root(host: &DomHost, owner: DomHandle) -> bool {
+ if host.is_connected(owner) {
+ return true;
+ }
+ // Documents without a browsing context have no native connected flag,
+ // but styles inserted into them still participate in their CSSOM.
+ let mut current = owner;
+ loop {
+ let Some(root) = host.root_node_handle(current) else {
+ return false;
+ };
+ if host.node(root).is_some_and(Node::is_document) {
+ return true;
+ }
+ let Some(shadow_host) = host.shadow_root_host(root) else {
+ return false;
+ };
+ current = shadow_host;
+ }
+}
diff --git a/moli-renderer-v8/src/style_engine/source_owner_text.rs b/moli-renderer-v8/src/style_engine/source_owner_text.rs
index 7bc5b1a2f..480df5e7f 100644
--- a/moli-renderer-v8/src/style_engine/source_owner_text.rs
+++ b/moli-renderer-v8/src/style_engine/source_owner_text.rs
@@ -59,10 +59,6 @@ impl InstalledOwnerStyleSheet {
#[derive(Debug, Default)]
pub(super) struct OwnerStyleSheetSources {
sources_by_owner: HashMap<DomHandle, InstalledOwnerStyleSheet>,
- // A CSSOM rule mutation does not rewrite the owning <style> text nodes.
- // Parser/runtime reconciliation must therefore preserve this source until
- // an actual DOM stylesheet-content mutation calls `set_source` again.
- cssom_authoritative_owners: HashSet<DomHandle>,
// Projection of DocumentRuntime's CSP disposition. This set only suppresses
// retained/cascade sources; it is not queried for request or event policy.
csp_suppressed_owners: HashSet<DomHandle>,
@@ -87,17 +83,16 @@ impl OwnerStyleSheetSources {
pub(super) fn clear_all(&mut self) {
self.sources_by_owner.clear();
- self.cssom_authoritative_owners.clear();
self.csp_suppressed_owners.clear();
}
+ #[cfg(test)]
pub(super) fn set_source(
&mut self,
owner: DomHandle,
css_text: String,
parser_base: url::Url,
) -> bool {
- self.cssom_authoritative_owners.remove(&owner);
if self.sources_by_owner.get(&owner).is_some_and(|existing| {
existing
.processing_source
@@ -119,7 +114,6 @@ impl OwnerStyleSheetSources {
css_text: String,
parser_base: url::Url,
) {
- self.cssom_authoritative_owners.remove(&owner);
let processing_source = Arc::new(OwnerStyleSheetSource::new(owner, css_text, parser_base));
self.sources_by_owner.insert(
owner,
@@ -166,7 +160,6 @@ impl OwnerStyleSheetSources {
}
pub(super) fn remove_owner(&mut self, owner: DomHandle) -> bool {
- self.cssom_authoritative_owners.remove(&owner);
self.csp_suppressed_owners.remove(&owner);
self.sources_by_owner.remove(&owner).is_some()
}
@@ -183,14 +176,6 @@ impl OwnerStyleSheetSources {
self.csp_suppressed_owners.contains(&owner)
}
- pub(super) fn mark_cssom_authoritative(&mut self, owner: DomHandle) {
- self.cssom_authoritative_owners.insert(owner);
- }
-
- pub(super) fn cssom_source_is_authoritative(&self, owner: DomHandle) -> bool {
- self.cssom_authoritative_owners.contains(&owner)
- }
-
pub(super) fn text(&self, owner: DomHandle) -> Option<&str> {
self.sources_by_owner
.get(&owner)
diff --git a/moli-renderer-v8/src/style_engine/tests/lifecycle.rs b/moli-renderer-v8/src/style_engine/tests/lifecycle.rs
index ee648ef7e..0461a8c42 100644
--- a/moli-renderer-v8/src/style_engine/tests/lifecycle.rs
+++ b/moli-renderer-v8/src/style_engine/tests/lifecycle.rs
@@ -1,5 +1,69 @@
use super::*;
+#[test]
+fn style_element_initialization_waits_for_parser_and_preserves_prepared_sources() {
+ let mut host = test_host();
+ let document = host.document_handle();
+ let owner = host.create_parser_element_without_attributes(
+ "style".into(),
+ "http://www.w3.org/1999/xhtml".into(),
+ None,
+ );
+ assert!(host.set_text_content(owner, ".first { color: red; }"));
+ let insertion = host.append_child_effects(document, owner);
+ let mut engine = MoliStyleEngine::new();
+ engine.apply_stylesheet_owner_changes_with_host(&host, insertion.stylesheet_owners().changes());
+ engine.initialize_style_element_sources_with_host(&host, document);
+ assert!(engine.owner_style_sheet_processing_source(owner).is_none());
+
+ let completion = host.finish_parsing_style_children_effects(owner);
+ engine
+ .apply_stylesheet_owner_changes_with_host(&host, completion.stylesheet_owners().changes());
+ let first = engine.owner_style_sheet_processing_source(owner).unwrap();
+ assert_eq!(first.css_text(), ".first { color: red; }");
+ engine.initialize_style_element_sources_with_host(&host, document);
+ assert!(std::sync::Arc::ptr_eq(
+ &first,
+ &engine.owner_style_sheet_processing_source(owner).unwrap(),
+ ));
+
+ let change = host.set_text_content_effects(owner, ".second { color: blue; }");
+ engine.apply_stylesheet_owner_changes_with_host(&host, change.stylesheet_owners().changes());
+ let second = engine.owner_style_sheet_processing_source(owner).unwrap();
+ assert_eq!(second.css_text(), ".second { color: blue; }");
+ assert!(!std::sync::Arc::ptr_eq(&first, &second));
+}
+
+#[test]
+fn styles_in_documents_without_browsing_context_follow_owner_lifecycle() {
+ let mut host = test_host();
+ let document = host.create_detached_html_document();
+ let style = host.create_element("style");
+ assert!(host.set_text_content(style, ".first { color: red; }"));
+ let mut engine = MoliStyleEngine::new();
+ let insertion = host.append_child_effects(document, style);
+ assert!(!host.is_connected(style));
+ engine.apply_stylesheet_owner_changes_with_host(&host, insertion.stylesheet_owners().changes());
+ assert_eq!(
+ engine
+ .owner_style_sheet_text_with_host(&host, style)
+ .as_deref(),
+ Some(".first { color: red; }"),
+ );
+
+ let change = host.set_text_content_effects(style, ".second { color: blue; }");
+ engine.apply_stylesheet_owner_changes_with_host(&host, change.stylesheet_owners().changes());
+ assert_eq!(
+ engine
+ .owner_style_sheet_text_with_host(&host, style)
+ .as_deref(),
+ Some(".second { color: blue; }"),
+ );
+ 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());
+}
+
#[test]
fn disabled_author_styles_use_stylo_author_origin_gate() {
let mut host = test_host();
diff --git a/moli-renderer-v8/src/stylesheet_runtime/connected.rs b/moli-renderer-v8/src/stylesheet_runtime/connected.rs
index 36eb0782a..2983c36c2 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/connected.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/connected.rs
@@ -1366,6 +1366,7 @@ impl DocumentRuntime {
let should_queue = match change.kind() {
DomStylesheetOwnerChangeKind::Registered
| DomStylesheetOwnerChangeKind::Contents
+ | DomStylesheetOwnerChangeKind::ParsingFinished
| DomStylesheetOwnerChangeKind::OwnerDocumentChanged
| DomStylesheetOwnerChangeKind::TreeConnectionChanged { connected: true } => true,
DomStylesheetOwnerChangeKind::Unregistered
@@ -1837,6 +1838,9 @@ fn connected_style_owner_kind(
element: &crate::dom::native::Element,
) -> Option<ConnectedStyleOwnerKind> {
if super::is_inline_style_element(element) {
+ if element.style_children_parsing() {
+ return None;
+ }
return if is_declarative_css_module_style_element(element) {
Some(ConnectedStyleOwnerKind::DeclarativeCssModule)
} else if crate::style_engine::stylesheet_owner_type_is_supported(element) {
diff --git a/moli-stylesheet-blocking/src/discovery.rs b/moli-stylesheet-blocking/src/discovery.rs
index c43e4c893..db622361b 100644
--- a/moli-stylesheet-blocking/src/discovery.rs
+++ b/moli-stylesheet-blocking/src/discovery.rs
@@ -124,7 +124,7 @@ impl StylesheetElementRead {
parser_blocking_eligible: if element.is_html_element("link") {
element.link_created_by_parser()
} else {
- node.flags().parser_created()
+ node.flags().parser_created() && !element.style_children_parsing()
},
rel: element.attribute("rel").map(str::to_owned),
href: element.attribute("href").map(str::to_owned),