Skip to content

Truly independent web browser

LibWeb: Implement the CSSOM style sheet interfaces in Rust

Andreas Kling46d9ffe56cf2
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_grouping_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_grouping_rule.rs
index 71dcf4e5584..3b9e7538fab 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_grouping_rule.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_grouping_rule.rs
@@ -44,7 +44,7 @@ impl Inherits<CSSRule> for CSSGroupingRule {
}
}
-fn insertion_error(result: RuleInsertionResult) -> WebIdlResult<()> {
+pub(crate) fn insertion_error(result: RuleInsertionResult) -> WebIdlResult<()> {
match result {
RuleInsertionResult::Success => Ok(()),
RuleInsertionResult::IndexSizeError => Err(Exception::index_size_error(Utf16String::from_utf8(
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_import_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_import_rule.rs
index 1c620844d0f..6f8bda03966 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_import_rule.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_import_rule.rs
@@ -14,9 +14,9 @@ use ak::Utf16String;
use libjs_rust::api::{Trace, Vm};
use libweb_rust::NativeRule;
-use super::css_rule::{AnyCSSRule, CSSRule, RuleText, impl_rule_wrappable, selector_list_text, wrap_cpp_cell};
+use super::css_rule::{AnyCSSRule, CSSRule, RuleText, impl_rule_wrappable, selector_list_text};
+use super::css_style_sheet::CSSStyleSheet;
use super::media_list::MediaList;
-use crate::bindings::conversions::CppInterface;
use crate::bindings::cpp_cell::CppCell;
use crate::bindings::interface::{Inherits, Ref, allocate, cell_from_abi};
use crate::bindings::{CallContext, WebIdlResult};
@@ -106,15 +106,11 @@ impl CSSImportRule {
}
// https://drafts.csswg.org/cssom/#dom-cssimportrule-stylesheet
- pub(crate) fn style_sheet(&self, cx: &mut CallContext) -> WebIdlResult<Option<CppInterface>> {
+ pub(crate) fn style_sheet(&self, _: &mut CallContext) -> WebIdlResult<Option<Ref<CSSStyleSheet>>> {
// SAFETY: The cell is live.
let sheet = unsafe { web_css_import_style_sheet(self.import.as_ptr()) };
- if sheet.is_null() {
- return Ok(None);
- }
- // SAFETY: LibWeb returns a live cell.
- let sheet = unsafe { CppCell::from_raw(sheet) };
- Ok(Some(wrap_cpp_cell(cx, &sheet)))
+ // SAFETY: LibWeb returns the live cell of a CSSStyleSheet, or null.
+ Ok((!sheet.is_null()).then(|| unsafe { cell_from_abi(sheet) }))
}
// https://drafts.csswg.org/cssom/#dom-cssimportrule-layername
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs
index ccb24c7feeb..e9e3669ab68 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs
@@ -38,10 +38,11 @@ use super::css_property_rule::CSSPropertyRule;
use super::css_rule_list::CSSRuleList;
use super::css_scope_rule::CSSScopeRule;
use super::css_style_rule::CSSStyleRule;
+use super::css_style_sheet::CSSStyleSheet;
use super::css_supports_rule::CSSSupportsRule;
use crate::bindings::conversions::{CppInterface, ToJs};
use crate::bindings::cpp_cell::CppCell;
-use crate::bindings::interface::{Ref, Wrappable, cell_into_abi, wrap};
+use crate::bindings::interface::{Ref, Wrappable, cell_from_abi, cell_into_abi, wrap};
use crate::bindings::{CallContext, WebIdlResult};
unsafe extern "C" {
@@ -196,8 +197,10 @@ impl CSSRule {
}
// https://drafts.csswg.org/cssom/#dom-cssrule-parentstylesheet
- pub(crate) fn parent_style_sheet(&self, cx: &mut CallContext) -> WebIdlResult<Option<CppInterface>> {
- Ok(self.parent_sheet().map(|sheet| wrap_cpp_cell(cx, &sheet)))
+ pub(crate) fn parent_style_sheet(&self, _: &mut CallContext) -> WebIdlResult<Option<Ref<CSSStyleSheet>>> {
+ let sheet = self.parent_style_sheet.borrow();
+ // SAFETY: The cell is that of a live CSSStyleSheet.
+ Ok(sheet.as_ref().map(|sheet| unsafe { cell_from_abi(sheet.as_ptr()) }))
}
// https://drafts.csswg.org/cssom/#dom-cssrule-type
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_style_sheet.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_sheet.rs
new file mode 100644
index 00000000000..bcd16643f96
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_sheet.rs
@@ -0,0 +1,308 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSStyleSheet, https://drafts.csswg.org/cssom/#the-cssstylesheet-interface
+
+use core::ffi::c_void;
+use core::ptr::null_mut;
+use std::rc::Rc;
+
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::{NativeRule, NativeRuleList, NativeRuleType, NativeStyleSheetFlag};
+
+use super::css_grouping_rule::{insertion_error, validate_rule_removal};
+use super::css_rule::AnyCSSRule;
+use super::css_rule_list::CSSRuleList;
+use super::exports::rule_from_abi;
+use super::media_list::MediaList;
+use super::style_sheet::StyleSheet;
+use crate::bindings::conversions::UsvString;
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, cell_from_abi};
+use crate::bindings::promise::{WebIdlPromise, promise_from_abi};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+unsafe extern "C" {
+ fn web_css_realm_document(realm: *mut c_void) -> *mut c_void;
+ fn web_css_style_sheet_construct(
+ document: *mut c_void,
+ has_base_url: bool,
+ base_url: usize,
+ media_list: *mut c_void,
+ media_text: usize,
+ disabled: bool,
+ ) -> *mut c_void;
+ fn web_css_sheet_state_native_rules(state: *mut c_void) -> *const c_void;
+ fn web_css_sheet_state_owner_rule(state: *mut c_void) -> *mut c_void;
+ fn web_css_sheet_state_rule_list(state: *mut c_void) -> *mut c_void;
+ fn web_css_sheet_state_parse_rule(state: *mut c_void, rule: usize) -> *const c_void;
+ fn web_css_sheet_state_rule_inserted(state: *mut c_void, rule: *const c_void);
+ fn web_css_sheet_state_remove_rule(state: *mut c_void, index: u32);
+ fn web_css_sheet_state_replace(state: *mut c_void, text: usize) -> *mut c_void;
+ fn web_css_sheet_state_replace_rules(state: *mut c_void, text: usize);
+}
+
+/// The union (MediaList or DOMString) of CSSStyleSheetInit.
+pub(crate) enum MediaListOrDOMString {
+ MediaList(Ref<MediaList>),
+ DOMString(Utf16String),
+}
+
+// https://drafts.csswg.org/cssom/#dictdef-cssstylesheetinit
+pub(crate) struct CSSStyleSheetInit {
+ pub(crate) base_url: Option<Utf16String>,
+ pub(crate) media: MediaListOrDOMString,
+ pub(crate) disabled: bool,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSStyleSheet {
+ style_sheet: StyleSheet,
+}
+
+impl Wrappable for CSSStyleSheet {
+ const OWNS_EXTERNAL_MEMORY: bool = true;
+
+ fn external_memory_size(&self) -> usize {
+ self.style_sheet.state_external_memory_size()
+ }
+}
+
+impl Inherits<StyleSheet> for CSSStyleSheet {
+ fn parent(&self) -> &StyleSheet {
+ &self.style_sheet
+ }
+}
+
+impl CSSStyleSheet {
+ pub(crate) fn create(vm: &Vm, state: CppCell) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ style_sheet: StyleSheet::new(state),
+ })
+ }
+
+ pub(crate) fn state_cell(&self) -> &CppCell {
+ self.style_sheet.state_cell()
+ }
+
+ fn state(&self) -> *mut c_void {
+ self.style_sheet.state()
+ }
+
+ fn native_rules(&self) -> Rc<NativeRuleList> {
+ // SAFETY: The cell is live.
+ let rules = unsafe { web_css_sheet_state_native_rules(self.state()) };
+ // SAFETY: LibWeb returns the live list of the sheet.
+ unsafe { NativeRuleList::retained_from_raw(rules.cast()) }
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstylesheet-cssstylesheet
+ pub(crate) fn construct(cx: &mut CallContext, options: CSSStyleSheetInit) -> WebIdlResult<Ref<Self>> {
+ // SAFETY: The realm is live.
+ let document = unsafe { web_css_realm_document(cx.realm().as_ptr().cast()) };
+ let has_base_url = options.base_url.is_some();
+ let base_url = options
+ .base_url
+ .unwrap_or_else(|| Utf16String::from_ascii(b""))
+ .into_raw();
+ let (media_list, media_text) = match options.media {
+ MediaListOrDOMString::MediaList(list) => (list.as_ptr().cast(), Utf16String::from_ascii(b"").into_raw()),
+ MediaListOrDOMString::DOMString(text) => (null_mut(), text.into_raw()),
+ };
+ // SAFETY: The document and the list are live, and the strings are handed over.
+ let sheet = unsafe {
+ web_css_style_sheet_construct(
+ document,
+ has_base_url,
+ base_url,
+ media_list,
+ media_text,
+ options.disabled,
+ )
+ };
+ if sheet.is_null() {
+ return Err(not_allowed_error("Constructed style sheets must have a valid base URL"));
+ }
+ // SAFETY: LibWeb returns the live cell of a CSSStyleSheet.
+ Ok(unsafe { cell_from_abi(sheet) })
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstylesheet-ownerrule
+ pub(crate) fn owner_rule(&self, _: &mut CallContext) -> WebIdlResult<Option<AnyCSSRule>> {
+ // The ownerRule attribute must return the owner CSS rule.
+ // SAFETY: The cell is live.
+ let rule = unsafe { web_css_sheet_state_owner_rule(self.state()) };
+ // SAFETY: LibWeb returns the live cell of a CSSImportRule, or null.
+ Ok((!rule.is_null()).then(|| unsafe { rule_from_abi(rule) }))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstylesheet-cssrules
+ pub(crate) fn css_rules(&self, _: &mut CallContext) -> WebIdlResult<Ref<CSSRuleList>> {
+ // 1. If the origin-clean flag is unset, throw a SecurityError exception.
+ if !self.style_sheet.flag(NativeStyleSheetFlag::OriginClean) {
+ return Err(security_error("Can't access the rules of cross-origin stylesheets."));
+ }
+
+ // 2. Return a read-only, live CSSRuleList object representing the CSS rules.
+ // SAFETY: The cell is live, and LibWeb returns the live cell of a CSSRuleList.
+ Ok(unsafe { cell_from_abi(web_css_sheet_state_rule_list(self.state())) })
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstylesheet-rules
+ pub(crate) fn rules(&self, cx: &mut CallContext) -> WebIdlResult<Ref<CSSRuleList>> {
+ // The rules attribute must follow the same steps as cssRules, and return the same object cssRules would return.
+ self.css_rules(cx)
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstylesheet-insertrule
+ pub(crate) fn insert_rule(&self, _: &mut CallContext, rule: Utf16String, index: u32) -> WebIdlResult<u32> {
+ // 1. If the origin-clean flag is unset, throw a SecurityError exception.
+ if !self.style_sheet.flag(NativeStyleSheetFlag::OriginClean) {
+ return Err(security_error("Can't call insert_rule() on cross-origin stylesheets."));
+ }
+
+ // 2. If the disallow modification flag is set, throw a NotAllowedError DOMException.
+ if self.style_sheet.flag(NativeStyleSheetFlag::DisallowModification) {
+ return Err(not_allowed_error(
+ "Can't call insert_rule() on non-modifiable stylesheets.",
+ ));
+ }
+
+ // 3. Let parsed rule be the return value of invoking parse a rule with rule.
+ // SAFETY: The cell is live, and the text is handed over.
+ let parsed_rule = unsafe { web_css_sheet_state_parse_rule(self.state(), rule.into_raw()) };
+
+ // 4. If parsed rule is a syntax error, throw a SyntaxError DOMException.
+ if parsed_rule.is_null() {
+ return Err(Exception::syntax_error(Utf16String::from_utf8(
+ "Unable to parse CSS rule.",
+ )));
+ }
+ // SAFETY: LibWeb hands over a reference to the rule.
+ let parsed_rule = unsafe { Rc::from_raw(parsed_rule.cast::<NativeRule>()) };
+
+ // 5. If parsed rule is an @import rule, and the constructed flag is set, throw a SyntaxError DOMException.
+ if self.style_sheet.flag(NativeStyleSheetFlag::Constructed)
+ && parsed_rule.cssom_type() == NativeRuleType::Import
+ {
+ return Err(Exception::syntax_error(Utf16String::from_utf8(
+ "Can't insert @import rules into a constructed stylesheet.",
+ )));
+ }
+
+ // 6. Return the result of invoking insert a CSS rule rule in the CSS rules at index.
+ insertion_error(
+ self.native_rules()
+ .cssom_insert_rule(index as usize, Rc::clone(&parsed_rule), false),
+ )?;
+
+ // SAFETY: The cell is live, and so is the rule.
+ unsafe { web_css_sheet_state_rule_inserted(self.state(), Rc::as_ptr(&parsed_rule).cast()) };
+ Ok(index)
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstylesheet-deleterule
+ pub(crate) fn delete_rule(&self, _: &mut CallContext, index: u32) -> WebIdlResult<()> {
+ // 1. If the origin-clean flag is unset, throw a SecurityError exception.
+ if !self.style_sheet.flag(NativeStyleSheetFlag::OriginClean) {
+ return Err(security_error("Can't call delete_rule() on cross-origin stylesheets."));
+ }
+
+ // 2. If the disallow modification flag is set, throw a NotAllowedError DOMException.
+ if self.style_sheet.flag(NativeStyleSheetFlag::DisallowModification) {
+ return Err(not_allowed_error(
+ "Can't call delete_rule() on non-modifiable stylesheets.",
+ ));
+ }
+
+ // 3. Remove a CSS rule in the CSS rules at index.
+ validate_rule_removal(self.native_rules().cssom_validate_removal(index as usize))?;
+ // SAFETY: The cell is live, and the index is valid.
+ unsafe { web_css_sheet_state_remove_rule(self.state(), index) };
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstylesheet-replace
+ pub(crate) fn replace(&self, _: &mut CallContext, text: UsvString) -> WebIdlResult<WebIdlPromise> {
+ let text = text.into_utf16_string().into_raw();
+ // SAFETY: The cell is live, the text is handed over, and LibWeb returns a live promise.
+ Ok(unsafe { promise_from_abi(web_css_sheet_state_replace(self.state(), text)) })
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstylesheet-replacesync
+ pub(crate) fn replace_sync(&self, _: &mut CallContext, text: UsvString) -> WebIdlResult<()> {
+ // https://drafts.csswg.org/cssom/#synchronously-replace-the-rules-of-a-cssstylesheet
+ // 1. If the constructed flag is not set, or the disallow modification flag is set, throw a NotAllowedError
+ // DOMException.
+ if !self.style_sheet.flag(NativeStyleSheetFlag::Constructed) {
+ return Err(not_allowed_error(
+ "Can't call replaceSync() on non-constructed stylesheets",
+ ));
+ }
+ if self.style_sheet.flag(NativeStyleSheetFlag::DisallowModification) {
+ return Err(not_allowed_error(
+ "Can't call replaceSync() on non-modifiable stylesheets",
+ ));
+ }
+
+ let text = text.into_utf16_string().into_raw();
+ // SAFETY: The cell is live, and the text is handed over.
+ unsafe { web_css_sheet_state_replace_rules(self.state(), text) };
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstylesheet-addrule
+ pub(crate) fn add_rule(
+ &self,
+ cx: &mut CallContext,
+ selector: Utf16String,
+ style: Utf16String,
+ index: Option<u32>,
+ ) -> WebIdlResult<i32> {
+ // 1. Let rule be an empty string.
+ // 2. Append selector to rule.
+ let mut rule = selector.to_utf16().into_owned();
+
+ // 3. Append " { " to rule.
+ rule.extend(" { ".encode_utf16());
+
+ // 4. If block is not empty, append block, followed by a space, to rule.
+ if !style.is_empty() {
+ rule.extend_from_slice(&style.to_utf16());
+ rule.extend(" ".encode_utf16());
+ }
+
+ // 5. Append "}" to rule
+ rule.extend("}".encode_utf16());
+
+ // 6. Let index be optionalIndex if provided, or the number of CSS rules in the stylesheet otherwise.
+ let index = index.unwrap_or_else(|| {
+ u32::try_from(self.native_rules().cssom_length()).expect("a sheet has fewer than 2^32 rules")
+ });
+
+ // 7. Call insertRule(), with rule and index as arguments.
+ self.insert_rule(cx, Utf16String::from_utf16(&rule), index)?;
+
+ // 8. Return -1.
+ Ok(-1)
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssstylesheet-removerule
+ pub(crate) fn remove_rule(&self, cx: &mut CallContext, index: Option<u32>) -> WebIdlResult<()> {
+ // The removeRule(index) method must run the same steps as deleteRule().
+ self.delete_rule(cx, index.unwrap_or(0))
+ }
+}
+
+fn security_error(message: &str) -> Exception {
+ Exception::Dom("SecurityError", Utf16String::from_utf8(message))
+}
+
+fn not_allowed_error(message: &str) -> Exception {
+ Exception::Dom("NotAllowedError", Utf16String::from_utf8(message))
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
index aef0dbc2ec8..e00d6660aa0 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
@@ -50,6 +50,7 @@ use super::css_rule::AnyCSSRule;
use super::css_rule_list::CSSRuleList;
use super::css_scope_rule::CSSScopeRule;
use super::css_style_rule::CSSStyleRule;
+use super::css_style_sheet::CSSStyleSheet;
use super::css_style_value::{AnyCSSStyleValue, CSSStyleValue, PerformTypeCheck};
use super::css_supports_rule::CSSSupportsRule;
use super::css_transform_value::CSSTransformValue;
@@ -57,6 +58,7 @@ use super::css_unit_value::CSSUnitValue;
use super::css_unparsed_value::CSSUnparsedValue;
use super::media_list::MediaList;
use super::media_query_list_event::{MediaQueryListEvent, MediaQueryListEventInit};
+use super::style_sheet_list::StyleSheetList;
use super::transition_event::{TransitionEvent, TransitionEventInit};
use super::typed_om;
use crate::bindings::Exception;
@@ -867,3 +869,43 @@ pub unsafe extern "C" fn web_css_style_rule_set_selector_text(rule: *mut c_void,
let (rule, text): (Ref<CSSStyleRule>, _) = unsafe { (cell_from_abi(rule), Utf16String::from_raw_owned(text)) };
rule.replace_selectors(&text.to_utf16());
}
+
+/// A new CSSStyleSheet for the cell that holds the state of the sheet.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `state` a live cell.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_style_sheet_create(vm: *mut c_void, state: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes the live VM and a live cell.
+ let (vm, state) = unsafe { (vm_from_abi(vm), CppCell::from_raw(state)) };
+ cell_into_abi(CSSStyleSheet::create(vm, state))
+}
+
+/// The cell that holds the state of the sheet.
+///
+/// # Safety
+///
+/// `sheet` must be the live cell of a CSSStyleSheet.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_style_sheet_state(sheet: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes a live cell of a CSSStyleSheet.
+ let sheet: Ref<CSSStyleSheet> = unsafe { cell_from_abi(sheet) };
+ sheet.state_cell().as_ptr()
+}
+
+/// A new StyleSheetList of the sheets of `scope`, which belongs to `node`.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `node` the live cell of the Document or ShadowRoot that owns `scope`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_style_sheet_list_create(
+ vm: *mut c_void,
+ scope: *mut c_void,
+ node: *mut c_void,
+) -> *mut c_void {
+ // SAFETY: The caller passes the live VM and a live cell.
+ let (vm, node) = unsafe { (vm_from_abi(vm), CppCell::from_raw(node)) };
+ cell_into_abi(allocate(vm, |_| StyleSheetList::new(scope, node)))
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
index a322678fa5c..6aa0f520b85 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
@@ -50,6 +50,7 @@ pub(crate) mod css_skew;
pub(crate) mod css_skew_x;
pub(crate) mod css_skew_y;
pub(crate) mod css_style_rule;
+pub(crate) mod css_style_sheet;
pub(crate) mod css_style_value;
pub(crate) mod css_supports_rule;
pub(crate) mod css_transform_component;
@@ -61,5 +62,7 @@ pub(crate) mod css_variable_reference_value;
pub(crate) mod exports;
pub(crate) mod media_list;
pub(crate) mod media_query_list_event;
+pub(crate) mod style_sheet;
+pub(crate) mod style_sheet_list;
pub(crate) mod transition_event;
pub(crate) mod typed_om;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/style_sheet.rs b/Libraries/LibWeb/Bindings/Rust/src/css/style_sheet.rs
new file mode 100644
index 00000000000..dd996ce4d43
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/style_sheet.rs
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! StyleSheet, https://drafts.csswg.org/cssom/#the-stylesheet-interface
+
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use ak::Utf16String;
+use libjs_rust::api::Trace;
+use libweb_rust::NativeStyleSheetFlag;
+
+use super::css_rule::wrap_cpp_cell;
+use super::css_style_sheet::CSSStyleSheet;
+use super::media_list::MediaList;
+use crate::bindings::conversions::{CppInterface, UsvString};
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::interface::{Ref, Wrappable, cell_from_abi};
+use crate::bindings::{CallContext, WebIdlResult};
+
+unsafe extern "C" {
+ fn web_css_sheet_state_external_memory_size(state: *mut c_void) -> usize;
+ fn web_css_sheet_state_flag(state: *mut c_void, flag: u8) -> bool;
+ fn web_css_sheet_state_set_disabled(state: *mut c_void, disabled: bool);
+ fn web_css_sheet_state_location(state: *mut c_void, location: *mut usize) -> bool;
+ fn web_css_sheet_state_title(state: *mut c_void) -> usize;
+ fn web_css_sheet_state_owner_node(state: *mut c_void) -> *mut c_void;
+ fn web_css_sheet_state_parent_style_sheet(state: *mut c_void) -> *mut c_void;
+ fn web_css_sheet_state_media(state: *mut c_void) -> *mut c_void;
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct StyleSheet {
+ /// The cell that holds the Web::CSS::StyleSheetState, which attaches the sheet to its documents and loads it.
+ state: CppCell,
+}
+
+impl Wrappable for StyleSheet {}
+
+impl StyleSheet {
+ pub(crate) fn new(state: CppCell) -> Self {
+ Self { state }
+ }
+
+ pub(crate) fn state(&self) -> *mut c_void {
+ self.state.as_ptr()
+ }
+
+ pub(crate) fn state_cell(&self) -> &CppCell {
+ &self.state
+ }
+
+ pub(crate) fn state_external_memory_size(&self) -> usize {
+ // SAFETY: The cell is live.
+ unsafe { web_css_sheet_state_external_memory_size(self.state()) }
+ }
+
+ pub(crate) fn flag(&self, flag: NativeStyleSheetFlag) -> bool {
+ // SAFETY: The cell is live.
+ unsafe { web_css_sheet_state_flag(self.state(), flag as u8) }
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-stylesheet-type
+ pub(crate) fn r#type(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ // The type attribute must return the type.
+ Ok(Utf16String::from_ascii(b"text/css"))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-stylesheet-href
+ pub(crate) fn href(&self, _: &mut CallContext) -> WebIdlResult<Option<UsvString>> {
+ // The href attribute must return the location.
+ let mut location = 0;
+ // SAFETY: The cell is live, and the out pointer is valid.
+ if !unsafe { web_css_sheet_state_location(self.state(), &raw mut location) } {
+ return Ok(None);
+ }
+ // SAFETY: LibWeb hands over the string.
+ let location = unsafe { Utf16String::from_raw_owned(location) };
+ Ok(Some(UsvString::from_utf16_replacing_lone_surrogates(
+ &location.to_utf16(),
+ )))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-stylesheet-ownernode
+ pub(crate) fn owner_node(&self, cx: &mut CallContext) -> WebIdlResult<Option<CppInterface>> {
+ // The ownerNode attribute must return the owner node.
+ // SAFETY: The cell is live.
+ let Some(node) = NonNull::new(unsafe { web_css_sheet_state_owner_node(self.state()) }) else {
+ return Ok(None);
+ };
+ // SAFETY: LibWeb returns a live cell.
+ let node = unsafe { CppCell::from_raw(node.as_ptr()) };
+ Ok(Some(wrap_cpp_cell(cx, &node)))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-stylesheet-parentstylesheet
+ pub(crate) fn parent_style_sheet(&self, _: &mut CallContext) -> WebIdlResult<Option<Ref<CSSStyleSheet>>> {
+ // The parentStyleSheet attribute must return the parent CSS style sheet.
+ // SAFETY: The cell is live.
+ let sheet = unsafe { web_css_sheet_state_parent_style_sheet(self.state()) };
+ // SAFETY: LibWeb returns the live cell of a CSSStyleSheet, or null.
+ Ok((!sheet.is_null()).then(|| unsafe { cell_from_abi(sheet) }))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-stylesheet-title
+ pub(crate) fn title(&self, _: &mut CallContext) -> WebIdlResult<Option<Utf16String>> {
+ // The title attribute must return the title or null if title is the empty string.
+ // SAFETY: The cell is live, and LibWeb hands over the string.
+ let title = unsafe { Utf16String::from_raw_owned(web_css_sheet_state_title(self.state())) };
+ Ok((!title.is_empty()).then_some(title))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-stylesheet-media
+ pub(crate) fn media(&self, _: &mut CallContext) -> WebIdlResult<Ref<MediaList>> {
+ // The media attribute must return the media.
+ // SAFETY: The cell is live, and LibWeb returns the live cell of a MediaList.
+ Ok(unsafe { cell_from_abi(web_css_sheet_state_media(self.state())) })
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-stylesheet-disabled
+ pub(crate) fn disabled(&self, _: &mut CallContext) -> WebIdlResult<bool> {
+ // The disabled attribute, on getting, must return true if the disabled flag is set, or false otherwise.
+ Ok(self.flag(NativeStyleSheetFlag::Disabled))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-stylesheet-disabled
+ pub(crate) fn set_disabled(&self, _: &mut CallContext, value: bool) -> WebIdlResult<()> {
+ // On setting, the disabled attribute must set the disabled flag if the new value is true, or unset the disabled
+ // flag otherwise.
+ // SAFETY: The cell is live.
+ unsafe { web_css_sheet_state_set_disabled(self.state(), value) };
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/style_sheet_list.rs b/Libraries/LibWeb/Bindings/Rust/src/css/style_sheet_list.rs
new file mode 100644
index 00000000000..b214757fa52
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/style_sheet_list.rs
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! StyleSheetList, https://drafts.csswg.org/cssom/#the-stylesheetlist-interface
+
+use core::ffi::c_void;
+
+use libjs_rust::api::Trace;
+
+use super::css_style_sheet::CSSStyleSheet;
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::interface::{Ref, Wrappable, cell_from_abi};
+use crate::bindings::{CallContext, WebIdlResult};
+
+unsafe extern "C" {
+ fn web_css_style_sheet_list_length(scope: *mut c_void) -> u32;
+ fn web_css_style_sheet_list_item(scope: *mut c_void, index: u32) -> *mut c_void;
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct StyleSheetList {
+ /// The Web::CSS::StyleScope whose sheets the list represents, which belongs to the node.
+ #[gc(untraced)]
+ scope: *mut c_void,
+ /// The cell of the Document or ShadowRoot.
+ node: CppCell,
+}
+
+impl Wrappable for StyleSheetList {}
+
+impl StyleSheetList {
+ pub(crate) fn new(scope: *mut c_void, node: CppCell) -> Self {
+ Self { scope, node }
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-stylesheetlist-length
+ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ // SAFETY: The node keeps its scope alive.
+ Ok(unsafe { web_css_style_sheet_list_length(self.scope) })
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-stylesheetlist-item
+ pub(crate) fn item(&self, _: &mut CallContext, index: u32) -> WebIdlResult<Option<Ref<CSSStyleSheet>>> {
+ // SAFETY: The node keeps its scope alive.
+ let sheet = unsafe { web_css_style_sheet_list_item(self.scope, index) };
+ // SAFETY: LibWeb returns the live cell of a CSSStyleSheet, or null.
+ Ok((!sheet.is_null()).then(|| unsafe { cell_from_abi(sheet) }))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
index 66e6a322bcf..8acc190529e 100644
--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
@@ -137,6 +137,7 @@ bool web_bindings_message_port_transport_send(IPC::Transport*, HTML::SerializedT
bool web_bindings_message_port_transport_read_messages(IPC::Transport*, void* records, void (*append)(void*, HTML::SerializedTransferRecord*));
void* web_css_wrap_object(void* realm, void* cell);
+void* web_css_realm_document(void* realm);
void* web_bindings_wrapper_world(void* realm, bool* is_main_world)
{
@@ -166,6 +167,11 @@ void* web_css_wrap_object(void* realm, void* cell)
return JS::HostABI::object_to_abi(wrapper.ptr());
}
+void* web_css_realm_document(void* realm)
+{
+ return static_cast<GC::Cell*>(const_cast<DOM::Document*>(HTML::relevant_window(static_cast<JS::Realm*>(realm)->global_object()).document().ptr()));
+}
+
bool web_bindings_realm_is_window(void* realm)
{
return HTML::window_from_global_object(static_cast<JS::Realm*>(realm)->global_object());
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index acb5f0a4447..5033dc03561 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -162,11 +162,9 @@ set(SOURCES
CSS/Zoom.cpp
CSS/StylePropertyMap.cpp
CSS/StyleScope.cpp
- CSS/StyleSheet.cpp
CSS/StyleSheetIdentifier.cpp
CSS/StyleSheetImport.cpp
CSS/StyleSheetInvalidation.cpp
- CSS/StyleSheetList.cpp
CSS/StyleSheetState.cpp
CSS/StyleValues/AbstractImageStyleValue.cpp
CSS/StyleValues/AngleStyleValue.cpp
diff --git a/Libraries/LibWeb/CSS/CSSRule.cpp b/Libraries/LibWeb/CSS/CSSRule.cpp
index 34b1e860ef6..defccd41c77 100644
--- a/Libraries/LibWeb/CSS/CSSRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSRule.cpp
@@ -58,7 +58,7 @@ void* web_css_font_feature_values_map_create(void* rule, u8 kind);
static StyleSheetState& state_of_sheet(void* sheet)
{
- return static_cast<CSSStyleSheet*>(static_cast<GC::Cell*>(sheet))->state();
+ return static_cast<CSSStyleSheet*>(sheet)->state();
}
CSSRule::Type CSSRule::type() const
diff --git a/Libraries/LibWeb/CSS/CSSRuleList.cpp b/Libraries/LibWeb/CSS/CSSRuleList.cpp
index 1fa3c922f76..6d0af825dd9 100644
--- a/Libraries/LibWeb/CSS/CSSRuleList.cpp
+++ b/Libraries/LibWeb/CSS/CSSRuleList.cpp
@@ -69,7 +69,7 @@ CSSRule* CSSRuleList::existing_wrapper(u64 identity) const
void CSSRuleList::set_parent_style_sheet(StyleSheetState* sheet)
{
- web_css_rule_list_set_parent_style_sheet(vm_abi(), this, sheet ? static_cast<GC::Cell*>(&sheet->cssom_sheet()) : nullptr);
+ web_css_rule_list_set_parent_style_sheet(vm_abi(), this, sheet ? &sheet->cssom_sheet() : nullptr);
}
CSSRule* CSSRuleList::rule_for_identity(u64 identity) const
diff --git a/Libraries/LibWeb/CSS/CSSStyleSheet.cpp b/Libraries/LibWeb/CSS/CSSStyleSheet.cpp
index fcbd75311b1..1a70a1ce4ab 100644
--- a/Libraries/LibWeb/CSS/CSSStyleSheet.cpp
+++ b/Libraries/LibWeb/CSS/CSSStyleSheet.cpp
@@ -7,17 +7,98 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibGC/Cell.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/CSS/CSSImportRule.h>
#include <LibWeb/CSS/CSSRuleList.h>
#include <LibWeb/CSS/CSSStyleSheet.h>
+#include <LibWeb/CSS/StyleScope.h>
#include <LibWeb/CSS/StyleSheetImport.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/Window.h>
-#include <LibWeb/WebIDL/DOMException.h>
+#include <LibWeb/CSS/StyleSheetList.h>
+#include <LibWeb/CSS/StyleSheetState.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/DOM/Element.h>
namespace Web::CSS {
-GC_DEFINE_ALLOCATOR(CSSStyleSheet);
+// What the CSSStyleSheet of a sheet holds it by, as the object is a cell that keeps it alive and traces its edges.
+// It also keeps the observable owner chain alive, which the state only refers to weakly.
+class StyleSheetStateCell final : public GC::Cell {
+ GC_CELL(StyleSheetStateCell, GC::Cell);
+ GC_DECLARE_ALLOCATOR(StyleSheetStateCell);
+
+public:
+ explicit StyleSheetStateCell(StyleSheetState& state)
+ : m_state(state)
+ {
+ }
+
+ StyleSheetState& state() const { return m_state; }
+
+ void update_owner_chain()
+ {
+ auto* parent = m_state->parent_style_sheet();
+ m_parent_sheet = parent ? &parent->cssom_sheet() : nullptr;
+ m_owner_import = m_state->owner_import();
+ }
+
+private:
+ virtual void visit_edges(GC::Cell::Visitor& visitor) override
+ {
+ Base::visit_edges(visitor);
+ visitor.visit(m_state);
+ visitor.visit(m_parent_sheet);
+ visitor.visit(m_owner_import);
+ }
+
+ NonnullRefPtr<StyleSheetState> m_state;
+ GC::Ptr<CSSStyleSheet> m_parent_sheet;
+ RefPtr<StyleSheetImport> m_owner_import;
+};
+
+GC_DEFINE_ALLOCATOR(StyleSheetStateCell);
+
+// NB: What the implementation of the sheets in Rust offers to the C++ code of LibWeb.
+extern "C" {
+void* web_css_style_sheet_create(void* vm, void* state);
+void* web_css_style_sheet_state(void* sheet);
+void* web_css_style_sheet_list_create(void* vm, void* scope, void* node);
+}
+
+// NB: What the implementation of the sheets in Rust asks of the C++ code of LibWeb.
+extern "C" {
+void* web_css_style_sheet_construct(void* document, bool has_base_url, FlatPtr base_url, void* media_list, FlatPtr media_text, bool disabled);
+size_t web_css_sheet_state_external_memory_size(void* state);
+bool web_css_sheet_state_flag(void* state, u8 flag);
+void web_css_sheet_state_set_disabled(void* state, bool disabled);
+bool web_css_sheet_state_location(void* state, FlatPtr* location);
+FlatPtr web_css_sheet_state_title(void* state);
+void* web_css_sheet_state_owner_node(void* state);
+void* web_css_sheet_state_parent_style_sheet(void* state);
+void* web_css_sheet_state_media(void* state);
+Parser::ValueParserFFI::NativeRuleList const* web_css_sheet_state_native_rules(void* state);
+void* web_css_sheet_state_owner_rule(void* state);
+void* web_css_sheet_state_rule_list(void* state);
+Parser::ValueParserFFI::NativeRule const* web_css_sheet_state_parse_rule(void* state, FlatPtr rule);
+void web_css_sheet_state_rule_inserted(void* state, Parser::ValueParserFFI::NativeRule const* rule);
+void web_css_sheet_state_remove_rule(void* state, u32 index);
+void* web_css_sheet_state_replace(void* state, FlatPtr text);
+void web_css_sheet_state_replace_rules(void* state, FlatPtr text);
+u32 web_css_style_sheet_list_length(void* scope);
+void* web_css_style_sheet_list_item(void* scope, u32 index);
+}
+
+static StyleSheetStateCell& state_cell_of(void* cell)
+{
+ return *static_cast<StyleSheetStateCell*>(static_cast<GC::Cell*>(cell));
+}
+
+static StyleSheetState& state_of(void* cell)
+{
+ return state_cell_of(cell).state();
+}
StyleSheetState* css_style_sheet_from_value(JS::Value value)
{
@@ -35,49 +116,150 @@ GC::Ref<JS::SyntheticModule> create_css_style_sheet_default_export_module(JS::Re
return JS::SyntheticModule::create_default_export_synthetic_module(realm, css_style_sheet(realm, style_sheet), filename);
}
-WebIDL::ExceptionOr<GC::Ref<CSSStyleSheet>> CSSStyleSheet::create_for_constructor(JS::Object& relevant_global_object, CSSStyleSheetOptions const& options)
+GC::Ref<CSSStyleSheet> CSSStyleSheet::create(StyleSheetState& state)
{
- auto associated_document = HTML::relevant_window(relevant_global_object).document();
- auto state = TRY(StyleSheetState::create_constructed(*associated_document, options));
- return GC::Ref { state->cssom_sheet() };
+ auto cell = GC::Heap::the().allocate<StyleSheetStateCell>(state);
+ cell->update_owner_chain();
+ auto* sheet = web_css_style_sheet_create(JS::HostABI::vm_to_abi(JS::VM::the()), static_cast<GC::Cell*>(cell.ptr()));
+ return *static_cast<CSSStyleSheet*>(sheet);
}
-GC::Ref<CSSStyleSheet> CSSStyleSheet::create(StyleSheetState& state)
+StyleSheetState& CSSStyleSheet::state() const
{
- return GC::Heap::the().allocate<CSSStyleSheet>(state);
+ return state_of(web_css_style_sheet_state(const_cast<CSSStyleSheet*>(this)));
}
-CSSStyleSheet::CSSStyleSheet(StyleSheetState& state)
- : StyleSheet(state)
+void CSSStyleSheet::update_owner_chain()
{
- update_owner_chain();
+ state_cell_of(web_css_style_sheet_state(this)).update_owner_chain();
}
-CSSStyleSheet::~CSSStyleSheet() = default;
+GC::Ref<StyleSheetList> StyleSheetList::create(StyleScope& scope)
+{
+ auto* list = web_css_style_sheet_list_create(JS::HostABI::vm_to_abi(JS::VM::the()), &scope, static_cast<GC::Cell*>(&scope.node()));
+ return *static_cast<StyleSheetList*>(list);
+}
-// https://drafts.csswg.org/cssom/#dom-cssstylesheet-cssrules
-WebIDL::ExceptionOr<GC::Ref<CSSRuleList>> CSSStyleSheet::css_rules()
+void* web_css_style_sheet_construct(void* document, bool has_base_url, FlatPtr base_url, void* media_list, FlatPtr media_text, bool disabled)
{
- // 1. If the origin-clean flag is unset, throw a SecurityError exception.
- if (!state().is_origin_clean())
- return WebIDL::SecurityError::create("Can't access the rules of cross-origin stylesheets."_utf16);
+ auto base_url_text = Utf16String::from_raw(base_url);
+ auto media_text_string = Utf16String::from_raw(media_text);
- // 2. Return a read-only, live CSSRuleList object representing the CSS rules.
- return GC::Ref { state().rules() };
+ CSSStyleSheetOptions options;
+ if (has_base_url)
+ options.base_url = move(base_url_text);
+ if (media_list)
+ options.media = GC::Ref { *static_cast<MediaList*>(media_list) };
+ else
+ options.media = move(media_text_string);
+ options.disabled = disabled;
+
+ auto state = StyleSheetState::create_constructed(*static_cast<DOM::Document*>(static_cast<GC::Cell*>(document)), options);
+ if (state.is_error())
+ return nullptr;
+ return &state.value()->cssom_sheet();
}
-void CSSStyleSheet::update_owner_chain()
+size_t web_css_sheet_state_external_memory_size(void* state)
+{
+ return state_of(state).external_memory_size();
+}
+
+bool web_css_sheet_state_flag(void* state, u8 flag)
+{
+ return state_of(state).native_sheet().flag(static_cast<RustStyleSheet::Flag>(flag));
+}
+
+void web_css_sheet_state_set_disabled(void* state, bool disabled)
+{
+ state_of(state).set_disabled(disabled);
+}
+
+bool web_css_sheet_state_location(void* state, FlatPtr* location)
+{
+ auto href = state_of(state).href_for_bindings();
+ if (!href.has_value())
+ return false;
+ *location = href.release_value().into_raw();
+ return true;
+}
+
+FlatPtr web_css_sheet_state_title(void* state)
+{
+ return Utf16String { state_of(state).title() }.into_raw();
+}
+
+void* web_css_sheet_state_owner_node(void* state)
+{
+ return static_cast<GC::Cell*>(state_of(state).owner_node());
+}
+
+void* web_css_sheet_state_parent_style_sheet(void* state)
+{
+ auto* parent = state_of(state).parent_style_sheet();
+ return parent ? &parent->cssom_sheet() : nullptr;
+}
+
+void* web_css_sheet_state_media(void* state)
+{
+ return state_of(state).media().ptr();
+}
+
+Parser::ValueParserFFI::NativeRuleList const* web_css_sheet_state_native_rules(void* state)
+{
+ return state_of(state).native_rules().handle();
+}
+
+void* web_css_sheet_state_owner_rule(void* state)
+{
+ return state_of(state).owner_rule().ptr();
+}
+
+void* web_css_sheet_state_rule_list(void* state)
+{
+ return &state_of(state).rules();
+}
+
+Parser::ValueParserFFI::NativeRule const* web_css_sheet_state_parse_rule(void* state, FlatPtr rule)
+{
+ auto text = Utf16String::from_raw(rule);
+ auto parsed_rule = state_of(state).parse_rule(text.utf16_view());
+ if (!parsed_rule.has_value())
+ return nullptr;
+ return Parser::ValueParserFFI::rust_rule_retain(parsed_rule->handle());
+}
+
+void web_css_sheet_state_rule_inserted(void* state, Parser::ValueParserFFI::NativeRule const* rule)
+{
+ state_of(state).rule_inserted(RustRule { rule });
+}
+
+void web_css_sheet_state_remove_rule(void* state, u32 index)
+{
+ state_of(state).remove_rule(index);
+}
+
+void* web_css_sheet_state_replace(void* state, FlatPtr text)
+{
+ return state_of(state).replace(Utf16String::from_raw(text)).ptr();
+}
+
+void web_css_sheet_state_replace_rules(void* state, FlatPtr text)
+{
+ state_of(state).replace_rules(Utf16String::from_raw(text));
+}
+
+u32 web_css_style_sheet_list_length(void* scope)
{
- auto* parent = state().parent_style_sheet();
- m_parent_sheet = parent ? &parent->cssom_sheet() : nullptr;
- m_owner_import = state().owner_import();
+ return static_cast<StyleScope*>(scope)->style_sheets().size();
}
-void CSSStyleSheet::visit_edges(GC::Cell::Visitor& visitor)
+void* web_css_style_sheet_list_item(void* scope, u32 index)
{
- Base::visit_edges(visitor);
- visitor.visit(m_parent_sheet);
- visitor.visit(m_owner_import);
+ auto const& sheets = static_cast<StyleScope*>(scope)->style_sheets();
+ if (index >= sheets.size())
+ return nullptr;
+ return &sheets[index]->cssom_sheet();
}
}
diff --git a/Libraries/LibWeb/CSS/CSSStyleSheet.h b/Libraries/LibWeb/CSS/CSSStyleSheet.h
index 81456900dc1..13aa3fa4c86 100644
--- a/Libraries/LibWeb/CSS/CSSStyleSheet.h
+++ b/Libraries/LibWeb/CSS/CSSStyleSheet.h
@@ -9,39 +9,22 @@
#pragma once
-#include <LibWeb/CSS/StyleSheet.h>
+#include <LibGC/Ptr.h>
+#include <LibWeb/Bindings/CSSStyleSheet.h>
+#include <LibWeb/Bindings/RustInterface.h>
+#include <LibWeb/Forward.h>
namespace Web::CSS {
// https://drafts.csswg.org/cssom-1/#cssstylesheet
-class WEB_API CSSStyleSheet final : public StyleSheet {
- WEB_WRAPPABLE(CSSStyleSheet, StyleSheet);
- GC_DECLARE_ALLOCATOR(CSSStyleSheet);
+class WEB_API CSSStyleSheet final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(CSSStyleSheet, css_style_sheet)
public:
- virtual ~CSSStyleSheet() override;
-
- static WebIDL::ExceptionOr<GC::Ref<CSSStyleSheet>> create_for_constructor(JS::Object&, CSSStyleSheetOptions const& options = {});
-
- GC::Ptr<CSSRule> owner_rule() { return state().owner_rule(); }
- WebIDL::ExceptionOr<GC::Ref<CSSRuleList>> css_rules();
-
- WebIDL::ExceptionOr<unsigned> insert_rule(Utf16View rule, unsigned index) { return state().insert_rule(rule, index); }
- WebIDL::ExceptionOr<WebIDL::Long> add_rule(Optional<Utf16String> selector, Optional<Utf16String> style, Optional<WebIDL::UnsignedLong> index) { return state().add_rule(move(selector), move(style), index); }
- WebIDL::ExceptionOr<void> remove_rule(Optional<WebIDL::UnsignedLong> index) { return state().remove_rule(index); }
- WebIDL::ExceptionOr<void> delete_rule(unsigned index) { return state().delete_rule(index); }
- GC::Ref<WebIDL::Promise> replace(Utf16String text) { return state().replace(move(text)); }
- WebIDL::ExceptionOr<void> replace_sync(Utf16View text) { return state().replace_sync(text); }
-
-private:
- friend class StyleSheetState;
[[nodiscard]] static GC::Ref<CSSStyleSheet> create(StyleSheetState&);
- explicit CSSStyleSheet(StyleSheetState&);
- virtual void visit_edges(GC::Cell::Visitor&) override;
- void update_owner_chain();
- GC::Ptr<CSSStyleSheet> m_parent_sheet;
- RefPtr<StyleSheetImport> m_owner_import;
+ StyleSheetState& state() const;
+ void update_owner_chain();
};
}
diff --git a/Libraries/LibWeb/CSS/CSSStyleSheet.idl b/Libraries/LibWeb/CSS/CSSStyleSheet.idl
index af78c55e619..5c35d604aa0 100644
--- a/Libraries/LibWeb/CSS/CSSStyleSheet.idl
+++ b/Libraries/LibWeb/CSS/CSSStyleSheet.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/cssom/#cssstylesheet
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSStyleSheet : StyleSheet {
constructor(optional CSSStyleSheetInit options = {});
@@ -12,7 +12,7 @@ interface CSSStyleSheet : StyleSheet {
undefined replaceSync(USVString text);
// https://drafts.csswg.org/cssom/#legacy-css-style-sheet-members
- [SameObject, ImplementedAs=css_rules] readonly attribute CSSRuleList rules;
+ [SameObject] readonly attribute CSSRuleList rules;
long addRule(optional DOMString selector = "undefined", optional DOMString style = "undefined", optional unsigned long index);
undefined removeRule(optional unsigned long index);
};
diff --git a/Libraries/LibWeb/CSS/MediaList.cpp b/Libraries/LibWeb/CSS/MediaList.cpp
index 6ce66b1b62d..865dc4393b2 100644
--- a/Libraries/LibWeb/CSS/MediaList.cpp
+++ b/Libraries/LibWeb/CSS/MediaList.cpp
@@ -44,7 +44,7 @@ RustMediaList MediaList::share_native_list() const
void MediaList::set_associated_style_sheet(NonnullRefPtr<StyleSheetState> sheet)
{
- web_media_list_set_associated_style_sheet(JS::HostABI::vm_to_abi(JS::VM::the()), this, static_cast<GC::Cell*>(&sheet->cssom_sheet()));
+ web_media_list_set_associated_style_sheet(JS::HostABI::vm_to_abi(JS::VM::the()), this, &sheet->cssom_sheet());
}
void MediaList::set_associated_rule(GC::Ref<CSSRule> rule)
@@ -54,7 +54,7 @@ void MediaList::set_associated_rule(GC::Ref<CSSRule> rule)
void web_css_media_list_changed(void* style_sheet_cell, void* rule_cell)
{
- auto* style_sheet = static_cast<CSSStyleSheet*>(static_cast<GC::Cell*>(style_sheet_cell));
+ auto* style_sheet = static_cast<CSSStyleSheet*>(style_sheet_cell);
auto* rule = static_cast<CSSRule*>(rule_cell);
// Both owners reach the same place: the sheet whose rules the gate belongs to.
diff --git a/Libraries/LibWeb/CSS/StyleSheet.cpp b/Libraries/LibWeb/CSS/StyleSheet.cpp
deleted file mode 100644
index d86324faaf8..00000000000
--- a/Libraries/LibWeb/CSS/StyleSheet.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (c) 2018-2021, Andreas Kling <[email protected]>
- * Copyright (c) 2021, the SerenityOS developers.
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibJS/Runtime/ExternalMemory.h>
-#include <LibWeb/CSS/CSSStyleSheet.h>
-#include <LibWeb/CSS/StyleSheet.h>
-
-namespace Web::CSS {
-
-StyleSheet::StyleSheet(StyleSheetState& state)
- : m_state(state)
-{
-}
-
-void StyleSheet::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_state);
-}
-
-CSSStyleSheet* StyleSheet::parent_style_sheet() const
-{
- auto* parent = m_state->parent_style_sheet();
- return parent ? &parent->cssom_sheet() : nullptr;
-}
-
-size_t StyleSheet::external_memory_size() const
-{
- return JS::saturating_add_external_memory_size(Base::external_memory_size(), m_state->external_memory_size());
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/StyleSheet.h b/Libraries/LibWeb/CSS/StyleSheet.h
deleted file mode 100644
index 20faa57e92f..00000000000
--- a/Libraries/LibWeb/CSS/StyleSheet.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2018-2021, Andreas Kling <[email protected]>
- * Copyright (c) 2021, the SerenityOS developers.
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/PlatformObject.h>
-#include <LibWeb/CSS/StyleSheetState.h>
-
-namespace Web::CSS {
-
-// https://drafts.csswg.org/cssom-1/#the-stylesheet-interface
-class WEB_API StyleSheet : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(StyleSheet, Bindings::GCAllocatedWrappable);
-
-public:
- virtual ~StyleSheet() override = default;
-
- StyleSheetState& state() { return m_state; }
- StyleSheetState const& state() const { return m_state; }
-
- Utf16FlyString type() const { return m_state->type(); }
- DOM::Element* owner_node() { return m_state->owner_node(); }
- Optional<Utf16String> href_for_bindings() const { return m_state->href_for_bindings(); }
- Optional<Utf16String> title_for_bindings() const { return m_state->title_for_bindings(); }
- GC::Ref<MediaList> media() const { return m_state->media(); }
- bool disabled() const { return m_state->disabled(); }
- void set_disabled(bool disabled) { m_state->set_disabled(disabled); }
- CSSStyleSheet* parent_style_sheet() const;
-
-protected:
- explicit StyleSheet(StyleSheetState&);
- virtual void visit_edges(GC::Cell::Visitor&) override;
- virtual size_t external_memory_size() const override;
-
-private:
- NonnullRefPtr<StyleSheetState> m_state;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/StyleSheet.idl b/Libraries/LibWeb/CSS/StyleSheet.idl
index 5c449ffc7dd..7c00f14f6dd 100644
--- a/Libraries/LibWeb/CSS/StyleSheet.idl
+++ b/Libraries/LibWeb/CSS/StyleSheet.idl
@@ -1,15 +1,15 @@
// https://drafts.csswg.org/cssom/#stylesheet
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface StyleSheet {
readonly attribute CSSOMString type;
- [ImplementedAs=href_for_bindings] readonly attribute USVString? href;
+ readonly attribute USVString? href;
// FIXME: readonly attribute (Element or ProcessingInstruction)? ownerNode;
readonly attribute Element? ownerNode;
readonly attribute CSSStyleSheet? parentStyleSheet;
- [ImplementedAs=title_for_bindings] readonly attribute DOMString? title;
+ readonly attribute DOMString? title;
[SameObject, PutForwards=mediaText] readonly attribute MediaList media;
attribute boolean disabled;
diff --git a/Libraries/LibWeb/CSS/StyleSheetImport.cpp b/Libraries/LibWeb/CSS/StyleSheetImport.cpp
index 05fd0fdcae2..ac17cd4d186 100644
--- a/Libraries/LibWeb/CSS/StyleSheetImport.cpp
+++ b/Libraries/LibWeb/CSS/StyleSheetImport.cpp
@@ -79,7 +79,7 @@ void web_css_import_set_rule(void* import, void* rule)
void web_css_import_set_parent_style_sheet(void* import_cell, void* sheet)
{
auto& import = import_from_cell(import_cell);
- auto* state = sheet ? &static_cast<CSSStyleSheet*>(static_cast<GC::Cell*>(sheet))->state() : nullptr;
+ auto* state = sheet ? &static_cast<CSSStyleSheet*>(sheet)->state() : nullptr;
if (import.parent_style_sheet() != state)
import.set_parent_style_sheet(state);
}
@@ -102,7 +102,7 @@ void* web_css_import_media(void* import)
void* web_css_import_style_sheet(void* import)
{
auto* sheet = import_from_cell(import).loaded_style_sheet();
- return sheet ? static_cast<GC::Cell*>(&sheet->cssom_sheet()) : nullptr;
+ return sheet ? &sheet->cssom_sheet() : nullptr;
}
NonnullRefPtr<StyleSheetImport> StyleSheetImport::create(RustRule rule, GC::Ptr<DOM::Document> document)
@@ -160,7 +160,7 @@ CSSImportRule& StyleSheetImport::cssom_rule() const
auto import = StyleSheetImportCell::create(const_cast<StyleSheetImport&>(*this));
auto* sheet = parent_style_sheet();
// NB: The new object tells this import that it is its rule.
- web_css_import_rule_create(JS::HostABI::vm_to_abi(JS::VM::the()), native_rule().handle(), static_cast<GC::Cell*>(import.ptr()), sheet ? static_cast<GC::Cell*>(&sheet->cssom_sheet()) : nullptr);
+ web_css_import_rule_create(JS::HostABI::vm_to_abi(JS::VM::the()), native_rule().handle(), static_cast<GC::Cell*>(import.ptr()), sheet ? &sheet->cssom_sheet() : nullptr);
}
return *m_cssom_rule;
}
diff --git a/Libraries/LibWeb/CSS/StyleSheetList.cpp b/Libraries/LibWeb/CSS/StyleSheetList.cpp
deleted file mode 100644
index 834ff158faa..00000000000
--- a/Libraries/LibWeb/CSS/StyleSheetList.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2020-2025, Andreas Kling <[email protected]>
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/StyleScope.h>
-#include <LibWeb/CSS/StyleSheetList.h>
-#include <LibWeb/CSS/StyleSheetState.h>
-#include <LibWeb/DOM/Node.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(StyleSheetList);
-
-GC::Ref<StyleSheetList> StyleSheetList::create(StyleScope& scope)
-{
- return GC::Heap::the().allocate<StyleSheetList>(scope);
-}
-
-StyleSheetList::StyleSheetList(StyleScope& scope)
- : m_scope(scope)
-{
-}
-
-CSSStyleSheet* StyleSheetList::item(size_t index) const
-{
- auto const& sheets = m_scope.style_sheets();
- if (index >= sheets.size())
- return nullptr;
- return &sheets[index]->cssom_sheet();
-}
-
-size_t StyleSheetList::length() const
-{
- return m_scope.style_sheets().size();
-}
-
-void StyleSheetList::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_scope.node());
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/StyleSheetList.h b/Libraries/LibWeb/CSS/StyleSheetList.h
index c5bdf2e8bae..29c79b2bf97 100644
--- a/Libraries/LibWeb/CSS/StyleSheetList.h
+++ b/Libraries/LibWeb/CSS/StyleSheetList.h
@@ -8,26 +8,19 @@
#pragma once
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Export.h>
+#include <LibGC/Ptr.h>
+#include <LibWeb/Bindings/RustInterface.h>
+#include <LibWeb/Bindings/StyleSheetList.h>
+#include <LibWeb/Forward.h>
namespace Web::CSS {
-class WEB_API StyleSheetList final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(StyleSheetList, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(StyleSheetList);
+// https://drafts.csswg.org/cssom/#the-stylesheetlist-interface
+class WEB_API StyleSheetList final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(StyleSheetList, style_sheet_list)
public:
[[nodiscard]] static GC::Ref<StyleSheetList> create(StyleScope&);
-
- CSSStyleSheet* item(size_t index) const;
- size_t length() const;
-
-private:
- explicit StyleSheetList(StyleScope&);
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- StyleScope& m_scope;
};
}
diff --git a/Libraries/LibWeb/CSS/StyleSheetList.idl b/Libraries/LibWeb/CSS/StyleSheetList.idl
index 002bac8ea91..f7054da2132 100644
--- a/Libraries/LibWeb/CSS/StyleSheetList.idl
+++ b/Libraries/LibWeb/CSS/StyleSheetList.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/cssom/#the-stylesheetlist-interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface StyleSheetList {
getter CSSStyleSheet? item(unsigned long index);
readonly attribute unsigned long length;
diff --git a/Libraries/LibWeb/CSS/StyleSheetState.cpp b/Libraries/LibWeb/CSS/StyleSheetState.cpp
index 5f534c5e3c2..7d9d110ac98 100644
--- a/Libraries/LibWeb/CSS/StyleSheetState.cpp
+++ b/Libraries/LibWeb/CSS/StyleSheetState.cpp
@@ -7,7 +7,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/Utf16StringBuilder.h>
#include <LibJS/Runtime/ExternalMemory.h>
#include <LibWeb/CSS/CSSImportRule.h>
#include <LibWeb/CSS/CSSNestedDeclarations.h>
@@ -259,61 +258,39 @@ size_t StyleSheetState::external_memory_size() const
// https://www.w3.org/TR/cssom/#dom-cssstylesheet-insertrule
WebIDL::ExceptionOr<unsigned> StyleSheetState::insert_rule(Utf16View rule, unsigned index)
{
- // 1. If the origin-clean flag is unset, throw a SecurityError exception.
- if (!is_origin_clean())
- return WebIDL::SecurityError::create("Can't call insert_rule() on cross-origin stylesheets."_utf16);
-
- // If the disallow modification flag is set, throw a NotAllowedError DOMException.
- if (disallow_modification())
- return WebIDL::NotAllowedError::create("Can't call insert_rule() on non-modifiable stylesheets."_utf16);
-
- // 3. Let parsed rule be the return value of invoking parse a rule with rule.
- auto parsed_rule = parse_css_rule(make_parsing_params(), rule);
-
- // 4. If parsed rule is a syntax error, return parsed rule.
+ auto parsed_rule = parse_rule(rule);
if (!parsed_rule.has_value())
return WebIDL::SyntaxError::create("Unable to parse CSS rule."_utf16);
-
- // 5. If parsed rule is an @import rule, and the constructed flag is set, throw a SyntaxError DOMException.
- if (constructed() && parsed_rule->type() == CSSRule::Type::Import)
- return WebIDL::SyntaxError::create("Can't insert @import rules into a constructed stylesheet."_utf16);
-
- // 6. Return the result of invoking insert a CSS rule rule in the CSS rules at index.
- auto result = CSSRuleList::insert_a_css_rule(m_native_sheet.rules(), *parsed_rule, index, CSSRuleList::Nested::No);
-
- if (!result.is_exception()) {
- recalculate_rule_caches();
- record_style_rule_inserted(*parsed_rule, *this);
-
- // OPTIMIZATION: A style rule or a keyframes rule arriving in a style element's own sheet changes only which
- // rules the scope holds, so dropping the rule cache is enough. Anything else can change what
- // the sheet as a whole contributes, which is what invalidate_owners() re-reads.
- auto style_element_sheet = !constructed() && owner_node() && owner_node()->is_html_style_element();
- auto rule_type = parsed_rule->type();
- if (style_element_sheet && (rule_type == CSSRule::Type::Keyframes || rule_type == CSSRule::Type::Style))
- invalidate_rule_cache_for_style_sheet_owners(*this);
- else
- invalidate_owners();
-
- synchronize_fonts_after_rule_change();
- }
-
+ auto result = TRY(CSSRuleList::insert_a_css_rule(m_native_sheet.rules(), *parsed_rule, index, CSSRuleList::Nested::No));
+ rule_inserted(*parsed_rule);
return result;
}
-// https://www.w3.org/TR/cssom/#dom-cssstylesheet-deleterule
-WebIDL::ExceptionOr<void> StyleSheetState::delete_rule(unsigned index)
+Optional<RustRule> StyleSheetState::parse_rule(Utf16View rule) const
{
- // 1. If the origin-clean flag is unset, throw a SecurityError exception.
- if (!is_origin_clean())
- return WebIDL::SecurityError::create("Can't call delete_rule() on cross-origin stylesheets."_utf16);
+ return parse_css_rule(make_parsing_params(), rule);
+}
+
+void StyleSheetState::rule_inserted(RustRule const& rule)
+{
+ recalculate_rule_caches();
+ record_style_rule_inserted(rule, *this);
+
+ // OPTIMIZATION: A style rule or a keyframes rule arriving in a style element's own sheet changes only which
+ // rules the scope holds, so dropping the rule cache is enough. Anything else can change what
+ // the sheet as a whole contributes, which is what invalidate_owners() re-reads.
+ auto style_element_sheet = !constructed() && owner_node() && owner_node()->is_html_style_element();
+ auto rule_type = rule.type();
+ if (style_element_sheet && (rule_type == CSSRule::Type::Keyframes || rule_type == CSSRule::Type::Style))
+ invalidate_rule_cache_for_style_sheet_owners(*this);
+ else
+ invalidate_owners();
- // 2. If the disallow modification flag is set, throw a NotAllowedError DOMException.
- if (disallow_modification())
- return WebIDL::NotAllowedError::create("Can't call delete_rule() on non-modifiable stylesheets."_utf16);
+ synchronize_fonts_after_rule_change();
+}
- // 3. Remove a CSS rule in the CSS rules at index.
- TRY(CSSRuleList::validate_rule_removal(native_rules(), index));
+void StyleSheetState::remove_rule(u32 index)
+{
auto removed_rule = native_rules().at(index);
RefPtr<StyleSheetState> detached_import;
if (auto* import = import_for_rule(removed_rule.identity()))
@@ -328,7 +305,6 @@ WebIDL::ExceptionOr<void> StyleSheetState::delete_rule(unsigned index)
record_style_rule_removed(*this, removed_rule, detached_import.ptr());
invalidate_owners();
synchronize_fonts_after_rule_change();
- return {};
}
// https://drafts.csswg.org/cssom/#dom-cssstylesheet-replace
@@ -371,15 +347,9 @@ GC::Ref<WebIDL::Promise> StyleSheetState::replace(Utf16String text)
return promise;
}
-// https://drafts.csswg.org/cssom/#dom-cssstylesheet-replacesync
-WebIDL::ExceptionOr<void> StyleSheetState::replace_sync(Utf16View text)
+// https://drafts.csswg.org/cssom/#synchronously-replace-the-rules-of-a-cssstylesheet
+void StyleSheetState::replace_rules(Utf16View text)
{
- // 1. If the constructed flag is not set, or the disallow modification flag is set, throw a NotAllowedError DOMException.
- if (!constructed())
- return WebIDL::NotAllowedError::create("Can't call replaceSync() on non-constructed stylesheets"_utf16);
- if (disallow_modification())
- return WebIDL::NotAllowedError::create("Can't call replaceSync() on non-modifiable stylesheets"_utf16);
-
// 2. Let rules be the result of running parse a stylesheet’s contents from text.
auto rules = CSS::Parser::Parser { make_parsing_params() }.parse_as_stylesheet_contents(text);
@@ -393,46 +363,6 @@ WebIDL::ExceptionOr<void> StyleSheetState::replace_sync(Utf16View text)
record_stylesheet_rules_replaced(*this);
invalidate_owners();
synchronize_fonts_after_rule_change();
-
- return {};
-}
-
-// https://drafts.csswg.org/cssom/#dom-cssstylesheet-addrule
-WebIDL::ExceptionOr<WebIDL::Long> StyleSheetState::add_rule(Optional<Utf16String> selector, Optional<Utf16String> style, Optional<WebIDL::UnsignedLong> index)
-{
- // 1. Let rule be an empty string.
- Utf16StringBuilder rule;
-
- // 2. Append selector to rule.
- if (selector.has_value())
- rule.append(selector.release_value());
-
- // 3. Append " { " to rule.
- rule.append_code_unit(u'{');
-
- // 4. If block is not empty, append block, followed by a space, to rule.
- if (style.has_value() && !style->is_empty()) {
- rule.append(style.release_value());
- rule.append_code_unit(u' ');
- }
-
- // 5. Append "}" to rule.
- rule.append_code_unit(u'}');
-
- // 6. Let index be optionalIndex if provided, or the number of CSS rules in the stylesheet otherwise.
- // 7. Call insertRule(), with rule and index as arguments.
- auto rule_text = rule.to_string();
- TRY(insert_rule(rule_text, index.value_or(m_native_sheet.rules().size())));
-
- // 8. Return -1.
- return -1;
-}
-
-// https://www.w3.org/TR/cssom/#dom-cssstylesheet-removerule
-WebIDL::ExceptionOr<void> StyleSheetState::remove_rule(Optional<WebIDL::UnsignedLong> index)
-{
- // The removeRule(index) method must run the same steps as deleteRule().
- return delete_rule(index.value_or(0));
}
void StyleSheetState::for_each_effective_rule_data(TraversalOrder order, Function<void(RustRuleView const&, Utf16View)> const& callback) const
@@ -971,14 +901,4 @@ void StyleSheetState::set_parent_css_style_sheet(StyleSheetState* parent)
m_cssom_sheet->update_owner_chain();
}
-// https://drafts.csswg.org/cssom/#dom-stylesheet-title
-Optional<Utf16String> StyleSheetState::title_for_bindings() const
-{
- // The title attribute must return the title or null if title is the empty string.
- if (m_title.is_empty())
- return {};
-
- return m_title;
-}
-
}
diff --git a/Libraries/LibWeb/CSS/StyleSheetState.h b/Libraries/LibWeb/CSS/StyleSheetState.h
index 379c89a94f8..b5146d3bd41 100644
--- a/Libraries/LibWeb/CSS/StyleSheetState.h
+++ b/Libraries/LibWeb/CSS/StyleSheetState.h
@@ -19,10 +19,10 @@
#include <AK/Weakable.h>
#include <LibGC/Cell.h>
#include <LibGC/Weak.h>
-#include <LibWeb/Bindings/CSSStyleSheet.h>
#include <LibWeb/CSS/CSSRule.h>
#include <LibWeb/CSS/CSSRuleList.h>
#include <LibWeb/CSS/CSSStyleRule.h>
+#include <LibWeb/CSS/CSSStyleSheet.h>
#include <LibWeb/CSS/MediaList.h>
#include <LibWeb/CSS/RustStyleSheet.h>
#include <LibWeb/CSS/StyleValues/ImageStyleValue.h>
@@ -45,7 +45,12 @@ class StyleSheetImport;
class StyleScope;
struct StyleRuleCache;
-using CSSStyleSheetOptions = Bindings::CSSStyleSheetInit;
+// https://drafts.csswg.org/cssom/#dictdef-cssstylesheetinit
+struct CSSStyleSheetOptions {
+ Optional<Utf16String> base_url;
+ Variant<GC::Ref<MediaList>, Utf16String> media { Utf16String {} };
+ bool disabled { false };
+};
WEB_API StyleSheetState* css_style_sheet_from_value(JS::Value);
WEB_API JS::Value css_style_sheet(JS::Realm&, StyleSheetState&);
@@ -91,13 +96,14 @@ public:
CSSRuleList* css_rules() { return &rules(); }
CSSRuleList const* css_rules() const { return &rules(); }
+ // NB: For the rules that LibWeb writes itself, which skips what the CSSOM method checks about its caller.
WebIDL::ExceptionOr<unsigned> insert_rule(Utf16View rule, unsigned index);
- WebIDL::ExceptionOr<WebIDL::Long> add_rule(Optional<Utf16String> selector, Optional<Utf16String> style, Optional<WebIDL::UnsignedLong> index);
- WebIDL::ExceptionOr<void> remove_rule(Optional<WebIDL::UnsignedLong> index);
- WebIDL::ExceptionOr<void> delete_rule(unsigned index);
+ Optional<RustRule> parse_rule(Utf16View rule) const;
+ void rule_inserted(RustRule const&);
+ void remove_rule(u32 index);
GC::Ref<WebIDL::Promise> replace(Utf16String text);
- WebIDL::ExceptionOr<void> replace_sync(Utf16View text);
+ void replace_rules(Utf16View text);
void for_each_effective_rule_data(TraversalOrder, Function<void(RustRuleView const&, Utf16View)> const&) const;
// Returns whether the match state of any media queries changed after evaluation.
@@ -184,7 +190,6 @@ public:
Optional<ReferrerPolicy::ReferrerPolicy> fetched_referrer_policy() const { return m_fetched_referrer_policy; }
Utf16String const& title() const { return m_title; }
- Optional<Utf16String> title_for_bindings() const;
void set_title(Utf16String title) { m_title = move(title); }
GC::Ref<MediaList> media() const;
diff --git a/Libraries/LibWeb/Editing/Internal/Algorithms.cpp b/Libraries/LibWeb/Editing/Internal/Algorithms.cpp
index e81d6b793b6..c673fb2422c 100644
--- a/Libraries/LibWeb/Editing/Internal/Algorithms.cpp
+++ b/Libraries/LibWeb/Editing/Internal/Algorithms.cpp
@@ -1140,13 +1140,10 @@ static bool author_style_sheet_sets_white_space(DOM::Element& element)
return false;
};
- auto& style_sheets = element.document().style_sheets();
- for (size_t index = 0; index < style_sheets.length(); ++index) {
- auto* style_sheet = style_sheets.item(index);
- if (!style_sheet || style_sheet->disabled())
+ for (auto const& style_sheet : element.document().style_scope().style_sheets()) {
+ if (style_sheet->disabled() || !style_sheet->is_origin_clean())
continue;
- auto rules = style_sheet->css_rules();
- if (!rules.is_error() && rule_list_sets_white_space(rule_list_sets_white_space, *rules.value()))
+ if (rule_list_sets_white_space(rule_list_sets_white_space, style_sheet->rules()))
return true;
}
return false;
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 34ebc7d4c93..d8721ef5e24 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -335,7 +335,6 @@ class StyleComputer;
class StylePropertyMap;
class StylePropertyMapReadOnly;
class StyleScope;
-class StyleSheet;
class StyleSheetImport;
class StyleSheetList;
class StyleValue;
diff --git a/Libraries/LibWeb/HTML/Scripting/ModuleScript.cpp b/Libraries/LibWeb/HTML/Scripting/ModuleScript.cpp
index b2b6156ce73..adb87c790c3 100644
--- a/Libraries/LibWeb/HTML/Scripting/ModuleScript.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/ModuleScript.cpp
@@ -179,11 +179,8 @@ WebIDL::ExceptionOr<GC::Ptr<ModuleScript>> ModuleScript::create_a_css_module_scr
// 6. Run the steps to synchronously replace the rules of a CSSStyleSheet on sheet given source.
// If this throws an exception, catch it, and set script's parse error to that exception, and return script.
- if (auto result = sheet->replace_sync(source); result.is_error()) {
- auto throw_completion = WebIDL::exception_to_throw_completion(realm.vm(), realm, result.exception());
- script->set_parse_error(throw_completion.value());
- return script;
- }
+ // NB: A new constructed sheet has the constructed flag and not the disallow modification flag, so this cannot throw.
+ sheet->replace_rules(source);
// 7. Set script's record to the result of CreateDefaultExportSyntheticModule(sheet).
script->m_record = CSS::create_css_style_sheet_default_export_module(realm, sheet, filename.view());
diff --git a/Libraries/LibWeb/Rust/src/css/style_sheet.rs b/Libraries/LibWeb/Rust/src/css/style_sheet.rs
index 978f1bd4e6c..df99f373b79 100644
--- a/Libraries/LibWeb/Rust/src/css/style_sheet.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_sheet.rs
@@ -22,7 +22,6 @@ static NEXT_SHEET_IDENTITY: AtomicU64 = AtomicU64::new(1);
#[derive(Clone, Copy)]
#[repr(u8)]
-#[cfg_attr(not(test), expect(dead_code, reason = "Flags are selected by CSSOM through FFI"))]
pub enum NativeStyleSheetFlag {
Disabled = 1,
Alternate = 2,
diff --git a/Libraries/LibWeb/Rust/src/lib.rs b/Libraries/LibWeb/Rust/src/lib.rs
index c20e32f7110..1ccf9368a41 100644
--- a/Libraries/LibWeb/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Rust/src/lib.rs
@@ -37,6 +37,7 @@ pub use css::font_feature_values::FontFeatureValuesRuleKind;
pub use css::media_list::{MediaList as NativeMediaList, MediaListDeleteResult};
pub use css::rule::cssom;
pub use css::rule::{NativeRule, NativeRuleList, NativeRuleType, RuleInsertionResult, RuleRemovalResult};
+pub use css::style_sheet::NativeStyleSheetFlag;
pub use css::typed_om;
pub use svg::gfx_path_from_path_data;
diff --git a/Libraries/LibWeb/ViewTransition/ViewTransition.cpp b/Libraries/LibWeb/ViewTransition/ViewTransition.cpp
index ac9cfa9599b..6af7dbf8ae3 100644
--- a/Libraries/LibWeb/ViewTransition/ViewTransition.cpp
+++ b/Libraries/LibWeb/ViewTransition/ViewTransition.cpp
@@ -1045,7 +1045,7 @@ void ViewTransition::clear_view_transition()
auto rules = stylesheet->css_rules();
for (u32 i = 0; i < rules->length(); i++) {
if (GC::Ptr { rules->item(i) } == style) {
- MUST(stylesheet->delete_rule(i));
+ stylesheet->remove_rule(i);
break;
}
}