Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(cssom): derive computed-style arguments and handle disconnected elements

ldm09e66b13ac19d
diff --git a/moli-renderer-v8/src/native_bridge/context_host/popups.rs b/moli-renderer-v8/src/native_bridge/context_host/popups.rs
index 7d98f934c..f8a53e3fd 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/popups.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/popups.rs
@@ -4685,13 +4685,11 @@ fn lightweight_popup_get_computed_style_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
- if args.length() == 0 {
- throw_type_error(
- scope,
- "Failed to execute 'getComputedStyle' on 'Window': 1 argument required, but only 0 present.",
- );
+ let Some(parsed) =
+ crate::webidl::parse_args::<crate::window_host::GetComputedStyleArgs>(scope, &args)
+ else {
return;
- }
+ };
let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
rv.set_null();
return;
@@ -4703,7 +4701,7 @@ fn lightweight_popup_get_computed_style_callback<'s>(
let Some(target) = crate::native_bridge::node::current_or_live_delegate_node_arg_handle(
scope,
host_ptr,
- args.get(0),
+ parsed.element.into(),
) else {
rv.set_null();
return;
@@ -4723,7 +4721,7 @@ fn lightweight_popup_get_computed_style_callback<'s>(
forced_empty,
pseudo_element,
pseudo_key,
- } = crate::window_host::computed_style_pseudo_argument_from_function_args(scope, &args);
+ } = parsed.pseudo_argument();
let descriptor =
ComputedStyleDescriptor::new(pseudo_key, ComputedStyleTargetKey::PopupDocument(document));
let host = unsafe { &mut *host_ptr };
diff --git a/moli-renderer-v8/src/native_bridge/document/detached_install/accessors/iframe_style.rs b/moli-renderer-v8/src/native_bridge/document/detached_install/accessors/iframe_style.rs
index 9796ec6c0..8bea41be2 100644
--- a/moli-renderer-v8/src/native_bridge/document/detached_install/accessors/iframe_style.rs
+++ b/moli-renderer-v8/src/native_bridge/document/detached_install/accessors/iframe_style.rs
@@ -42,6 +42,11 @@ fn detached_iframe_get_computed_style_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
+ let Some(parsed) =
+ crate::webidl::parse_args::<crate::window_host::GetComputedStyleArgs>(scope, &args)
+ else {
+ return;
+ };
let Some(runtime_ptr) = context_host_ptr_from_global_bridge(scope) else {
rv.set_null();
return;
@@ -50,9 +55,7 @@ fn detached_iframe_get_computed_style_callback<'s>(
rv.set_null();
return;
};
- let Some(target) = v8::Local::<v8::Object>::try_from(args.get(0))
- .ok()
- .and_then(|target| detached_native_handle_for_runtime(scope, runtime_ptr, target))
+ let Some(target) = detached_native_handle_for_runtime(scope, runtime_ptr, parsed.element)
else {
rv.set_null();
return;
@@ -61,7 +64,7 @@ fn detached_iframe_get_computed_style_callback<'s>(
forced_empty,
pseudo_element,
pseudo_key,
- } = crate::window_host::computed_style_pseudo_argument_from_function_args(scope, &args);
+ } = parsed.pseudo_argument();
let target_key = detached_native_handle_for_runtime(scope, runtime_ptr, iframe)
.map(ComputedStyleTargetKey::DetachedIframe)
.unwrap_or(ComputedStyleTargetKey::Dynamic);
diff --git a/moli-renderer-v8/src/native_bridge/element/styles.rs b/moli-renderer-v8/src/native_bridge/element/styles.rs
index ef08baa1c..85d4b0070 100644
--- a/moli-renderer-v8/src/native_bridge/element/styles.rs
+++ b/moli-renderer-v8/src/native_bridge/element/styles.rs
@@ -98,6 +98,16 @@ fn style_object_forces_empty_computed<'s>(
{
return true;
}
+ // A target can retain its child or popup document while detached. Check
+ // connection before consulting the cached browsing-context state.
+ if let BridgeHandle::ComputedStyle(handle, _) = &bridge_handle
+ && !unsafe { &*runtime_ptr }
+ .dom_host()
+ .is_connected_to_document(*handle)
+ {
+ unsafe { &*runtime_ptr }.retire_computed_style_for_inactive_handle(*handle);
+ return true;
+ }
if let Some(value) =
get_private_value(scope, style, STYLE_DECLARATION_TARGET_EMPTY_COMPUTED_SLOT)
&& value.is_boolean()
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs
index 65ca237bd..c32393428 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs
@@ -63,4 +63,5 @@ mod nested_document_invalidation;
mod properties_and_selectors;
mod stylesheet_and_document_lifecycle;
+mod cssom_arguments;
mod cssom_write_conversion;
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/cssom_arguments.js b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/cssom_arguments.js
new file mode 100644
index 000000000..bd889372d
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/cssom_arguments.js
@@ -0,0 +1,132 @@
+(() => {
+ const checks = [];
+ const record = (name, verify) => {
+ try {
+ checks.push({name, passed: verify() === true});
+ } catch (error) {
+ checks.push({name, passed: false, error: String(error)});
+ }
+ };
+ const capture = callback => {
+ try { return {threw: false, value: callback()}; }
+ catch (error) { return {threw: true, error}; }
+ };
+ const frame = document.createElement('iframe');
+ document.body.appendChild(frame);
+ const popup = window.open('about:blank', '_blank');
+ try {
+ for (const [index, owner] of [window, frame.contentWindow, popup].entries()) {
+ const doc = owner.document;
+ const calleeRealm = owner.getComputedStyle.constructor('return globalThis')();
+ const element = doc.createElement('div');
+ element.id = 'computed-style-arguments-target';
+ element.style.color = 'rgb(1, 2, 3)';
+ const sheet = doc.createElement('style');
+ sheet.textContent = '#computed-style-arguments-target::before { content: "x"; color: rgb(4, 5, 6); }';
+ doc.head.appendChild(sheet);
+ doc.body.appendChild(element);
+ const call = (...args) => Reflect.apply(owner.getComputedStyle, owner, args);
+ const label = name => `owner ${index}/${name}`;
+ const shadowHost = doc.createElement('div');
+ const revoked = Proxy.revocable(element, {});
+ revoked.revoke();
+ let traps = 0;
+ const authorProxy = new Proxy(element, {get() { traps++; return undefined; }});
+ const invalid = [
+ ['undefined', undefined], ['null', null], ['boolean', false], ['number', 0],
+ ['NaN', NaN], ['bigint', 1n], ['string', 'div'], ['symbol', Symbol('element')],
+ ['object', {}], ['forged prototype', Object.create(calleeRealm.Element.prototype)],
+ ['inherited native', Object.create(element)], ['author Proxy', authorProxy],
+ ['revoked Proxy', revoked.proxy], ['Document', doc], ['Text', doc.createTextNode('x')],
+ ['Comment', doc.createComment('x')], ['DocumentFragment', doc.createDocumentFragment()],
+ ['ShadowRoot', shadowHost.attachShadow({mode: 'open'})], ['Window', owner],
+ ['CSSStyleProperties', element.style], ['Attr', doc.createAttribute('x')],
+ ];
+ for (const [name, value] of invalid) {
+ let conversions = 0;
+ const sentinel = {};
+ const pseudo = {get [Symbol.toPrimitive]() { conversions++; throw sentinel; }};
+ const failure = capture(() => call(value, pseudo));
+ record(label(name + '/callee TypeError'), () => failure.threw && failure.error instanceof calleeRealm.TypeError);
+ record(label(name + '/pseudo not converted'), () => conversions === 0);
+ record(label(name + '/no author traps'), () => traps === 0);
+ }
+ record(label('required element'), () => {
+ const failure = capture(() => call());
+ return failure.threw && failure.error instanceof calleeRealm.TypeError;
+ });
+ for (const [name, pseudo] of [['undefined', undefined], ['null', null], ['empty', ''],
+ ['no colon', 'before'], ['boolean', true], ['number', 7], ['bigint', 2n]]) {
+ record(label('nullable pseudo/' + name), () => call(element, pseudo).color === 'rgb(1, 2, 3)');
+ }
+ record(label('missing pseudo'), () => call(element).color === 'rgb(1, 2, 3)');
+ const svg = doc.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ svg.style.color = 'rgb(1, 2, 3)';
+ doc.body.appendChild(svg);
+ record(label('SVG Element'), () => call(svg).color === 'rgb(1, 2, 3)');
+ const detached = doc.createElement('div');
+ const detachedStyle = call(detached);
+ record(label('detached Element'), () => detachedStyle.length === 0);
+ doc.body.appendChild(detached);
+ record(label('connected Element updates retained style'), () => detachedStyle.length > 0);
+ detached.remove();
+ record(label('removed Element empties retained style'), () => detachedStyle.length === 0);
+ for (const [name, sentinel] of [['object', {}], ['undefined', undefined], ['null', null],
+ ['number', 19], ['symbol', Symbol('thrown')]]) {
+ let conversions = 0;
+ const pseudo = {toString() { conversions++; throw sentinel; }};
+ const failure = capture(() => call(element, pseudo));
+ record(label('thrown pseudo/' + name), () => failure.threw && failure.error === sentinel);
+ record(label('thrown pseudo/' + name + '/once'), () => conversions === 1);
+ record(label('thrown pseudo/' + name + '/next call usable'), () => call(element).color === 'rgb(1, 2, 3)');
+ }
+ for (const [name, pseudo] of [['symbol', Symbol('pseudo')], ['symbol result', {[Symbol.toPrimitive]() { return Symbol(); }}],
+ ['object result', {[Symbol.toPrimitive]() { return {}; }}]]) {
+ const failure = capture(() => call(element, pseudo));
+ record(label('pseudo TypeError/' + name), () => failure.threw && failure.error instanceof calleeRealm.TypeError);
+ }
+ for (const phase of ['primitive getter', 'primitive call', 'toString getter', 'valueOf call']) {
+ let steps = [];
+ const sentinel = {};
+ const pseudo = phase === 'primitive getter' ? {get [Symbol.toPrimitive]() { steps.push('get'); throw sentinel; }} :
+ phase === 'primitive call' ? {[Symbol.toPrimitive](hint) { steps.push(hint); throw sentinel; }} :
+ phase === 'toString getter' ? {get toString() { steps.push('get'); throw sentinel; }} :
+ {toString() { steps.push('toString'); return {}; }, valueOf() { steps.push('valueOf'); throw sentinel; }};
+ const failure = capture(() => call(element, pseudo));
+ record(label(phase + '/exception'), () => failure.threw && failure.error === sentinel);
+ record(label(phase + '/order'), () => steps.join(',') ===
+ (phase === 'primitive call' ? 'string' : phase === 'valueOf call' ? 'toString,valueOf' : 'get'));
+ }
+ let steps = [];
+ const pseudo = {
+ get [Symbol.toPrimitive]() {
+ steps.push('get');
+ return hint => { steps.push(hint); return '::before'; };
+ },
+ toString() { steps.push('unexpected'); return ''; },
+ };
+ const before = call(element, pseudo);
+ record(label('pseudo string conversion order'), () => steps.join(',') === 'get,string');
+ record(label('converted pseudo target'), () => before.color === 'rgb(4, 5, 6)');
+ record(label('originating style after pseudo'), () => call(element).color === 'rgb(1, 2, 3)');
+ svg.remove(); element.remove(); sheet.remove();
+ }
+ const detachedDocument = document.implementation.createHTMLDocument('');
+ const nativeProxy = detachedDocument.createElement('select');
+ record('native registered Proxy accepted', () => window.getComputedStyle(nativeProxy).length === 0);
+ let conversions = 0;
+ const pseudo = {toString() { conversions++; return ''; }};
+ const failure = capture(() => window.getComputedStyle(new Proxy(nativeProxy, {}), pseudo));
+ record('author Proxy around native Proxy rejected', () => failure.threw && failure.error instanceof TypeError);
+ record('author Proxy around native Proxy conversion order', () => conversions === 0);
+ globalThis.__computedStyleArgumentsResults = {
+ complete: true, total: checks.length,
+ passed: checks.filter(row => row.passed).length, checks,
+ };
+ globalThis.__uiEventResults = globalThis.__computedStyleArgumentsResults;
+ return true;
+ } finally {
+ frame.remove();
+ if (popup && !popup.closed) popup.close();
+ }
+})();
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/cssom_arguments.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/cssom_arguments.rs
new file mode 100644
index 000000000..2f12a1644
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/cssom_arguments.rs
@@ -0,0 +1,65 @@
+use super::*;
+
+#[test]
+fn computed_style_arguments_use_native_element_brands_and_preserve_exceptions() {
+ let mut vm = new_storage_page_task_executor_test_vm("https://computed-style-arguments.test/");
+ vm.eval(include_str!("cssom_arguments.js"))
+ .expect("computed-style argument conversions should evaluate");
+ assert_eq!(
+ vm.eval("__computedStyleArgumentsResults.complete").unwrap(),
+ "true"
+ );
+ assert_eq!(
+ vm.eval(
+ "JSON.stringify(__computedStyleArgumentsResults.checks.filter(row => !row.passed))"
+ )
+ .unwrap(),
+ "[]"
+ );
+ assert_eq!(
+ vm.eval("__computedStyleArgumentsResults.total === 318 && __computedStyleArgumentsResults.passed === 318")
+ .unwrap(),
+ "true"
+ );
+}
+
+#[test]
+fn detached_iframe_computed_style_uses_the_shared_argument_conversion() {
+ let mut vm = new_storage_page_task_executor_test_vm("https://detached-style-arguments.test/");
+ vm.eval(
+ r#"
+const detachedDocument = document.implementation.createHTMLDocument('');
+const frame = detachedDocument.createElement('iframe');
+detachedDocument.body.appendChild(frame);
+const child = frame.contentWindow;
+const target = child.document.createElement('select');
+child.document.body.appendChild(target);
+globalThis.__detachedStyleArgumentChecks = [];
+const check = value => __detachedStyleArgumentChecks.push(value);
+check(child.getComputedStyle(target) instanceof CSSStyleDeclaration);
+for (const value of [undefined, null, {}, child.document,
+ child.document.createTextNode('x'), Object.create(target),
+ new Proxy(target, {}), Object.create(Element.prototype)]) {
+ let conversions = 0;
+ let caught;
+ try {
+ child.getComputedStyle(value, {toString() { conversions++; return ''; }});
+ } catch (error) { caught = error; }
+ check(caught instanceof TypeError);
+ check(conversions === 0);
+}
+const sentinel = {};
+let caught;
+try { child.getComputedStyle(target, {toString() { throw sentinel; }}); }
+catch (error) { caught = error; }
+check(caught === sentinel);
+check(child.getComputedStyle(target, null) instanceof CSSStyleDeclaration);
+"#,
+ )
+ .expect("synthetic iframe should share argument conversion");
+ assert_eq!(
+ vm.eval("__detachedStyleArgumentChecks.length === 19 && __detachedStyleArgumentChecks.every(Boolean)")
+ .unwrap(),
+ "true"
+ );
+}
diff --git a/moli-renderer-v8/src/window_host.rs b/moli-renderer-v8/src/window_host.rs
index 69d5569d9..b1dd3654c 100644
--- a/moli-renderer-v8/src/window_host.rs
+++ b/moli-renderer-v8/src/window_host.rs
@@ -1055,18 +1055,29 @@ pub(crate) fn scroll_window_to(
queue_scroll_observable_effects(scope, host_ptr, document, true);
}
+#[derive(webidl::WebIdlArgs)]
+#[webidl(prefix = "Window.getComputedStyle")]
+pub(crate) struct GetComputedStyleArgs<'s> {
+ #[webidl(required, interface = web_api_interfaces::Element)]
+ pub(crate) element: v8::Local<'s, v8::Object>,
+ #[webidl(nullable)]
+ pseudo_element: Option<String>,
+}
+
+impl GetComputedStyleArgs<'_> {
+ pub(crate) fn pseudo_argument(&self) -> ComputedStylePseudoArgument {
+ computed_style_pseudo_argument(self.pseudo_element.as_deref().map_or(
+ moli_selector::GetComputedStylePseudoElement::OriginatingElement,
+ moli_selector::get_computed_style_pseudo_element,
+ ))
+ }
+}
+
pub(crate) fn window_get_computed_style_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
- if args.length() == 0 {
- throw_type_error(
- scope,
- "Failed to execute 'getComputedStyle' on 'Window': 1 argument required, but only 0 present.",
- );
- return;
- }
let Some(host_ptr) = context_host_ptr_from_window_object(scope, args.this()) else {
throw_type_error(
scope,
@@ -1074,12 +1085,16 @@ pub(crate) fn window_get_computed_style_callback<'s>(
);
return;
};
- let Some(handle) = current_or_live_delegate_node_arg_handle(scope, host_ptr, args.get(0))
+ let Some(parsed) = webidl::parse_args::<GetComputedStyleArgs>(scope, &args) else {
+ return;
+ };
+ let Some(handle) =
+ current_or_live_delegate_node_arg_handle(scope, host_ptr, parsed.element.into())
else {
rv.set_null();
return;
};
- let pseudo_argument = computed_style_pseudo_argument_from_function_args(scope, &args);
+ let pseudo_argument = parsed.pseudo_argument();
let child_window_handle = object_child_window_handle(scope, args.this())
.or_else(|| dom_handle_from_marker_value(scope, args.data()));
match build_computed_style_object(
@@ -1245,13 +1260,6 @@ impl ComputedStylePseudoArgument {
}
}
-pub(crate) fn computed_style_pseudo_argument_from_function_args<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- args: &v8::FunctionCallbackArguments<'s>,
-) -> ComputedStylePseudoArgument {
- computed_style_pseudo_argument(get_computed_style_pseudo_element_argument(scope, args))
-}
-
fn computed_style_pseudo_argument(
pseudo_element: moli_selector::GetComputedStylePseudoElement,
) -> ComputedStylePseudoArgument {
@@ -1292,19 +1300,6 @@ fn computed_style_pseudo_element_supported_by_stylo(pseudo_element: &str) -> boo
ComputedStylePseudoKey::from_stylo_pseudo(pseudo_element).is_some()
}
-fn get_computed_style_pseudo_element_argument<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- args: &v8::FunctionCallbackArguments<'s>,
-) -> moli_selector::GetComputedStylePseudoElement {
- if args.length() < 2 || args.get(1).is_undefined() {
- return moli_selector::GetComputedStylePseudoElement::OriginatingElement;
- }
- let Some(value) = args.get(1).to_string(scope) else {
- return moli_selector::GetComputedStylePseudoElement::EmptyStyle;
- };
- moli_selector::get_computed_style_pseudo_element(&value.to_rust_string_lossy(scope))
-}
-
fn mouse_event_offset_getter(
scope: &mut v8::PinScope<'_, '_>,
event: v8::Local<'_, v8::Object>,