fix(dom): select fragment parser contexts from native Range state

Read the stored start boundary and native node document instead of public
Node properties. Use parent elements for Text, CDATA and Comment contexts
and create an HTML body for the specified fallback cases.

Remove the script-visible detached DOM fallback and preserve the Range
receiver realm when wrapping the fragment. Cover property overrides,
windowless and parsed documents, cross-realm calls, conversion ordering,
and registered native Range proxies.
This commit is contained in:
ldm0
2026-11-03 18:08:17 +08:00
parent c884224a7b
commit 2b2e686efe
5 changed files with 151 additions and 91 deletions
@@ -1,21 +1,49 @@
use super::*;
use crate::util::{
call_script_visible_function, object_property_as_object, utf16_slice_lossy, v8_string, v8str,
};
use crate::util::utf16_slice_lossy;
pub(in crate::context_bootstrap) fn create_contextual_fragment_internal<'s>(
scope: &mut v8::PinScope<'s, '_>,
receiver: v8::Local<'s, v8::Object>,
context_node: v8::Local<'s, v8::Object>,
html: &str,
) -> Option<v8::Local<'s, v8::Object>> {
let start = native_range_boundary_point(scope, receiver, RangeBoundarySide::Start)?.container();
let host_ptr = context_host_ptr_from_global_bridge(scope)?;
let runtime = unsafe { &mut *host_ptr };
let document = node_owner_document_or_self(scope, context_node)?;
let Some(context_handle) = range_tree_op_node_handle(scope, host_ptr, context_node) else {
return create_detached_contextual_fragment(scope, document, html);
let document_handle = runtime.dom_host().owner_document_handle(start)?;
let element = match runtime.dom_host().node(start)?.node_type() {
NodeType::Element => Some(start),
NodeType::Text | NodeType::CDataSection | NodeType::Comment => {
runtime.dom_host().parent_node(start).filter(|parent| {
runtime
.dom_host()
.node(*parent)
.is_some_and(|node| node.is_element())
})
}
_ => None,
};
let document_handle = range_tree_op_node_handle(scope, host_ptr, document)?;
let element = element.filter(|element| {
!(runtime
.dom_host()
.node_document_is_html_document(*element)
.unwrap_or(false)
&& runtime
.dom_host()
.node(*element)
.is_some_and(|node| node.is_html_element_named("html")))
});
// Context selection uses the actual tree, including for windowless documents
// and registered native Proxies. Public Node properties are author-controlled.
let context_handle = element.unwrap_or_else(|| {
runtime
.dom_host_mut()
.create_element_without_attributes_for_document(
document_handle,
"body".to_owned(),
"http://www.w3.org/1999/xhtml".to_owned(),
None,
)
});
let fragment = runtime.build_range_contextual_fragment_from_html(
scope,
host_ptr,
@@ -28,66 +56,6 @@ pub(in crate::context_bootstrap) fn create_contextual_fragment_internal<'s>(
.wrap_handle_for_receiver(scope, host_ptr, receiver, fragment)
}
fn create_detached_contextual_fragment<'s>(
scope: &mut v8::PinScope<'s, '_>,
document: v8::Local<'s, v8::Object>,
html: &str,
) -> Option<v8::Local<'s, v8::Object>> {
let implementation = object_property_as_object(scope, document, "implementation")?;
let create_html_document =
implementation.get(scope, v8str(scope, "createHTMLDocument").into())?;
let create_html_document = v8::Local::<v8::Function>::try_from(create_html_document).ok()?;
let empty_title = v8_string(scope, "")?;
let scratch = call_script_visible_function(
scope,
create_html_document,
implementation.into(),
&[empty_title.into()],
"Range.createContextualFragment detached createHTMLDocument fallback",
)?;
let scratch = v8::Local::<v8::Object>::try_from(scratch).ok()?;
let scratch_body = object_property_as_object(scope, scratch, "body")?;
let html = v8_string(scope, html)?;
let _ = scratch_body.set(scope, v8str(scope, "innerHTML").into(), html.into());
let create_fragment = document.get(scope, v8str(scope, "createDocumentFragment").into())?;
let create_fragment = v8::Local::<v8::Function>::try_from(create_fragment).ok()?;
let fragment = call_script_visible_function(
scope,
create_fragment,
document.into(),
&[],
"Range.createContextualFragment detached createDocumentFragment fallback",
)?;
let fragment = v8::Local::<v8::Object>::try_from(fragment).ok()?;
let import_node = document.get(scope, v8str(scope, "importNode").into())?;
let import_node = v8::Local::<v8::Function>::try_from(import_node).ok()?;
let append_child = fragment.get(scope, v8str(scope, "appendChild").into())?;
let append_child = v8::Local::<v8::Function>::try_from(append_child).ok()?;
let child_nodes = object_property_as_object(scope, scratch_body, "childNodes")?;
let length = child_nodes
.get(scope, v8str(scope, "length").into())
.and_then(|length| length.uint32_value(scope))?;
for index in 0..length {
let child = child_nodes.get_index(scope, index)?;
let imported = call_script_visible_function(
scope,
import_node,
document.into(),
&[child, v8::Boolean::new(scope, true).into()],
"Range.createContextualFragment detached importNode fallback",
)?;
let _ = call_script_visible_function(
scope,
append_child,
fragment.into(),
&[imported],
"Range.createContextualFragment detached appendChild fallback",
);
}
Some(fragment)
}
pub(in crate::context_bootstrap::range_algorithms) fn create_document_fragment_handle(
scope: &mut v8::PinScope<'_, '_>,
document_handle: Option<DomHandle>,
@@ -89,22 +89,7 @@ pub(super) fn range_create_contextual_fragment_callback<'s>(
) else {
return;
};
let Some(start_container) =
range_boundary_container_object(scope, args.this(), RangeBoundarySide::Start)
else {
rv.set_undefined();
return;
};
let context_node =
if object_number_property(scope, start_container, "nodeType").unwrap_or(0.0) as u32 == 3 {
object_property_as_object(scope, start_container, "parentNode")
.unwrap_or(start_container)
} else {
start_container
};
let Some(fragment) =
create_contextual_fragment_internal(scope, args.this(), context_node, &markup)
else {
let Some(fragment) = create_contextual_fragment_internal(scope, args.this(), &markup) else {
rv.set_undefined();
return;
};
@@ -38,7 +38,6 @@ enum DocumentWriteParserPumpInput<'a> {
#[derive(Clone, Copy, Eq, PartialEq)]
enum HtmlFragmentParserContextMode {
Standard,
RangeCreateContextualFragment,
SiblingInsertion,
}
@@ -613,11 +612,8 @@ impl DocumentRuntime {
.and_then(Node::local_name)
.unwrap_or("body")
.to_owned();
if matches!(
context_mode,
HtmlFragmentParserContextMode::RangeCreateContextualFragment
| HtmlFragmentParserContextMode::SiblingInsertion
) && context_namespace == "http://www.w3.org/1999/xhtml"
if context_mode == HtmlFragmentParserContextMode::SiblingInsertion
&& context_namespace == "http://www.w3.org/1999/xhtml"
&& context_local_name.eq_ignore_ascii_case("html")
{
context_local_name = "body".to_owned();
@@ -724,7 +720,7 @@ impl DocumentRuntime {
html,
false,
HtmlFragmentCustomElementUpgradeTiming::InReturnedFragment,
HtmlFragmentParserContextMode::RangeCreateContextualFragment,
HtmlFragmentParserContextMode::Standard,
scripting_enabled,
false,
)
@@ -1,5 +1,26 @@
use super::*;
#[test]
fn range_contextual_fragments_use_native_context_and_preserve_receiver_realm() {
let mut vm = new_parsed_test_vm(
"https://range-contextual-fragments.test/",
"<!doctype html><iframe id=child></iframe>",
);
let result = vm
.eval(include_str!(
"../../../../tests/fixtures/range-contextual-fragment-native-context.js"
))
.expect("Contextual fragment context matrix should complete");
assert_eq!(vm.eval("__uiEventResults.total").unwrap(), "420");
assert_eq!(
result,
"true",
"{}",
vm.eval("JSON.stringify(__uiEventResults.rows.filter(row => !row.passed))")
.unwrap(),
);
}
#[test]
fn range_members_validate_native_receivers_before_argument_conversion() {
let mut vm = new_parsed_test_vm(
@@ -126,6 +147,14 @@ fn range_registered_native_proxies_share_boundaries_and_selection_identity() {
check(clone !== target && clone.startContainer === text && clone.startOffset === 2, 'cloneRange');
const fragment = methods.cloneContents.call(proxy);
check(fragment.textContent === 'c' && fragment.ownerDocument === text.ownerDocument, 'cloneContents');
if (flavor !== 'xml') {
for (const name of ['nodeType', 'parentNode', 'ownerDocument'])
Object.defineProperty(text, name, {configurable: true, get() {throw Error('public ' + name);}});
const parsed = methods.createContextualFragment.call(proxy, '<b>parsed</b>');
for (const name of ['nodeType', 'parentNode', 'ownerDocument']) delete text[name];
check(parsed.firstChild.localName === 'b' && parsed.textContent === 'parsed' &&
parsed.ownerDocument === text.ownerDocument, 'native contextual fragment');
}
methods.collapse.call(proxy, false);
check(get('collapsed') && get('startOffset') === 3 && target.startOffset === 3, 'collapse');
if (selected) {
@@ -0,0 +1,82 @@
(() => {
const rows = [];
const check = (name, body) => {
try { rows.push({name, passed: body() === true}); }
catch (error) { rows.push({name, passed: false, error: String(error)}); }
};
const realms = [['main', globalThis], ['child', document.querySelector('#child').contentWindow]];
const makeDocument = (owner, flavor) => flavor === 'live' ? owner.document :
flavor === 'html' ? owner.document.implementation.createHTMLDocument('fragment') :
new owner.DOMParser().parseFromString('<!doctype html><title>fragment</title><body>', 'text/html');
const makeContext = (doc, kind) => {
const table = doc.createElement('table');
if (kind === 'table') return {node: table, context: table};
if (kind === 'text' || kind === 'comment') {
const node = table.appendChild(kind === 'text' ? doc.createTextNode('x') : doc.createComment('x'));
return {node, context: table};
}
const body = doc.createElement('body');
if (kind === 'document') return {node: doc, context: body};
if (kind === 'fragment') return {node: doc.createDocumentFragment(), context: body};
if (kind === 'orphan-text') return {node: doc.createTextNode('x'), context: body};
if (kind === 'html') return {node: doc.documentElement, context: body};
const node = doc.createElement('div');
return {node, context: node};
};
for (const [ownerName, owner] of realms) for (const flavor of ['live', 'html', 'parsed']) {
const doc = makeDocument(owner, flavor);
for (const [calleeName, callee] of realms) {
const parse = callee.Range.prototype.createContextualFragment;
for (const kind of ['table', 'text', 'comment', 'div', 'document', 'fragment', 'orphan-text', 'html']) {
for (const property of [null, 'nodeType', 'parentNode', 'ownerDocument']) {
check(`${calleeName}/${ownerName}/${flavor}/${kind}/${property || 'plain'}`, () => {
const {node, context} = makeContext(doc, kind);
const reference = doc.createRange(); reference.selectNodeContents(context);
const expected = reference.createContextualFragment('<tr><td>x</td></tr>');
const range = doc.createRange(); range.setStart(node, 0);
let reads = 0;
const previous = property && Object.getOwnPropertyDescriptor(node, property);
if (property) Object.defineProperty(node, property, {configurable: true, get() {reads++; throw Error('public ' + property);}});
let fragment;
try { fragment = parse.call(range, '<tr><td>x</td></tr>'); }
finally {
if (property) {
if (previous) Object.defineProperty(node, property, previous);
else delete node[property];
}
}
return reads === 0 && fragment.ownerDocument === doc && fragment.isEqualNode(expected) &&
Object.getPrototypeOf(fragment) === owner.DocumentFragment.prototype &&
range.startContainer === node && range.startOffset === 0;
});
}
}
check(`${calleeName}/${ownerName}/${flavor}/conversion changes start`, () => {
const range = doc.createRange(), table = doc.createElement('table');
range.selectNodeContents(doc.createElement('div'));
let conversions = 0;
const fragment = parse.call(range, {toString() {
conversions++; range.selectNodeContents(table); return '<tr><td>x</td></tr>';
}});
return conversions === 1 && fragment.firstChild.localName === 'tbody' &&
fragment.ownerDocument === doc && range.startContainer === table;
});
check(`${calleeName}/${ownerName}/${flavor}/conversion exception identity`, () => {
const range = doc.createRange(), sentinel = {};
try { parse.call(range, {toString() {throw sentinel;}}); return false; }
catch (error) { return error === sentinel; }
});
}
for (const [rangeName, rangeOwner] of realms) check(`${rangeName}/${ownerName}/${flavor}/moved range owner realm`, () => {
const range = new rangeOwner.Range(), context = doc.createElement('table');
range.selectNodeContents(context);
const fragment = rangeOwner.Range.prototype.createContextualFragment.call(range, '<tr><td>x</td></tr>');
return fragment.ownerDocument === doc && Object.getPrototypeOf(fragment) === rangeOwner.DocumentFragment.prototype &&
Object.getPrototypeOf(fragment.firstChild) === rangeOwner.HTMLTableSectionElement.prototype &&
fragment.firstChild.localName === 'tbody';
});
}
globalThis.__uiEventResults = {complete: true, total: rows.length,
passed: rows.filter(row => row.passed).length, rows};
return rows.every(row => row.passed);
})()