mirror of
https://github.com/lexmount/moli.git
synced 2026-11-22 00:02:21 +00:00
fix(dom): preserve form state during bulk child removal
Capture option selectedness before removing any children and apply runtime removal effects once. Route markup and DOM replace-all through the same owner, queue one replacement record, and retain earlier independent observer records.
This commit is contained in:
@@ -914,11 +914,6 @@ impl DocumentRuntime {
|
||||
let Some(document_handle) = self.inner_html_document_handle(target) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let existing_children = self
|
||||
.dom_host()
|
||||
.node(target)
|
||||
.map(|node| node.child_ids(self.dom_host().dom()).collect::<Vec<_>>())
|
||||
.unwrap_or_default();
|
||||
let empty_html_context_creates_document_wrappers = self
|
||||
.dom_host()
|
||||
.node(context)
|
||||
@@ -928,7 +923,7 @@ impl DocumentRuntime {
|
||||
.node_document_is_html_document(document_handle)
|
||||
== Some(true)
|
||||
&& html.is_empty()
|
||||
&& existing_children.is_empty()
|
||||
&& self.dom_host().child_handles(target).next().is_none()
|
||||
&& !empty_html_context_creates_document_wrappers
|
||||
{
|
||||
return Ok(false);
|
||||
@@ -945,37 +940,7 @@ impl DocumentRuntime {
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
let added_children = self.dom_host().child_handles(fragment).collect::<Vec<_>>();
|
||||
let records_enabled = self.dom_host().mutation_records_enabled();
|
||||
let removes_existing_children = !existing_children.is_empty();
|
||||
for &child in &existing_children {
|
||||
let _ = self
|
||||
.remove_child_appending_to_current_reaction_queue(scope, host_ptr, target, child);
|
||||
}
|
||||
let changed = self.append_html_fragment_child_appending_to_current_reaction_queue(
|
||||
scope, host_ptr, target, fragment,
|
||||
) || removes_existing_children;
|
||||
if changed
|
||||
&& !self.upgrade_inserted_html_fragment_custom_elements(
|
||||
scope,
|
||||
host_ptr,
|
||||
target,
|
||||
&added_children,
|
||||
)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
if changed && records_enabled {
|
||||
crate::observer_runtime::coalesce_child_list_replacement_records(
|
||||
host_ptr,
|
||||
target,
|
||||
&added_children,
|
||||
&existing_children,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
}
|
||||
Ok(changed)
|
||||
Ok(self.replace_children_with_parsed_fragment(scope, host_ptr, target, fragment))
|
||||
}
|
||||
|
||||
pub(crate) fn set_html_unsafe(
|
||||
@@ -1005,30 +970,32 @@ impl DocumentRuntime {
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
self.replace_children_with_parsed_fragment(scope, host_ptr, target, fragment)
|
||||
}
|
||||
|
||||
/// The fragment is complete before any existing children are removed.
|
||||
/// Keep the HTML fragment insertion policy (inert scripts and deferred
|
||||
/// upgrades), while treating removal and observer delivery as replace-all.
|
||||
fn replace_children_with_parsed_fragment(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
host_ptr: *mut PageScriptHost,
|
||||
target: DomHandle,
|
||||
fragment: DomHandle,
|
||||
) -> bool {
|
||||
let added_children = self.dom_host().child_handles(fragment).collect::<Vec<_>>();
|
||||
let existing_children = self
|
||||
.dom_host()
|
||||
.node(target)
|
||||
.map(|node| node.child_ids(self.dom_host().dom()).collect::<Vec<_>>())
|
||||
.unwrap_or_default();
|
||||
for child in existing_children {
|
||||
let _ = self
|
||||
.remove_child_appending_to_current_reaction_queue(scope, host_ptr, target, child);
|
||||
}
|
||||
let changed = self.append_html_fragment_child_appending_to_current_reaction_queue(
|
||||
scope, host_ptr, target, fragment,
|
||||
);
|
||||
if changed
|
||||
&& !self.upgrade_inserted_html_fragment_custom_elements(
|
||||
scope,
|
||||
host_ptr,
|
||||
target,
|
||||
&added_children,
|
||||
)
|
||||
{
|
||||
if added_children.is_empty() && self.dom_host().child_handles(target).next().is_none() {
|
||||
return false;
|
||||
}
|
||||
changed
|
||||
if !self.replace_all_children_with_html_fragment(scope, host_ptr, target, fragment) {
|
||||
return false;
|
||||
}
|
||||
self.upgrade_inserted_html_fragment_custom_elements(
|
||||
scope,
|
||||
host_ptr,
|
||||
target,
|
||||
&added_children,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn set_outer_html(
|
||||
|
||||
@@ -5,7 +5,20 @@ use crate::{
|
||||
native_bridge::PageScriptHost,
|
||||
};
|
||||
|
||||
pub(super) struct TreeRemovalFormState {
|
||||
pub(super) option_selectedness: Vec<(DomHandle, bool)>,
|
||||
pub(super) selected_option_owners: Vec<(DomHandle, DomHandle)>,
|
||||
}
|
||||
|
||||
impl DocumentRuntime {
|
||||
pub(super) fn tree_removal_form_state(&self, root: DomHandle) -> TreeRemovalFormState {
|
||||
let roots = std::slice::from_ref(&root);
|
||||
TreeRemovalFormState {
|
||||
option_selectedness: self.option_selectedness_before_insert(roots),
|
||||
selected_option_owners: self.selected_option_owners_in_subtrees(roots),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn option_selectedness_before_insert(
|
||||
&self,
|
||||
roots: &[DomHandle],
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::super::{dom_binding_timing_started, record_dom_binding_timing};
|
||||
use super::{
|
||||
focus::TreeFocusRemovalPlan,
|
||||
form_control_state::TreeRemovalFormState,
|
||||
node_iterators::NodeIteratorRemovalPlan,
|
||||
policy::{TreeMutationObserverPolicy, TreeMutationSourceProfile},
|
||||
resources::ImageRelevantMutationPlan,
|
||||
@@ -23,8 +24,7 @@ pub(super) struct TreeRemovalPlan {
|
||||
pub(super) node_iterator_plan: Option<NodeIteratorRemovalPlan>,
|
||||
pub(super) registry_retargets: Vec<custom_elements::RegistryAssociationRetarget>,
|
||||
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)>,
|
||||
pub(super) form_state: TreeRemovalFormState,
|
||||
}
|
||||
|
||||
impl DocumentRuntime {
|
||||
@@ -33,6 +33,17 @@ impl DocumentRuntime {
|
||||
host_ptr: *mut PageScriptHost,
|
||||
parent: DomHandle,
|
||||
root: DomHandle,
|
||||
) -> TreeRemovalPlan {
|
||||
let form_state = self.tree_removal_form_state(root);
|
||||
self.tree_removal_plan_with_form_state(host_ptr, parent, root, form_state)
|
||||
}
|
||||
|
||||
fn tree_removal_plan_with_form_state(
|
||||
&self,
|
||||
host_ptr: *mut PageScriptHost,
|
||||
parent: DomHandle,
|
||||
root: DomHandle,
|
||||
form_state: TreeRemovalFormState,
|
||||
) -> TreeRemovalPlan {
|
||||
let roots = std::slice::from_ref(&root);
|
||||
let lifecycle_connected_roots_before_remove = roots
|
||||
@@ -60,9 +71,6 @@ 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 {
|
||||
parent,
|
||||
root,
|
||||
@@ -73,8 +81,7 @@ impl DocumentRuntime {
|
||||
node_iterator_plan,
|
||||
registry_retargets,
|
||||
image_relevant_mutation_plan,
|
||||
option_selectedness_before_remove,
|
||||
selected_option_owners_before_remove,
|
||||
form_state,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,29 +130,47 @@ impl DocumentRuntime {
|
||||
)
|
||||
}
|
||||
|
||||
/// Implements the DOM all-children removal used by `Document::open()`.
|
||||
///
|
||||
/// The structural work still runs through the ordinary removal owner so
|
||||
/// ranges, focus, stylesheet candidates, child browsing contexts, and
|
||||
/// custom-element reactions cannot drift from `removeChild()`. Applying
|
||||
/// the collected effects once also preserves the DOM replace-all observer
|
||||
/// contract: one record containing every removed document child.
|
||||
pub(crate) fn remove_all_children_for_document_replacement(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
host_ptr: *mut PageScriptHost,
|
||||
parent: DomHandle,
|
||||
) -> bool {
|
||||
self.remove_all_children_with_source_profile(
|
||||
scope,
|
||||
host_ptr,
|
||||
parent,
|
||||
TreeMutationSourceProfile::js_dom_api_appending_to_current_reaction_queue(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Remove all children before applying runtime effects. In particular,
|
||||
/// select fallback selection must not run between these removals.
|
||||
/// Positional plans still advance in tree order for ranges and iterators.
|
||||
pub(super) fn remove_all_children_with_source_profile(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
host_ptr: *mut PageScriptHost,
|
||||
parent: DomHandle,
|
||||
profile: TreeMutationSourceProfile,
|
||||
) -> bool {
|
||||
let removed_children = self.dom_host.child_handles(parent).collect::<Vec<_>>();
|
||||
if removed_children.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Capture form state before any splice: even a read-only selectedness
|
||||
// query can choose a fallback from a partially removed select.
|
||||
let form_states = removed_children
|
||||
.iter()
|
||||
.map(|&child| self.tree_removal_form_state(child))
|
||||
.collect::<Vec<_>>();
|
||||
let mut removal_plans = Vec::with_capacity(removed_children.len());
|
||||
let mut combined_effects = DomMutationEffects::default();
|
||||
let mut prepublished_removals = Vec::new();
|
||||
for &child in &removed_children {
|
||||
let removal_plan = self.tree_removal_plan(host_ptr, parent, child);
|
||||
for (&child, form_state) in removed_children.iter().zip(form_states) {
|
||||
let removal_plan =
|
||||
self.tree_removal_plan_with_form_state(host_ptr, parent, child, form_state);
|
||||
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);
|
||||
@@ -161,6 +186,9 @@ impl DocumentRuntime {
|
||||
removal_plans.push(removal_plan);
|
||||
}
|
||||
combined_effects.coalesce_child_list_removals(parent, &removed_children);
|
||||
if profile.suppresses_observers() {
|
||||
combined_effects.suppress_child_list_mutations_for_target(parent);
|
||||
}
|
||||
|
||||
let changed = self.apply_runtime_mutation_effects_with_prepublished_removals(
|
||||
scope,
|
||||
@@ -170,8 +198,6 @@ impl DocumentRuntime {
|
||||
prepublished_removals,
|
||||
);
|
||||
if changed {
|
||||
let profile =
|
||||
TreeMutationSourceProfile::js_dom_api_appending_to_current_reaction_queue();
|
||||
for removal_plan in &removal_plans {
|
||||
self.dispatch_tree_removal_side_effects_after_change(
|
||||
scope,
|
||||
|
||||
@@ -24,12 +24,12 @@ impl DocumentRuntime {
|
||||
self.preserve_selectedness_for_options_removed_from_select(
|
||||
scope,
|
||||
host_ptr,
|
||||
&removal_plan.option_selectedness_before_remove,
|
||||
&removal_plan.form_state.option_selectedness,
|
||||
);
|
||||
self.queue_selectedcontent_updates_after_tree_removal(
|
||||
scope,
|
||||
host_ptr,
|
||||
&removal_plan.selected_option_owners_before_remove,
|
||||
&removal_plan.form_state.selected_option_owners,
|
||||
);
|
||||
self.dispatch_tree_removal_pre_reaction_followups_after_change(
|
||||
scope,
|
||||
|
||||
@@ -7,14 +7,49 @@ use crate::{
|
||||
};
|
||||
|
||||
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_appending_to_current_reaction_queue(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
host_ptr: *mut PageScriptHost,
|
||||
parent: DomHandle,
|
||||
node: Option<DomHandle>,
|
||||
) -> bool {
|
||||
self.replace_all_children_with_source_profile(
|
||||
scope,
|
||||
host_ptr,
|
||||
parent,
|
||||
node,
|
||||
TreeMutationSourceProfile::js_dom_api_appending_to_current_reaction_queue(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn replace_all_children_with_html_fragment(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
host_ptr: *mut PageScriptHost,
|
||||
parent: DomHandle,
|
||||
fragment: DomHandle,
|
||||
) -> bool {
|
||||
self.replace_all_children_with_source_profile(
|
||||
scope,
|
||||
host_ptr,
|
||||
parent,
|
||||
Some(fragment),
|
||||
TreeMutationSourceProfile::html_fragment_insertion_appending_to_current_reaction_queue(
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// DOM replace-all: conversion and parsing have already completed. Suppress
|
||||
/// only this operation's intermediate target records, then queue its own
|
||||
/// replacement record without merging earlier, independent mutations.
|
||||
fn replace_all_children_with_source_profile(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
host_ptr: *mut PageScriptHost,
|
||||
parent: DomHandle,
|
||||
node: Option<DomHandle>,
|
||||
source_profile: TreeMutationSourceProfile,
|
||||
) -> bool {
|
||||
let removed = self.dom_host.child_handles(parent).collect::<Vec<_>>();
|
||||
let added = node
|
||||
@@ -23,19 +58,16 @@ impl DocumentRuntime {
|
||||
.unwrap_or_else(|| vec![node])
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let source_profile =
|
||||
TreeMutationSourceProfile::js_dom_api_appending_to_current_reaction_queue()
|
||||
.suppressing_observers();
|
||||
for &child in &removed {
|
||||
if !self.remove_child_with_source_profile(
|
||||
let source_profile = source_profile.suppressing_observers();
|
||||
if !removed.is_empty()
|
||||
&& !self.remove_all_children_with_source_profile(
|
||||
scope,
|
||||
host_ptr,
|
||||
parent,
|
||||
child,
|
||||
source_profile,
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let inserted = match node {
|
||||
Some(node) => self.insert_before_with_source_profile(
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bulk_child_removal_preserves_option_selectedness_and_one_observer_record() {
|
||||
let mut vm = new_parsed_test_vm(
|
||||
"https://bulk-child-removal.test/",
|
||||
"<!doctype html><iframe id=child></iframe>",
|
||||
);
|
||||
let result = vm
|
||||
.eval(include_str!(
|
||||
"../../../../tests/fixtures/bulk-child-removal.js"
|
||||
))
|
||||
.expect("bulk child removal matrix should complete");
|
||||
assert_eq!(vm.eval("__uiEventResults.total").unwrap(), "1794");
|
||||
assert_eq!(
|
||||
result,
|
||||
"true",
|
||||
"{}",
|
||||
vm.eval("JSON.stringify(__uiEventResults.rows.filter(row => !row.passed))")
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_child_removal_preserves_ranges_and_custom_element_reaction_order() {
|
||||
let mut vm = new_parsed_test_vm(
|
||||
"https://bulk-child-removal-boundaries.test/",
|
||||
"<!doctype html><iframe id=child></iframe>",
|
||||
);
|
||||
let result = vm
|
||||
.eval(include_str!(
|
||||
"../../../../tests/fixtures/bulk-child-removal-boundaries.js"
|
||||
))
|
||||
.expect("bulk child removal boundary matrix should complete");
|
||||
assert_eq!(vm.eval("__uiEventResults.total").unwrap(), "32");
|
||||
assert_eq!(
|
||||
result,
|
||||
"true",
|
||||
"{}",
|
||||
vm.eval("JSON.stringify(__uiEventResults.rows.filter(row => !row.passed))")
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bulk_child_removal_keeps_prior_independent_observer_records() {
|
||||
let mut vm = new_parsed_test_vm(
|
||||
"https://bulk-child-removal-record-history.test/",
|
||||
"<!doctype html><iframe id=child></iframe>",
|
||||
);
|
||||
let result = vm
|
||||
.eval(include_str!(
|
||||
"../../../../tests/fixtures/bulk-child-removal-record-history.js"
|
||||
))
|
||||
.expect("bulk child removal record history matrix should complete");
|
||||
assert_eq!(vm.eval("__uiEventResults.total").unwrap(), "32");
|
||||
assert_eq!(
|
||||
result,
|
||||
"true",
|
||||
"{}",
|
||||
vm.eval("JSON.stringify(__uiEventResults.rows.filter(row => !row.passed))")
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ mod adopted_style_sheets;
|
||||
mod bar_prop;
|
||||
mod basic_event_init;
|
||||
mod broadcast_channel;
|
||||
mod bulk_child_removal;
|
||||
mod cache_add;
|
||||
mod cache_array_results;
|
||||
mod cache_query;
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
(() => {
|
||||
const rows = [];
|
||||
const realms = [['main', globalThis], ['child', document.querySelector('#child').contentWindow]];
|
||||
const same = (a, b) => a.length === b.length && a.every((value, index) => value === b[index]);
|
||||
for (const [ownerName, owner] of realms) {
|
||||
const callbacks = [];
|
||||
owner.customElements.define('bulk-removal-child', class extends owner.HTMLElement {
|
||||
disconnectedCallback() {
|
||||
callbacks.push({node: this, siblingsGone: this.savedSiblings.every(sibling => sibling.parentNode === null),
|
||||
replacement: this.savedParent.firstChild});
|
||||
}
|
||||
});
|
||||
for (const [calleeName, callee] of realms) {
|
||||
for (const sink of ['innerHTML', 'textContent', 'replaceChildren', 'setHTMLUnsafe']) {
|
||||
for (const replace of [false, true]) {
|
||||
const name = `${calleeName}/${ownerName}/${sink}/${replace}`;
|
||||
const host = owner.document.body.appendChild(owner.document.createElement('div'));
|
||||
const nodes = ['alpha', 'middle', 'omega'].map(text => {
|
||||
const node = host.appendChild(owner.document.createElement('bulk-removal-child'));
|
||||
node.appendChild(owner.document.createTextNode(text));
|
||||
return node;
|
||||
});
|
||||
nodes.forEach(node => {node.savedSiblings = nodes; node.savedParent = host;});
|
||||
callbacks.length = 0;
|
||||
const firstText = nodes[0].firstChild;
|
||||
const inside = owner.document.createRange(); inside.setStart(firstText, 1); inside.setEnd(firstText, 3);
|
||||
const boundary = owner.document.createRange(); boundary.setStart(host, 1); boundary.setEnd(host, 3);
|
||||
const subtreeIterator = owner.document.createNodeIterator(nodes[0]);
|
||||
subtreeIterator.nextNode();subtreeIterator.nextNode();
|
||||
const walker = owner.document.createTreeWalker(host);walker.currentNode = firstText;
|
||||
const observer = new owner.MutationObserver(() => {});
|
||||
observer.observe(host, {childList: true, subtree: true, characterData: true, characterDataOldValue: true});
|
||||
try {
|
||||
if (sink === 'innerHTML') Object.getOwnPropertyDescriptor(callee.Element.prototype, 'innerHTML').set.call(host,
|
||||
replace ? '<u>replacement</u>' : '');
|
||||
else if (sink === 'textContent') Object.getOwnPropertyDescriptor(callee.Node.prototype, 'textContent').set.call(host,
|
||||
replace ? 'replacement' : '');
|
||||
else if (sink === 'replaceChildren') {
|
||||
if (replace) callee.Element.prototype.replaceChildren.call(host, owner.document.createElement('u'));
|
||||
else callee.Element.prototype.replaceChildren.call(host);
|
||||
} else callee.Element.prototype.setHTMLUnsafe.call(host, replace ? '<u>replacement</u>' : '');
|
||||
const added = [...host.childNodes];
|
||||
const records = observer.takeRecords();
|
||||
const failures = [];
|
||||
if (![inside, boundary].every(range => range.startContainer === host && range.endContainer === host &&
|
||||
range.startOffset === 0 && range.endOffset === 0 && range.collapsed)) failures.push('ranges');
|
||||
if (subtreeIterator.referenceNode !== firstText || subtreeIterator.nextNode() !== null) failures.push('subtree iterator');
|
||||
if (walker.currentNode !== firstText) failures.push('walker');
|
||||
if (!same(callbacks.map(row => row.node), nodes) || !callbacks.every(row => row.siblingsGone && row.replacement === host.firstChild))
|
||||
failures.push('reactions');
|
||||
if (records.length !== 1 || records[0].target !== host || records[0].previousSibling !== null || records[0].nextSibling !== null ||
|
||||
!same([...records[0].removedNodes], nodes) || !same([...records[0].addedNodes], added)) failures.push('replacement record');
|
||||
rows.push({name, passed: failures.length === 0, failures});
|
||||
} catch (error) {rows.push({name, passed: false, error: String(error)});}
|
||||
finally {observer.disconnect();host.remove();}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
globalThis.__uiEventResults = {complete: true, total: rows.length, passed: rows.filter(row => row.passed).length, rows};
|
||||
return rows.every(row => row.passed);
|
||||
})()
|
||||
@@ -0,0 +1,38 @@
|
||||
(() => {
|
||||
const rows = [], realms = [['main', globalThis], ['child', document.querySelector('#child').contentWindow]];
|
||||
const same = (a, b) => a.length === b.length && a.every((value, index) => value === b[index]);
|
||||
for (const [ownerName, owner] of realms) for (const [calleeName, callee] of realms) {
|
||||
for (const sink of ['innerHTML', 'textContent', 'replaceChildren', 'setHTMLUnsafe']) for (const replacement of [false, true]) {
|
||||
const name = `${calleeName}/${ownerName}/${sink}/${replacement}`;
|
||||
const host = owner.document.body.appendChild(owner.document.createElement('div'));
|
||||
const nodes = ['i', 'b', 'u'].map(tag => host.appendChild(owner.document.createElement(tag)));
|
||||
const observer = new owner.MutationObserver(() => {});
|
||||
observer.observe(host, {childList: true});
|
||||
try {
|
||||
host.removeChild(nodes[0]);
|
||||
host.insertBefore(nodes[0], nodes[1]);
|
||||
if (sink === 'innerHTML') Object.getOwnPropertyDescriptor(callee.Element.prototype, 'innerHTML').set.call(host,
|
||||
replacement ? '<em>new</em>' : '');
|
||||
else if (sink === 'textContent') Object.getOwnPropertyDescriptor(callee.Node.prototype, 'textContent').set.call(host,
|
||||
replacement ? 'new' : '');
|
||||
else if (sink === 'replaceChildren') {
|
||||
if (replacement) callee.Element.prototype.replaceChildren.call(host, owner.document.createElement('em'));
|
||||
else callee.Element.prototype.replaceChildren.call(host);
|
||||
} else callee.Element.prototype.setHTMLUnsafe.call(host, replacement ? '<em>new</em>' : '');
|
||||
const records = observer.takeRecords();
|
||||
const added = [...host.childNodes];
|
||||
const passed = records.length === 3 && records.every(record => record.target === host) &&
|
||||
same([...records[0].removedNodes], [nodes[0]]) && records[0].addedNodes.length === 0 &&
|
||||
records[0].previousSibling === null && records[0].nextSibling === nodes[1] &&
|
||||
same([...records[1].addedNodes], [nodes[0]]) && records[1].removedNodes.length === 0 &&
|
||||
records[1].previousSibling === null && records[1].nextSibling === nodes[1] &&
|
||||
same([...records[2].removedNodes], nodes) && same([...records[2].addedNodes], added) &&
|
||||
records[2].previousSibling === null && records[2].nextSibling === null;
|
||||
rows.push({name, passed});
|
||||
} catch (error) {rows.push({name, passed: false, error: String(error)});}
|
||||
finally {observer.disconnect();host.remove();}
|
||||
}
|
||||
}
|
||||
globalThis.__uiEventResults = {complete: true, total: rows.length, passed: rows.filter(row => row.passed).length, rows};
|
||||
return rows.every(row => row.passed);
|
||||
})()
|
||||
@@ -0,0 +1,86 @@
|
||||
(() => {
|
||||
const rows = [], H = 'http://www.w3.org/1999/xhtml';
|
||||
const realms = [['main', globalThis], ['child', document.querySelector('#child').contentWindow]];
|
||||
const check = (name, body) => {
|
||||
try { rows.push({name, passed: body() === true}); }
|
||||
catch (error) {rows.push({name, passed: false, error: String(error)});}
|
||||
};
|
||||
const same = (left, right) => left.length === right.length && left.every((value, index) => value === right[index]);
|
||||
const documents = (owner, flavor) => flavor === 'live' ? owner.document : flavor === 'html' ?
|
||||
owner.document.implementation.createHTMLDocument('bulk removal') : flavor === 'parsed' ?
|
||||
new owner.DOMParser().parseFromString('<!doctype html><body>', 'text/html') :
|
||||
owner.document.implementation.createDocument(H, 'html');
|
||||
const modes = ['default', 'first', 'middle', 'dirty-middle', 'last', 'multiple', 'listbox'];
|
||||
for (const [ownerName, owner] of realms) for (const flavor of ['live', 'html', 'parsed', 'xml']) {
|
||||
const doc = documents(owner, flavor);
|
||||
for (const [calleeName, callee] of realms) for (const grouped of [false, true]) for (const mode of modes) {
|
||||
for (const sink of ['innerHTML', 'textContent', 'replaceChildren', 'setHTMLUnsafe']) for (const replacement of [false, true]) {
|
||||
const label = `${calleeName}/${ownerName}/${flavor}/${grouped}/${mode}/${sink}/${replacement}`;
|
||||
check(label, () => {
|
||||
const select = doc.createElementNS(H, 'select');
|
||||
select.multiple = mode === 'multiple';
|
||||
if (mode === 'listbox') select.size = 3;
|
||||
const group = grouped ? select.appendChild(doc.createElementNS(H, 'optgroup')) : select;
|
||||
const options = ['one', 'two', 'three'].map(value => {
|
||||
const option = doc.createElementNS(H, 'option');option.value = value;option.textContent = value;
|
||||
if ((mode === 'first' && value === 'one') ||
|
||||
(['middle', 'listbox'].includes(mode) && value === 'two') ||
|
||||
(mode === 'last' && value === 'three') ||
|
||||
(mode === 'multiple' && value !== 'three')) option.defaultSelected = true;
|
||||
group.appendChild(option);return option;
|
||||
});
|
||||
(doc.body || doc.documentElement).appendChild(select);
|
||||
if (mode === 'dirty-middle') select.value = 'two';
|
||||
const selected = options.map(option => option.selected);
|
||||
const original = [...select.childNodes];
|
||||
const live = select.selectedOptions;
|
||||
const observer = new owner.MutationObserver(() => {});
|
||||
observer.observe(select, {childList: true});
|
||||
try {
|
||||
if (sink === 'innerHTML') Object.getOwnPropertyDescriptor(callee.Element.prototype, 'innerHTML').set.call(select,
|
||||
replacement ? '<option selected="">new</option>' : '');
|
||||
else if (sink === 'textContent') Object.getOwnPropertyDescriptor(callee.Node.prototype, 'textContent').set.call(select,
|
||||
replacement ? 'new' : '');
|
||||
else if (sink === 'replaceChildren') {
|
||||
const method = callee.Element.prototype.replaceChildren;
|
||||
if (replacement) method.call(select, doc.createElementNS(H, 'option'));
|
||||
else method.call(select);
|
||||
} else callee.Element.prototype.setHTMLUnsafe.call(select,
|
||||
replacement ? '<option selected="">new</option>' : '');
|
||||
const records = observer.takeRecords();
|
||||
const removedSelectedness = options.map(option => option.selected);
|
||||
const added = [...select.childNodes];
|
||||
if (!same(removedSelectedness, selected) || !options.every(option => option.ownerDocument === doc) ||
|
||||
records.length !== 1 || records[0].target !== select || records[0].previousSibling !== null || records[0].nextSibling !== null ||
|
||||
!same([...records[0].removedNodes], original) || !same([...records[0].addedNodes], added)) return false;
|
||||
// Clear only the newly constructed children; the original options
|
||||
// are still detached and their selectedness must remain intact.
|
||||
while (select.firstChild) select.removeChild(select.firstChild);
|
||||
if (live.length !== 0) return false;
|
||||
if (grouped) {
|
||||
for (const option of options) if (option.parentNode !== group) return false;
|
||||
select.appendChild(group);
|
||||
} else for (const option of options) select.appendChild(option);
|
||||
return same(options.map(option => option.selected), selected) &&
|
||||
same([...live], options.filter((_, index) => selected[index]));
|
||||
} finally {observer.disconnect();select.remove();}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Individual removals remain observable operations: the select chooses a
|
||||
// new fallback after each removal. They must not inherit batch semantics.
|
||||
for (const [ownerName, owner] of realms) {
|
||||
check(ownerName+'/sequential removal preserves its separate fallback selections', () => {
|
||||
const select = owner.document.createElement('select');
|
||||
select.innerHTML = '<option>one</option><option selected>two</option><option>three</option>';
|
||||
const options = [...select.options];
|
||||
select.removeChild(options[0]);select.removeChild(options[1]);select.removeChild(options[2]);
|
||||
const flags = options.map(option => option.selected);
|
||||
options.forEach(option => select.appendChild(option));
|
||||
return same(flags, [false, true, true]) && select.value === 'three';
|
||||
});
|
||||
}
|
||||
globalThis.__uiEventResults = {complete: true, total: rows.length, passed: rows.filter(row => row.passed).length, rows};
|
||||
return rows.every(row => row.passed);
|
||||
})()
|
||||
Reference in New Issue
Block a user