Skip to content

armgit / moli

Public Imported from GitHub
0

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

perf(parser): build fragments directly in live DOM

ldm09953237e66dd
diff --git a/moli-dom/src/native/host/mutation/tree.rs b/moli-dom/src/native/host/mutation/tree.rs
index d3a73fb6c..bd360d3fa 100644
--- a/moli-dom/src/native/host/mutation/tree.rs
+++ b/moli-dom/src/native/host/mutation/tree.rs
@@ -11,10 +11,21 @@ impl DomHost {
&mut self,
parent: DomHandle,
child: DomHandle,
+ ) -> bool {
+ self.insert_before_without_mutation_effects(parent, child, None)
+ }
+
+ /// Raw tree splice for parser/clone staging trees that are not yet exposed
+ /// through a Web mutation surface.
+ pub fn insert_before_without_mutation_effects(
+ &mut self,
+ parent: DomHandle,
+ child: DomHandle,
+ reference_child: Option<DomHandle>,
) -> bool {
let previous_shadow_root = self.containing_shadow_root(child);
- let appended = self.dom.append_child(parent, child);
- if appended {
+ let inserted = self.dom.insert_before(parent, child, reference_child);
+ if inserted {
if let Some(shadow_root) = previous_shadow_root {
self.invalidate_shadow_slot_name_index(shadow_root);
}
@@ -26,7 +37,24 @@ impl DomHost {
// this does not advance query_version or emit mutation effects.
self.record_query_index_candidates_in_subtree(child);
}
- appended
+ inserted
+ }
+
+ /// Raw removal counterpart to [`Self::insert_before_without_mutation_effects`].
+ pub fn remove_child_without_mutation_effects(
+ &mut self,
+ parent: DomHandle,
+ child: DomHandle,
+ ) -> bool {
+ let previous_shadow_root = self.containing_shadow_root(child);
+ let removed = self.dom.remove_child(parent, child);
+ if removed {
+ if let Some(shadow_root) = previous_shadow_root {
+ self.invalidate_shadow_slot_name_index(shadow_root);
+ }
+ self.invalidate_shadow_slot_name_index_for_tree_parent(parent);
+ }
+ removed
}
pub fn remove_child(&mut self, parent: DomHandle, child: DomHandle) -> bool {
diff --git a/moli-dom/src/native/host/query_index.rs b/moli-dom/src/native/host/query_index.rs
index dca654758..4edf59601 100644
--- a/moli-dom/src/native/host/query_index.rs
+++ b/moli-dom/src/native/host/query_index.rs
@@ -704,6 +704,36 @@ mod tests {
);
}
+ #[test]
+ fn silent_staging_splice_keeps_versions_stable_and_query_index_complete() {
+ let mut host = test_host();
+ let detached_document = host.create_detached_html_document();
+ let detached_style = host.create_element("style");
+
+ assert!(
+ host.html_elements_by_local_name_in_document_tree_order(detached_document, "style")
+ .is_empty()
+ );
+ let dom_version = host.dom_version();
+ let query_version = host.query_version();
+
+ assert!(host.append_child_without_mutation_effects(detached_document, detached_style));
+ assert_eq!(host.dom_version(), dom_version);
+ assert_eq!(host.query_version(), query_version);
+ assert_eq!(
+ host.html_elements_by_local_name_in_document_tree_order(detached_document, "style"),
+ vec![detached_style]
+ );
+
+ assert!(host.remove_child_without_mutation_effects(detached_document, detached_style));
+ assert_eq!(host.dom_version(), dom_version);
+ assert_eq!(host.query_version(), query_version);
+ assert!(
+ host.html_elements_by_local_name_in_document_tree_order(detached_document, "style")
+ .is_empty()
+ );
+ }
+
#[test]
fn shared_script_query_honors_requested_light_tree_root_and_namespace() {
let mut host = test_host();
diff --git a/moli-parser/src/html.rs b/moli-parser/src/html.rs
index 01c48b9df..0babd2177 100644
--- a/moli-parser/src/html.rs
+++ b/moli-parser/src/html.rs
@@ -22,7 +22,6 @@ use moli_stylesheet_blocking::{
DocumentBlockingStylesheetSignature, DocumentOwnedBlockingStylesheetDiscoveryInput,
};
-#[cfg(any(test, feature = "test-support"))]
use super::live_target::new_live_fragment_root_html_tree_sink_stream;
use super::live_target::{
ParserDomMutationConsumer, ParserDomReadConsumer, ParserElementCreationConsumer,
@@ -519,6 +518,53 @@ impl HtmlParser {
}
parser.finish().finish_dom_host()
}
+
+ /// Parses an inert HTML fragment directly into a runtime-owned detached
+ /// `DocumentFragment`.
+ ///
+ /// The parser mutates only through the scoped consumer callbacks. Custom
+ /// elements are intentionally left unconstructed so the caller can apply
+ /// the fragment API's required upgrade timing after normalization or
+ /// insertion.
+ #[allow(clippy::too_many_arguments)]
+ pub fn parse_fragment_into_live_dom<T>(
+ &self,
+ final_url: Url,
+ fragment_handle: NativeNodeId,
+ owner_document_handle: NativeNodeId,
+ context_handle: NativeNodeId,
+ context_namespace: &str,
+ context_local_name: &str,
+ html: &str,
+ consumer: &mut T,
+ allow_declarative_shadow_roots: bool,
+ ) -> ParserFinishDiscoverySignals
+ where
+ T: ParserDomReadConsumer + ParserDomMutationConsumer + ParserMutationEffectConsumer,
+ {
+ // TreeBuilder::new_for_fragment creates its synthetic root eagerly, so
+ // construction itself must run under the same scoped runtime sinks as
+ // every later feed/finish operation.
+ let runtime_dom_sinks =
+ // SAFETY: `consumer` remains exclusively borrowed until the
+ // constructor clears the sink bundle before returning.
+ unsafe { ParserRuntimeDomSinks::from_consumer_without_element_creation(consumer) };
+ let mut stream = DocumentStream::new_live_fragment_root(
+ final_url,
+ fragment_handle,
+ owner_document_handle,
+ context_handle,
+ context_namespace,
+ context_local_name,
+ runtime_dom_sinks,
+ allow_declarative_shadow_roots,
+ self.scripting_enabled,
+ );
+ for chunk in html_chunks(html) {
+ stream.feed_with_runtime_dom_consumer_without_element_creation(chunk, consumer);
+ }
+ stream.finish_with_runtime_dom_consumer_without_element_creation(consumer)
+ }
}
impl Default for ParserInputQueue {
@@ -550,10 +596,10 @@ impl DocumentStream {
}
}
- #[cfg(any(test, feature = "test-support"))]
fn new_live_fragment_root(
final_url: Url,
fragment_handle: NativeNodeId,
+ owner_document_handle: NativeNodeId,
context_handle: NativeNodeId,
context_namespace: &str,
context_local_name: &str,
@@ -565,6 +611,7 @@ impl DocumentStream {
inner: new_live_fragment_root_html_tree_sink_stream(
final_url,
fragment_handle,
+ owner_document_handle,
context_handle,
context_namespace,
context_local_name,
@@ -598,6 +645,7 @@ impl DocumentStream {
pub fn new_live_fragment_root_for_testing<T>(
final_url: Url,
fragment_handle: NativeNodeId,
+ owner_document_handle: NativeNodeId,
context_handle: NativeNodeId,
context_namespace: &str,
context_local_name: &str,
@@ -615,6 +663,7 @@ impl DocumentStream {
Self::new_live_fragment_root(
final_url,
fragment_handle,
+ owner_document_handle,
context_handle,
context_namespace,
context_local_name,
@@ -660,6 +709,22 @@ impl DocumentStream {
self.inner.feed(chunk)
}
+ fn feed_with_runtime_dom_consumer_without_element_creation<T>(
+ &mut self,
+ chunk: &str,
+ consumer: &mut T,
+ ) where
+ T: ParserDomReadConsumer + ParserDomMutationConsumer + ParserMutationEffectConsumer,
+ {
+ // SAFETY: `consumer` stays exclusively borrowed for this call; the
+ // parser-step Drop guard removes every erased callback before return.
+ let sinks =
+ unsafe { ParserRuntimeDomSinks::from_consumer_without_element_creation(consumer) };
+ self.inner.enter_runtime_dom_sinks_parse_step(sinks);
+ let mut step = RuntimeDomSinksParserStep { stream: self };
+ step.feed(chunk);
+ }
+
/// Append decoded document input to the parser-owned end segment chain.
///
/// The tokenizer only receives a bounded prefix when the owner pumps the
@@ -896,6 +961,20 @@ impl DocumentStream {
self.finish_with_runtime_dom_sinks(sinks)
}
+ fn finish_with_runtime_dom_consumer_without_element_creation<T>(
+ self,
+ consumer: &mut T,
+ ) -> ParserFinishDiscoverySignals
+ where
+ T: ParserDomReadConsumer + ParserDomMutationConsumer + ParserMutationEffectConsumer,
+ {
+ // SAFETY: `consumer` stays exclusively borrowed for this call. The
+ // finish guard clears the callbacks if parser finalization unwinds.
+ let sinks =
+ unsafe { ParserRuntimeDomSinks::from_consumer_without_element_creation(consumer) };
+ self.finish_with_runtime_dom_sinks(sinks)
+ }
+
fn finish_with_runtime_dom_sinks(
mut self,
sinks: ParserRuntimeDomSinks,
@@ -998,6 +1077,10 @@ struct RuntimeDomSinksParserStep<'a> {
}
impl RuntimeDomSinksParserStep<'_> {
+ fn feed(&mut self, chunk: &str) {
+ self.stream.inner.feed(chunk);
+ }
+
fn pump_parser_step(&mut self, chunk: &str) -> ParserPumpOutcome {
self.stream.pump_parser_step(chunk)
}
diff --git a/moli-parser/src/live_target.rs b/moli-parser/src/live_target.rs
index 8c5c3a314..52792b34f 100644
--- a/moli-parser/src/live_target.rs
+++ b/moli-parser/src/live_target.rs
@@ -515,6 +515,27 @@ impl ParserDomMutation {
Self::RemoveChild { parent, child } => host.remove_child_effects(parent, child),
}
}
+
+ /// Applies a parser tree edit to an unexposed staging fragment.
+ ///
+ /// The fragment acquires normal Web mutation semantics when its roots are
+ /// inserted into the live tree. Running the observer/style/slot pipeline
+ /// for every tokenizer splice before then is redundant and expensive.
+ pub fn apply_to_detached_dom_host(self, host: &mut DomHost) -> bool {
+ match self {
+ Self::AppendChild { parent, child } => {
+ host.append_child_without_mutation_effects(parent, child)
+ }
+ Self::InsertBefore {
+ parent,
+ child,
+ reference_child,
+ } => host.insert_before_without_mutation_effects(parent, child, reference_child),
+ Self::RemoveChild { parent, child } => {
+ host.remove_child_without_mutation_effects(parent, child)
+ }
+ }
+ }
}
pub trait ParserDomMutationConsumer {
@@ -541,16 +562,23 @@ pub trait ParserDomMutationConsumer {
attrs: Vec<NativeAttribute>,
);
- fn create_text_node(&mut self, text: String) -> NativeNodeId;
+ fn create_text_node(&mut self, document_handle: NativeNodeId, text: String) -> NativeNodeId;
- fn create_comment(&mut self, text: String) -> NativeNodeId;
+ fn create_comment(&mut self, document_handle: NativeNodeId, text: String) -> NativeNodeId;
- fn create_processing_instruction(&mut self, target: String, data: String) -> NativeNodeId;
+ fn create_processing_instruction(
+ &mut self,
+ document_handle: NativeNodeId,
+ target: String,
+ data: String,
+ ) -> NativeNodeId;
- fn create_cdata_section(&mut self, data: String) -> NativeNodeId;
+ fn create_cdata_section(&mut self, document_handle: NativeNodeId, data: String)
+ -> NativeNodeId;
fn create_document_type(
&mut self,
+ document_handle: NativeNodeId,
name: String,
public_id: String,
system_id: String,
@@ -587,11 +615,13 @@ struct ParserDomMutationSink {
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>),
- create_text_node: unsafe fn(NonNull<()>, String) -> NativeNodeId,
- create_comment: unsafe fn(NonNull<()>, String) -> NativeNodeId,
- create_processing_instruction: unsafe fn(NonNull<()>, String, String) -> NativeNodeId,
- create_cdata_section: unsafe fn(NonNull<()>, String) -> NativeNodeId,
- create_document_type: unsafe fn(NonNull<()>, String, String, String) -> NativeNodeId,
+ create_text_node: unsafe fn(NonNull<()>, NativeNodeId, String) -> NativeNodeId,
+ create_comment: unsafe fn(NonNull<()>, NativeNodeId, String) -> NativeNodeId,
+ create_processing_instruction:
+ unsafe fn(NonNull<()>, NativeNodeId, String, String) -> NativeNodeId,
+ create_cdata_section: unsafe fn(NonNull<()>, NativeNodeId, String) -> NativeNodeId,
+ create_document_type:
+ unsafe fn(NonNull<()>, NativeNodeId, String, String, String) -> NativeNodeId,
prepend_text_to_text_node: unsafe fn(NonNull<()>, NativeNodeId, String),
append_text_to_text_node: unsafe fn(NonNull<()>, NativeNodeId, String),
push_parse_error: unsafe fn(NonNull<()>, String),
@@ -644,46 +674,60 @@ impl ParserDomMutationSink {
}
unsafe fn create_text_node_impl<T: ParserDomMutationConsumer>(
data: NonNull<()>,
+ document_handle: NativeNodeId,
text: 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_text_node(text)
+ unsafe { data.cast::<T>().as_mut() }.create_text_node(document_handle, text)
}
unsafe fn create_comment_impl<T: ParserDomMutationConsumer>(
data: NonNull<()>,
+ document_handle: NativeNodeId,
text: 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_comment(text)
+ unsafe { data.cast::<T>().as_mut() }.create_comment(document_handle, text)
}
unsafe fn create_processing_instruction_impl<T: ParserDomMutationConsumer>(
data: NonNull<()>,
+ document_handle: NativeNodeId,
target: String,
data_text: 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_processing_instruction(target, data_text)
+ unsafe { data.cast::<T>().as_mut() }.create_processing_instruction(
+ document_handle,
+ target,
+ data_text,
+ )
}
unsafe fn create_cdata_section_impl<T: ParserDomMutationConsumer>(
data: NonNull<()>,
+ document_handle: NativeNodeId,
cdata: 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_cdata_section(cdata)
+ unsafe { data.cast::<T>().as_mut() }.create_cdata_section(document_handle, cdata)
}
unsafe fn create_document_type_impl<T: ParserDomMutationConsumer>(
data: NonNull<()>,
+ document_handle: NativeNodeId,
name: String,
public_id: String,
system_id: 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_document_type(name, public_id, system_id)
+ unsafe { data.cast::<T>().as_mut() }.create_document_type(
+ document_handle,
+ name,
+ public_id,
+ system_id,
+ )
}
unsafe fn prepend_text_to_text_node_impl<T: ParserDomMutationConsumer>(
data: NonNull<()>,
@@ -822,39 +866,47 @@ impl ParserDomMutationSink {
unsafe { (self.add_attrs_if_missing_for_parser)(self.data, node_id, attrs) };
}
- fn create_text_node(self, text: String) -> NativeNodeId {
+ fn create_text_node(self, document_handle: NativeNodeId, text: 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_text_node)(self.data, text) }
+ unsafe { (self.create_text_node)(self.data, document_handle, text) }
}
- fn create_comment(self, text: String) -> NativeNodeId {
+ fn create_comment(self, document_handle: NativeNodeId, text: 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_comment)(self.data, text) }
+ unsafe { (self.create_comment)(self.data, document_handle, text) }
}
- fn create_processing_instruction(self, target: String, data: String) -> NativeNodeId {
+ fn create_processing_instruction(
+ self,
+ document_handle: NativeNodeId,
+ target: String,
+ data: 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_processing_instruction)(self.data, target, data) }
+ unsafe { (self.create_processing_instruction)(self.data, document_handle, target, data) }
}
- fn create_cdata_section(self, data: String) -> NativeNodeId {
+ fn create_cdata_section(self, document_handle: NativeNodeId, data: 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_cdata_section)(self.data, data) }
+ unsafe { (self.create_cdata_section)(self.data, document_handle, data) }
}
fn create_document_type(
self,
+ document_handle: NativeNodeId,
name: String,
public_id: String,
system_id: 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_document_type)(self.data, name, public_id, system_id) }
+ unsafe {
+ (self.create_document_type)(self.data, document_handle, name, public_id, system_id)
+ }
}
fn prepend_text_to_text_node(self, node_id: NativeNodeId, text: String) {
@@ -1361,39 +1413,58 @@ impl ParserDomMutationConsumer for TestMutationEffectCollector<'_> {
unsafe { &mut *self.host }.add_attrs_if_missing_for_parser(node_id, attrs);
}
- fn create_text_node(&mut self, text: String) -> NativeNodeId {
+ fn create_text_node(&mut self, document_handle: NativeNodeId, text: 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_text_node(&text)
+ unsafe { &mut *self.host }.create_text_node_for_document(document_handle, &text)
}
- fn create_comment(&mut self, text: String) -> NativeNodeId {
+ fn create_comment(&mut self, document_handle: NativeNodeId, text: 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_comment(&text)
+ unsafe { &mut *self.host }.create_comment_for_document(document_handle, &text)
}
- fn create_processing_instruction(&mut self, target: String, data: String) -> NativeNodeId {
+ fn create_processing_instruction(
+ &mut self,
+ document_handle: NativeNodeId,
+ target: String,
+ data: 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_processing_instruction(&target, &data)
+ unsafe { &mut *self.host }.create_processing_instruction_for_document(
+ document_handle,
+ &target,
+ &data,
+ )
}
- fn create_cdata_section(&mut self, data: String) -> NativeNodeId {
+ fn create_cdata_section(
+ &mut self,
+ document_handle: NativeNodeId,
+ data: 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_cdata_section(&data)
+ unsafe { &mut *self.host }.create_cdata_section_for_document(document_handle, &data)
}
fn create_document_type(
&mut self,
+ document_handle: NativeNodeId,
name: String,
public_id: String,
system_id: 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_document_type(&name, &public_id, &system_id)
+ unsafe { &mut *self.host }.create_document_type_for_document(
+ document_handle,
+ &name,
+ &public_id,
+ &system_id,
+ )
}
fn prepend_text_to_text_node(&mut self, node_id: NativeNodeId, text: String) {
@@ -1701,39 +1772,58 @@ impl ParserDomMutationConsumer for TestReadTrackingCollector<'_> {
unsafe { &mut *self.host }.add_attrs_if_missing_for_parser(node_id, attrs);
}
- fn create_text_node(&mut self, text: String) -> NativeNodeId {
+ fn create_text_node(&mut self, document_handle: NativeNodeId, text: 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_text_node(&text)
+ unsafe { &mut *self.host }.create_text_node_for_document(document_handle, &text)
}
- fn create_comment(&mut self, text: String) -> NativeNodeId {
+ fn create_comment(&mut self, document_handle: NativeNodeId, text: 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_comment(&text)
+ unsafe { &mut *self.host }.create_comment_for_document(document_handle, &text)
}
- fn create_processing_instruction(&mut self, target: String, data: String) -> NativeNodeId {
+ fn create_processing_instruction(
+ &mut self,
+ document_handle: NativeNodeId,
+ target: String,
+ data: 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_processing_instruction(&target, &data)
+ unsafe { &mut *self.host }.create_processing_instruction_for_document(
+ document_handle,
+ &target,
+ &data,
+ )
}
- fn create_cdata_section(&mut self, data: String) -> NativeNodeId {
+ fn create_cdata_section(
+ &mut self,
+ document_handle: NativeNodeId,
+ data: 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_cdata_section(&data)
+ unsafe { &mut *self.host }.create_cdata_section_for_document(document_handle, &data)
}
fn create_document_type(
&mut self,
+ document_handle: NativeNodeId,
name: String,
public_id: String,
system_id: 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_document_type(&name, &public_id, &system_id)
+ unsafe { &mut *self.host }.create_document_type_for_document(
+ document_handle,
+ &name,
+ &public_id,
+ &system_id,
+ )
}
fn prepend_text_to_text_node(&mut self, node_id: NativeNodeId, text: String) {
@@ -1852,19 +1942,22 @@ pub(super) struct ParserStreamHtmlTreeSinkTarget {
/// DomHost owned by the parser before the runtime takes over the initial document.
/// Set to `None` after `take_parser_stream_document()`.
owned_dom_host: Option<DomHost>,
- /// Document root that html5ever should treat as this parser stream's
- /// document. Owned bootstrap streams use the DomHost document root; runtime
- /// live-DOM streams can target a detached child document in the same host.
- parser_document_handle: Option<NativeNodeId>,
+ /// Root that html5ever mutates for this parser stream. This is normally a
+ /// Document, but fragment parsing targets a detached DocumentFragment.
+ parser_root_handle: Option<NativeNodeId>,
+ /// Document that owns nodes created by this parser stream. This differs
+ /// from `parser_root_handle` only for fragment parsing.
+ parser_owner_document_handle: Option<NativeNodeId>,
/// Parser document URL cached outside the active DomHost so runtime sink
/// steps do not need to read the document node.
parser_document_url: Option<Url>,
/// Runtime-owned read/mutation/effect sinks for the current parser step.
/// Present only while a runtime DOM sink step is active.
runtime_dom_sinks: Option<ParserRuntimeDomSinks>,
- /// Set when html5ever resolves the next insertion point to template contents.
- /// The next element creation or direct append consumes the hint.
- next_insertion_is_template_contents: bool,
+ /// Set when html5ever resolves the next insertion point to template
+ /// contents. The handle also identifies the inert owner Document to use
+ /// when creating the next node.
+ next_template_contents_insertion: Option<NativeNodeId>,
open_template_element_depth: usize,
pending_open_parser_element: Option<NativeNodeId>,
open_parser_elements: Vec<OpenParserElement>,
@@ -1903,10 +1996,11 @@ impl ParserStreamHtmlTreeSinkTarget {
let document_handle = dom_host.document_handle();
Self {
owned_dom_host: Some(dom_host),
- parser_document_handle: Some(document_handle),
+ parser_root_handle: Some(document_handle),
+ parser_owner_document_handle: Some(document_handle),
parser_document_url: Some(final_url),
runtime_dom_sinks: None,
- next_insertion_is_template_contents: false,
+ next_template_contents_insertion: None,
open_template_element_depth: 0,
pending_open_parser_element: None,
open_parser_elements: Vec::new(),
@@ -1921,10 +2015,11 @@ impl ParserStreamHtmlTreeSinkTarget {
let document_handle = dom_host.document_handle();
Self {
owned_dom_host: Some(dom_host),
- parser_document_handle: Some(document_handle),
+ parser_root_handle: Some(document_handle),
+ parser_owner_document_handle: Some(document_handle),
parser_document_url: Some(final_url),
runtime_dom_sinks: None,
- next_insertion_is_template_contents: false,
+ next_template_contents_insertion: None,
open_template_element_depth: 0,
pending_open_parser_element: None,
open_parser_elements: Vec::new(),
@@ -1956,10 +2051,11 @@ impl ParserStreamHtmlTreeSinkTarget {
) -> Self {
Self {
owned_dom_host: None,
- parser_document_handle: Some(document_handle),
+ parser_root_handle: Some(document_handle),
+ parser_owner_document_handle: Some(document_handle),
parser_document_url: Some(final_url),
runtime_dom_sinks: None,
- next_insertion_is_template_contents: false,
+ next_template_contents_insertion: None,
open_template_element_depth: 0,
pending_open_parser_element: None,
open_parser_elements: Vec::new(),
@@ -1969,19 +2065,20 @@ impl ParserStreamHtmlTreeSinkTarget {
}
}
- #[cfg(any(test, feature = "test-support"))]
pub(super) fn new_live_fragment_root(
final_url: Url,
fragment_handle: NativeNodeId,
+ owner_document_handle: NativeNodeId,
runtime_dom_sinks: ParserRuntimeDomSinks,
allow_declarative_shadow_roots: bool,
) -> Self {
Self {
owned_dom_host: None,
- parser_document_handle: Some(fragment_handle),
+ parser_root_handle: Some(fragment_handle),
+ parser_owner_document_handle: Some(owner_document_handle),
parser_document_url: Some(final_url),
runtime_dom_sinks: Some(runtime_dom_sinks),
- next_insertion_is_template_contents: false,
+ next_template_contents_insertion: None,
open_template_element_depth: 0,
pending_open_parser_element: None,
open_parser_elements: Vec::new(),
@@ -2087,7 +2184,7 @@ impl ParserStreamHtmlTreeSinkTarget {
}
fn read_document_base_url(&self) -> Option<Url> {
- let document_handle = self.parser_document_node_id();
+ let document_handle = self.parser_owner_document_node_id();
if let Some(owner) = &self.runtime_dom_sinks {
owner.dom_read_sink().document_base_url(document_handle)
} else {
@@ -2097,7 +2194,7 @@ impl ParserStreamHtmlTreeSinkTarget {
}
fn read_document_body_handle(&self) -> Option<NativeNodeId> {
- let document_handle = self.parser_document_node_id();
+ let document_handle = self.parser_owner_document_node_id();
if let Some(owner) = &self.runtime_dom_sinks {
owner
.dom_read_sink()
@@ -2160,16 +2257,35 @@ impl ParserStreamHtmlTreeSinkTarget {
}
}
- pub(super) fn parser_document_node_id(&self) -> NativeNodeId {
- self.parser_document_handle
- .expect("parser stream should record its parser document/root handle")
+ pub(super) fn parser_root_node_id(&self) -> NativeNodeId {
+ self.parser_root_handle
+ .expect("parser stream should record its parser root handle")
+ }
+
+ pub(super) fn parser_owner_document_node_id(&self) -> NativeNodeId {
+ self.parser_owner_document_handle
+ .expect("parser stream should record its owner Document handle")
+ }
+
+ fn parses_whole_document(&self) -> bool {
+ self.parser_root_node_id() == self.parser_owner_document_node_id()
}
fn intended_parent_for_next_parser_element(&self) -> Option<NativeNodeId> {
self.open_parser_elements
.last()
.map(|element| element.node_id)
- .or_else(|| Some(self.parser_document_node_id()))
+ .or_else(|| Some(self.parser_root_node_id()))
+ }
+
+ fn owner_document_for_next_parser_node(&self) -> NativeNodeId {
+ self.next_template_contents_insertion
+ .and_then(|handle| self.read_owner_document(handle))
+ .or_else(|| {
+ self.intended_parent_for_next_parser_element()
+ .and_then(|handle| self.read_owner_document(handle))
+ })
+ .unwrap_or_else(|| self.parser_owner_document_node_id())
}
fn parser_document_url(&self) -> Option<&Url> {
@@ -2183,11 +2299,11 @@ impl ParserStreamHtmlTreeSinkTarget {
if !include_template_contents && let Some(owner) = &self.runtime_dom_sinks {
return owner
.dom_read_sink()
- .document_order_script_handles(self.parser_document_node_id());
+ .document_order_script_handles(self.parser_root_node_id());
}
let mut handles = Vec::new();
self.collect_script_handles_from_node(
- self.parser_document_node_id(),
+ self.parser_root_node_id(),
include_template_contents,
&mut handles,
);
@@ -2246,7 +2362,9 @@ impl ParserStreamHtmlTreeSinkTarget {
"cannot take owned DomHost while a runtime-DOM sink step is active"
);
debug_assert!(
- self.parser_document_handle.is_some() && self.parser_document_url.is_some(),
+ self.parser_root_handle.is_some()
+ && self.parser_owner_document_handle.is_some()
+ && self.parser_document_url.is_some(),
"parser stream should cache document handle/url before runtime takes the DOM"
);
self.owned_dom_host
@@ -2313,7 +2431,7 @@ impl ParserStreamHtmlTreeSinkTarget {
self.pending_open_parser_element = None;
if self.state.parser_meta_csp_candidates.remove(&node_id)
&& self.read_is_connected(node_id)
- && self.read_owner_document(node_id) == Some(self.parser_document_node_id())
+ && self.read_owner_document(node_id) == Some(self.parser_owner_document_node_id())
{
self.state
.discovered_parser_meta_csp_candidates
@@ -2374,7 +2492,7 @@ impl ParserStreamHtmlTreeSinkTarget {
// are owned by an inert template Document and must never start the
// main Document's resource lifecycle.
if !self.read_is_connected(node_id)
- || self.read_owner_document(node_id) != Some(self.parser_document_node_id())
+ || self.read_owner_document(node_id) != Some(self.parser_owner_document_node_id())
{
return false;
}
@@ -2475,7 +2593,22 @@ impl ParserStreamHtmlTreeSinkTarget {
namespace: String,
prefix: Option<String>,
) -> NativeNodeId {
- let document_handle = self.parser_document_node_id();
+ 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,
+ local_name: String,
+ namespace: String,
+ prefix: Option<String>,
+ ) -> NativeNodeId {
if let Some(owner) = &self.runtime_dom_sinks {
owner
.dom_mutation_sink()
@@ -2511,19 +2644,30 @@ impl ParserStreamHtmlTreeSinkTarget {
}
}
- pub(super) fn create_text_node(&mut self, text: String) -> NativeNodeId {
+ pub(super) fn create_text_node_for_document(
+ &mut self,
+ document_handle: NativeNodeId,
+ text: String,
+ ) -> NativeNodeId {
if let Some(owner) = &self.runtime_dom_sinks {
- owner.dom_mutation_sink().create_text_node(text)
+ owner
+ .dom_mutation_sink()
+ .create_text_node(document_handle, text)
} else {
- self.dom_host_mut().create_text_node(&text)
+ self.dom_host_mut()
+ .create_text_node_for_document(document_handle, &text)
}
}
pub(super) fn create_comment_node(&mut self, text: String) -> NativeNodeId {
+ let document_handle = self.owner_document_for_next_parser_node();
if let Some(owner) = &self.runtime_dom_sinks {
- owner.dom_mutation_sink().create_comment(text)
+ owner
+ .dom_mutation_sink()
+ .create_comment(document_handle, text)
} else {
- self.dom_host_mut().create_comment(&text)
+ self.dom_host_mut()
+ .create_comment_for_document(document_handle, &text)
}
}
@@ -2532,20 +2676,23 @@ impl ParserStreamHtmlTreeSinkTarget {
target: String,
data: String,
) -> NativeNodeId {
+ let document_handle = self.owner_document_for_next_parser_node();
if let Some(owner) = &self.runtime_dom_sinks {
owner
.dom_mutation_sink()
- .create_processing_instruction(target, data)
+ .create_processing_instruction(document_handle, target, data)
} else {
self.dom_host_mut()
- .create_processing_instruction(&target, &data)
+ .create_processing_instruction_for_document(document_handle, &target, &data)
}
}
pub(super) fn create_cdata_section_node(&mut self, data: String) -> NativeNodeId {
- let document_handle = self.parser_document_node_id();
+ let document_handle = self.owner_document_for_next_parser_node();
if let Some(owner) = &self.runtime_dom_sinks {
- owner.dom_mutation_sink().create_cdata_section(data)
+ owner
+ .dom_mutation_sink()
+ .create_cdata_section(document_handle, data)
} else {
self.dom_host_mut()
.create_cdata_section_for_document(document_handle, &data)
@@ -2558,13 +2705,21 @@ impl ParserStreamHtmlTreeSinkTarget {
public_id: String,
system_id: String,
) -> NativeNodeId {
+ let document_handle = self.parser_owner_document_node_id();
if let Some(owner) = &self.runtime_dom_sinks {
- owner
- .dom_mutation_sink()
- .create_document_type(name, public_id, system_id)
+ owner.dom_mutation_sink().create_document_type(
+ document_handle,
+ name,
+ public_id,
+ system_id,
+ )
} else {
- self.dom_host_mut()
- .create_document_type(&name, &public_id, &system_id)
+ self.dom_host_mut().create_document_type_for_document(
+ document_handle,
+ &name,
+ &public_id,
+ &system_id,
+ )
}
}
@@ -2829,7 +2984,10 @@ impl ParserStreamHtmlTreeSinkTarget {
return ParserMutationEffectDelivery::none();
}
- let text_node = self.create_text_node(text);
+ let document_handle = self
+ .read_owner_document(parent_id)
+ .unwrap_or_else(|| self.parser_owner_document_node_id());
+ let text_node = self.create_text_node_for_document(document_handle, text);
if let Some(reference_child) = reference_child {
let Some(parent) = self.read_parent_node(reference_child) else {
return ParserMutationEffectDelivery::none();
@@ -2852,16 +3010,20 @@ impl ParserStreamHtmlTreeSinkTarget {
}
pub(super) fn push_parse_error(&mut self, error: String) {
- self.push_parse_error_to_dom_host(error);
+ if self.parses_whole_document() {
+ self.push_parse_error_to_dom_host(error);
+ }
}
pub(super) fn document_handle(&self) -> ParseHandle {
- ParseHandle::new(self.parser_document_node_id(), None)
+ ParseHandle::new(self.parser_root_node_id(), None)
}
pub(super) fn set_html_quirks_mode(&mut self, quirks_mode: QuirksMode) {
self.state.html_quirks_mode = quirks_mode;
- self.set_html_quirks_mode_for_dom_host(quirks_mode);
+ if self.parses_whole_document() {
+ self.set_html_quirks_mode_for_dom_host(quirks_mode);
+ }
}
pub(super) fn set_current_position(&mut self, line_number: u64, column_number: u64) {
@@ -2890,8 +3052,14 @@ impl ParserStreamHtmlTreeSinkTarget {
flags: ElementFlags,
) -> ParseHandle {
let parser_flags = ParserElementFlags::from_html5ever(&flags);
+ let template_contents_insertion = self.take_template_contents_insertion_hint();
let insertion_is_template_contents =
- self.open_template_element_depth > 0 || self.take_template_contents_insertion_hint();
+ self.open_template_element_depth > 0 || template_contents_insertion.is_some();
+ let intended_parent = self.intended_parent_for_next_parser_element();
+ let document_handle = template_contents_insertion
+ .and_then(|handle| self.read_owner_document(handle))
+ .or_else(|| intended_parent.and_then(|handle| self.read_owner_document(handle)))
+ .unwrap_or_else(|| self.parser_owner_document_node_id());
let element_name = Rc::new(name.clone());
let local_name = name.local.to_string();
let namespace = name.ns.to_string();
@@ -2938,8 +3106,8 @@ impl ParserStreamHtmlTreeSinkTarget {
.and_then(ParserRuntimeDomSinks::element_creation_sink)
{
let request = ParserElementCreationRequest {
- document_handle: self.parser_document_node_id(),
- intended_parent: self.intended_parent_for_next_parser_element(),
+ document_handle,
+ intended_parent,
local_name: &local_name,
namespace: &namespace,
prefix: prefix.as_deref(),
@@ -2966,7 +3134,12 @@ impl ParserStreamHtmlTreeSinkTarget {
let token_namespace = namespace.clone();
let token_prefix = prefix.clone();
let token_attributes = attributes.clone();
- let node_id = self.create_parser_element_without_attributes(local_name, namespace, prefix);
+ let node_id = self.create_parser_element_without_attributes_for_document(
+ document_handle,
+ local_name,
+ namespace,
+ prefix,
+ );
self.add_attrs_if_missing_for_parser(node_id, attributes);
self.finish_created_element(
node_id,
@@ -3113,7 +3286,7 @@ impl ParserStreamHtmlTreeSinkTarget {
public_id: String,
system_id: String,
) -> ParserMutationEffectDelivery {
- let document_handle = self.parser_document_node_id();
+ let document_handle = self.parser_root_node_id();
let doctype = self.create_document_type_node(name, public_id, system_id);
self.record_parser_dom_mutation(ParserDomMutation::AppendChild {
parent: document_handle,
@@ -3128,18 +3301,18 @@ impl ParserStreamHtmlTreeSinkTarget {
let handle = self
.read_template_contents_handle(node_id)
.map(|handle| ParseHandle::new(handle, None));
- if handle.is_some() {
- self.next_insertion_is_template_contents = true;
+ if let Some(handle) = handle.as_ref() {
+ self.next_template_contents_insertion = Some(handle.node_id());
}
handle
}
- fn take_template_contents_insertion_hint(&mut self) -> bool {
- std::mem::take(&mut self.next_insertion_is_template_contents)
+ fn take_template_contents_insertion_hint(&mut self) -> Option<NativeNodeId> {
+ self.next_template_contents_insertion.take()
}
fn clear_template_contents_insertion_hint(&mut self) {
- self.next_insertion_is_template_contents = false;
+ self.next_template_contents_insertion = None;
}
pub(super) fn attach_declarative_shadow(
@@ -3293,7 +3466,8 @@ impl ParserStreamHtmlTreeSinkTarget {
}
pub(super) fn replace_parser_stream_document(&mut self, document: NativeDom) {
- self.parser_document_handle = Some(document.document_node_id());
+ self.parser_root_handle = Some(document.document_node_id());
+ self.parser_owner_document_handle = Some(document.document_node_id());
self.parser_document_url = document.final_url().cloned();
self.owned_dom_host = Some(DomHost::from_dom(document));
}
@@ -3339,10 +3513,10 @@ pub(super) fn new_live_document_root_html_tree_sink_stream(
)
}
-#[cfg(any(test, feature = "test-support"))]
pub(super) fn new_live_fragment_root_html_tree_sink_stream(
final_url: Url,
fragment_handle: NativeNodeId,
+ owner_document_handle: NativeNodeId,
context_handle: NativeNodeId,
context_namespace: &str,
context_local_name: &str,
@@ -3354,6 +3528,7 @@ pub(super) fn new_live_fragment_root_html_tree_sink_stream(
ParserStreamHtmlTreeSinkTarget::new_live_fragment_root(
final_url,
fragment_handle,
+ owner_document_handle,
runtime_dom_sinks,
allow_declarative_shadow_roots,
),
@@ -3420,7 +3595,7 @@ impl StylesheetBlockingReadView for ParserStreamHtmlTreeSinkTarget {
}
fn document_node_id(&self) -> NativeNodeId {
- self.parser_document_node_id()
+ self.parser_owner_document_node_id()
}
fn document_order_stylesheet_candidate_ids_before(
@@ -3432,13 +3607,13 @@ impl StylesheetBlockingReadView for ParserStreamHtmlTreeSinkTarget {
owner
.dom_read_sink()
.document_order_stylesheet_candidate_handles_before(
- self.parser_document_node_id(),
+ self.parser_root_node_id(),
stop_at,
)
} else {
self.dom_host()
.stylesheet_candidate_handles_before_in_tree_scope(
- self.parser_document_node_id(),
+ self.parser_root_node_id(),
stop_at,
)
}
@@ -3990,6 +4165,7 @@ fn parser_stream_live_document_root_writes_detached_document() {
fn parser_stream_live_fragment_root_writes_fragment() {
let url = Url::parse("https://example.test/").expect("test url");
let mut dom_host = DomHost::from_dom(NativeDom::new_html(url.clone()));
+ let document = dom_host.document_handle();
let fragment = dom_host.create_document_fragment();
let context = dom_host.create_parser_element_without_attributes(
"div".to_owned(),
@@ -4008,6 +4184,7 @@ fn parser_stream_live_fragment_root_writes_fragment() {
let mut stream = crate::DocumentStream::new_live_fragment_root_for_testing(
url,
fragment,
+ document,
context,
"http://www.w3.org/1999/xhtml",
"div",
@@ -4053,6 +4230,11 @@ fn parser_stream_live_fragment_root_writes_fragment() {
dom_host.text_content(root_children[0]).as_deref(),
Some("fragment text")
);
+ assert_eq!(
+ dom_host.owner_document_handle(root_children[0]),
+ Some(document),
+ "live fragment nodes must be owned by the target Document, not by the fragment root"
+ );
assert!(
dom_host
.elements_by_tag_name(dom_host.document_handle(), "span", false)
@@ -4061,6 +4243,65 @@ fn parser_stream_live_fragment_root_writes_fragment() {
);
}
+#[test]
+fn live_fragment_parser_uses_template_contents_owner_document() {
+ let url = Url::parse("https://example.test/").expect("test url");
+ let mut dom_host = DomHost::from_dom(NativeDom::new_html(url.clone()));
+ let document = dom_host.document_handle();
+ let fragment = dom_host.create_document_fragment_for_document(document);
+ let context = dom_host.create_parser_element_without_attributes_for_document(
+ document,
+ "div".to_owned(),
+ "http://www.w3.org/1999/xhtml".to_owned(),
+ None,
+ );
+ let ptr = &mut dom_host as *mut DomHost;
+ let mut effects = DomMutationEffects::default();
+
+ let signals = {
+ let mut collector = TestMutationEffectCollector {
+ host: ptr,
+ effects: &mut effects,
+ panic_on_mutation: false,
+ };
+ crate::HtmlParser::with_scripting_enabled(true).parse_fragment_into_live_dom(
+ url,
+ fragment,
+ document,
+ context,
+ "http://www.w3.org/1999/xhtml",
+ "div",
+ "<template><span>inside</span></template>",
+ &mut collector,
+ false,
+ )
+ };
+
+ assert!(signals.parser_created_null_registry_elements.is_empty());
+ let template = dom_host
+ .elements_by_tag_name(fragment, "template", false)
+ .into_iter()
+ .next()
+ .expect("parsed template");
+ let contents = dom_host
+ .parser_template_contents_handle(template)
+ .expect("template contents");
+ let contents_document = dom_host
+ .owner_document_handle(contents)
+ .expect("template contents owner Document");
+ let span = dom_host
+ .child_handles(contents)
+ .next()
+ .expect("template contents child");
+
+ assert_eq!(dom_host.owner_document_handle(template), Some(document));
+ assert_ne!(contents_document, document);
+ assert_eq!(
+ dom_host.owner_document_handle(span),
+ Some(contents_document)
+ );
+}
+
#[test]
fn parser_stream_element_creation_sink_can_own_token_attributes() {
let url = Url::parse("https://example.test/").expect("test url");
diff --git a/moli-parser/src/session.rs b/moli-parser/src/session.rs
index 7a06aee4c..c60fbedcb 100644
--- a/moli-parser/src/session.rs
+++ b/moli-parser/src/session.rs
@@ -1,7 +1,5 @@
-#[cfg(any(test, feature = "test-support"))]
use std::rc::Rc;
-#[cfg(any(test, feature = "test-support"))]
use html5ever::{LocalName, Namespace, QualName};
use html5ever::{
ParseOpts,
@@ -12,7 +10,6 @@ use html5ever::{
tree_builder::{TreeBuilder, TreeBuilderOpts, TreeSink},
};
use markup5ever::TokenizerResult;
-#[cfg(any(test, feature = "test-support"))]
use moli_dom::native::NativeNodeId;
use super::{
@@ -322,7 +319,6 @@ pub(super) fn new_html_tree_sink_session(
}
}
-#[cfg(any(test, feature = "test-support"))]
pub(super) fn new_fragment_html_tree_sink_session(
target: ParserStreamHtmlTreeSinkTarget,
context_handle: NativeNodeId,
diff --git a/moli-parser/src/stream.rs b/moli-parser/src/stream.rs
index 6eb4516fa..0cdef602f 100644
--- a/moli-parser/src/stream.rs
+++ b/moli-parser/src/stream.rs
@@ -17,8 +17,6 @@ use crate::script_planning::{
classify_parser_script,
};
-#[cfg(any(test, feature = "test-support"))]
-use super::session::new_fragment_html_tree_sink_session;
use super::{
html::{
ParserBlockingStylesheetPause, ParserFinishDiscoverySignals, ParserInputQueue,
@@ -27,7 +25,10 @@ use super::{
ParserYield,
},
live_target::{ParserRuntimeDomSinks, ParserStreamHtmlTreeSinkTarget},
- session::{HtmlParserSession, HtmlParserSessionResult, new_html_tree_sink_session},
+ session::{
+ HtmlParserSession, HtmlParserSessionResult, new_fragment_html_tree_sink_session,
+ new_html_tree_sink_session,
+ },
};
pub(super) struct HtmlTreeSinkStream {
@@ -437,7 +438,6 @@ impl HtmlTreeSinkStream {
}
}
- #[cfg(any(test, feature = "test-support"))]
pub(super) fn from_fragment_target(
target: ParserStreamHtmlTreeSinkTarget,
context_handle: NativeNodeId,
@@ -1048,34 +1048,57 @@ mod tests {
unsafe { &mut *self.host }.add_attrs_if_missing_for_parser(node_id, attrs);
}
- fn create_text_node(&mut self, text: String) -> NativeNodeId {
+ fn create_text_node(
+ &mut self,
+ document_handle: NativeNodeId,
+ text: String,
+ ) -> NativeNodeId {
// SAFETY: the test keeps the DomHost alive for this parser pump step.
- unsafe { &mut *self.host }.create_text_node(&text)
+ unsafe { &mut *self.host }.create_text_node_for_document(document_handle, &text)
}
- fn create_comment(&mut self, text: String) -> NativeNodeId {
+ fn create_comment(&mut self, document_handle: NativeNodeId, text: String) -> NativeNodeId {
// SAFETY: the test keeps the DomHost alive for this parser pump step.
- unsafe { &mut *self.host }.create_comment(&text)
+ unsafe { &mut *self.host }.create_comment_for_document(document_handle, &text)
}
- fn create_processing_instruction(&mut self, target: String, data: String) -> NativeNodeId {
+ fn create_processing_instruction(
+ &mut self,
+ document_handle: NativeNodeId,
+ target: String,
+ data: String,
+ ) -> NativeNodeId {
// SAFETY: the test keeps the DomHost alive for this parser pump step.
- unsafe { &mut *self.host }.create_processing_instruction(&target, &data)
+ unsafe { &mut *self.host }.create_processing_instruction_for_document(
+ document_handle,
+ &target,
+ &data,
+ )
}
- fn create_cdata_section(&mut self, data: String) -> NativeNodeId {
+ fn create_cdata_section(
+ &mut self,
+ document_handle: NativeNodeId,
+ data: String,
+ ) -> NativeNodeId {
// SAFETY: the test keeps the DomHost alive for this parser pump step.
- unsafe { &mut *self.host }.create_cdata_section(&data)
+ unsafe { &mut *self.host }.create_cdata_section_for_document(document_handle, &data)
}
fn create_document_type(
&mut self,
+ document_handle: NativeNodeId,
name: String,
public_id: String,
system_id: String,
) -> NativeNodeId {
// SAFETY: the test keeps the DomHost alive for this parser pump step.
- unsafe { &mut *self.host }.create_document_type(&name, &public_id, &system_id)
+ unsafe { &mut *self.host }.create_document_type_for_document(
+ document_handle,
+ &name,
+ &public_id,
+ &system_id,
+ )
}
fn prepend_text_to_text_node(&mut self, node_id: NativeNodeId, text: String) {
diff --git a/moli-parser/src/xml_tree_viewer.rs b/moli-parser/src/xml_tree_viewer.rs
index 4c0f2c36f..4f296d351 100644
--- a/moli-parser/src/xml_tree_viewer.rs
+++ b/moli-parser/src/xml_tree_viewer.rs
@@ -98,7 +98,7 @@ pub(super) fn transform_parser_target_to_xml_tree_view(
return;
}
- let parser_document = target.parser_document_node_id();
+ let parser_document = target.parser_root_node_id();
if source_document.document_node_id() != parser_document {
return;
}
@@ -160,7 +160,10 @@ fn materialize_transformed_viewer_node(
target.add_attrs_if_missing_for_parser(handle, element.attributes().to_vec());
handle
}
- NodeData::Text(text) => target.create_text_node(text.data().to_owned()),
+ NodeData::Text(text) => target.create_text_node_for_document(
+ target.parser_owner_document_node_id(),
+ text.data().to_owned(),
+ ),
NodeData::CDataSection(cdata) => target.create_cdata_section_node(cdata.data().to_owned()),
NodeData::Comment(comment) => target.create_comment_node(comment.data().to_owned()),
NodeData::ProcessingInstruction(instruction) => target.create_processing_instruction_node(
diff --git a/moli-renderer-v8/src/document_runtime/document_write.rs b/moli-renderer-v8/src/document_runtime/document_write.rs
index cc31ce76b..6be3fdc3d 100644
--- a/moli-renderer-v8/src/document_runtime/document_write.rs
+++ b/moli-renderer-v8/src/document_runtime/document_write.rs
@@ -42,12 +42,37 @@ struct DocumentWriteParserMutationOwner<'a, 'scope, 'pin> {
runtime: &'a mut DocumentRuntime,
scope: &'a mut v8::PinScope<'scope, 'pin>,
host_ptr: *mut JsContextHost,
+ target: DocumentWriteParserMutationTarget,
+}
+
+#[derive(Clone, Copy)]
+enum DocumentWriteParserMutationTarget {
+ LiveDocument,
+ DetachedFragment { owner_document: DomHandle },
+}
+
+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)
+ }
}
impl LiveDocumentParserOwner for DocumentWriteParserMutationOwner<'_, '_, '_> {}
impl ParserMutationEffectConsumer for DocumentWriteParserMutationOwner<'_, '_, '_> {
fn consume_parser_mutation_effects(&mut self, effects: DomMutationEffects) {
+ if !self.targets_live_document() {
+ return;
+ }
self.runtime
.apply_parser_stream_mutation_effects_to_live_dom_host(
self.scope,
@@ -150,6 +175,11 @@ impl ParserDomReadConsumer for DocumentWriteParserMutationOwner<'_, '_, '_> {
impl ParserDomMutationConsumer for DocumentWriteParserMutationOwner<'_, '_, '_> {
fn apply_parser_dom_mutation(&mut self, mutation: ParserDomMutation) {
+ if !self.targets_live_document() {
+ let _ = mutation
+ .apply_to_detached_dom_host(self.runtime.dom_host_mut_for_active_parser_step());
+ return;
+ }
self.runtime.apply_parser_dom_mutation_to_live_dom_host(
self.scope,
self.host_ptr,
@@ -165,9 +195,13 @@ impl ParserDomMutationConsumer for DocumentWriteParserMutationOwner<'_, '_, '_>
namespace: String,
prefix: Option<String>,
) -> DomHandle {
+ let document_handle = self.owner_document_handle();
self.runtime
- .create_parser_element_without_attributes_in_live_dom_host(
- local_name, namespace, prefix,
+ .create_parser_element_for_document_without_attributes_in_live_dom_host(
+ document_handle,
+ local_name,
+ namespace,
+ prefix,
)
}
@@ -196,31 +230,45 @@ impl ParserDomMutationConsumer for DocumentWriteParserMutationOwner<'_, '_, '_>
.add_attrs_if_missing_for_parser_in_live_dom_host(node_id, attrs);
}
- fn create_text_node(&mut self, text: String) -> DomHandle {
- self.runtime.create_text_node_in_live_dom_host(text)
+ fn create_text_node(&mut self, document_handle: DomHandle, text: String) -> DomHandle {
+ self.runtime
+ .dom_host_mut_for_active_parser_step()
+ .create_text_node_for_document(document_handle, &text)
}
- fn create_comment(&mut self, text: String) -> DomHandle {
- self.runtime.create_comment_in_live_dom_host(text)
+ fn create_comment(&mut self, document_handle: DomHandle, text: String) -> DomHandle {
+ self.runtime
+ .dom_host_mut_for_active_parser_step()
+ .create_comment_for_document(document_handle, &text)
}
- fn create_processing_instruction(&mut self, target: String, data: String) -> DomHandle {
+ fn create_processing_instruction(
+ &mut self,
+ document_handle: DomHandle,
+ target: String,
+ data: String,
+ ) -> DomHandle {
self.runtime
- .create_processing_instruction_in_live_dom_host(target, data)
+ .dom_host_mut_for_active_parser_step()
+ .create_processing_instruction_for_document(document_handle, &target, &data)
}
- fn create_cdata_section(&mut self, data: String) -> DomHandle {
- self.runtime.create_cdata_section_in_live_dom_host(data)
+ fn create_cdata_section(&mut self, document_handle: DomHandle, data: String) -> DomHandle {
+ self.runtime
+ .dom_host_mut_for_active_parser_step()
+ .create_cdata_section_for_document(document_handle, &data)
}
fn create_document_type(
&mut self,
+ document_handle: DomHandle,
name: String,
public_id: String,
system_id: String,
) -> DomHandle {
self.runtime
- .create_document_type_in_live_dom_host(name, public_id, system_id)
+ .dom_host_mut_for_active_parser_step()
+ .create_document_type_for_document(document_handle, &name, &public_id, &system_id)
}
fn prepend_text_to_text_node(&mut self, node_id: DomHandle, text: String) {
@@ -234,12 +282,16 @@ impl ParserDomMutationConsumer for DocumentWriteParserMutationOwner<'_, '_, '_>
}
fn push_parse_error(&mut self, error: String) {
- self.runtime.push_parse_error_in_live_dom_host(error);
+ if self.targets_live_document() {
+ self.runtime.push_parse_error_in_live_dom_host(error);
+ }
}
fn set_html_quirks_mode_for_parser(&mut self, quirks_mode: QuirksMode) {
- self.runtime
- .set_html_quirks_mode_for_parser_in_live_dom_host(quirks_mode);
+ if self.targets_live_document() {
+ self.runtime
+ .set_html_quirks_mode_for_parser_in_live_dom_host(quirks_mode);
+ }
}
fn mark_script_already_started_for_parser(&mut self, node_id: DomHandle) {
@@ -398,6 +450,7 @@ impl DocumentRuntime {
runtime,
scope,
host_ptr,
+ target: DocumentWriteParserMutationTarget::LiveDocument,
};
parser.finish(&mut mutation_owner)
});
@@ -469,133 +522,13 @@ impl DocumentRuntime {
if self.dom_host().node(root).is_some_and(|node| {
node.is_document() || node.is_document_fragment() || node.is_element()
}) {
- unsafe { &mut *host_ptr }.set_custom_element_registry_association(root, association);
- }
- }
-
- fn set_fragment_null_registry_associations_from_native_dom(
- &self,
- host_ptr: *mut JsContextHost,
- source: &NativeDom,
- source_root: DomHandle,
- imported_root: DomHandle,
- ) {
- let mut stack = vec![(source_root, imported_root)];
- while let Some((source_handle, imported_handle)) = stack.pop() {
- if source_node_has_null_registry_attribute(source.node(source_handle)) {
- unsafe { &mut *host_ptr }.set_custom_element_registry_association(
- imported_handle,
- custom_elements::CustomElementRegistryAssociation::Null,
- );
- }
-
- let source_children = source.child_ids(source_handle).collect::<Vec<_>>();
- let imported_children = self
- .dom_host()
- .child_handles(imported_handle)
- .collect::<Vec<_>>();
- for (source_child, imported_child) in
- source_children.into_iter().zip(imported_children).rev()
- {
- stack.push((source_child, imported_child));
- }
- if let (Some(source_template), Some(imported_template)) = (
- source
- .node(source_handle)
- .and_then(Node::as_element)
- .and_then(|element| element.template_contents()),
- self.dom_host()
- .node(imported_handle)
- .and_then(Node::as_element)
- .and_then(|element| element.template_contents()),
- ) {
- stack.push((source_template, imported_template));
+ let host = unsafe { &mut *host_ptr };
+ if host.effective_custom_element_registry_association(root) != association {
+ host.set_custom_element_registry_association(root, association);
}
}
}
- fn set_fragment_null_registry_associations_from_dom_host(
- &self,
- host_ptr: *mut JsContextHost,
- source: &DomHost,
- source_root: DomHandle,
- imported_root: DomHandle,
- ) {
- let mut stack = vec![(source_root, imported_root)];
- while let Some((source_handle, imported_handle)) = stack.pop() {
- if source_node_has_null_registry_attribute(source.node(source_handle)) {
- unsafe { &mut *host_ptr }.set_custom_element_registry_association(
- imported_handle,
- custom_elements::CustomElementRegistryAssociation::Null,
- );
- }
-
- let source_children = source.child_handles(source_handle).collect::<Vec<_>>();
- let imported_children = self
- .dom_host()
- .child_handles(imported_handle)
- .collect::<Vec<_>>();
- for (source_child, imported_child) in
- source_children.into_iter().zip(imported_children).rev()
- {
- stack.push((source_child, imported_child));
- }
- if let (Some(source_template), Some(imported_template)) = (
- source
- .node(source_handle)
- .and_then(Node::as_element)
- .and_then(|element| element.template_contents()),
- self.dom_host()
- .node(imported_handle)
- .and_then(Node::as_element)
- .and_then(|element| element.template_contents()),
- ) {
- stack.push((source_template, imported_template));
- }
- if let (Some(source_shadow), Some(imported_shadow)) = (
- source.shadow_root_handle(source_handle),
- self.dom_host().shadow_root_handle(imported_handle),
- ) {
- self.set_fragment_declarative_shadow_root_registry_association(
- host_ptr,
- source,
- source_shadow,
- imported_shadow,
- );
- stack.push((source_shadow, imported_shadow));
- }
- }
- }
-
- fn set_fragment_declarative_shadow_root_registry_association(
- &self,
- host_ptr: *mut JsContextHost,
- source: &DomHost,
- source_shadow: DomHandle,
- imported_shadow: DomHandle,
- ) {
- if !source
- .shadow_root_is_declarative(source_shadow)
- .unwrap_or(false)
- {
- return;
- }
- let association = if source
- .shadow_root_uses_null_custom_element_registry(source_shadow)
- .unwrap_or(false)
- {
- custom_elements::CustomElementRegistryAssociation::Null
- } else {
- let Some(owner_document) = self.dom_host().owner_document_handle(imported_shadow)
- else {
- return;
- };
- unsafe { &*host_ptr }.effective_custom_element_registry_association(owner_document)
- };
- unsafe { &mut *host_ptr }
- .set_custom_element_registry_association(imported_shadow, association);
- }
-
fn build_fragment_from_html_with_context_mode(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
@@ -607,6 +540,7 @@ impl DocumentRuntime {
custom_element_upgrade_timing: HtmlFragmentCustomElementUpgradeTiming,
context_mode: HtmlFragmentParserContextMode,
scripting_enabled: bool,
+ allow_declarative_shadow_roots: bool,
) -> Option<DomHandle> {
let first_node_index = self.dom_host().dom().len();
let parser = HtmlParser::with_scripting_enabled(scripting_enabled);
@@ -625,73 +559,80 @@ impl DocumentRuntime {
{
context_local_name = "body".to_owned();
}
- let parsed = parser.parse_fragment_without_declarative_shadow_roots(
- self.document_url().clone(),
- &context_namespace,
- &context_local_name,
- html.to_owned(),
- );
let is_frameset_context = context_namespace == "http://www.w3.org/1999/xhtml"
&& context_local_name.eq_ignore_ascii_case("frameset");
let registry_association =
self.fragment_context_custom_element_registry_association(host_ptr, context_handle);
- let fragment = self.create_document_fragment();
- self.initialize_new_native_node_owner_document(document_handle, fragment)
- .map(|_| ())?;
- let preserves_html_context_wrappers = custom_element_upgrade_timing
- == HtmlFragmentCustomElementUpgradeTiming::AfterInsertion
- && context_namespace == "http://www.w3.org/1999/xhtml"
- && context_local_name.eq_ignore_ascii_case("html");
- let source_root = if preserves_html_context_wrappers {
- let document_root = parsed.document_node_id();
- parsed
- .child_ids(document_root)
- .find(|child| {
- parsed
- .node(*child)
- .is_some_and(|node| node.is_html_element_named("html"))
- })
- .unwrap_or(document_root)
- } else {
- parsed.body_node_id().unwrap_or_else(|| {
- let document_root = parsed.document_node_id();
- let document_children = parsed.child_ids(document_root).collect::<Vec<_>>();
- if document_children.len() == 1
- && parsed
- .node(document_children[0])
- .is_some_and(|node| node.is_html_element_named("html"))
- {
- document_children[0]
- } else {
- document_root
- }
- })
- };
- for child in parsed.child_ids(source_root) {
- if parsed.node(child).is_some_and(|node| {
+ let fragment = self.create_document_fragment_for_document(document_handle);
+ let finish_signals = self.with_dom_host_parse_step(|runtime| {
+ let mut mutation_owner = DocumentWriteParserMutationOwner {
+ runtime,
+ scope,
+ host_ptr,
+ target: DocumentWriteParserMutationTarget::DetachedFragment {
+ owner_document: document_handle,
+ },
+ };
+ parser.parse_fragment_into_live_dom(
+ mutation_owner.runtime.document_url().clone(),
+ fragment,
+ document_handle,
+ context_handle,
+ &context_namespace,
+ &context_local_name,
+ html,
+ &mut mutation_owner,
+ allow_declarative_shadow_roots,
+ )
+ });
+ let synthetic_html_root = self.dom_host().child_handles(fragment).find(|child| {
+ self.dom_host()
+ .node(*child)
+ .is_some_and(|node| node.is_html_element_named("html"))
+ });
+ let source_root = synthetic_html_root.unwrap_or(fragment);
+ let source_children = self
+ .dom_host()
+ .child_handles(source_root)
+ .collect::<Vec<_>>();
+ let mut fragment_roots = Vec::with_capacity(source_children.len());
+ for child in source_children {
+ if self.dom_host().node(child).is_some_and(|node| {
Self::frameset_fragment_child_is_ignored(is_frameset_context, node)
}) {
+ let _ = self.dom_host_mut().remove_child(source_root, child);
continue;
}
- let imported =
- self.dom_host_mut()
- .import_foreign_node(document_handle, &parsed, child, true)?;
+ if source_root != fragment
+ && !self
+ .dom_host_mut()
+ .append_child_without_mutation_effects(fragment, child)
+ {
+ return None;
+ }
self.set_fragment_root_custom_element_registry_association(
host_ptr,
- imported,
+ child,
registry_association,
);
- self.set_fragment_null_registry_associations_from_native_dom(
- host_ptr, &parsed, child, imported,
- );
self.dom_host_mut()
- .set_subtree_script_already_started(imported, scripts_already_started);
- let _ = self.dom_host_mut().append_child(fragment, imported);
- if custom_element_upgrade_timing
- == HtmlFragmentCustomElementUpgradeTiming::InReturnedFragment
- && !custom_elements::upgrade_subtree_if_defined(scope, host_ptr, imported)
- {
- return None;
+ .set_subtree_script_already_started(child, scripts_already_started);
+ fragment_roots.push(child);
+ }
+ if source_root != fragment {
+ let _ = self.dom_host_mut().remove_child(fragment, source_root);
+ }
+ custom_elements::apply_parser_created_null_registry_associations(
+ host_ptr,
+ &finish_signals.parser_created_null_registry_elements,
+ );
+ if custom_element_upgrade_timing
+ == HtmlFragmentCustomElementUpgradeTiming::InReturnedFragment
+ {
+ for root in fragment_roots {
+ if !custom_elements::upgrade_subtree_if_defined(scope, host_ptr, root) {
+ return None;
+ }
}
}
unsafe { &mut *host_ptr }.capture_node_creation_stack_traces_since(scope, first_node_index);
@@ -717,6 +658,7 @@ impl DocumentRuntime {
HtmlFragmentCustomElementUpgradeTiming::InReturnedFragment,
HtmlFragmentParserContextMode::RangeCreateContextualFragment,
scripting_enabled,
+ false,
)
}
@@ -741,6 +683,7 @@ impl DocumentRuntime {
custom_element_upgrade_timing,
HtmlFragmentParserContextMode::Standard,
scripting_enabled,
+ false,
)
}
@@ -753,92 +696,19 @@ impl DocumentRuntime {
html: &str,
custom_element_upgrade_timing: HtmlFragmentCustomElementUpgradeTiming,
) -> Option<DomHandle> {
- let first_node_index = self.dom_host().dom().len();
let scripting_enabled = unsafe { &*host_ptr }.document_scripting_enabled(document_handle);
- let parser = HtmlParser::with_scripting_enabled(scripting_enabled);
- let context_node = self.dom_host().node(context_handle);
- let context_namespace = context_node
- .and_then(Node::namespace)
- .unwrap_or("http://www.w3.org/1999/xhtml")
- .to_owned();
- let context_local_name = context_node
- .and_then(Node::local_name)
- .unwrap_or("body")
- .to_owned();
- let parsed = parser.parse_fragment_dom_host(
- self.document_url().clone(),
- &context_namespace,
- &context_local_name,
- html.to_owned(),
- );
- let is_frameset_context = context_namespace == "http://www.w3.org/1999/xhtml"
- && context_local_name.eq_ignore_ascii_case("frameset");
- let registry_association =
- self.fragment_context_custom_element_registry_association(host_ptr, context_handle);
- let fragment = self.create_document_fragment();
- self.initialize_new_native_node_owner_document(document_handle, fragment)
- .map(|_| ())?;
- let preserves_html_context_wrappers = custom_element_upgrade_timing
- == HtmlFragmentCustomElementUpgradeTiming::AfterInsertion
- && context_namespace == "http://www.w3.org/1999/xhtml"
- && context_local_name.eq_ignore_ascii_case("html");
- let source_root = if preserves_html_context_wrappers {
- let document_root = parsed.document_handle();
- parsed
- .child_handles(document_root)
- .find(|child| {
- parsed
- .node(*child)
- .is_some_and(|node| node.is_html_element_named("html"))
- })
- .unwrap_or(document_root)
- } else {
- parsed.dom().body_node_id().unwrap_or_else(|| {
- let document_root = parsed.document_handle();
- let document_children = parsed.child_handles(document_root).collect::<Vec<_>>();
- if document_children.len() == 1
- && parsed
- .node(document_children[0])
- .is_some_and(|node| node.is_html_element_named("html"))
- {
- document_children[0]
- } else {
- document_root
- }
- })
- };
- for child in parsed.child_handles(source_root) {
- if parsed.node(child).is_some_and(|node| {
- Self::frameset_fragment_child_is_ignored(is_frameset_context, node)
- }) {
- continue;
- }
- let imported = self.dom_host_mut().import_foreign_node_with_shadow_roots(
- document_handle,
- &parsed,
- child,
- true,
- )?;
- self.set_fragment_root_custom_element_registry_association(
- host_ptr,
- imported,
- registry_association,
- );
- self.set_fragment_null_registry_associations_from_dom_host(
- host_ptr, &parsed, child, imported,
- );
- self.dom_host_mut()
- .set_subtree_script_already_started(imported, true);
- let _ = self.dom_host_mut().append_child(fragment, imported);
- if custom_element_upgrade_timing
- == HtmlFragmentCustomElementUpgradeTiming::InReturnedFragment
- && !custom_elements::upgrade_subtree_if_defined(scope, host_ptr, imported)
- {
- return None;
- }
- }
- unsafe { &mut *host_ptr }.capture_node_creation_stack_traces_since(scope, first_node_index);
- Some(fragment)
+ self.build_fragment_from_html_with_context_mode(
+ scope,
+ host_ptr,
+ document_handle,
+ context_handle,
+ html,
+ true,
+ custom_element_upgrade_timing,
+ HtmlFragmentParserContextMode::Standard,
+ scripting_enabled,
+ true,
+ )
}
fn is_template_contents_fragment(&self, handle: DomHandle) -> bool {
@@ -1838,6 +1708,7 @@ impl DocumentRuntime {
runtime,
scope,
host_ptr,
+ target: DocumentWriteParserMutationTarget::LiveDocument,
};
match input {
DocumentWriteParserPumpInput::Inserted(chunk) => stream
@@ -2690,17 +2561,6 @@ fn record_document_write_modulepreload_warning(
}
}
-fn source_node_has_null_registry_attribute(node: Option<&Node>) -> bool {
- node.and_then(Node::as_element).is_some_and(|element| {
- element.attributes().iter().any(|attribute| {
- attribute.namespace().is_empty()
- && attribute
- .local_name()
- .eq_ignore_ascii_case("customelementregistry")
- })
- })
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/moli-renderer-v8/src/document_runtime/dom_facade.rs b/moli-renderer-v8/src/document_runtime/dom_facade.rs
index 9b2387452..0e21f44d7 100644
--- a/moli-renderer-v8/src/document_runtime/dom_facade.rs
+++ b/moli-renderer-v8/src/document_runtime/dom_facade.rs
@@ -362,38 +362,52 @@ impl DocumentRuntime {
}
}
- pub(crate) fn create_text_node_in_live_dom_host(&mut self, text: String) -> DomHandle {
+ pub(crate) fn create_text_node_for_document_in_live_dom_host(
+ &mut self,
+ document_handle: DomHandle,
+ text: String,
+ ) -> DomHandle {
self.dom_host_mut_for_active_parser_step()
- .create_text_node(&text)
+ .create_text_node_for_document(document_handle, &text)
}
- pub(crate) fn create_comment_in_live_dom_host(&mut self, text: String) -> DomHandle {
+ pub(crate) fn create_comment_for_document_in_live_dom_host(
+ &mut self,
+ document_handle: DomHandle,
+ text: String,
+ ) -> DomHandle {
self.dom_host_mut_for_active_parser_step()
- .create_comment(&text)
+ .create_comment_for_document(document_handle, &text)
}
- pub(crate) fn create_processing_instruction_in_live_dom_host(
+ pub(crate) fn create_processing_instruction_for_document_in_live_dom_host(
&mut self,
+ document_handle: DomHandle,
target: String,
data: String,
) -> DomHandle {
self.dom_host_mut_for_active_parser_step()
- .create_processing_instruction(&target, &data)
+ .create_processing_instruction_for_document(document_handle, &target, &data)
}
- pub(crate) fn create_cdata_section_in_live_dom_host(&mut self, data: String) -> DomHandle {
+ pub(crate) fn create_cdata_section_for_document_in_live_dom_host(
+ &mut self,
+ document_handle: DomHandle,
+ data: String,
+ ) -> DomHandle {
self.dom_host_mut_for_active_parser_step()
- .create_cdata_section(&data)
+ .create_cdata_section_for_document(document_handle, &data)
}
- pub(crate) fn create_document_type_in_live_dom_host(
+ pub(crate) fn create_document_type_for_document_in_live_dom_host(
&mut self,
+ document_handle: DomHandle,
name: String,
public_id: String,
system_id: String,
) -> DomHandle {
self.dom_host_mut_for_active_parser_step()
- .create_document_type(&name, &public_id, &system_id)
+ .create_document_type_for_document(document_handle, &name, &public_id, &system_id)
}
pub(crate) fn prepend_text_to_text_node_in_live_dom_host(
@@ -583,17 +597,6 @@ impl DocumentRuntime {
.create_document_fragment_for_document(document_handle)
}
- pub(in crate::document_runtime) fn initialize_new_native_node_owner_document(
- &mut self,
- document_handle: DomHandle,
- handle: DomHandle,
- ) -> Option<DomHandle> {
- // This is creation-time owner assignment for a freshly created native
- // node. User-visible adoption must go through adopt_node(...), which
- // snapshots registry/adoptedCallback side effects before mutating.
- self.dom_host.adopt_node(document_handle, handle)
- }
-
pub(crate) fn create_detached_html_document(&mut self) -> DomHandle {
self.dom_host.create_detached_html_document()
}
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 7a209a6a4..04ec6fa99 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
@@ -295,33 +295,48 @@ impl ParserDomMutationConsumer for ChildFrameLiveParserOwner<'_, '_, '_> {
.add_attrs_if_missing_for_parser(node_id, attrs);
}
- fn create_text_node(&mut self, text: String) -> DomHandle {
- self.host.dom_host_mut().create_text_node(&text)
+ fn create_text_node(&mut self, document_handle: DomHandle, text: String) -> DomHandle {
+ self.host
+ .dom_host_mut()
+ .create_text_node_for_document(document_handle, &text)
}
- fn create_comment(&mut self, text: String) -> DomHandle {
- self.host.dom_host_mut().create_comment(&text)
+ fn create_comment(&mut self, document_handle: DomHandle, text: String) -> DomHandle {
+ self.host
+ .dom_host_mut()
+ .create_comment_for_document(document_handle, &text)
}
- fn create_processing_instruction(&mut self, target: String, data: String) -> DomHandle {
+ fn create_processing_instruction(
+ &mut self,
+ document_handle: DomHandle,
+ target: String,
+ data: String,
+ ) -> DomHandle {
self.host
.dom_host_mut()
- .create_processing_instruction(&target, &data)
+ .create_processing_instruction_for_document(document_handle, &target, &data)
}
- fn create_cdata_section(&mut self, data: String) -> DomHandle {
- self.host.dom_host_mut().create_cdata_section(&data)
+ fn create_cdata_section(&mut self, document_handle: DomHandle, data: String) -> DomHandle {
+ self.host
+ .dom_host_mut()
+ .create_cdata_section_for_document(document_handle, &data)
}
fn create_document_type(
&mut self,
+ document_handle: DomHandle,
name: String,
public_id: String,
system_id: String,
) -> DomHandle {
- self.host
- .dom_host_mut()
- .create_document_type(&name, &public_id, &system_id)
+ self.host.dom_host_mut().create_document_type_for_document(
+ document_handle,
+ &name,
+ &public_id,
+ &system_id,
+ )
}
fn prepend_text_to_text_node(&mut self, node_id: DomHandle, text: String) {
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 03790eaaa..b0c6d120d 100644
--- a/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs
@@ -235,39 +235,58 @@ impl ParserDomMutationConsumer for PhaseOneParserOwner<'_> {
.add_attrs_if_missing_for_parser_in_live_dom_host(node_id, attrs);
}
- fn create_text_node(&mut self, text: String) -> NativeNodeId {
+ fn create_text_node(&mut self, document_handle: NativeNodeId, text: String) -> NativeNodeId {
self.vm
.document_runtime
- .create_text_node_in_live_dom_host(text)
+ .create_text_node_for_document_in_live_dom_host(document_handle, text)
}
- fn create_comment(&mut self, text: String) -> NativeNodeId {
+ fn create_comment(&mut self, document_handle: NativeNodeId, text: String) -> NativeNodeId {
self.vm
.document_runtime
- .create_comment_in_live_dom_host(text)
+ .create_comment_for_document_in_live_dom_host(document_handle, text)
}
- fn create_processing_instruction(&mut self, target: String, data: String) -> NativeNodeId {
+ fn create_processing_instruction(
+ &mut self,
+ document_handle: NativeNodeId,
+ target: String,
+ data: String,
+ ) -> NativeNodeId {
self.vm
.document_runtime
- .create_processing_instruction_in_live_dom_host(target, data)
+ .create_processing_instruction_for_document_in_live_dom_host(
+ document_handle,
+ target,
+ data,
+ )
}
- fn create_cdata_section(&mut self, data: String) -> NativeNodeId {
+ fn create_cdata_section(
+ &mut self,
+ document_handle: NativeNodeId,
+ data: String,
+ ) -> NativeNodeId {
self.vm
.document_runtime
- .create_cdata_section_in_live_dom_host(data)
+ .create_cdata_section_for_document_in_live_dom_host(document_handle, data)
}
fn create_document_type(
&mut self,
+ document_handle: NativeNodeId,
name: String,
public_id: String,
system_id: String,
) -> NativeNodeId {
self.vm
.document_runtime
- .create_document_type_in_live_dom_host(name, public_id, system_id)
+ .create_document_type_for_document_in_live_dom_host(
+ document_handle,
+ name,
+ public_id,
+ system_id,
+ )
}
fn prepend_text_to_text_node(&mut self, node_id: NativeNodeId, text: String) {
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements.rs
index 485cef4d5..e62cf3c94 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements.rs
@@ -2901,6 +2901,49 @@ fn scoped_registry_define_upgrades_associated_connected_nodes() {
assert_eq!(result, "true|true|true|true|true|true|direct,shadow");
}
+#[test]
+fn fragment_html_skips_redundant_default_registry_associations() {
+ let mut vm = new_storage_test_vm("https://example.com/");
+
+ let setup = vm
+ .eval(
+ r#"
+ (() => {
+ const container = document.createElement("div");
+ window.__moliDefaultRegistryContainer = container;
+ return container.customElementRegistry === customElements;
+ })()
+ "#,
+ )
+ .expect("default registry fragment setup should evaluate");
+ assert_eq!(setup, "true");
+ let associations_before = vm.custom_element_registry_association_count_for_test();
+
+ let result = vm
+ .eval(
+ r#"
+ (() => {
+ const container = window.__moliDefaultRegistryContainer;
+ container.innerHTML = "<div></div>".repeat(128);
+ return [
+ container.children.length,
+ Array.from(container.children).every(
+ child => child.customElementRegistry === customElements
+ )
+ ].join("|");
+ })()
+ "#,
+ )
+ .expect("default registry fragment should evaluate");
+
+ assert_eq!(result, "128|true");
+ assert_eq!(
+ vm.custom_element_registry_association_count_for_test(),
+ associations_before,
+ "fragment roots using their owner document's default registry should not need explicit associations"
+ );
+}
+
#[test]
fn fragment_html_uses_context_custom_element_registry_association() {
let mut vm = new_storage_test_vm("https://example.com/");