Skip to content

armgit / moli

Public Imported from GitHub
0

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

refactor(cssom): derive stylesheet options and retain native media lists

ldm0fba82ac39886
diff --git a/moli-renderer-v8/src/context_bootstrap/css_stylesheet_runtime/constructor.rs b/moli-renderer-v8/src/context_bootstrap/css_stylesheet_runtime/constructor.rs
index 2bb156a2b..77f726fe4 100644
--- a/moli-renderer-v8/src/context_bootstrap/css_stylesheet_runtime/constructor.rs
+++ b/moli-renderer-v8/src/context_bootstrap/css_stylesheet_runtime/constructor.rs
@@ -21,21 +21,77 @@ pub(crate) fn css_style_sheet_constructor_callback<'s>(
construct_css_style_sheet(scope, &args, rv);
}
+#[derive(webidl::WebIdlArgs)]
+#[webidl(prefix = "CSSStyleSheet")]
+struct CssStyleSheetConstructorArgs<'s> {
+ #[webidl(dictionary)]
+ options: CssStyleSheetInit<'s>,
+}
+
+#[derive(webidl::WebIdlDictionary)]
+#[webidl(prefix = "CSSStyleSheetInit")]
+struct CssStyleSheetInit<'s> {
+ // Constructed sheets have no title; the alternate flag has no selection
+ // effect, but its WebIDL conversion still runs before the other members.
+ #[webidl(name = "alternate", default = false)]
+ _alternate: bool,
+ #[webidl(name = "baseURL")]
+ base_url: Option<String>,
+ #[webidl(default = false)]
+ disabled: bool,
+ #[webidl(default = CssStyleSheetMedia::Text(String::new()), converter = "raw")]
+ media: CssStyleSheetMedia<'s>,
+}
+
+enum CssStyleSheetMedia<'s> {
+ Native(v8::Local<'s, v8::Object>),
+ Text(String),
+}
+
+impl<'s> webidl::WebIdlConverter<'s> for CssStyleSheetMedia<'s> {
+ type Options = ();
+
+ fn convert(
+ scope: &mut v8::PinScope<'s, '_>,
+ value: v8::Local<'s, v8::Value>,
+ context: webidl::Context,
+ _: &(),
+ ) -> Result<Self, webidl::WebIdlError> {
+ if let Ok(list) = v8::Local::<v8::Object>::try_from(value)
+ && crate::web_api_interfaces::MediaList::is_instance(scope, list)
+ {
+ return Ok(Self::Native(list));
+ }
+ webidl::convert::<webidl::DomString>(scope, value, context).map(|text| Self::Text(text.0))
+ }
+}
+
+impl<'s> CssStyleSheetMedia<'s> {
+ fn into_text(self, scope: &mut v8::PinScope<'s, '_>) -> String {
+ match self {
+ Self::Native(list) => media_list_native_text(scope, list),
+ Self::Text(text) => text,
+ }
+ }
+}
+
fn construct_css_style_sheet<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: &v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
- initialize_css_style_sheet_object(scope, args.this());
- let Some(media_text) = constructor_media_option(scope, args) else {
+ let Some(parsed) = webidl::parse_args::<CssStyleSheetConstructorArgs>(scope, args) else {
return;
};
- let disabled = constructor_disabled_option(scope, args);
let constructor_document =
current_css_style_sheet_constructor_document_handle_for_context(scope);
- let Some(base_url) = constructor_base_url_option(scope, args, constructor_document) else {
+ let Some(base_url) =
+ constructor_base_url_option(scope, parsed.options.base_url, constructor_document)
+ else {
return;
};
+ let media_text = parsed.options.media.into_text(scope);
+ initialize_css_style_sheet_object(scope, args.this());
set_private_value(
scope,
args.this(),
@@ -57,7 +113,7 @@ fn construct_css_style_sheet<'s>(
if !media_text.is_empty() {
sync_style_sheet_media_text(scope, args.this(), &media_text);
}
- if disabled {
+ if parsed.options.disabled {
require_css_style_sheet_live_stylesheet(scope, args.this()).set_disabled(true);
}
rv.set(args.this().into());
@@ -89,57 +145,14 @@ fn child_handle_marker(scope: &mut v8::PinScope<'_, '_>) -> Option<DomHandle> {
.and_then(|value| dom_handle_from_marker_value(scope, value))
}
-fn constructor_media_option<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- args: &v8::FunctionCallbackArguments<'s>,
-) -> Option<String> {
- if args.length() == 0 || webidl::is_nullish(args.get(0)) || !args.get(0).is_object() {
- return Some(String::new());
- }
- let Some(media) = v8::Local::<v8::Object>::try_from(args.get(0))
- .ok()
- .and_then(|options| webidl::property(scope, options, "media"))
- else {
- return Some(String::new());
- };
- if media.is_undefined() {
- return Some(String::new());
- }
- cssom_dom_string_property_value(scope, media, "CSSStyleSheetInit", "media")
-}
-
-fn constructor_disabled_option<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- args: &v8::FunctionCallbackArguments<'s>,
-) -> bool {
- if args.length() == 0 || webidl::is_nullish(args.get(0)) || !args.get(0).is_object() {
- return false;
- }
- v8::Local::<v8::Object>::try_from(args.get(0))
- .ok()
- .and_then(|options| webidl::property(scope, options, "disabled"))
- .is_some_and(|value| value.boolean_value(scope))
-}
-
-fn constructor_base_url_option<'s>(
- scope: &mut v8::PinScope<'s, '_>,
- args: &v8::FunctionCallbackArguments<'s>,
+fn constructor_base_url_option(
+ scope: &mut v8::PinScope<'_, '_>,
+ base_url_text: Option<String>,
constructor_document: Option<DomHandle>,
) -> Option<Option<url::Url>> {
- if args.length() == 0 || webidl::is_nullish(args.get(0)) || !args.get(0).is_object() {
- return Some(None);
- }
- let Some(base_url_value) = v8::Local::<v8::Object>::try_from(args.get(0))
- .ok()
- .and_then(|options| webidl::property(scope, options, "baseURL"))
- else {
+ let Some(base_url_text) = base_url_text else {
return Some(None);
};
- if base_url_value.is_undefined() {
- return Some(None);
- }
- let base_url_text =
- cssom_dom_string_property_value(scope, base_url_value, "CSSStyleSheetInit", "baseURL")?;
let document_base_url = constructor_document_base_url(scope, constructor_document)?;
match url::Url::options()
.base_url(Some(&document_base_url))
diff --git a/moli-renderer-v8/src/context_bootstrap/css_stylesheet_runtime/media_list.rs b/moli-renderer-v8/src/context_bootstrap/css_stylesheet_runtime/media_list.rs
index af51869d8..89ab00dc0 100644
--- a/moli-renderer-v8/src/context_bootstrap/css_stylesheet_runtime/media_list.rs
+++ b/moli-renderer-v8/src/context_bootstrap/css_stylesheet_runtime/media_list.rs
@@ -60,6 +60,32 @@ pub(crate) fn media_list_text<'s>(
media_list_items_from_object(scope, list).join(", ")
}
+/// Read the native MediaList union value without calling author getters or
+/// stringifiers on its JavaScript projection.
+pub(crate) fn media_list_native_text<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ list: v8::Local<'s, v8::Object>,
+) -> String {
+ let Some(owner) = get_private_value(scope, list, CSS_MEDIA_LIST_OWNER_RULE_SLOT)
+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
+ else {
+ return String::new();
+ };
+ match private_string(scope, list, CSS_MEDIA_LIST_OWNER_KIND_SLOT).as_str() {
+ CSS_MEDIA_LIST_OWNER_STYLE_SHEET => {
+ require_css_style_sheet_live_stylesheet(scope, owner).media_text()
+ }
+ CSS_MEDIA_LIST_OWNER_IMPORT_RULE => css_import_rule_view_from_object(scope, owner)
+ .map(|view| view.media_text)
+ .unwrap_or_default(),
+ CSS_MEDIA_LIST_OWNER_MEDIA_RULE => css_condition_rule_read_from_object(scope, owner)
+ .filter(|view| view.rule_type == CssRuleType::Media)
+ .map(|view| view.condition_text)
+ .unwrap_or_default(),
+ _ => String::new(),
+ }
+}
+
pub(crate) fn set_media_list_from_text<'s>(
scope: &mut v8::PinScope<'s, '_>,
list: v8::Local<'s, v8::Object>,
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
index e1ebcabc2..9ad785f33 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs
@@ -67,6 +67,7 @@ mod speech_synthesis_events;
mod storage_access;
mod storage_event_init;
mod structured_clone;
+mod stylesheet_init;
mod transferable_streams;
mod traversal;
mod traversal_coordinator;
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/stylesheet_init.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/stylesheet_init.rs
new file mode 100644
index 000000000..922574464
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/stylesheet_init.rs
@@ -0,0 +1,33 @@
+use super::*;
+
+#[test]
+fn stylesheet_constructor_derives_options_and_uses_native_media_list_state() {
+ let mut vm = new_storage_html_test_vm("https://stylesheet-options.test/");
+ assert_eq!(
+ vm.eval(include_str!(
+ "../../../../tests/fixtures/stylesheet-init-dictionary.js"
+ ))
+ .unwrap(),
+ "true"
+ );
+ assert_eq!(
+ vm.eval(
+ r#"(() => {
+ const trace = [], sentinel = {};
+ let error;
+ try { new CSSStyleSheet({
+ get alternate() { trace.push('alternate'); },
+ get baseURL() { trace.push('baseURL'); throw sentinel; },
+ get disabled() { trace.push('disabled'); },
+ get media() { trace.push('media'); }
+ }); } catch (caught) { error = caught; }
+ if (error !== sentinel || trace.join() !== 'alternate,baseURL') return false;
+ const media = new CSSStyleSheet({media: 'screen'}).media;
+ Object.defineProperty(media, '0', {get() { throw Error('author index'); }});
+ return new CSSStyleSheet({media}).media.mediaText === 'screen';
+ })()"#,
+ )
+ .unwrap(),
+ "true"
+ );
+}
diff --git a/moli-renderer-v8/tests/fixtures/stylesheet-init-dictionary.js b/moli-renderer-v8/tests/fixtures/stylesheet-init-dictionary.js
new file mode 100644
index 000000000..dcad58198
--- /dev/null
+++ b/moli-renderer-v8/tests/fixtures/stylesheet-init-dictionary.js
@@ -0,0 +1,54 @@
+(() => {
+ const assert = (ok, label) => { if (!ok) throw Error(label); };
+ const members = ['alternate','disabled','media'];
+ const trace = [], options = {}, sentinel = {};
+ for (const key of members) Object.defineProperty(options, key, {
+ configurable: true, get() { trace.push(key); }
+ });
+ new CSSStyleSheet(options);
+ assert(trace.join() === members.join(), 'CSSStyleSheetInit supported member order: ' + trace);
+ for (const stop of members) {
+ trace.length = 0;
+ const bad = Object.create(options);
+ Object.defineProperty(bad, stop, {get() { trace.push(stop); throw sentinel; }});
+ let error;
+ try { new CSSStyleSheet(bad); } catch (caught) { error = caught; }
+ assert(error === sentinel && trace.join() === members.slice(0, members.indexOf(stop) + 1).join(), stop + ' original exception and short circuit');
+ }
+ for (const options of [1, true, 'options', 1n, Symbol('options')]) {
+ let error;
+ try { new CSSStyleSheet(options); } catch (caught) { error = caught; }
+ assert(error instanceof TypeError, 'primitive dictionary rejected');
+ }
+ const disabled = new CSSStyleSheet({alternate: true, disabled: true, media: 'screen'});
+ assert(disabled.disabled && disabled.media.mediaText === 'screen', 'native options projection');
+ trace.length = 0;
+ new CSSStyleSheet({get disabled() { trace.push('disabled'); }, get media() {
+ trace.push('media'); return {toString() { trace.push('string'); return 'print'; }};
+ }});
+ assert(trace.join() === 'disabled,media,string', 'DOMString union conversion');
+ const sheet = new CSSStyleSheet({media: 'screen'});
+ sheet.replaceSync('@media print { body { color: red; } }');
+ const detachedRule = sheet.cssRules[0];
+ const ruleMedia = detachedRule.media;
+ sheet.deleteRule(0);
+ const style = document.createElement('style');
+ style.textContent = '@import url("data:text/css,") print;';
+ document.head.appendChild(style);
+ try {
+ const lists = [sheet.media, ruleMedia, style.sheet.cssRules[0].media];
+ const readText = Object.getOwnPropertyDescriptor(MediaList.prototype, 'mediaText').get;
+ for (const list of lists) {
+ const expected = readText.call(list);
+ let authorReads = 0;
+ Object.defineProperty(list, 'toString', {value() { authorReads++; throw sentinel; }});
+ Object.defineProperty(list, 'mediaText', {get() { authorReads++; throw sentinel; }});
+ Object.setPrototypeOf(list, null);
+ const copied = new CSSStyleSheet({media: list});
+ assert(copied.media.mediaText === expected && authorReads === 0, 'native MediaList union preserves identity and bypasses author projection');
+ }
+ } finally {
+ style.remove();
+ }
+ return true;
+})()