mirror of
https://github.com/lexmount/moli.git
synced 2026-11-18 16:08:37 +00:00
fix(dom): select fragment parser contexts from native Range state
Extracted from 0c2db95817 on wpt-misc-fix.
This commit is contained in:
@@ -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;
|
||||
};
|
||||
|
||||
@@ -32,12 +32,6 @@ enum DocumentWriteParserPumpInput<'a> {
|
||||
QueuedOrBuffered,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||
enum HtmlFragmentParserContextMode {
|
||||
Standard,
|
||||
RangeCreateContextualFragment,
|
||||
}
|
||||
|
||||
struct DocumentWriteParserMutationOwner<'a, 'scope, 'pin> {
|
||||
runtime: &'a mut DocumentRuntime,
|
||||
scope: &'a mut v8::PinScope<'scope, 'pin>,
|
||||
@@ -523,7 +517,7 @@ impl DocumentRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
fn build_fragment_from_html_with_context_mode(
|
||||
fn build_fragment_from_html_internal(
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
host_ptr: *mut PageScriptHost,
|
||||
@@ -532,7 +526,6 @@ impl DocumentRuntime {
|
||||
html: &str,
|
||||
scripts_already_started: bool,
|
||||
custom_element_upgrade_timing: HtmlFragmentCustomElementUpgradeTiming,
|
||||
context_mode: HtmlFragmentParserContextMode,
|
||||
scripting_enabled: bool,
|
||||
allow_declarative_shadow_roots: bool,
|
||||
) -> Option<DomHandle> {
|
||||
@@ -543,16 +536,10 @@ impl DocumentRuntime {
|
||||
.and_then(Node::namespace)
|
||||
.unwrap_or("http://www.w3.org/1999/xhtml")
|
||||
.to_owned();
|
||||
let mut context_local_name = context_node
|
||||
let context_local_name = context_node
|
||||
.and_then(Node::local_name)
|
||||
.unwrap_or("body")
|
||||
.to_owned();
|
||||
if context_mode == HtmlFragmentParserContextMode::RangeCreateContextualFragment
|
||||
&& context_namespace == "http://www.w3.org/1999/xhtml"
|
||||
&& context_local_name.eq_ignore_ascii_case("html")
|
||||
{
|
||||
context_local_name = "body".to_owned();
|
||||
}
|
||||
let is_frameset_context = context_namespace == "http://www.w3.org/1999/xhtml"
|
||||
&& context_local_name.eq_ignore_ascii_case("frameset");
|
||||
let registry_association =
|
||||
@@ -647,7 +634,7 @@ impl DocumentRuntime {
|
||||
html: &str,
|
||||
) -> Option<DomHandle> {
|
||||
let scripting_enabled = unsafe { &*host_ptr }.document_scripting_enabled(document_handle);
|
||||
self.build_fragment_from_html_with_context_mode(
|
||||
self.build_fragment_from_html_internal(
|
||||
scope,
|
||||
host_ptr,
|
||||
document_handle,
|
||||
@@ -655,7 +642,6 @@ impl DocumentRuntime {
|
||||
html,
|
||||
false,
|
||||
HtmlFragmentCustomElementUpgradeTiming::InReturnedFragment,
|
||||
HtmlFragmentParserContextMode::RangeCreateContextualFragment,
|
||||
scripting_enabled,
|
||||
false,
|
||||
)
|
||||
@@ -672,7 +658,7 @@ impl DocumentRuntime {
|
||||
custom_element_upgrade_timing: HtmlFragmentCustomElementUpgradeTiming,
|
||||
) -> Option<DomHandle> {
|
||||
let scripting_enabled = unsafe { &*host_ptr }.document_scripting_enabled(document_handle);
|
||||
self.build_fragment_from_html_with_context_mode(
|
||||
self.build_fragment_from_html_internal(
|
||||
scope,
|
||||
host_ptr,
|
||||
document_handle,
|
||||
@@ -680,7 +666,6 @@ impl DocumentRuntime {
|
||||
html,
|
||||
scripts_already_started,
|
||||
custom_element_upgrade_timing,
|
||||
HtmlFragmentParserContextMode::Standard,
|
||||
scripting_enabled,
|
||||
false,
|
||||
)
|
||||
@@ -696,7 +681,7 @@ impl DocumentRuntime {
|
||||
custom_element_upgrade_timing: HtmlFragmentCustomElementUpgradeTiming,
|
||||
) -> Option<DomHandle> {
|
||||
let scripting_enabled = unsafe { &*host_ptr }.document_scripting_enabled(document_handle);
|
||||
self.build_fragment_from_html_with_context_mode(
|
||||
self.build_fragment_from_html_internal(
|
||||
scope,
|
||||
host_ptr,
|
||||
document_handle,
|
||||
@@ -704,7 +689,6 @@ impl DocumentRuntime {
|
||||
html,
|
||||
true,
|
||||
custom_element_upgrade_timing,
|
||||
HtmlFragmentParserContextMode::Standard,
|
||||
scripting_enabled,
|
||||
true,
|
||||
)
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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);
|
||||
})()
|
||||
Reference in New Issue
Block a user