feat(dom): preserve ordered subtree-removal observer effects

Preserve the old ancestor handles and mutation order for subtree removals,
independently of web-visible childList records. Suppression, clearing and
coalescing retain removal steps while keeping the existing records() view.
Capture this information only for MutationObserver interest; DevTools-only
recording keeps its existing payload and behavior.

Cover batch merging/coalescing/suppression and old ancestry across moves.
Validation: cargo fmt --all; strict workspace/all-targets/all-features clippy;
full nextest (23116 passed, 17 existing skipped, combined final source tree).
This commit is contained in:
ldm0
2026-11-22 02:02:05 +08:00
parent bc1f764c14
commit e7dfaf7adb
6 changed files with 221 additions and 25 deletions
+5 -5
View File
@@ -36,11 +36,11 @@ pub(crate) use stylesheet_candidates::{StylesheetCandidateChanges, StylesheetCan
pub use self::mutation::{
DomAttributeMutation, DomAttributeMutationOutcome, DomChildListMutation, DomMutationEffects,
DomMutationRecord, DomMutationRecordBatch, DomMutationRecordKind, DomScriptMutationEffects,
DomSlotAssignmentChange, DomSlotMutationEffects, DomStyleInvalidationInputs,
DomStylesheetOwnerChange, DomStylesheetOwnerChangeKind, DomStylesheetOwnerTransitions,
DomStylesheetOwnerTreeScopes, DomTextNormalizationStep, DomTextareaValueChange,
DomTreeMutationEffects, ScriptPrepareTrigger, ScriptPrepareTriggerKind,
DomMutationObserverEffect, DomMutationRecord, DomMutationRecordBatch, DomMutationRecordKind,
DomScriptMutationEffects, DomSlotAssignmentChange, DomSlotMutationEffects,
DomStyleInvalidationInputs, DomStylesheetOwnerChange, DomStylesheetOwnerChangeKind,
DomStylesheetOwnerTransitions, DomStylesheetOwnerTreeScopes, DomTextNormalizationStep,
DomTextareaValueChange, DomTreeMutationEffects, ScriptPrepareTrigger, ScriptPrepareTriggerKind,
};
use self::query_index::ElementQueryIndex;
+5 -5
View File
@@ -12,11 +12,11 @@ pub use normalization::DomTextNormalizationStep;
pub use effects::{
DomAttributeMutation, DomAttributeMutationOutcome, DomChildListMutation, DomMutationEffects,
DomMutationRecord, DomMutationRecordBatch, DomMutationRecordKind, DomScriptMutationEffects,
DomSlotAssignmentChange, DomSlotMutationEffects, DomStyleInvalidationInputs,
DomStylesheetOwnerChange, DomStylesheetOwnerChangeKind, DomStylesheetOwnerTransitions,
DomStylesheetOwnerTreeScopes, DomTextareaValueChange, DomTreeMutationEffects,
ScriptPrepareTrigger, ScriptPrepareTriggerKind,
DomMutationObserverEffect, DomMutationRecord, DomMutationRecordBatch, DomMutationRecordKind,
DomScriptMutationEffects, DomSlotAssignmentChange, DomSlotMutationEffects,
DomStyleInvalidationInputs, DomStylesheetOwnerChange, DomStylesheetOwnerChangeKind,
DomStylesheetOwnerTransitions, DomStylesheetOwnerTreeScopes, DomTextareaValueChange,
DomTreeMutationEffects, ScriptPrepareTrigger, ScriptPrepareTriggerKind,
};
impl Deref for DomHost {
@@ -11,7 +11,9 @@ mod stylesheet;
mod text_control;
mod tree;
pub use observer::{DomMutationRecord, DomMutationRecordBatch, DomMutationRecordKind};
pub use observer::{
DomMutationObserverEffect, DomMutationRecord, DomMutationRecordBatch, DomMutationRecordKind,
};
pub use script::{DomScriptMutationEffects, ScriptPrepareTrigger, ScriptPrepareTriggerKind};
pub use slot::{DomSlotAssignmentChange, DomSlotMutationEffects};
pub use style::{DomAttributeMutation, DomChildListMutation, DomStyleInvalidationInputs};
@@ -1,8 +1,30 @@
use super::{DomAttributeMutation, DomChildListMutation, DomHandle, DomMutationEffects};
use std::sync::Arc;
/// Observer work in mutation order. Subtree removal is independent of the
/// suppress-observers flag and must survive child-list record coalescing.
#[derive(Debug, Clone, Copy)]
pub enum DomMutationObserverEffect<'a> {
Record(&'a DomMutationRecord),
SubtreeRemoval {
node: DomHandle,
ancestors: &'a [DomHandle],
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum ObserverStep {
Record(usize),
SubtreeRemoval {
node: DomHandle,
ancestors: Arc<[DomHandle]>,
},
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DomMutationRecordBatch {
pub(super) records: Vec<DomMutationRecord>,
steps: Vec<ObserverStep>,
}
impl DomMutationRecordBatch {
@@ -10,13 +32,55 @@ impl DomMutationRecordBatch {
&self.records
}
pub fn effects(&self) -> impl Iterator<Item = DomMutationObserverEffect<'_>> {
self.steps.iter().map(|step| match step {
ObserverStep::Record(index) => DomMutationObserverEffect::Record(&self.records[*index]),
ObserverStep::SubtreeRemoval { node, ancestors } => {
DomMutationObserverEffect::SubtreeRemoval {
node: *node,
ancestors,
}
}
})
}
fn push(&mut self, record: DomMutationRecord) {
self.steps.push(ObserverStep::Record(self.records.len()));
self.records.push(record);
}
fn retain_records(&mut self, mut retain: impl FnMut(&DomMutationRecord) -> bool) {
let mut indices = Vec::with_capacity(self.records.len());
let mut next_index = 0;
self.records.retain(|record| {
let keep = retain(record);
indices.push(keep.then(|| {
let index = next_index;
next_index += 1;
index
}));
keep
});
self.steps.retain_mut(|step| match step {
ObserverStep::Record(index) => {
if let Some(new_index) = indices[*index] {
*index = new_index;
true
} else {
false
}
}
ObserverStep::SubtreeRemoval { .. } => true,
});
}
pub(super) fn remove_replacement_parts(
&mut self,
target: DomHandle,
added_nodes: &[DomHandle],
removed_node: DomHandle,
) {
self.records.retain(|record| {
self.retain_records(|record| {
if record.target != target {
return true;
}
@@ -35,6 +99,12 @@ impl DomMutationRecordBatch {
}
pub(super) fn merge(&mut self, other: Self) {
let offset = self.records.len();
self.steps
.extend(other.steps.into_iter().map(|step| match step {
ObserverStep::Record(index) => ObserverStep::Record(index + offset),
removal @ ObserverStep::SubtreeRemoval { .. } => removal,
}));
self.records.extend(other.records);
}
@@ -48,7 +118,7 @@ impl DomMutationRecordBatch {
}
let mut coalesced_nodes = Vec::new();
self.records.retain(|record| {
self.retain_records(|record| {
if record.target != target {
return true;
}
@@ -74,7 +144,7 @@ impl DomMutationRecordBatch {
coalesced_nodes, removed_nodes,
"all-children removal records must retain tree order"
);
self.records.push(DomMutationRecord {
self.push(DomMutationRecord {
target,
kind: DomMutationRecordKind::ChildList(DomChildListMutation::new(
target,
@@ -98,7 +168,7 @@ impl DomMutationRecordBatch {
}
let mut coalesced_nodes = Vec::new();
self.records.retain(|record| {
self.retain_records(|record| {
if record.target != target {
return true;
}
@@ -124,7 +194,7 @@ impl DomMutationRecordBatch {
coalesced_nodes, added_nodes,
"batched insertion records must retain tree order"
);
self.records.push(DomMutationRecord {
self.push(DomMutationRecord {
target,
kind: DomMutationRecordKind::ChildList(DomChildListMutation::new(
target,
@@ -137,7 +207,7 @@ impl DomMutationRecordBatch {
}
pub(super) fn push_attribute_mutation_record(&mut self, mutation: DomAttributeMutation) {
self.records.push(DomMutationRecord {
self.push(DomMutationRecord {
target: mutation.target,
kind: DomMutationRecordKind::Attributes(mutation),
});
@@ -172,17 +242,27 @@ impl DomMutationRecord {
impl DomMutationEffects {
pub(super) fn push_mutation_record(&mut self, record: DomMutationRecord) {
self.changed = true;
self.observer_records.records.push(record);
self.observer_records.push(record);
}
pub(in crate::native::host::mutation) fn clear_mutation_records(&mut self) {
self.observer_records.records.clear();
self.observer_records.retain_records(|_| false);
}
pub(in crate::native::host::mutation) fn mark_observer_subtree_removal(
&mut self,
node: DomHandle,
ancestors: Arc<[DomHandle]>,
) {
self.observer_records
.steps
.push(ObserverStep::SubtreeRemoval { node, ancestors });
}
/// Apply the DOM suppress-observers flag to this operation's target. Source
/// removals and non-observer mutation effects must remain observable.
pub fn suppress_child_list_mutations_for_target(&mut self, target: DomHandle) {
self.observer_records.records.retain(|record| {
self.observer_records.retain_records(|record| {
record.target != target || !matches!(record.kind, DomMutationRecordKind::ChildList(_))
});
}
@@ -277,6 +357,46 @@ impl DomMutationEffects {
mod tests {
use super::*;
#[test]
fn subtree_removals_keep_their_order_when_record_batches_merge_and_coalesce() {
let parent = DomHandle::new(1);
let first = DomHandle::new(2);
let second = DomHandle::new(3);
let text = DomHandle::new(4);
let ancestors: Arc<[DomHandle]> = Arc::from([parent]);
let mut effects = DomMutationEffects::default();
effects.queue_character_data_mutation(text, None);
effects.mark_observer_subtree_removal(first, Arc::clone(&ancestors));
effects.queue_child_list_mutation(parent, &[], &[first], None, Some(second));
let mut next = DomMutationEffects::default();
next.mark_observer_subtree_removal(second, ancestors);
next.queue_child_list_mutation(parent, &[], &[second], None, None);
effects.merge(next);
effects.coalesce_child_list_removals(parent, &[first, second]);
let steps = effects.observer_records().effects().collect::<Vec<_>>();
assert_eq!(steps.len(), 4);
assert!(
matches!(steps[0], DomMutationObserverEffect::Record(record) if record.target() == text)
);
assert!(
matches!(steps[1], DomMutationObserverEffect::SubtreeRemoval { node, ancestors } if node == first && ancestors == [parent])
);
assert!(
matches!(steps[2], DomMutationObserverEffect::SubtreeRemoval { node, ancestors } if node == second && ancestors == [parent])
);
assert!(
matches!(steps[3], DomMutationObserverEffect::Record(record) if record.target() == parent)
);
effects.suppress_child_list_mutations_for_target(parent);
assert_eq!(effects.observer_records().records().len(), 1);
assert_eq!(effects.observer_records().effects().count(), 3);
effects.clear_mutation_records();
assert!(effects.observer_records().records().is_empty());
assert_eq!(effects.observer_records().effects().count(), 2);
}
#[test]
fn coalesces_insertion_batch_without_discarding_other_records() {
let target = DomHandle::new(1);
+32
View File
@@ -1,4 +1,5 @@
use super::*;
use std::sync::Arc;
impl DomHost {
pub fn append_child(&mut self, parent: DomHandle, child: DomHandle) -> bool {
@@ -93,6 +94,10 @@ impl DomHost {
) -> DomMutationEffects {
let owner_document = self.owner_document_handle(parent);
let records_enabled = self.mutation_records_enabled();
let observer_ancestors = self
.mutation_observer_records_enabled
.get()
.then(|| self.observer_removal_ancestors(parent));
let removed_tree_was_connected = self.is_connected(child);
let parser_form_owner_resets = self.parser_form_owner_resets_for_removed_subtrees(&[child]);
let removal_context = self.subtree_removal_context(child);
@@ -147,6 +152,9 @@ impl DomHost {
self.update_document_target_from_url(document);
}
effects.mark_disconnected_root(child);
if let Some(ancestors) = observer_ancestors {
effects.mark_observer_subtree_removal(child, ancestors);
}
if records_enabled {
effects.mark_child_list_mutation(
parent,
@@ -182,6 +190,16 @@ impl DomHost {
DomMutationEffects::default()
}
fn observer_removal_ancestors(&self, parent: DomHandle) -> Arc<[DomHandle]> {
let mut ancestors = Vec::new();
let mut current = Some(parent);
while let Some(node) = current {
ancestors.push(node);
current = self.parent_node(node);
}
ancestors.into()
}
fn clear_popover_open_states(
&mut self,
open_popovers: &[DomHandle],
@@ -327,6 +345,15 @@ impl DomHost {
next_sibling,
))
};
let observer_ancestors = self
.mutation_observer_records_enabled
.get()
.then(|| {
removal_record
.as_ref()
.map(|(parent, ..)| self.observer_removal_ancestors(*parent))
})
.flatten();
let insertion_slot_assignment_snapshots = if self.shadow_root_handle(parent).is_none() {
Vec::new()
} else if inserted_fragment_children.is_empty() {
@@ -472,6 +499,11 @@ impl DomHost {
if let Some((old_parent, removed_nodes, previous_sibling, next_sibling)) =
removal_record
{
if let Some(ancestors) = observer_ancestors {
for &node in &removed_nodes {
effects.mark_observer_subtree_removal(node, Arc::clone(&ancestors));
}
}
if records_enabled {
effects.mark_child_list_mutation(
old_parent,
+47 -5
View File
@@ -33,11 +33,11 @@ use host::StylesheetCandidateRegistries;
pub use host::{
ConnectedShadowRootSnapshot, DomAdoptionTarget, DomAssociatedTreeEdgeKind,
DomAttributeMutation, DomAttributeMutationOutcome, DomChildListMutation, DomHost,
DomMutationEffects, DomMutationRecord, DomMutationRecordBatch, DomMutationRecordKind,
DomScriptMutationEffects, DomSlotAssignmentChange, DomSlotMutationEffects,
DomStyleInvalidationInputs, DomStylesheetOwnerChange, DomStylesheetOwnerChangeKind,
DomStylesheetOwnerTransitions, DomStylesheetOwnerTreeScopes, DomSubtreeTransfer,
DomSubtreeTransferError, DomTextNormalizationStep, DomTextareaValueChange,
DomMutationEffects, DomMutationObserverEffect, DomMutationRecord, DomMutationRecordBatch,
DomMutationRecordKind, DomScriptMutationEffects, DomSlotAssignmentChange,
DomSlotMutationEffects, DomStyleInvalidationInputs, DomStylesheetOwnerChange,
DomStylesheetOwnerChangeKind, DomStylesheetOwnerTransitions, DomStylesheetOwnerTreeScopes,
DomSubtreeTransfer, DomSubtreeTransferError, DomTextNormalizationStep, DomTextareaValueChange,
DomTreeMutationEffects, ScriptPrepareTrigger, ScriptPrepareTriggerKind,
StylesheetCandidateTreeScopeSnapshots,
};
@@ -937,6 +937,48 @@ mod tests {
assert!(effects.observer_records().records().is_empty());
}
#[test]
fn observer_removals_capture_the_original_ancestors_before_moves_and_suppression() {
let mut host = DomHost::from_dom(NativeDom::new_html(test_url()));
let parent = host.create_element("div");
let branch = host.create_element("section");
let leaf = host.create_element("span");
let destination = host.create_element("aside");
assert!(host.append_child(parent, branch));
assert!(host.append_child(branch, leaf));
host.set_mutation_observer_records_enabled(true);
let mut effects = host.remove_child_effects(branch, leaf);
effects.suppress_child_list_mutations_for_target(branch);
assert!(host.append_child(destination, branch));
let removal = effects.observer_records().effects().collect::<Vec<_>>();
assert_eq!(removal.len(), 1);
assert!(
matches!(removal[0], DomMutationObserverEffect::SubtreeRemoval { node, ancestors } if node == leaf && ancestors == [branch, parent])
);
let effects = host.append_child_effects(parent, branch);
let removal = effects.observer_records().effects().next().unwrap();
assert!(
matches!(removal, DomMutationObserverEffect::SubtreeRemoval { node, ancestors } if node == branch && ancestors == [destination])
);
host.set_mutation_observer_records_enabled(false);
let effects = host.remove_child_effects(parent, branch);
assert_eq!(effects.observer_records().effects().count(), 0);
assert!(host.append_child(parent, branch));
host.set_devtools_mutation_records_enabled(true);
let effects = host.remove_child_effects(parent, branch);
assert_eq!(effects.observer_records().records().len(), 1);
assert!(
effects
.observer_records()
.effects()
.all(|effect| matches!(effect, DomMutationObserverEffect::Record(_)))
);
}
#[test]
fn appending_text_preserves_replacement_mutation_effects() {
for parent_name in ["p", "style", "script", "textarea"] {