diff --git a/moli-renderer-v8/src/custom_elements.rs b/moli-renderer-v8/src/custom_elements.rs index 0bb6ce3b10a..3863d41b62a 100644 --- a/moli-renderer-v8/src/custom_elements.rs +++ b/moli-renderer-v8/src/custom_elements.rs @@ -83,13 +83,10 @@ pub(crate) use attribute_lifecycle::{ }; pub(crate) use connected_lifecycle::{ enqueue_connected_callback, enqueue_connected_move_callback, enqueue_disconnected_callback, - enqueue_disconnected_callback_unless_pending, }; pub(crate) use connected_subtree_lifecycle::enqueue_connected_and_form_callbacks_for_already_upgraded_subtrees; mod disconnected_subtree_lifecycle; -pub(crate) use disconnected_subtree_lifecycle::{ - dispatch_disconnected_callbacks_for_subtree, enqueue_disconnected_callbacks_for_subtree, -}; +pub(crate) use disconnected_subtree_lifecycle::enqueue_disconnected_callbacks_for_subtree; pub(crate) use lifecycle::call_lifecycle_callback; mod parser_handoff; mod parser_handoff_attributes; diff --git a/moli-renderer-v8/src/custom_elements/connected_lifecycle.rs b/moli-renderer-v8/src/custom_elements/connected_lifecycle.rs index 2035020b866..c741117bc0a 100644 --- a/moli-renderer-v8/src/custom_elements/connected_lifecycle.rs +++ b/moli-renderer-v8/src/custom_elements/connected_lifecycle.rs @@ -57,20 +57,6 @@ pub(crate) fn enqueue_disconnected_callback( ) } -pub(crate) fn enqueue_disconnected_callback_unless_pending( - scope: &mut v8::PinScope<'_, '_>, - host_ptr: *mut PageScriptHost, - handle: DomHandle, -) -> bool { - if unsafe { &*host_ptr } - .custom_element_reactions() - .pending_reactions_end_with(handle, &CustomElementReaction::Disconnected) - { - return false; - } - enqueue_disconnected_callback(scope, host_ptr, handle) -} - pub(crate) fn enqueue_connected_move_callback( scope: &mut v8::PinScope<'_, '_>, host_ptr: *mut PageScriptHost, diff --git a/moli-renderer-v8/src/custom_elements/definition_state.rs b/moli-renderer-v8/src/custom_elements/definition_state.rs index a32d3b20fc2..a70705f3494 100644 --- a/moli-renderer-v8/src/custom_elements/definition_state.rs +++ b/moli-renderer-v8/src/custom_elements/definition_state.rs @@ -65,6 +65,10 @@ impl CustomElementStore { .has_pending_wrapper_for(scope, new_target) } + pub(crate) fn upgraded_handles(&self) -> impl Iterator + '_ { + self.upgraded_handles.iter().copied() + } + pub(crate) fn is_upgraded_handle(&self, handle: DomHandle) -> bool { self.upgraded_handles.contains(&handle) } diff --git a/moli-renderer-v8/src/custom_elements/disconnected_subtree_lifecycle.rs b/moli-renderer-v8/src/custom_elements/disconnected_subtree_lifecycle.rs index 2a7f0389870..8b1e0f364aa 100644 --- a/moli-renderer-v8/src/custom_elements/disconnected_subtree_lifecycle.rs +++ b/moli-renderer-v8/src/custom_elements/disconnected_subtree_lifecycle.rs @@ -1,25 +1,7 @@ use super::super::{document_runtime::DomHandle, native_bridge::PageScriptHost}; use super::connected_lifecycle::enqueue_disconnected_callback; -use super::reactions::with_custom_element_reaction_scope; use super::traversal::collect_shadow_including_subtree_handles; -pub(crate) fn dispatch_disconnected_callbacks_for_subtree( - scope: &mut v8::PinScope<'_, '_>, - host_ptr: *mut PageScriptHost, - root: DomHandle, -) { - if unsafe { &*host_ptr }.custom_elements_subtree_lifecycle_quiescent() { - return; - } - let mut handles = Vec::new(); - collect_shadow_including_subtree_handles(host_ptr, root, &mut handles); - with_custom_element_reaction_scope(scope, host_ptr, |scope| { - for handle in handles { - enqueue_disconnected_callback(scope, host_ptr, handle); - } - }); -} - pub(crate) fn enqueue_disconnected_callbacks_for_subtree( scope: &mut v8::PinScope<'_, '_>, host_ptr: *mut PageScriptHost, diff --git a/moli-renderer-v8/src/custom_elements/form_lifecycle_scans.rs b/moli-renderer-v8/src/custom_elements/form_lifecycle_scans.rs index 5c4a205335d..6ab6dac30b5 100644 --- a/moli-renderer-v8/src/custom_elements/form_lifecycle_scans.rs +++ b/moli-renderer-v8/src/custom_elements/form_lifecycle_scans.rs @@ -47,17 +47,15 @@ pub(crate) fn enqueue_form_association_callbacks_for_all( scope: &mut v8::PinScope<'_, '_>, host_ptr: *mut PageScriptHost, ) { - let handles = unsafe { &*host_ptr } - .dom_host() - .nodes() - .iter() - .enumerate() - .filter_map(|(index, _)| { - let handle = DomHandle::new(index); - is_form_associated_custom_element_handle(unsafe { &*host_ptr }, handle) - .then_some(handle) - }) + let host = unsafe { &*host_ptr }; + // Only upgraded elements can receive reactions. Enumerating their native + // stores keeps ID changes independent of unrelated nodes in the DOM arena. + let mut handles = host + .upgraded_custom_element_handles() + .filter(|&handle| is_form_associated_custom_element_handle(host, handle)) .collect::>(); + handles.sort_unstable_by_key(|handle| handle.index()); + handles.dedup(); for handle in handles { enqueue_form_association_callback_if_needed(scope, host_ptr, handle); } diff --git a/moli-renderer-v8/src/custom_elements/reaction_queue.rs b/moli-renderer-v8/src/custom_elements/reaction_queue.rs index 348c8a8dddc..b2a02e759c6 100644 --- a/moli-renderer-v8/src/custom_elements/reaction_queue.rs +++ b/moli-renderer-v8/src/custom_elements/reaction_queue.rs @@ -55,16 +55,6 @@ impl CustomElementReactionCoordinator { needs_backup_microtask } - pub(super) fn pending_reactions_end_with( - &self, - handle: DomHandle, - reaction: &CustomElementReaction, - ) -> bool { - self.element_reactions - .get(&handle) - .is_some_and(|queue| queue.pending_reactions_end_with(reaction)) - } - pub(super) fn next_current_element(&mut self) -> Option { self.stack.last_mut()?.next() } diff --git a/moli-renderer-v8/src/custom_elements/reaction_queue_storage.rs b/moli-renderer-v8/src/custom_elements/reaction_queue_storage.rs index a388cc923f0..ff3766fc6c2 100644 --- a/moli-renderer-v8/src/custom_elements/reaction_queue_storage.rs +++ b/moli-renderer-v8/src/custom_elements/reaction_queue_storage.rs @@ -61,13 +61,4 @@ impl ElementReactionQueue { pub(super) fn is_drained(&self) -> bool { self.index >= self.reactions.len() } - - pub(super) fn pending_reactions_end_with(&self, reaction: &CustomElementReaction) -> bool { - self.reactions - .iter() - .skip(self.index) - .rev() - .find_map(Option::as_ref) - == Some(reaction) - } } diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands.rs b/moli-renderer-v8/src/document_runtime/mutation_commands.rs index 6f45bbbdec2..5828be95a78 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands.rs @@ -46,13 +46,13 @@ enum TextContentReactionPolicy { AppendToCurrentQueue, } -struct DomDebuggerTreeInsertionEffects { +struct TreeInsertionEffects { effects: DomMutationEffects, prepublished_removals: Vec, } impl DocumentRuntime { - fn tree_insertion_effects_with_dom_debugger( + fn tree_insertion_effects_for_roots( &mut self, host_ptr: *mut PageScriptHost, parent: DomHandle, @@ -60,9 +60,13 @@ impl DocumentRuntime { insertion_roots: &[DomHandle], reference_child: Option, is_atomic_move: bool, - ) -> Option { + ) -> Option { let host = unsafe { &mut *host_ptr }; - if !host.has_dom_debugger_dom_breakpoints() { + let is_fragment = self + .dom_host + .node(child) + .is_some_and(Node::is_document_fragment); + if !host.has_dom_debugger_dom_breakpoints() && !is_fragment { return None; } @@ -72,7 +76,7 @@ impl DocumentRuntime { // while retaining the existing combined-effects fast path when no DOM // breakpoint is installed. if insertion_roots.is_empty() { - return Some(DomDebuggerTreeInsertionEffects { + return Some(TreeInsertionEffects { effects: self.insert_before_effects_in_structural_scope_with_state_preservation( parent, child, @@ -103,7 +107,7 @@ impl DocumentRuntime { &mut prepublished_removals, is_atomic_move, ) { - return Some(DomDebuggerTreeInsertionEffects { + return Some(TreeInsertionEffects { effects, prepublished_removals, }); @@ -118,7 +122,7 @@ impl DocumentRuntime { is_atomic_move, ); if !inserted.did_change() { - return Some(DomDebuggerTreeInsertionEffects { + return Some(TreeInsertionEffects { effects, prepublished_removals, }); @@ -133,7 +137,7 @@ impl DocumentRuntime { &lifecycle_connected_before, &mut effects, ); - Some(DomDebuggerTreeInsertionEffects { + Some(TreeInsertionEffects { effects, prepublished_removals, }) @@ -294,12 +298,42 @@ impl DocumentRuntime { value: &str, reaction_policy: TextContentReactionPolicy, ) -> bool { + if matches!(reaction_policy, TextContentReactionPolicy::DispatchNow) { + return custom_elements::with_custom_element_reaction_scope(scope, host_ptr, |scope| { + self.set_text_content_with_reaction_policy( + scope, + host_ptr, + handle, + value, + TextContentReactionPolicy::AppendToCurrentQueue, + ) + }); + } let started = dom_binding_timing_started(); - let mut break_after_character_data_change = false; - let mut prepublished_removals = Vec::new(); - if unsafe { &*host_ptr }.has_dom_debugger_dom_breakpoints() { - let node_type = self.dom_host.node(handle).map(Node::node_type); - if node_type.is_some_and(|node_type| { + let node_type = self.dom_host.node(handle).map(Node::node_type); + if node_type.is_some_and(|node_type| { + matches!(node_type, NodeType::Element | NodeType::DocumentFragment) + }) { + let node = if value.is_empty() { + if self.dom_host.first_child(handle).is_none() { + return false; + } + None + } else { + let Some(document) = self.dom_host.owner_document_handle(handle) else { + return false; + }; + Some(self.create_text_node_for_document(document, value)) + }; + let changed = self.replace_all_children_appending_to_current_reaction_queue( + scope, host_ptr, handle, node, false, + ); + record_dom_binding_timing("dom.setTextContent", started); + return changed; + } + let break_after_character_data_change = unsafe { &*host_ptr } + .has_dom_debugger_dom_breakpoints() + && node_type.is_some_and(|node_type| { matches!( node_type, NodeType::Text @@ -307,70 +341,18 @@ impl DocumentRuntime { | NodeType::ProcessingInstruction | NodeType::Comment ) - }) { - break_after_character_data_change = - self.dom_host.node(handle).and_then(Node::node_value) != Some(value); - } else if node_type.is_some_and(|node_type| { - matches!(node_type, NodeType::Element | NodeType::DocumentFragment) - }) { - let children = self.dom_host.child_handles(handle).collect::>(); - for child in children { - prepublished_removals.extend( - self.break_on_dom_debugger_before_tree_removal(host_ptr, handle, child), - ); - } - if !value.is_empty() { - unsafe { &mut *host_ptr }.break_on_dom_debugger_will_insert_dom_node(handle); - } - } - } - let disconnected_lifecycle_roots = self - .dom_host - .child_handles(handle) - .filter(|child| { - self.dom_host.is_connected(*child) - || custom_elements::is_shadow_including_rooted_in_document( - &self.dom_host, - *child, - ) }) - .collect::>(); + && self.dom_host.node(handle).and_then(Node::node_value) != Some(value); let effects = self.dom_host.set_text_content_effects(handle, value); if break_after_character_data_change && effects.did_change() { unsafe { &mut *host_ptr }.break_on_dom_debugger_character_data_modified(handle); } - let changed = self.apply_runtime_mutation_effects_with_prepublished_removals( + let changed = self.apply_runtime_mutation_effects( scope, host_ptr, effects, RuntimeMutationOptions::js_dom_api(), - prepublished_removals, ); - if changed { - for root in disconnected_lifecycle_roots { - if self.dom_host.is_connected(root) - || custom_elements::is_shadow_including_rooted_in_document(&self.dom_host, root) - { - continue; - } - unsafe { &mut *host_ptr }.mark_disconnected_shadow_roots_in_subtree(root); - match reaction_policy { - TextContentReactionPolicy::DispatchNow => { - custom_elements::dispatch_disconnected_callbacks_for_subtree( - scope, host_ptr, root, - ); - } - TextContentReactionPolicy::AppendToCurrentQueue => { - custom_elements::enqueue_disconnected_callbacks_for_subtree( - scope, host_ptr, root, - ); - } - } - PageScriptHost::drop_child_browsing_context_subtree_with_window_realm( - scope, host_ptr, root, - ); - } - } record_dom_binding_timing("dom.setTextContent", started); changed } diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/selectedcontent.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/selectedcontent.rs index d1e30e5557d..51d8e9990d9 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/selectedcontent.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/selectedcontent.rs @@ -48,13 +48,6 @@ impl DocumentRuntime { run_post_connection_steps: bool, prepublished_removals: Vec, ) -> bool { - if effects.did_change() && !options.dispatch_atomic_move_callbacks { - self.discard_child_contexts_before_reinsertion_followups( - scope, - host_ptr, - insertion_plan, - ); - } if !run_post_connection_steps || !insertion_plan.requires_interleaved_post_connection_steps() { @@ -463,11 +456,11 @@ impl DocumentRuntime { } } - self.replace_all_children_with_node_appending_to_current_reaction_queue( + self.replace_all_children_appending_to_current_reaction_queue( scope, host_ptr, selectedcontent, - fragment, + Some(fragment), false, ) } diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/custom_element_lifecycle.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/custom_element_lifecycle.rs index 7d6ac77c885..c4cda6c318a 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/custom_element_lifecycle.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/custom_element_lifecycle.rs @@ -31,65 +31,6 @@ impl DocumentRuntime { enqueued } - pub(super) fn enqueue_custom_element_disconnected_callbacks_in_subtrees_unless_pending( - &mut self, - scope: &mut v8::PinScope<'_, '_>, - host_ptr: *mut PageScriptHost, - roots: &[DomHandle], - ) -> bool { - if unsafe { &*host_ptr }.custom_elements_subtree_lifecycle_quiescent() { - return false; - } - let mut enqueued = false; - for &root in roots { - let mut handles = Vec::new(); - self.collect_subtree_handles_preorder(root, &mut handles); - for handle in handles { - if custom_elements::enqueue_disconnected_callback_unless_pending( - scope, host_ptr, handle, - ) { - enqueued = true; - } - } - } - enqueued - } - - pub(super) fn enqueue_custom_element_disconnected_callbacks_for_moved_roots_if_needed( - &mut self, - scope: &mut v8::PinScope<'_, '_>, - host_ptr: *mut PageScriptHost, - roots: &[DomHandle], - was_connected: bool, - ) { - if !was_connected { - return; - } - let disconnected_roots = roots - .iter() - .copied() - .filter(|root| !self.is_custom_element_lifecycle_connected(*root)) - .collect::>(); - if disconnected_roots.is_empty() { - return; - } - for root in disconnected_roots { - unsafe { &mut *host_ptr }.mark_disconnected_shadow_roots_in_subtree(root); - unsafe { &mut *host_ptr } - .clear_pending_pointer_capture_targets_in_disconnected_subtree(root); - let mut handles = Vec::new(); - self.collect_subtree_handles_preorder(root, &mut handles); - for handle in handles { - custom_elements::enqueue_disconnected_callback_unless_pending( - scope, host_ptr, handle, - ); - } - PageScriptHost::drop_child_browsing_context_subtree_with_window_realm( - scope, host_ptr, root, - ); - } - } - pub(super) fn enqueue_custom_element_connected_callbacks( &mut self, scope: &mut v8::PinScope<'_, '_>, @@ -160,6 +101,9 @@ impl DocumentRuntime { host_ptr: *mut PageScriptHost, root: DomHandle, ) -> bool { + if unsafe { &*host_ptr }.custom_elements_subtree_lifecycle_quiescent() { + return false; + } let mut handles = Vec::new(); self.collect_subtree_handles_preorder(root, &mut handles); let mut enqueued = false; @@ -181,10 +125,16 @@ impl DocumentRuntime { if roots.is_empty() || unsafe { &*host_ptr }.custom_elements_subtree_lifecycle_quiescent() { return false; } - if !roots - .iter() - .any(|root| self.subtree_contains_html_form(*root)) - { + // An ID on a non-form element can mask an external form= reference. + let changes_form_lookup = roots.iter().any(|&root| { + let mut handles = Vec::new(); + self.collect_subtree_handles_preorder(root, &mut handles); + handles.into_iter().any(|handle| { + self.dom_host.is_html_element_named(handle, "form") + || self.dom_host.get_attribute(handle, "id").is_some() + }) + }); + if !changes_form_lookup { return false; } custom_elements::enqueue_form_association_callbacks_for_all(scope, host_ptr); diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/focus.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/focus.rs index 944ef1db8cb..d0ffb897230 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/focus.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/focus.rs @@ -1,3 +1,7 @@ +use super::{ + policy::{TreeMutationSideEffectSource, TreeMutationSourceProfile}, + removal::TreeRemovalPlan, +}; use crate::{ document_runtime::{DocumentRuntime, DomHandle}, native_bridge::PageScriptHost, @@ -56,21 +60,26 @@ impl DocumentRuntime { handles } - pub(super) fn reset_focus_for_non_preserving_connected_move_before_insert( + pub(super) fn reset_focus_before_tree_removal( &mut self, scope: &mut v8::PinScope<'_, '_>, host_ptr: *mut PageScriptHost, - insertion_roots: &[DomHandle], - was_connected: bool, + removal_plan: &TreeRemovalPlan, + profile: TreeMutationSourceProfile, ) { - if !was_connected { - return; - } - let Some(active) = self.active_element_handle() else { - return; - }; - if self.focus_is_in_changing_subtrees(insertion_roots, active) { - crate::native_bridge::element::update_focus(scope, host_ptr, None); + // Focus events must still propagate through the old parent chain. + match profile.source { + TreeMutationSideEffectSource::JsDomApi => { + if let Some(active) = removal_plan.focus_reset_handle_before_remove { + crate::native_bridge::element::reset_focus_from_previous_handle_with_previous_focus_within( + scope, + host_ptr, + active, + removal_plan.focus_within_handles_before_remove.clone(), + ); + } + } + TreeMutationSideEffectSource::ParserTreeSink => {} } } } diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/form_control_state.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/form_control_state.rs index 7e823f6f875..379f8799fea 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/form_control_state.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/form_control_state.rs @@ -37,7 +37,7 @@ impl DocumentRuntime { element.selected() } - fn preserve_selectedness_for_options_removed_from_select( + pub(super) fn preserve_selectedness_for_options_removed_from_select( &mut self, scope: &mut v8::PinScope<'_, '_>, host_ptr: *mut PageScriptHost, diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion.rs index 32bc9ee5e17..e7211dbc1cc 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion.rs @@ -3,9 +3,10 @@ use super::super::{ }; use super::{ insertion_plan::{TreeInsertionPlanOptions, TreeInsertionSelectednessPolicy}, - policy::TreeMutationSourceProfile, + policy::{TreeMutationSourceProfile, TreeReactionDispatchPolicy}, }; use crate::{ + custom_elements, document_runtime::{DocumentRuntime, DomHandle}, dom::native::Node, mutation_coordinator::{ConnectedScriptMutationPolicy, RuntimeMutationOptions}, @@ -70,6 +71,23 @@ impl DocumentRuntime { child: DomHandle, source_profile: TreeMutationSourceProfile, ) -> bool { + if matches!( + source_profile.reaction_policy, + TreeReactionDispatchPolicy::DispatchNow + ) { + return custom_elements::with_custom_element_reaction_scope(scope, host_ptr, |scope| { + self.append_child_with_source_profile( + scope, + host_ptr, + parent, + child, + TreeMutationSourceProfile { + reaction_policy: TreeReactionDispatchPolicy::AppendToCurrentQueue, + ..source_profile + }, + ) + }); + } let cpu_profile_enabled = moli_trace::cpu_profile_enabled(); let total_started = cpu_profile_enabled.then(std::time::Instant::now); let started = dom_binding_timing_started(); @@ -88,6 +106,20 @@ impl DocumentRuntime { let fragment_us = fragment_started .map(|started| started.elapsed().as_micros()) .unwrap_or_default(); + let removal_started = cpu_profile_enabled.then(std::time::Instant::now); + if !self.remove_insertion_roots( + scope, + host_ptr, + parent, + child, + insertion_roots, + source_profile, + ) { + return false; + } + let removal_us = removal_started + .map(|started| started.elapsed().as_micros()) + .unwrap_or_default(); let plan_started = cpu_profile_enabled.then(std::time::Instant::now); let insertion_plan = self.tree_insertion_plan( parent, @@ -95,7 +127,6 @@ impl DocumentRuntime { host_ptr, TreeInsertionPlanOptions::insert( None, - fragment_children.is_some() && !self.dom_host.is_shadow_root(child), TreeInsertionSelectednessPolicy::CaptureAndRestore, ), ); @@ -103,36 +134,27 @@ impl DocumentRuntime { .map(|started| started.elapsed().as_micros()) .unwrap_or_default(); let subtree_node_count = insertion_plan.subtree_plan.node_count; - let was_connected = insertion_plan.was_lifecycle_connected_before_insert(); - let focus_started = cpu_profile_enabled.then(std::time::Instant::now); - self.reset_focus_for_non_preserving_connected_move_before_insert( - scope, - host_ptr, - insertion_plan.insertion_roots, - was_connected, - ); - let focus_us = focus_started - .map(|started| started.elapsed().as_micros()) - .unwrap_or_default(); let effects_started = cpu_profile_enabled.then(std::time::Instant::now); - let (mut effects, prepublished_removals) = match self - .tree_insertion_effects_with_dom_debugger( - host_ptr, - parent, - child, - insertion_plan.insertion_roots, - None, - false, - ) { + let (mut effects, prepublished_removals) = match self.tree_insertion_effects_for_roots( + host_ptr, + parent, + child, + insertion_plan.insertion_roots, + None, + false, + ) { Some(result) => (result.effects, result.prepublished_removals), None => ( self.append_child_effects_in_structural_scope(parent, child), Vec::new(), ), }; - if source_profile.suppress_observers { - effects.suppress_child_list_mutations_for_target(parent); - } + source_profile.apply_insertion_observer_policy( + &mut effects, + parent, + insertion_plan.insertion_roots, + self.dom_host.mutation_records_enabled(), + ); let effects_us = effects_started .map(|started| started.elapsed().as_micros()) .unwrap_or_default(); @@ -196,7 +218,7 @@ impl DocumentRuntime { parent_connected = self.dom_host.is_connected(parent), fragment_us, plan_us, - focus_us, + removal_us, effects_us, iterator_us, mutation_us, @@ -336,6 +358,27 @@ impl DocumentRuntime { connected_script_policy: ConnectedScriptMutationPolicy, source_profile: TreeMutationSourceProfile, ) -> bool { + if matches!( + source_profile.reaction_policy, + TreeReactionDispatchPolicy::DispatchNow + ) { + return custom_elements::with_custom_element_reaction_scope(scope, host_ptr, |scope| { + self.insert_before_with_nonce_handling( + scope, + host_ptr, + parent, + child, + reference_child, + hide_nonce_content_attributes, + is_atomic_move, + connected_script_policy, + TreeMutationSourceProfile { + reaction_policy: TreeReactionDispatchPolicy::AppendToCurrentQueue, + ..source_profile + }, + ) + }); + } let mutation_options = RuntimeMutationOptions::js_dom_api() .with_connected_script_policy(connected_script_policy) .with_nonce_hiding(hide_nonce_content_attributes) @@ -356,34 +399,36 @@ impl DocumentRuntime { Some(handles) => handles, None => std::slice::from_ref(&child), }; + if !is_atomic_move + && !self.remove_insertion_roots( + scope, + host_ptr, + parent, + child, + insertion_roots, + source_profile, + ) + { + return false; + } let insertion_plan = self.tree_insertion_plan( parent, insertion_roots, host_ptr, TreeInsertionPlanOptions::insert( reference_child, - fragment_children.is_some() && !self.dom_host.is_shadow_root(child), TreeInsertionSelectednessPolicy::CaptureAndRestore, ), ); let was_connected = insertion_plan.was_lifecycle_connected_before_insert(); - if !is_atomic_move { - self.reset_focus_for_non_preserving_connected_move_before_insert( - scope, - host_ptr, - insertion_plan.insertion_roots, - was_connected, - ); - } - let (mut effects, prepublished_removals) = match self - .tree_insertion_effects_with_dom_debugger( - host_ptr, - parent, - child, - insertion_plan.insertion_roots, - reference_child, - is_atomic_move, - ) { + let (mut effects, prepublished_removals) = match self.tree_insertion_effects_for_roots( + host_ptr, + parent, + child, + insertion_plan.insertion_roots, + reference_child, + is_atomic_move, + ) { Some(result) => (result.effects, result.prepublished_removals), None => ( self.insert_before_effects_in_structural_scope_with_state_preservation( @@ -395,9 +440,12 @@ impl DocumentRuntime { Vec::new(), ), }; - if source_profile.suppress_observers { - effects.suppress_child_list_mutations_for_target(parent); - } + source_profile.apply_insertion_observer_policy( + &mut effects, + parent, + insertion_plan.insertion_roots, + self.dom_host.mutation_records_enabled(), + ); if effects.did_change() && source_profile.queue_parser_details_toggle_events { for &root in insertion_plan.insertion_roots { crate::native_bridge::element::queue_parser_details_toggle_events_in_subtree( diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion_followups.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion_followups.rs index 55d434becb1..8be194c5bf6 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion_followups.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion_followups.rs @@ -148,24 +148,8 @@ impl DocumentRuntime { profile: TreeMutationSourceProfile, ) { let was_connected = insertion_plan.was_lifecycle_connected_before_insert(); - // Ordinary insertion removes a connected input before reinserting it, - // even when the node keeps its parent and position in the same document. - if was_connected - && !insertion_plan.inserting_fragment_children - && !profile.preserve_connection - { - self.enqueue_custom_element_disconnected_callbacks_in_subtrees_unless_pending( - scope, - host_ptr, - &insertion_plan.lifecycle_connected_roots_before_insert, - ); - } - self.enqueue_custom_element_disconnected_callbacks_for_moved_roots_if_needed( - scope, - host_ptr, - insertion_plan.insertion_roots, - was_connected, - ); + // Ordinary inputs have already run removal steps in this reaction + // scope. Parser and atomic moves retain their separate connection policy. custom_elements::apply_registry_association_retargets( host_ptr, &insertion_plan.adoption.custom_elements().registry_retargets, diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion_plan.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion_plan.rs index b90d6bc94c9..49084dd0483 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion_plan.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/insertion_plan.rs @@ -29,7 +29,6 @@ impl TreeInsertionPostConnectionStep { pub(in crate::document_runtime::mutation_commands) struct TreeInsertionPlan<'a> { pub(super) parent: DomHandle, pub(super) insertion_roots: &'a [DomHandle], - pub(super) inserting_fragment_children: bool, pub(super) lifecycle_connected_roots_before_insert: Vec, pub(super) adoption: TreeAdoptionPlan, pub(super) focus_reset_handle_before_insert: Option, @@ -45,12 +44,6 @@ pub(in crate::document_runtime::mutation_commands) struct TreeInsertionPlan<'a> Vec, } -#[derive(Clone, Copy)] -enum TreeInsertionLiveRangeMode { - Insert { reference_child: Option }, - Replace { old_child: DomHandle }, -} - #[derive(Clone, Copy)] pub(super) enum TreeInsertionSelectednessPolicy { Skip, @@ -58,8 +51,7 @@ pub(super) enum TreeInsertionSelectednessPolicy { } pub(super) struct TreeInsertionPlanOptions { - live_range_mode: TreeInsertionLiveRangeMode, - inserting_fragment_children: bool, + reference_child: Option, selectedness_policy: TreeInsertionSelectednessPolicy, } @@ -76,15 +68,6 @@ impl TreeInsertionPlan<'_> { } } -impl TreeInsertionLiveRangeMode { - fn reference_child(self) -> Option { - match self { - Self::Insert { reference_child } => reference_child, - Self::Replace { old_child } => Some(old_child), - } - } -} - impl TreeInsertionSelectednessPolicy { fn captures(self) -> bool { matches!(self, Self::CaptureAndRestore) @@ -94,23 +77,13 @@ impl TreeInsertionSelectednessPolicy { impl TreeInsertionPlanOptions { pub(super) fn insert( reference_child: Option, - inserting_fragment_children: bool, selectedness_policy: TreeInsertionSelectednessPolicy, ) -> Self { Self { - live_range_mode: TreeInsertionLiveRangeMode::Insert { reference_child }, - inserting_fragment_children, + reference_child, selectedness_policy, } } - - pub(super) fn replacement(old_child: DomHandle, inserting_fragment_children: bool) -> Self { - Self { - live_range_mode: TreeInsertionLiveRangeMode::Replace { old_child }, - inserting_fragment_children, - selectedness_policy: TreeInsertionSelectednessPolicy::CaptureAndRestore, - } - } } impl DocumentRuntime { @@ -121,25 +94,14 @@ impl DocumentRuntime { host_ptr: *mut PageScriptHost, options: TreeInsertionPlanOptions, ) -> TreeInsertionPlan<'a> { - let replaced_child = match options.live_range_mode { - TreeInsertionLiveRangeMode::Insert { .. } => None, - TreeInsertionLiveRangeMode::Replace { old_child } => Some(old_child), + let live_range_plan = if unsafe { &mut *host_ptr } + .needs_live_tree_boundary_updates(insertion_roots.iter().copied()) + { + Some(self.live_range_pre_insert_plan(parent, insertion_roots, options.reference_child)) + } else { + None }; - let removed_roots = insertion_roots.iter().copied().chain(replaced_child); - let live_range_plan = - if !unsafe { &mut *host_ptr }.needs_live_tree_boundary_updates(removed_roots) { - None - } else { - match options.live_range_mode { - TreeInsertionLiveRangeMode::Insert { reference_child } => Some( - self.live_range_pre_insert_plan(parent, insertion_roots, reference_child), - ), - TreeInsertionLiveRangeMode::Replace { old_child } => { - self.live_range_replace_plan(parent, insertion_roots, old_child) - } - } - }; - let reference_child = options.live_range_mode.reference_child(); + let reference_child = options.reference_child; let node_iterator_plan = if unsafe { &*host_ptr }.node_iterators_is_empty() { Vec::new() } else { @@ -178,7 +140,6 @@ impl DocumentRuntime { TreeInsertionPlan { parent, insertion_roots, - inserting_fragment_children: options.inserting_fragment_children, lifecycle_connected_roots_before_insert, adoption, focus_reset_handle_before_insert, diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/live_ranges.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/live_ranges.rs index f6810fc1355..af3fb67fe47 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/live_ranges.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/live_ranges.rs @@ -20,25 +20,6 @@ pub(super) struct LiveRangePreInsertPlan { } impl DocumentRuntime { - fn prospective_child_index( - &self, - parent: DomHandle, - excluded_children: &HashSet, - target: DomHandle, - ) -> Option { - let mut index = 0; - for candidate in self.dom_host.child_handles(parent) { - if excluded_children.contains(&candidate) { - continue; - } - if candidate == target { - return Some(index); - } - index += 1; - } - None - } - fn prospective_child_index_and_count( &self, parent: DomHandle, @@ -87,41 +68,6 @@ impl DocumentRuntime { } } - pub(super) fn live_range_replace_plan( - &self, - parent: DomHandle, - insertion_roots: &[DomHandle], - old_child: DomHandle, - ) -> Option { - let old_index = self.dom_host.child_index(parent, old_child)? as u32; - let mut removals = vec![LiveRangeRemoval { - parent, - child: old_child, - index: old_index, - previous_sibling: self.dom_host.node(old_child).and_then(Node::prev_sibling), - }]; - if insertion_roots != [old_child] { - removals.extend(insertion_roots.iter().filter_map(|child| { - let old_parent = self.dom_host.node(*child)?.parent_node()?; - let old_index = self.dom_host.child_index(old_parent, *child)? as u32; - Some(LiveRangeRemoval { - parent: old_parent, - child: *child, - index: old_index, - previous_sibling: self.dom_host.node(*child).and_then(Node::prev_sibling), - }) - })); - } - let excluded_children = insertion_roots.iter().copied().collect::>(); - let insertion_index = self - .prospective_child_index(parent, &excluded_children, old_child) - .unwrap_or(old_index as usize) as u32; - Some(LiveRangePreInsertPlan { - removals, - insertion_index, - }) - } - pub(super) fn apply_live_range_pre_insert_plan( &self, scope: &mut v8::PinScope<'_, '_>, diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/parser.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/parser.rs index 9aa89cc119c..9bf4a97419c 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/parser.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/parser.rs @@ -91,11 +91,7 @@ impl DocumentRuntime { parent, insertion_roots, host_ptr, - TreeInsertionPlanOptions::insert( - None, - fragment_children.is_some() && !self.dom_host.is_shadow_root(child), - TreeInsertionSelectednessPolicy::Skip, - ), + TreeInsertionPlanOptions::insert(None, TreeInsertionSelectednessPolicy::Skip), ); let effects = self.parser_append_child_effects_in_structural_scope(parent, child); if effects.did_change() { @@ -136,7 +132,6 @@ impl DocumentRuntime { host_ptr, TreeInsertionPlanOptions::insert( reference_child, - fragment_children.is_some() && !self.dom_host.is_shadow_root(child), TreeInsertionSelectednessPolicy::Skip, ), ); diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/policy.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/policy.rs index 5145d08d663..6e0a65492b1 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/policy.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/policy.rs @@ -1,3 +1,5 @@ +use crate::{document_runtime::DomHandle, dom::native::DomMutationEffects}; + #[derive(Clone, Copy)] pub(super) enum TreeMutationSideEffectSource { JsDomApi, @@ -16,6 +18,17 @@ pub(super) enum TreeNoncePolicy { PreserveInsertedContentAttributes, } +#[derive(Clone, Copy)] +pub(super) enum TreeMutationObserverPolicy { + Queue, + Suppress, + ReplaceChild { + removed: DomHandle, + previous_sibling: Option, + next_sibling: Option, + }, +} + #[derive(Clone, Copy)] pub(super) struct TreeMutationSourceProfile { pub(super) source: TreeMutationSideEffectSource, @@ -25,7 +38,7 @@ pub(super) struct TreeMutationSourceProfile { pub(super) upgrade_connected_subtrees: bool, pub(super) queue_parser_details_toggle_events: bool, pub(super) queue_resource_followups: bool, - pub(super) suppress_observers: bool, + pub(super) observers: TreeMutationObserverPolicy, } impl TreeNoncePolicy { @@ -60,7 +73,7 @@ impl TreeMutationSourceProfile { upgrade_connected_subtrees: true, queue_parser_details_toggle_events: false, queue_resource_followups: true, - suppress_observers: false, + observers: TreeMutationObserverPolicy::Queue, } } @@ -80,7 +93,7 @@ impl TreeMutationSourceProfile { upgrade_connected_subtrees: false, queue_parser_details_toggle_events: true, queue_resource_followups: true, - suppress_observers: false, + observers: TreeMutationObserverPolicy::Queue, } } @@ -110,12 +123,65 @@ impl TreeMutationSourceProfile { upgrade_connected_subtrees: false, queue_parser_details_toggle_events: true, queue_resource_followups: true, - suppress_observers: false, + observers: TreeMutationObserverPolicy::Queue, } } - pub(super) fn suppressing_observers(mut self) -> Self { - self.suppress_observers = true; - self + pub(super) fn suppressing_observers(self) -> Self { + Self { + observers: TreeMutationObserverPolicy::Suppress, + ..self + } + } + + pub(super) fn suppresses_observers(self) -> bool { + !matches!(self.observers, TreeMutationObserverPolicy::Queue) + } + + pub(super) fn replacing_child( + self, + removed: DomHandle, + previous_sibling: Option, + next_sibling: Option, + ) -> Self { + Self { + observers: TreeMutationObserverPolicy::ReplaceChild { + removed, + previous_sibling, + next_sibling, + }, + ..self + } + } + + pub(super) fn apply_insertion_observer_policy( + self, + effects: &mut DomMutationEffects, + parent: DomHandle, + roots: &[DomHandle], + records_enabled: bool, + ) { + if self.suppresses_observers() { + effects.suppress_child_list_mutations_for_target(parent); + } + if effects.did_change() + && records_enabled + && let TreeMutationObserverPolicy::ReplaceChild { + removed, + previous_sibling, + next_sibling, + } = self.observers + { + // replaceChild's combined record precedes insertion's script and + // selectedcontent post-connection steps. Replace-all queues its + // record only after insertion returns, using Suppress instead. + effects.queue_child_list_mutation( + parent, + roots, + &[removed], + previous_sibling, + next_sibling, + ); + } } } diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/removal.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/removal.rs index 7f5f6377f54..4d3fffde325 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/removal.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/removal.rs @@ -1,6 +1,7 @@ use super::super::{dom_binding_timing_started, record_dom_binding_timing}; use super::{ - node_iterators::NodeIteratorRemovalPlan, policy::TreeMutationSourceProfile, + node_iterators::NodeIteratorRemovalPlan, + policy::{TreeMutationObserverPolicy, TreeMutationSourceProfile}, resources::ImageRelevantMutationPlan, }; use crate::{ @@ -22,6 +23,7 @@ pub(super) struct TreeRemovalPlan { pub(super) node_iterator_plan: Option, pub(super) registry_retargets: Vec, pub(super) image_relevant_mutation_plan: ImageRelevantMutationPlan, + pub(super) option_selectedness_before_remove: Vec<(DomHandle, bool)>, pub(super) selected_option_owners_before_remove: Vec<(DomHandle, DomHandle)>, } @@ -62,6 +64,7 @@ impl DocumentRuntime { custom_elements::registry_association_retargets_before_removal(host_ptr, root); let image_relevant_mutation_plan = self.image_relevant_mutation_plan_before_remove(parent, root); + let option_selectedness_before_remove = self.option_selectedness_before_insert(roots); let selected_option_owners_before_remove = self.selected_option_owners_in_subtrees(std::slice::from_ref(&root)); TreeRemovalPlan { @@ -75,6 +78,7 @@ impl DocumentRuntime { node_iterator_plan, registry_retargets, image_relevant_mutation_plan, + option_selectedness_before_remove, selected_option_owners_before_remove, } } @@ -147,6 +151,12 @@ impl DocumentRuntime { let mut prepublished_removals = Vec::new(); for &child in &removed_children { let removal_plan = self.tree_removal_plan(host_ptr, parent, child); + self.reset_focus_before_tree_removal( + scope, + host_ptr, + &removal_plan, + TreeMutationSourceProfile::js_dom_api_appending_to_current_reaction_queue(), + ); prepublished_removals .extend(self.break_on_dom_debugger_before_tree_removal(host_ptr, parent, child)); let effects = self.remove_child_effects_in_structural_scope(parent, child); @@ -182,6 +192,74 @@ impl DocumentRuntime { changed } + /// Removal is observable even when the node will immediately be inserted + /// again. Queue its reactions in the caller's scope while its old parent + /// and form owner are gone; insertion then builds a fresh, read-only plan. + pub(super) fn remove_insertion_roots( + &mut self, + scope: &mut v8::PinScope<'_, '_>, + host_ptr: *mut PageScriptHost, + parent: DomHandle, + child: DomHandle, + roots: &[DomHandle], + profile: TreeMutationSourceProfile, + ) -> bool { + if profile.preserve_connection { + return true; + } + // Preserve registry identity while the source parent is still known. + // Detaching must not make an inherited document registry start using + // the destination shadow root's scoped registry on reinsertion. + if let Some(document) = roots + .first() + .and_then(|root| self.dom_host.owner_document_handle(*root)) + { + let targets = self.dom_host.adoption_targets_for_roots(roots, document); + let registry_plan = custom_elements::adoption_plan_before_adoption(host_ptr, &targets); + custom_elements::apply_registry_association_retargets( + host_ptr, + ®istry_plan.registry_retargets, + ); + } + let fragment = self + .dom_host + .node(child) + .is_some_and(Node::is_document_fragment); + for &root in roots { + let Some(old_parent) = self.dom_host.parent_node(root) else { + continue; + }; + let removal_profile = TreeMutationSourceProfile { + observers: if fragment || (profile.suppresses_observers() && old_parent == parent) { + TreeMutationObserverPolicy::Suppress + } else { + TreeMutationObserverPolicy::Queue + }, + ..profile + }; + if !self.remove_child_with_source_profile( + scope, + host_ptr, + old_parent, + root, + removal_profile, + ) { + return false; + } + } + if fragment && !roots.is_empty() && self.dom_host.mutation_records_enabled() { + let mut effects = DomMutationEffects::default(); + effects.queue_child_list_mutation(child, &[], roots, None, None); + crate::observer_runtime::queue_mutation_records( + scope, + host_ptr, + &self.dom_host, + &effects, + ); + } + true + } + pub(super) fn remove_child_with_source_profile( &mut self, scope: &mut v8::PinScope<'_, '_>, @@ -190,12 +268,16 @@ impl DocumentRuntime { child: DomHandle, source_profile: TreeMutationSourceProfile, ) -> bool { + if self.dom_host.parent_node(child) != Some(parent) { + return false; + } let started = dom_binding_timing_started(); let removal_plan = self.tree_removal_plan(host_ptr, parent, child); + self.reset_focus_before_tree_removal(scope, host_ptr, &removal_plan, source_profile); let prepublished_removals = self.break_on_dom_debugger_before_tree_removal(host_ptr, parent, child); let mut effects = self.remove_child_effects_in_structural_scope(parent, child); - if source_profile.suppress_observers { + if source_profile.suppresses_observers() { effects.suppress_child_list_mutations_for_target(parent); } self.apply_tree_removal_node_iterator_plan_if_changed(host_ptr, &removal_plan, &effects); diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/removal_followups.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/removal_followups.rs index c9e94edf9ae..f7803589dc9 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/removal_followups.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/removal_followups.rs @@ -21,6 +21,11 @@ impl DocumentRuntime { removal_plan: &TreeRemovalPlan, profile: TreeMutationSourceProfile, ) { + self.preserve_selectedness_for_options_removed_from_select( + scope, + host_ptr, + &removal_plan.option_selectedness_before_remove, + ); self.queue_selectedcontent_updates_after_tree_removal( scope, host_ptr, @@ -31,19 +36,6 @@ impl DocumentRuntime { host_ptr, removal_plan, ); - match profile.source { - TreeMutationSideEffectSource::JsDomApi => { - if let Some(active) = removal_plan.focus_reset_handle_before_remove { - crate::native_bridge::element::reset_focus_from_previous_handle_with_previous_focus_within( - scope, - host_ptr, - active, - removal_plan.focus_within_handles_before_remove.clone(), - ); - } - } - TreeMutationSideEffectSource::ParserTreeSink => {} - } self.dispatch_tree_removal_custom_element_reactions(scope, host_ptr, removal_plan, profile); self.queue_image_relevant_mutation_loads( scope, @@ -117,6 +109,18 @@ impl DocumentRuntime { let reaction_groups = self.tree_removal_reaction_groups_after_change(removal_plan); match profile.reaction_policy { TreeReactionDispatchPolicy::DispatchNow => { + if removal_plan + .lifecycle_connected_roots_before_remove + .is_empty() + { + custom_elements::with_custom_element_reaction_scope(scope, host_ptr, |scope| { + self.enqueue_custom_element_form_association_callbacks_in_subtree( + scope, + host_ptr, + removal_plan.root, + ); + }); + } let dispatches_removed_from_lifecycle = !reaction_groups.removed_from_lifecycle_roots.is_empty(); if dispatches_removed_from_lifecycle { @@ -194,6 +198,16 @@ impl DocumentRuntime { host_ptr, &reaction_groups.removed_from_lifecycle_roots, ); + if removal_plan + .lifecycle_connected_roots_before_remove + .is_empty() + { + self.enqueue_custom_element_form_association_callbacks_in_subtree( + scope, + host_ptr, + removal_plan.root, + ); + } self.enqueue_custom_element_form_association_callbacks_for_form_owner_subtrees( scope, host_ptr, diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/replacement.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/replacement.rs index 26a9525d7f3..a8ec52b27d6 100644 --- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/replacement.rs +++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/replacement.rs @@ -1,36 +1,30 @@ -use super::{ - insertion_plan::{TreeInsertionPlan, TreeInsertionPlanOptions}, - policy::{TreeMutationSourceProfile, TreeNoncePolicy, TreeReactionDispatchPolicy}, - removal::TreeRemovalPlan, -}; +use super::policy::{TreeMutationSourceProfile, TreeReactionDispatchPolicy}; use crate::{ custom_elements, document_runtime::{DocumentRuntime, DomHandle}, dom::native::Node, - mutation_coordinator::{ConnectedScriptMutationPolicy, RuntimeMutationOptions}, + mutation_coordinator::ConnectedScriptMutationPolicy, native_bridge::PageScriptHost, }; -struct TreeReplacementPlan<'a> { - insertion: TreeInsertionPlan<'a>, - removal: TreeRemovalPlan, -} - impl DocumentRuntime { /// DOM replace-all: conversion has already completed. Suppress only this /// operation's intermediate target records, then queue one replacement. - pub(crate) fn replace_all_children_with_node_appending_to_current_reaction_queue( + pub(crate) fn replace_all_children_appending_to_current_reaction_queue( &mut self, scope: &mut v8::PinScope<'_, '_>, host_ptr: *mut PageScriptHost, parent: DomHandle, - node: DomHandle, + node: Option, detached: bool, ) -> bool { let removed = self.dom_host.child_handles(parent).collect::>(); - let added = self - .fragment_insertion_children(node) - .unwrap_or_else(|| vec![node]); + let added = node + .map(|node| { + self.fragment_insertion_children(node) + .unwrap_or_else(|| vec![node]) + }) + .unwrap_or_default(); let source_profile = TreeMutationSourceProfile::js_dom_api_appending_to_current_reaction_queue() .suppressing_observers(); @@ -45,24 +39,24 @@ impl DocumentRuntime { return false; } } - let inserted = if detached { - self.insert_detached_native_child_with_source_profile( + let inserted = match node { + Some(node) if detached => self.insert_detached_native_child_with_source_profile( scope, host_ptr, parent, node, None, source_profile, - ) - } else { - self.insert_before_with_source_profile( + ), + Some(node) => self.insert_before_with_source_profile( scope, host_ptr, parent, node, None, source_profile, - ) + ), + None => true, }; if !inserted { return false; @@ -109,57 +103,24 @@ impl DocumentRuntime { reaction_policy: TreeReactionDispatchPolicy, connected_script_policy: ConnectedScriptMutationPolicy, ) -> bool { - let mutation_options = RuntimeMutationOptions::js_dom_api() - .with_connected_script_policy(connected_script_policy); - if new_child == old_child { - if self.dom_host.node(old_child).and_then(Node::parent_node) != Some(parent) { - return false; - } - // Replace adopts the input first. For self replacement this is a - // removal followed by insertion, including lifecycle and range - // effects, not just two synthetic observer records. - let reference = self.dom_host.node(old_child).and_then(Node::next_sibling); - return self.insert_before_with_nonce_handling( - scope, - host_ptr, - parent, - new_child, - reference, - true, - false, - connected_script_policy, - TreeMutationSourceProfile::js_dom_api_with( - reaction_policy, - TreeNoncePolicy::HideInsertedContentAttributes, - ), - ); + if matches!(reaction_policy, TreeReactionDispatchPolicy::DispatchNow) { + return custom_elements::with_custom_element_reaction_scope(scope, host_ptr, |scope| { + self.replace_child_with_reaction_policy( + scope, + host_ptr, + parent, + new_child, + old_child, + TreeReactionDispatchPolicy::AppendToCurrentQueue, + connected_script_policy, + ) + }); } - - let fragment_children = self.fragment_insertion_children(new_child); - let insertion_roots: &[DomHandle] = match fragment_children.as_deref() { - Some(handles) => handles, - None => std::slice::from_ref(&new_child), - }; - let insertion_plan = self.tree_insertion_plan( - parent, - insertion_roots, - host_ptr, - TreeInsertionPlanOptions::replacement( - old_child, - fragment_children.is_some() && !self.dom_host.is_shadow_root(new_child), - ), - ); - let inserted_was_connected = insertion_plan.was_lifecycle_connected_before_insert(); - self.reset_focus_for_non_preserving_connected_move_before_insert( - scope, - host_ptr, - insertion_plan.insertion_roots, - inserted_was_connected, - ); - let removal_plan = self.tree_removal_plan(host_ptr, parent, old_child); - // DOM replacement removes an attached new node, then oldChild, then - // inserts the replacement. The intermediate values are observable in - // text-control selections even without a DOM debugger breakpoint. + if self.dom_host.parent_node(old_child) != Some(parent) { + return false; + } + let source_profile = + TreeMutationSourceProfile::js_dom_api_appending_to_current_reaction_queue(); let reference_child = self .dom_host .node(old_child) @@ -171,169 +132,62 @@ impl DocumentRuntime { Some(next) } }); - let removed_previous_sibling = self.dom_host.node(old_child).and_then(Node::prev_sibling); - let lifecycle_connected_before = insertion_plan - .insertion_roots - .iter() - .copied() - .filter(|root| self.is_custom_element_lifecycle_connected(*root)) - .collect::>(); - let mut before_removal = crate::dom::native::DomMutationEffects::default(); - let mut prepublished_removals = Vec::new(); + if new_child == old_child { + return self.insert_before_with_nonce_handling( + scope, + host_ptr, + parent, + new_child, + reference_child, + true, + false, + connected_script_policy, + source_profile, + ); + } + let fragment_children = self.fragment_insertion_children(new_child); + let added = fragment_children + .as_deref() + .unwrap_or_else(|| std::slice::from_ref(&new_child)); + // Replace adopts an attached input before removing oldChild. Fragment + // children are removed later, as part of insertion. Both phases use + // ordinary removal, retaining their actual form and lifecycle states. if fragment_children.is_none() - && !self.remove_tree_insertion_roots_with_dom_debugger( + && !self.remove_insertion_roots( + scope, host_ptr, - insertion_plan.insertion_roots, - &mut before_removal, - &mut prepublished_removals, - false, + parent, + new_child, + added, + source_profile, ) { return false; } - prepublished_removals - .extend(self.break_on_dom_debugger_before_tree_removal(host_ptr, parent, old_child)); - let removed = self.remove_child_effects_in_structural_scope(parent, old_child); - if !removed.did_change() { + let previous_sibling = self.dom_host.node(old_child).and_then(Node::prev_sibling); + let replacement_profile = source_profile.suppressing_observers(); + if !self.remove_child_with_source_profile( + scope, + host_ptr, + parent, + old_child, + replacement_profile, + ) { return false; } - let mut inserted = crate::dom::native::DomMutationEffects::default(); - if fragment_children.is_some() - && !self.remove_tree_insertion_roots_with_dom_debugger( - host_ptr, - insertion_plan.insertion_roots, - &mut inserted, - &mut prepublished_removals, - false, - ) - { - return false; - } - if !insertion_plan.insertion_roots.is_empty() { - unsafe { &mut *host_ptr }.break_on_dom_debugger_will_insert_dom_node(parent); - for &root in insertion_plan.insertion_roots { - let effects = - self.insert_before_effects_in_structural_scope(parent, root, reference_child); - if !effects.did_change() { - return false; - } - inserted.merge(effects); - } - } - if before_removal.did_change() || inserted.did_change() { - self.apply_node_iterator_pre_remove_plans(host_ptr, &insertion_plan.node_iterator_plan); - } - self.apply_tree_removal_node_iterator_plan_if_changed(host_ptr, &removal_plan, &removed); - let mut effects = before_removal; - effects.merge(removed); - effects.merge(inserted); - self.finish_split_tree_insertion_effects( + if !self.insert_before_with_nonce_handling( + scope, + host_ptr, parent, new_child, - insertion_plan.insertion_roots, - &lifecycle_connected_before, - &mut effects, - ); - if self.dom_host.mutation_records_enabled() { - // An empty replacement has no inserted node from which to read - // its boundaries. Retain the removed child's original position. - let previous_sibling = insertion_plan - .insertion_roots - .first() - .map_or(removed_previous_sibling, |handle| { - self.dom_host.node(*handle).and_then(Node::prev_sibling) - }); - let next_sibling = insertion_plan - .insertion_roots - .last() - .map_or(reference_child, |handle| { - self.dom_host.node(*handle).and_then(Node::next_sibling) - }); - effects.coalesce_child_list_replacement( - parent, - insertion_plan.insertion_roots, - old_child, - previous_sibling, - next_sibling, - ); - } - let changed = self.apply_tree_insertion_mutation_effects_with_post_connection_steps( - scope, - host_ptr, - &insertion_plan, - effects, - mutation_options, - reaction_policy, + reference_child, true, - prepublished_removals, - ); - if !changed { + false, + connected_script_policy, + source_profile.replacing_child(old_child, previous_sibling, reference_child), + ) { return false; } - let replacement_plan = TreeReplacementPlan { - insertion: insertion_plan, - removal: removal_plan, - }; - self.dispatch_tree_replacement_side_effects_after_change( - scope, - host_ptr, - &replacement_plan, - reaction_policy, - ); true } - - fn dispatch_tree_replacement_side_effects_after_change( - &mut self, - scope: &mut v8::PinScope<'_, '_>, - host_ptr: *mut PageScriptHost, - replacement_plan: &TreeReplacementPlan<'_>, - reaction_policy: TreeReactionDispatchPolicy, - ) { - self.queue_selectedcontent_updates_after_tree_removal( - scope, - host_ptr, - &replacement_plan - .removal - .selected_option_owners_before_remove, - ); - let insertion_plan = &replacement_plan.insertion; - let mut dispatch_reactions = |scope: &mut v8::PinScope<'_, '_>| { - self.dispatch_tree_insertion_immediate_side_effects_after_change( - scope, - host_ptr, - insertion_plan, - TreeMutationSourceProfile::js_dom_api_with( - reaction_policy, - TreeNoncePolicy::HideInsertedContentAttributes, - ), - ); - self.dispatch_tree_removal_custom_element_reactions( - scope, - host_ptr, - &replacement_plan.removal, - TreeMutationSourceProfile::js_dom_api_with( - reaction_policy, - TreeNoncePolicy::HideInsertedContentAttributes, - ), - ); - }; - match reaction_policy { - TreeReactionDispatchPolicy::DispatchNow => { - custom_elements::with_custom_element_reaction_scope(scope, host_ptr, |scope| { - dispatch_reactions(scope); - }); - } - TreeReactionDispatchPolicy::AppendToCurrentQueue => { - dispatch_reactions(scope); - } - } - self.preserve_selectedness_for_insertion_plan(scope, host_ptr, insertion_plan); - self.queue_image_relevant_mutation_loads( - scope, - host_ptr, - &replacement_plan.removal.image_relevant_mutation_plan, - crate::types::SubresourceRequestInitiatorType::Script, - ); - } } 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 ae1a80a5e87..7f999ed1f6e 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/core.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs @@ -2450,10 +2450,6 @@ impl PageScriptHost { &mut self.custom_element_reactions } - pub(crate) fn custom_element_reactions(&self) -> &CustomElementReactionCoordinator { - &self.custom_element_reactions - } - pub(crate) fn enter_parser_pause(&mut self) -> crate::document_runtime::ParserPauseGuard { unsafe { &mut *self.document_runtime }.enter_parser_pause() } @@ -2570,6 +2566,13 @@ impl PageScriptHost { } } + pub(crate) fn upgraded_custom_element_handles(&self) -> impl Iterator + '_ { + std::iter::once(&self.custom_elements) + .chain(self.child_custom_elements.values()) + .chain(self.scoped_custom_elements.values()) + .flat_map(CustomElementStore::upgraded_handles) + } + pub(crate) fn custom_elements_subtree_lifecycle_quiescent(&self) -> bool { self.custom_elements.is_subtree_lifecycle_quiescent() && self diff --git a/moli-renderer-v8/src/native_bridge/element/content.rs b/moli-renderer-v8/src/native_bridge/element/content.rs index e6960273250..75ce3a5a6f0 100644 --- a/moli-renderer-v8/src/native_bridge/element/content.rs +++ b/moli-renderer-v8/src/native_bridge/element/content.rs @@ -1232,11 +1232,11 @@ pub(in crate::native_bridge) fn set_inner_text_in_reaction_scope( let Some(fragment) = rendered_text_fragment(runtime, document, value) else { return false; }; - runtime.replace_all_children_with_node_appending_to_current_reaction_queue( + runtime.replace_all_children_appending_to_current_reaction_queue( scope, runtime_ptr, handle, - fragment, + Some(fragment), false, ) }) diff --git a/moli-renderer-v8/src/native_bridge/node/mutation/parent_node.rs b/moli-renderer-v8/src/native_bridge/node/mutation/parent_node.rs index a21f96b940e..09541c82231 100644 --- a/moli-renderer-v8/src/native_bridge/node/mutation/parent_node.rs +++ b/moli-renderer-v8/src/native_bridge/node/mutation/parent_node.rs @@ -103,11 +103,11 @@ pub(in crate::native_bridge) fn mutate_parent_node<'s>( let runtime = unsafe { &mut *runtime_ptr }; let inserted = match mutation { ParentNodeMutation::ReplaceChildren => runtime - .replace_all_children_with_node_appending_to_current_reaction_queue( + .replace_all_children_appending_to_current_reaction_queue( scope, runtime_ptr, parent, - node, + Some(node), detached, ), _ if detached => runtime diff --git a/moli-renderer-v8/src/runtime/phase_one/tests/extracted/custom_element_lifecycle.rs b/moli-renderer-v8/src/runtime/phase_one/tests/extracted/custom_element_lifecycle.rs index c12c729eed1..2fdd7cc61ec 100644 --- a/moli-renderer-v8/src/runtime/phase_one/tests/extracted/custom_element_lifecycle.rs +++ b/moli-renderer-v8/src/runtime/phase_one/tests/extracted/custom_element_lifecycle.rs @@ -908,7 +908,7 @@ fieldset.appendChild(jsTarget); assert_eq!( result.get("value").and_then(serde_json::Value::as_str), Some( - r#"{"events":["js-face-target:connected:parser-face-fieldset","js-face-target:form:parser-face-form-b","js-face-target:disabled:true","parser-face-target:form:parser-face-form-b","parser-face-target:disabled:true"],"parserParent":"parser-face-fieldset","jsParent":"parser-face-fieldset"}"# + r#"{"events":["js-face-target:form:null","js-face-target:connected:parser-face-fieldset","js-face-target:form:parser-face-form-b","js-face-target:disabled:true","parser-face-target:form:parser-face-form-b","parser-face-target:disabled:true"],"parserParent":"parser-face-fieldset","jsParent":"parser-face-fieldset"}"# ), "parser FACE reparent should retain form-state reactions without the JS insertion connection callback" ); diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy.rs index 6b3075cc1db..f7ca8c7e840 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/security_policy.rs @@ -671,13 +671,14 @@ globalThis.__blockedInlineStyle.events.length ); assert_eq!( drain_pre_domcontentloaded_non_script_page_tasks_for_test(&mut vm), - 1 + 2, + "text replacement processes removal of the old text and insertion of the new text" ); assert!(vm.apply_connected_style_lifecycle_bodies_for_test()); assert_eq!( vm.eval("JSON.stringify(globalThis.__blockedInlineStyle.events)") .expect("second blocked processing error should be observable"), - r#"[{"type":"error","target":true,"bubbles":false,"cancelable":false},{"type":"error","target":true,"bubbles":false,"cancelable":false}]"# + r#"[{"type":"error","target":true,"bubbles":false,"cancelable":false},{"type":"error","target":true,"bubbles":false,"cancelable":false},{"type":"error","target":true,"bubbles":false,"cancelable":false}]"# ); } diff --git a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/detached_documents_and_reactions.rs b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/detached_documents_and_reactions.rs index 16ee1617fc8..1b97e031d33 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/detached_documents_and_reactions.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_elements/custom_elements/detached_documents_and_reactions.rs @@ -79,6 +79,15 @@ fn template_adoption_reactions_use_each_associated_tree_document() { ); } +#[test] +fn form_associated_custom_elements_preserve_removal_and_insertion_owner_transitions() { + let mut vm = new_storage_test_vm("https://form-association-removal.test/"); + let result = vm + .eval(include_str!("../../form_association_removal.js")) + .expect("form owner removal and insertion reactions should evaluate"); + assert_eq!(result, "true"); +} + #[test] fn custom_state_set_invalidates_shadow_source_scopes() { let mut vm = new_storage_test_vm("https://custom-state-shadow-scope.test/"); diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/cssom/extracted/stylesheets_and_at_rules.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/cssom/extracted/stylesheets_and_at_rules.rs index 50c4a4bbee5..e5f48e8f816 100644 --- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/cssom/extracted/stylesheets_and_at_rules.rs +++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/cssom/extracted/stylesheets_and_at_rules.rs @@ -3154,8 +3154,8 @@ fn svg_style_uses_the_shared_owner_live_stylesheet_pipeline() { assert_eq!(mutated, "true|true|true|2|17px|19px"); assert_eq!( crate::live_stylesheet::live_stylesheet_parse_count_for_test(), - 1, - "changing SVG style text should parse one replacement live stylesheet" + 2, + "SVG style processes the empty contents after removal and the inserted replacement text" ); assert_eq!( crate::live_stylesheet::live_stylesheet_css_text_projection_count_for_test(), diff --git a/moli-renderer-v8/src/script_vm/tests/form_association_removal.js b/moli-renderer-v8/src/script_vm/tests/form_association_removal.js new file mode 100644 index 00000000000..0c11f281ed7 --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/form_association_removal.js @@ -0,0 +1,245 @@ +(() => { + if (!document.documentElement) document.append(document.createElement('html')); + if (!document.body) document.documentElement.append(document.createElement('body')); + const iframe = document.createElement('iframe'); + document.body.append(iframe); + const failures = []; + const check = (actual, expected, label) => { + if (JSON.stringify(actual) !== JSON.stringify(expected)) { + failures.push(`${label}: ${JSON.stringify(actual)} != ${JSON.stringify(expected)}`); + } + }; + for (const doc of [document, iframe.contentDocument]) { + const win = doc.defaultView; + class MovingFace extends win.HTMLElement { + static formAssociated = true; + constructor() { super(); this.internals = this.attachInternals(); this.events = []; } + connectedCallback() { this.events.push('connected'); } + disconnectedCallback() { this.events.push('disconnected'); } + connectedMoveCallback() { this.events.push('moved'); } + formAssociatedCallback(form) { this.events.push(`form:${form ? form.dataset.label : 'null'}`); } + formDisabledCallback(value) { this.events.push(`disabled:${value}`); } + } + win.customElements.define('form-removal-face', MovingFace); + const form = (id) => { + const node = doc.createElement('form'); + node.id = id; + node.dataset.label = id; + return node; + }; + for (const connected of [false, true]) { + for (const explicit of [false, true]) { + for (const operation of ['appendChild', 'insertBefore', 'append', 'prepend', 'before', + 'after', 'replaceChild', 'replaceWith', 'replaceChildren', 'selfAppend', 'selfReplace', + 'wrapper', 'remove', 'fragment']) { + const label = `${doc === document ? 'main' : 'iframe'}/${connected}/${explicit}/${operation}`; + const root = doc.createElement('div'); + const a = form('a'), b = form('b'); + const wrapper = doc.createElement('div'); + const sibling = doc.createElement('span'); + const face = doc.createElement('form-removal-face'); + if (explicit) face.setAttribute('form', 'a'); + wrapper.append(face); a.append(wrapper); b.append(sibling); root.append(a, b); + if (connected) doc.body.append(root); + face.events.length = 0; + switch (operation) { + case 'appendChild': b.appendChild(face); break; + case 'insertBefore': b.insertBefore(face, sibling); break; + case 'append': b.append(face); break; + case 'prepend': b.prepend(face); break; + case 'before': sibling.before(face); break; + case 'after': sibling.after(face); break; + case 'replaceChild': b.replaceChild(face, sibling); break; + case 'replaceWith': sibling.replaceWith(face); break; + case 'replaceChildren': b.replaceChildren(face); break; + case 'selfAppend': wrapper.append(face); break; + case 'selfReplace': wrapper.replaceChild(face, face); break; + case 'wrapper': b.append(wrapper); break; + case 'remove': face.remove(); break; + case 'fragment': { + const fragment = doc.createDocumentFragment(); + fragment.append(face); + b.append(fragment); + break; + } + } + const owner = operation === 'remove' ? null : + operation.startsWith('self') || (connected && explicit) ? a : b; + const expected = connected ? ['disconnected', 'form:null'] : ['form:null']; + if (operation !== 'remove') { + if (connected) expected.push('connected'); + expected.push(`form:${owner.dataset.label}`); + } + check(face.events, expected, label); + check(face.internals.form === owner, true, `${label}/owner`); + root.remove(); + } + } + } + for (const connected of [false, true]) { + const owner = form('disabled-owner'), fieldset = doc.createElement('fieldset'); + fieldset.disabled = true; + const face = doc.createElement('form-removal-face'); + fieldset.append(face); owner.append(fieldset); + if (connected) doc.body.append(owner); + face.events.length = 0; + face.remove(); + check(face.events, [...(connected ? ['disconnected'] : []), 'form:null', 'disabled:false'], + `remove disabled FACE/${connected}`); + check(face.internals.form, null, 'removed disabled FACE owner'); + owner.remove(); + } + // Removal of the old form must be observed before its same-ID replacement. + for (const attached of [false, true]) { + const root = doc.createElement('div'), oldForm = form('target'), newForm = form('target'); + oldForm.dataset.label = 'old'; newForm.dataset.label = 'new'; + const face = doc.createElement('form-removal-face'); face.setAttribute('form', 'target'); + root.append(oldForm, face); + if (attached) root.append(newForm); + doc.body.append(root); face.events.length = 0; + root.replaceChild(newForm, oldForm); + check(face.events, ['form:null', 'form:new'], `replace external form/${attached}`); + check(face.internals.form === newForm, true, 'external replacement owner'); + root.remove(); + } + // All replace-all entry points perform the same removal, including detached + // forms, and retain one combined childList record for the target. + for (const connected of [false, true]) { + for (const method of ['textContent', 'textContentWithText', 'innerHTML', 'replaceChildren']) { + const owner = form('bulk-owner'), face = doc.createElement('form-removal-face'); + owner.append(face); + if (connected) doc.body.append(owner); + const observer = new win.MutationObserver(() => {}); + observer.observe(owner, {childList: true}); face.events.length = 0; + if (method === 'textContentWithText') owner.textContent = 'replacement'; + else if (method === 'replaceChildren') owner.replaceChildren(); + else owner[method] = ''; + const records = observer.takeRecords(); observer.disconnect(); + const label = `bulk removal/${connected}/${method}`; + check(face.events, [...(connected ? ['disconnected'] : []), 'form:null'], label); + check(face.internals.form, null, `${label}/owner`); + check(records.length, 1, `${label}/records`); + if (records.length) { + check(Array.from(records[0].removedNodes).includes(face), true, `${label}/removed`); + check(records[0].addedNodes.length, method === 'textContentWithText' ? 1 : 0, `${label}/added`); + } + owner.remove(); + } + } + // An implicit owner traveling in the same subtree stays associated. + { + const root = doc.createElement('div'), owner = form('carried'); + const face = doc.createElement('form-removal-face'); + owner.append(face); root.append(owner); doc.body.append(root); face.events.length = 0; + root.append(owner); + check(face.events, ['disconnected', 'connected'], 'move owner with descendant'); + face.events.length = 0; + owner.remove(); + check(face.events, ['disconnected'], 'remove owner with descendant'); + check(face.internals.form === owner, true, 'detached subtree keeps implicit owner'); + root.remove(); + } + // Explicit owners outside the moved subtree must see both ID lookup states. + for (const duplicate of [false, true]) { + const root = doc.createElement('div'), a = form('target'), b = form('other'); + if (duplicate) b.id = 'target'; + const face = doc.createElement('form-removal-face'); face.setAttribute('form', 'target'); + root.append(a, b, face); doc.body.append(root); face.events.length = 0; + root.append(a); + check(face.events, duplicate ? ['form:other'] : ['form:null', 'form:target'], 'move external owner'); + check(face.internals.form === (duplicate ? b : a), true, 'external owner after move'); + root.remove(); + } + // A non-form element can mask the referenced ID during each phase, too. + { + const root = doc.createElement('div'), owner = form('target'); + const mask = doc.createElement('div'); mask.id = 'target'; + const face = doc.createElement('form-removal-face'); face.setAttribute('form', 'target'); + root.append(mask, owner, face); doc.body.append(root); face.events.length = 0; + root.insertBefore(mask, mask); + check(face.events, ['form:target', 'form:null'], 'remove and reinsert ID mask'); + check(face.internals.form, null, 'ID mask restored'); + root.remove(); + } + // Pre-insertion validation must finish before any removal or reactions. + { + const owner = form('invalid'), face = doc.createElement('form-removal-face'); + owner.append(face); doc.body.append(owner); face.events.length = 0; + let error = null; + try { face.append(owner); } catch (e) { error = e.name; } + check(error, 'HierarchyRequestError', 'cyclic insertion'); + check(face.events, [], 'invalid insertion has no reactions'); + check(face.internals.form === owner, true, 'invalid insertion retains owner'); + owner.remove(); + } + // CE reactions can reenter the DOM after the original removal/insert has + // completed. Callback arguments retain history; internals.form is live. + { + const root = doc.createElement('div'), a = form('a'), b = form('b'), c = form('c'); + const events = []; + class ReentrantFace extends win.HTMLElement { + static formAssociated = true; + constructor() { super(); this.internals = this.attachInternals(); } + formAssociatedCallback(owner) { + events.push([owner && owner.id, this.internals.form && this.internals.form.id]); + if (!owner && this.parentNode === b) c.append(this); + } + } + win.customElements.define('reentrant-form-removal-face', ReentrantFace); + const face = doc.createElement('reentrant-form-removal-face'); + root.append(a, b, c); a.append(face); doc.body.append(root); events.length = 0; + b.append(face); + check(events, [[null, 'b'], ['b', 'c'], [null, 'c'], ['c', 'c']], 'reentrant owner history'); + check(face.internals.form === c, true, 'reentrant final owner'); + root.remove(); + } + // Focus reset belongs to removal, before the old event path disappears. + { + const a = doc.createElement('section'), b = doc.createElement('section'); + const button = doc.createElement('button'); a.append(button); doc.body.append(a, b); + const events = []; + const listener = event => { if (event.target === button) events.push(event.type); }; + doc.addEventListener('focusin', listener); doc.addEventListener('focusout', listener); + button.focus(); b.moveBefore(button, null); + check(events, ['focusin'], 'atomic move preserves focus'); + check(doc.activeElement === button, true, 'atomic active element'); + a.append(button); + check(events, ['focusin', 'focusout'], 'ordinary move dispatches focusout through old parent'); + button.focus(); button.remove(); + check(events, ['focusin', 'focusout', 'focusin', 'focusout'], 'direct removal dispatches focusout'); + check(doc.activeElement === doc.body, true, 'removal resets active element'); + doc.removeEventListener('focusin', listener); doc.removeEventListener('focusout', listener); + a.remove(); b.remove(); + } + // A replacement's observer record must retain its timing relative to an + // inserted classic script, as well as its eventual contents. + for (const method of ['replaceChild', 'replaceChildren', 'textContent']) { + const parent = doc.createElement(method === 'textContent' ? 'script' : 'div'); + const old = doc.createElement('span'); + if (method !== 'textContent') parent.append(old); + doc.body.append(parent); + const observer = new win.MutationObserver(() => {}); + observer.observe(parent, {childList: true}); + const describe = records => Array.from(records, record => ({ + added: Array.from(record.addedNodes, node => node.nodeName), + removed: Array.from(record.removedNodes, node => node.nodeName) + })); + let during = null; + win.__formRemovalObserveInsertion = () => { during = describe(observer.takeRecords()); }; + const script = doc.createElement('script'); + script.textContent = '__formRemovalObserveInsertion()'; + if (method === 'replaceChild') parent.replaceChild(script, old); + else if (method === 'replaceChildren') parent.replaceChildren(script); + else parent.textContent = '__formRemovalObserveInsertion()'; + const expected = [{added: [method === 'textContent' ? '#text' : 'SCRIPT'], + removed: method === 'textContent' ? [] : ['SPAN']}]; + check(during, method === 'replaceChild' ? expected : [], `${method}/observer during script`); + check(describe(observer.takeRecords()), method === 'replaceChild' ? [] : expected, + `${method}/observer after script`); + observer.disconnect(); parent.remove(); delete win.__formRemovalObserveInsertion; + } + } + iframe.remove(); + if (failures.length) throw new Error(failures.join('\n')); + return true; +})()