Skip to content

Truly independent web browser

LibWeb: Implement the CSSOM rule interfaces in Rust

Andreas Klingd6f9e8deaf2b
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_condition_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_condition_rule.rs
new file mode 100644
index 00000000000..cd73e0ae702
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_condition_rule.rs
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSConditionRule, https://drafts.csswg.org/css-conditional-3/#the-cssconditionrule-interface
+
+use std::rc::Rc;
+
+use ak::Utf16String;
+use libjs_rust::api::Trace;
+use libweb_rust::NativeRule;
+
+use super::css_grouping_rule::CSSGroupingRule;
+use super::css_rule::{AnyCSSRule, CSSRule};
+use crate::bindings::interface::{Inherits, Wrappable};
+use crate::bindings::{CallContext, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSConditionRule {
+ grouping_rule: CSSGroupingRule,
+}
+
+impl Wrappable for CSSConditionRule {}
+
+impl Inherits<CSSGroupingRule> for CSSConditionRule {
+ fn parent(&self) -> &CSSGroupingRule {
+ &self.grouping_rule
+ }
+}
+
+impl CSSConditionRule {
+ pub(crate) fn new(native_rule: Rc<NativeRule>) -> Self {
+ Self {
+ grouping_rule: CSSGroupingRule::new(native_rule),
+ }
+ }
+
+ pub(crate) fn grouping_rule(&self) -> &CSSGroupingRule {
+ &self.grouping_rule
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ self.grouping_rule.rule()
+ }
+
+ // https://drafts.csswg.org/css-conditional-3/#dom-cssconditionrule-conditiontext
+ pub(crate) fn condition_text(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(match self.rule().object() {
+ AnyCSSRule::CSSContainerRule(object) => object.serialized_condition_text(),
+ AnyCSSRule::CSSMediaRule(object) => object.serialized_condition_text(),
+ AnyCSSRule::CSSSupportsRule(object) => object.serialized_condition_text(),
+ _ => unreachable!("only these rules are condition rules"),
+ })
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_container_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_container_rule.rs
new file mode 100644
index 00000000000..261823973f9
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_container_rule.rs
@@ -0,0 +1,167 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSContainerRule, https://drafts.csswg.org/css-conditional-5/#the-csscontainerrule-interface
+
+use super::css_condition_rule::CSSConditionRule;
+use super::css_grouping_rule::CSSGroupingRule;
+use super::css_rule::impl_rule_wrappable;
+use super::css_rule::{CSSRule, RuleText, serialize_block_of_rules};
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use std::rc::Rc;
+
+/// The dictionary CSSContainerCondition of CSS/CSSContainerRule.idl.
+pub(crate) struct CSSContainerCondition {
+ pub(crate) name: Utf16String,
+ pub(crate) query: Utf16String,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSContainerRule {
+ condition_rule: CSSConditionRule,
+}
+
+impl_rule_wrappable!(CSSContainerRule);
+
+impl Inherits<CSSConditionRule> for CSSContainerRule {
+ fn parent(&self) -> &CSSConditionRule {
+ &self.condition_rule
+ }
+}
+
+impl CSSContainerRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ condition_rule: CSSConditionRule::new(native_rule),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ self.condition_rule.rule()
+ }
+
+ pub(crate) fn grouping_rule(&self) -> &CSSGroupingRule {
+ self.condition_rule.grouping_rule()
+ }
+
+ // https://drafts.csswg.org/css-conditional-5/#the-csscontainerrule-interface
+ pub(crate) fn serialized_condition_text(&self) -> Utf16String {
+ // The conditionText attribute (defined on the CSSConditionRule parent rule), on getting, must return a value as
+ // follows:
+
+ // 1. Let conditions be the result of getting the conditions attribute.
+ let conditions = self.rule().native_rule().container_conditions();
+
+ // 2. Let first be true.
+ let mut first = true;
+
+ // 2. Let result be the empty string.
+ let mut result = RuleText::default();
+
+ // 3. For each condition in conditions:
+ for condition in &conditions {
+ // 1. If first is false, append ", " to result.
+ if !first {
+ result.push_str(", ");
+ }
+
+ // 2. Set first to false.
+ first = false;
+
+ // 3. If condition's name is not empty:
+ if !condition.name.is_empty() {
+ // 1. Append condition's name to result.
+ result.push(&condition.name);
+
+ // 2. If condition's query is not empty, append a single space to result.
+ if !condition.query.is_empty() {
+ result.push_str(" ");
+ }
+ }
+
+ // 4. Append condition's query to result.
+ result.push(&condition.query);
+ }
+
+ // 5. Return result.
+ result.finish()
+ }
+
+ // https://drafts.csswg.org/cssom-1/#serialize-a-css-rule
+ pub(crate) fn serialized(&self, vm: &Vm) -> Utf16String {
+ // AD-HOC: The spec does not define @container serialization, so this is based on CSSMediaRule::serialized().
+ let mut text = RuleText::new("@container ");
+ text.push(&self.serialized_condition_text());
+ serialize_block_of_rules(text, vm, self.grouping_rule().child_rules(vm))
+ }
+
+ // https://drafts.csswg.org/css-conditional-5/#dom-csscontainerrule-containername
+ pub(crate) fn container_name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ // The containerName attribute, on getting, must return a value as follows:
+
+ // 1. Let conditions be the result of getting the conditions attribute.
+ let mut conditions = self.rule().native_rule().container_conditions();
+
+ // 2. If the length of conditions is 1:
+ if conditions.len() == 1 {
+ // 1. Return the only condition's name.
+ return Ok(conditions.swap_remove(0).name);
+ }
+
+ // 3. Return "".
+ Ok(Utf16String::from_utf16(&[]))
+ }
+
+ // https://drafts.csswg.org/css-conditional-5/#dom-csscontainerrule-containerquery
+ pub(crate) fn container_query(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ // The containerQuery attribute, on getting, must return a value as follows:
+
+ // 1. Let conditions be the result of getting the conditions attribute.
+ let mut conditions = self.rule().native_rule().container_conditions();
+
+ // 2. If the length of conditions is 1:
+ if conditions.len() == 1 {
+ // 1. Return the only condition's query.
+ return Ok(conditions.swap_remove(0).query);
+ }
+
+ // 3. Return "".
+ Ok(Utf16String::from_utf16(&[]))
+ }
+
+ // https://drafts.csswg.org/css-conditional-5/#dom-csscontainerrule-conditions
+ pub(crate) fn conditions(&self, _: &mut CallContext) -> WebIdlResult<Vec<CSSContainerCondition>> {
+ // The conditions attribute, on getting, must return a value as follows:
+
+ // 1. Let result be an empty list.
+ // 2. For each <container-condition> condition specified in the rule:
+ // 1. Let dict be a new CSSContainerCondition with name set to the serialized <container-name> of condition if
+ // specified, or "" otherwise, and query set to the <container-query> specified in condition without any
+ // logical simplifications, so that the returned query will evaluate to the same result as the specified
+ // query in any conformant implementation of this specification (including implementations that implement
+ // future extensions allowed by the <general-enclosed> extensibility mechanism in this specification). In
+ // other words, token stream simplifications are allowed (such as reducing whitespace to a single space or
+ // omitting it in cases where it is known to be optional), but logical simplifications (such as removal of
+ // unneeded parentheses, or simplification based on evaluating results) are not allowed.
+ // 2. Append dict to result.
+ // 3. Return result.
+ Ok(self
+ .rule()
+ .native_rule()
+ .container_conditions()
+ .into_iter()
+ .map(|condition| CSSContainerCondition {
+ name: condition.name,
+ query: condition.query,
+ })
+ .collect())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_counter_style_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_counter_style_rule.rs
new file mode 100644
index 00000000000..0bbbcabd1d8
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_counter_style_rule.rs
@@ -0,0 +1,217 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSCounterStyleRule, https://drafts.csswg.org/css-counter-styles/#the-csscounterstylerule-interface
+
+use super::css_rule::CSSRule;
+use super::css_rule::RuleText;
+use super::css_rule::impl_rule_wrappable;
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use core::ffi::c_void;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use libweb_rust::cssom::serialize_identifier;
+use std::rc::Rc;
+
+unsafe extern "C" {
+ fn web_css_counter_style_rule_changed(rule: *mut c_void);
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSCounterStyleRule {
+ rule: CSSRule,
+}
+
+impl_rule_wrappable!(CSSCounterStyleRule);
+
+impl Inherits<CSSRule> for CSSCounterStyleRule {
+ fn parent(&self) -> &CSSRule {
+ &self.rule
+ }
+}
+
+impl CSSCounterStyleRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ rule: CSSRule::new(native_rule),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ &self.rule
+ }
+
+ fn changed(&self) {
+ // SAFETY: The cell is that of this object, which is live.
+ unsafe { web_css_counter_style_rule_changed(self.rule.object().cell()) };
+ }
+
+ fn set_descriptor(&self, name: &str, value: &Utf16String) {
+ if self
+ .rule
+ .native_rule()
+ .set_counter_style_descriptor(name, &value.to_utf16())
+ {
+ self.changed();
+ }
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-name
+ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().counter_style_name())
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-name
+ pub(crate) fn set_name(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ if self.rule.native_rule().set_counter_style_name(&value.to_utf16()) {
+ self.changed();
+ }
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-system
+ pub(crate) fn system(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().counter_style_descriptor("system"))
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-system
+ pub(crate) fn set_system(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ self.set_descriptor("system", &value);
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-symbols
+ pub(crate) fn symbols(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().counter_style_descriptor("symbols"))
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-symbols
+ pub(crate) fn set_symbols(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ self.set_descriptor("symbols", &value);
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-additivesymbols
+ pub(crate) fn additive_symbols(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().counter_style_descriptor("additive-symbols"))
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-additivesymbols
+ pub(crate) fn set_additive_symbols(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ self.set_descriptor("additive-symbols", &value);
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-negative
+ pub(crate) fn negative(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().counter_style_descriptor("negative"))
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-negative
+ pub(crate) fn set_negative(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ self.set_descriptor("negative", &value);
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-prefix
+ pub(crate) fn prefix(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().counter_style_descriptor("prefix"))
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-prefix
+ pub(crate) fn set_prefix(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ self.set_descriptor("prefix", &value);
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-suffix
+ pub(crate) fn suffix(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().counter_style_descriptor("suffix"))
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-suffix
+ pub(crate) fn set_suffix(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ self.set_descriptor("suffix", &value);
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-range
+ pub(crate) fn range(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().counter_style_descriptor("range"))
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-range
+ pub(crate) fn set_range(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ self.set_descriptor("range", &value);
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-pad
+ pub(crate) fn pad(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().counter_style_descriptor("pad"))
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-pad
+ pub(crate) fn set_pad(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ self.set_descriptor("pad", &value);
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-speakas
+ pub(crate) fn speak_as(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().counter_style_descriptor("speak-as"))
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-speakas
+ pub(crate) fn set_speak_as(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ self.set_descriptor("speak-as", &value);
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-fallback
+ pub(crate) fn fallback(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().counter_style_descriptor("fallback"))
+ }
+
+ // https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-fallback
+ pub(crate) fn set_fallback(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ self.set_descriptor("fallback", &value);
+ Ok(())
+ }
+
+ pub(crate) fn serialized(&self, _: &Vm) -> Utf16String {
+ let native_rule = self.rule.native_rule();
+ let mut text = RuleText::new("@counter-style ");
+ text.push(&serialize_identifier(&native_rule.counter_style_name().to_utf16()));
+ text.push_str(" {");
+ for name in [
+ "system",
+ "negative",
+ "prefix",
+ "suffix",
+ "range",
+ "pad",
+ "fallback",
+ "symbols",
+ "additive-symbols",
+ "speak-as",
+ ] {
+ let value = native_rule.counter_style_descriptor(name);
+ if !value.is_empty() {
+ text.push_str(" ");
+ text.push_str(name);
+ text.push_str(": ");
+ text.push(&value);
+ text.push_str(";");
+ }
+ }
+ text.push_str(" }");
+ text.finish()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_font_face_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_font_face_rule.rs
new file mode 100644
index 00000000000..bf865630284
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_font_face_rule.rs
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSFontFaceRule, https://drafts.csswg.org/css-fonts/#om-fontface
+
+use super::css_rule::CSSRule;
+use super::css_rule::RuleText;
+use super::css_rule::impl_rule_wrappable;
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use std::rc::Rc;
+
+/// AtRuleID::FontFace.
+const FONT_FACE_AT_RULE: u8 = 0;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSFontFaceRule {
+ rule: CSSRule,
+}
+
+impl_rule_wrappable!(CSSFontFaceRule);
+
+impl Inherits<CSSRule> for CSSFontFaceRule {
+ fn parent(&self) -> &CSSRule {
+ &self.rule
+ }
+}
+
+impl CSSFontFaceRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ rule: CSSRule::new(native_rule),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ &self.rule
+ }
+
+ // https://drafts.csswg.org/css-fonts/#dom-cssfontfacerule-style
+ pub(crate) fn style(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(self.rule.style_attribute(cx))
+ }
+
+ fn descriptor(&self, name: &str) -> Option<Utf16String> {
+ self.rule.native_rule().descriptor_text(FONT_FACE_AT_RULE, name)
+ }
+
+ // https://drafts.csswg.org/cssom/#ref-for-cssfontfacerule
+ pub(crate) fn serialized(&self, _: &Vm) -> Utf16String {
+ // The result of concatenating the following:
+
+ // 1. The string "@font-face {".
+ let mut text = RuleText::new("@font-face {");
+
+ // 2. If the font-family descriptor is present:
+ if let Some(font_family) = self.descriptor("font-family") {
+ // 1. A single SPACE (U+0020), followed by the string "font-family:", followed by a single SPACE (U+0020).
+ text.push_str(" font-family: ");
+
+ // 2. The result of performing serialize a string on the rule’s font family name.
+ text.push(&font_family);
+
+ // 3. The string ";", i.e., SEMICOLON (U+003B).
+ text.push_str(";");
+ }
+
+ // 3. If the rule’s associated source list is not empty, follow these substeps:
+ if let Some(sources) = self.descriptor("src") {
+ // 1. A single SPACE (U+0020), followed by the string "src:", followed by a single SPACE (U+0020).
+ text.push_str(" src: ");
+
+ // 2. The result of invoking serialize a comma-separated list on performing serialize a URL or serialize a
+ // LOCAL for each source on the source list.
+ text.push(&sources);
+
+ // 3. The string ";", i.e., SEMICOLON (U+003B).
+ text.push_str(";");
+ }
+
+ // 4. If rule’s associated unicode-range descriptor is present, a single SPACE (U+0020), followed by the string
+ // "unicode-range:", followed by a single SPACE (U+0020), followed by the result of performing serialize a
+ // <'unicode-range'>, followed by the string ";", i.e., SEMICOLON (U+003B).
+ self.append_descriptor(&mut text, "unicode-range", "unicode-range");
+
+ // FIXME: 5. If rule’s associated font-variant descriptor is present, a single SPACE (U+0020),
+ // followed by the string "font-variant:", followed by a single SPACE (U+0020),
+ // followed by the result of performing serialize a <'font-variant'>,
+ // followed by the string ";", i.e., SEMICOLON (U+003B).
+
+ // 6. If rule’s associated font-feature-settings descriptor is present, a single SPACE (U+0020),
+ // followed by the string "font-feature-settings:", followed by a single SPACE (U+0020),
+ // followed by the result of performing serialize a <'font-feature-settings'>,
+ // followed by the string ";", i.e., SEMICOLON (U+003B).
+ self.append_descriptor(&mut text, "font-feature-settings", "font-feature-settings");
+
+ // 7. If rule’s associated font-stretch descriptor is present, a single SPACE (U+0020),
+ // followed by the string "font-stretch:", followed by a single SPACE (U+0020),
+ // followed by the result of performing serialize a <'font-stretch'>,
+ // followed by the string ";", i.e., SEMICOLON (U+003B).
+ // NOTE: font-stretch is now an alias for font-width, so we use that instead.
+ self.append_descriptor(&mut text, "font-stretch", "font-width");
+
+ // 8. If rule’s associated font-weight descriptor is present, a single SPACE (U+0020),
+ // followed by the string "font-weight:", followed by a single SPACE (U+0020),
+ // followed by the result of performing serialize a <'font-weight'>,
+ // followed by the string ";", i.e., SEMICOLON (U+003B).
+ self.append_descriptor(&mut text, "font-weight", "font-weight");
+
+ // 9. If rule’s associated font-style descriptor is present, a single SPACE (U+0020),
+ // followed by the string "font-style:", followed by a single SPACE (U+0020),
+ // followed by the result of performing serialize a <'font-style'>,
+ // followed by the string ";", i.e., SEMICOLON (U+003B).
+ self.append_descriptor(&mut text, "font-style", "font-style");
+
+ // 10. A single SPACE (U+0020), followed by the string "}", i.e., RIGHT CURLY BRACKET (U+007D).
+ text.push_str(" }");
+ text.finish()
+ }
+
+ fn append_descriptor(&self, text: &mut RuleText, label: &str, descriptor: &str) {
+ if let Some(value) = self.descriptor(descriptor) {
+ text.push_str(" ");
+ text.push_str(label);
+ text.push_str(": ");
+ text.push(&value);
+ text.push_str(";");
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_font_feature_values_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_font_feature_values_rule.rs
new file mode 100644
index 00000000000..60c80c79c32
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_font_feature_values_rule.rs
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSFontFeatureValuesRule, https://drafts.csswg.org/css-fonts/#cssfontfeaturevaluesrule
+
+use super::css_rule::CSSRule;
+use super::css_rule::impl_rule_wrappable;
+use super::css_rule::{RuleText, wrap_cpp_cell};
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use core::ffi::c_void;
+use libjs_rust::api::GcRefCell;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::FontFeatureValuesRuleKind;
+use libweb_rust::NativeRule;
+use libweb_rust::cssom::{FONT_FEATURE_VALUES_KINDS, serialize_identifier, serialize_string_value};
+use std::rc::Rc;
+
+unsafe extern "C" {
+ fn web_css_font_feature_values_map_create(rule: *mut c_void, kind: u8) -> *mut c_void;
+}
+
+/// https://infra.spec.whatwg.org/#ascii-whitespace
+fn is_ascii_whitespace(unit: u16) -> bool {
+ matches!(unit, 0x09 | 0x0a | 0x0c | 0x0d | 0x20)
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSFontFeatureValuesRule {
+ rule: CSSRule,
+ /// The cells of the CSSFontFeatureValuesMaps of the rule, by the kind of its feature values.
+ maps: GcRefCell<[Option<CppCell>; 7]>,
+}
+
+impl_rule_wrappable!(CSSFontFeatureValuesRule);
+
+impl Inherits<CSSRule> for CSSFontFeatureValuesRule {
+ fn parent(&self) -> &CSSRule {
+ &self.rule
+ }
+}
+
+impl CSSFontFeatureValuesRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ rule: CSSRule::new(native_rule),
+ maps: GcRefCell::new(Default::default()),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ &self.rule
+ }
+
+ fn map(&self, cx: &CallContext, kind: FontFeatureValuesRuleKind) -> CppInterface {
+ let index = kind as usize;
+ if let Some(map) = &self.maps.borrow()[index] {
+ return wrap_cpp_cell(cx, map);
+ }
+ // SAFETY: The cell is that of this object, which is live.
+ let map = unsafe { web_css_font_feature_values_map_create(self.rule.object().cell(), kind as u8) };
+ // SAFETY: LibWeb returns a live cell.
+ let map = unsafe { CppCell::from_raw(map) };
+ let result = wrap_cpp_cell(cx, &map);
+ self.maps.borrow_mut(cx.vm())[index] = Some(map);
+ result
+ }
+
+ fn serialized_font_family(&self) -> Utf16String {
+ let mut text = RuleText::default();
+ for (index, family) in self
+ .rule
+ .native_rule()
+ .font_feature_values_families()
+ .iter()
+ .enumerate()
+ {
+ if index != 0 {
+ text.push_str(", ");
+ }
+ let units = family.to_utf16();
+ if units.iter().any(|unit| is_ascii_whitespace(*unit)) {
+ text.push(&serialize_string_value(&units));
+ } else {
+ text.push(&serialize_identifier(&units));
+ }
+ }
+ text.finish()
+ }
+
+ // https://drafts.csswg.org/css-fonts/#dom-cssfontfeaturevaluesrule-fontfamily
+ pub(crate) fn font_family(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.serialized_font_family())
+ }
+
+ // https://drafts.csswg.org/css-fonts/#dom-cssfontfeaturevaluesrule-fontfamily
+ pub(crate) fn set_font_family(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ let units = value.to_utf16();
+ let families = units
+ .split(|unit| *unit == u16::from(b','))
+ .filter(|family| !family.is_empty())
+ .map(|family| {
+ let start = family
+ .iter()
+ .position(|unit| !is_ascii_whitespace(*unit))
+ .unwrap_or(family.len());
+ let end = family
+ .iter()
+ .rposition(|unit| !is_ascii_whitespace(*unit))
+ .map_or(start, |end| end + 1);
+ family[start..end].to_vec()
+ })
+ .collect();
+ self.rule.native_rule().set_font_feature_values_families(families);
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/css-fonts/#dom-cssfontfeaturevaluesrule-annotation
+ pub(crate) fn annotation(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(self.map(cx, FontFeatureValuesRuleKind::Annotation))
+ }
+
+ // https://drafts.csswg.org/css-fonts/#dom-cssfontfeaturevaluesrule-ornaments
+ pub(crate) fn ornaments(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(self.map(cx, FontFeatureValuesRuleKind::Ornaments))
+ }
+
+ // https://drafts.csswg.org/css-fonts/#dom-cssfontfeaturevaluesrule-stylistic
+ pub(crate) fn stylistic(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(self.map(cx, FontFeatureValuesRuleKind::Stylistic))
+ }
+
+ // https://drafts.csswg.org/css-fonts/#dom-cssfontfeaturevaluesrule-swash
+ pub(crate) fn swash(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(self.map(cx, FontFeatureValuesRuleKind::Swash))
+ }
+
+ // https://drafts.csswg.org/css-fonts/#dom-cssfontfeaturevaluesrule-charactervariant
+ pub(crate) fn character_variant(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(self.map(cx, FontFeatureValuesRuleKind::CharacterVariant))
+ }
+
+ // https://drafts.csswg.org/css-fonts/#dom-cssfontfeaturevaluesrule-styleset
+ pub(crate) fn styleset(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(self.map(cx, FontFeatureValuesRuleKind::Styleset))
+ }
+
+ // https://drafts.csswg.org/css-fonts/#dom-cssfontfeaturevaluesrule-historicalforms
+ pub(crate) fn historical_forms(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(self.map(cx, FontFeatureValuesRuleKind::HistoricalForms))
+ }
+
+ pub(crate) fn serialized(&self, _: &Vm) -> Utf16String {
+ let mut text = RuleText::new("@font-feature-values ");
+ text.push(&self.serialized_font_family());
+ text.push_str(" {");
+ for (kind, at_rule_name) in FONT_FEATURE_VALUES_KINDS {
+ let entries = self.rule.native_rule().font_feature_values_entries(kind);
+ if entries.is_empty() {
+ continue;
+ }
+ text.push_str(" @");
+ text.push_str(at_rule_name);
+ text.push_str(" {");
+ for (name, values) in entries {
+ text.push_str(" ");
+ text.push(&serialize_identifier(&name));
+ text.push_str(":");
+ for value in values {
+ text.push_str(&format!(" {value}"));
+ }
+ text.push_str(";");
+ }
+ text.push_str(" }");
+ }
+ text.push_str(" }");
+ text.finish()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_function_declarations.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_function_declarations.rs
new file mode 100644
index 00000000000..996edfb31b5
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_function_declarations.rs
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSFunctionDeclarations, https://drafts.csswg.org/css-mixins-1/#cssfunctiondeclarations
+
+use super::css_rule::CSSRule;
+use super::css_rule::impl_rule_wrappable;
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use std::rc::Rc;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSFunctionDeclarations {
+ rule: CSSRule,
+}
+
+impl_rule_wrappable!(CSSFunctionDeclarations);
+
+impl Inherits<CSSRule> for CSSFunctionDeclarations {
+ fn parent(&self) -> &CSSRule {
+ &self.rule
+ }
+}
+
+impl CSSFunctionDeclarations {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ rule: CSSRule::new(native_rule),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ &self.rule
+ }
+
+ // https://drafts.csswg.org/css-mixins-1/#dom-cssfunctiondeclarations-style
+ pub(crate) fn style(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(self.rule.style_attribute(cx))
+ }
+
+ pub(crate) fn serialized(&self, vm: &Vm) -> Utf16String {
+ // https://drafts.csswg.org/css-mixins-1/#the-function-declarations-interface
+ // The CSSFunctionDeclarations rule, like CSSNestedDeclarations, serializes as if its declaration block had been
+ // serialized directly.
+ self.rule.serialized_declarations(vm)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_function_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_function_rule.rs
new file mode 100644
index 00000000000..4a32ffe5b46
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_function_rule.rs
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSFunctionRule, https://drafts.csswg.org/css-mixins-1/#cssfunctionrule
+
+use super::css_grouping_rule::CSSGroupingRule;
+use super::css_rule::impl_rule_wrappable;
+use super::css_rule::{CSSRule, RuleText, serialized_rules};
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use std::rc::Rc;
+
+/// The dictionary FunctionParameter of CSS/CSSFunctionRule.idl.
+pub(crate) struct FunctionParameter {
+ pub(crate) name: Utf16String,
+ pub(crate) r#type: Utf16String,
+ pub(crate) default_value: Option<Utf16String>,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSFunctionRule {
+ grouping_rule: CSSGroupingRule,
+}
+
+impl_rule_wrappable!(CSSFunctionRule);
+
+impl Inherits<CSSGroupingRule> for CSSFunctionRule {
+ fn parent(&self) -> &CSSGroupingRule {
+ &self.grouping_rule
+ }
+}
+
+impl CSSFunctionRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ grouping_rule: CSSGroupingRule::new(native_rule),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ self.grouping_rule.rule()
+ }
+
+ pub(crate) fn grouping_rule(&self) -> &CSSGroupingRule {
+ &self.grouping_rule
+ }
+
+ // https://drafts.csswg.org/css-mixins-1/#dom-cssfunctionrule-name
+ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule().native_rule().function_name())
+ }
+
+ // https://drafts.csswg.org/css-mixins-1/#dom-cssfunctionrule-getparameters
+ pub(crate) fn get_parameters(&self, _: &mut CallContext) -> WebIdlResult<Vec<FunctionParameter>> {
+ Ok(self
+ .rule()
+ .native_rule()
+ .function_parameters()
+ .into_iter()
+ .map(|parameter| FunctionParameter {
+ name: parameter.name,
+ r#type: parameter.parameter_type,
+ default_value: parameter.default_value,
+ })
+ .collect())
+ }
+
+ // https://drafts.csswg.org/css-mixins-1/#dom-cssfunctionrule-returntype
+ pub(crate) fn return_type(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule().native_rule().function_return_type())
+ }
+
+ // https://drafts.csswg.org/css-mixins-1/#serialize-a-cssfunctionrule
+ pub(crate) fn serialized(&self, vm: &Vm) -> Utf16String {
+ // NB: The native rule serializes steps 1 to 5, which read only what it holds.
+ let mut text = RuleText::default();
+ text.push(&self.rule().native_rule().function_prelude_text());
+
+ // 6. A single SPACE (U+0020), followed by a LEFT CURLY BRACKET (U+007B).
+ text.push_str(" {");
+
+ // 7. The result of performing serialize a CSS rule on each rule in cssRules, filtering out empty strings, each
+ // preceded by a single SPACE (U+0020).
+ for rule in serialized_rules(vm, self.grouping_rule.child_rules(vm)) {
+ text.push_str(" ");
+ text.push(&rule);
+ }
+
+ // 8. A single SPACE (U+0020), followed by a single RIGHT CURLY BRACKET (U+007D).
+ text.push_str(" }");
+ text.finish()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_grouping_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_grouping_rule.rs
new file mode 100644
index 00000000000..71dcf4e5584
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_grouping_rule.rs
@@ -0,0 +1,176 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSGroupingRule, https://drafts.csswg.org/cssom/#the-cssgroupingrule-interface
+
+use core::ffi::c_void;
+use std::rc::Rc;
+
+use ak::Utf16String;
+use libjs_rust::api::{GcRefCell, Trace, Vm};
+use libweb_rust::{NativeRule, RuleInsertionResult, RuleRemovalResult};
+
+use super::css_rule::CSSRule;
+use super::css_rule_list::CSSRuleList;
+use crate::bindings::interface::{Inherits, Ref, Wrappable};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+unsafe extern "C" {
+ fn web_css_grouping_rule_parse_rule(
+ rule: *mut c_void,
+ text: usize,
+ declarations_failed: *mut bool,
+ ) -> *const c_void;
+ fn web_css_grouping_rule_inserted(rule: *mut c_void, inserted: *const c_void);
+ fn web_css_grouping_rule_removed(rule: *mut c_void, removed: *const c_void);
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSGroupingRule {
+ rule: CSSRule,
+ /// The list of the child rules, which the first read makes, as most style rules nest none.
+ rules: GcRefCell<Option<Ref<CSSRuleList>>>,
+}
+
+impl Wrappable for CSSGroupingRule {}
+
+impl Inherits<CSSRule> for CSSGroupingRule {
+ fn parent(&self) -> &CSSRule {
+ &self.rule
+ }
+}
+
+fn insertion_error(result: RuleInsertionResult) -> WebIdlResult<()> {
+ match result {
+ RuleInsertionResult::Success => Ok(()),
+ RuleInsertionResult::IndexSizeError => Err(Exception::index_size_error(Utf16String::from_utf8(
+ "CSS rule index out of bounds.",
+ ))),
+ RuleInsertionResult::HierarchyRequestError => Err(Exception::Dom(
+ "HierarchyRequestError",
+ Utf16String::from_utf8("Cannot insert rule at specified index."),
+ )),
+ RuleInsertionResult::InvalidStateError => Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_utf8("Cannot insert @namespace rule into a stylesheet with non-namespace/import rules"),
+ )),
+ }
+}
+
+/// https://drafts.csswg.org/cssom/#remove-a-css-rule
+pub(crate) fn validate_rule_removal(result: RuleRemovalResult) -> WebIdlResult<()> {
+ match result {
+ RuleRemovalResult::Success => Ok(()),
+ RuleRemovalResult::IndexSizeError => Err(Exception::index_size_error(Utf16String::from_utf8(
+ "CSS rule index out of bounds.",
+ ))),
+ RuleRemovalResult::InvalidStateError => Err(Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_utf8("Cannot remove @namespace rule from a stylesheet with non-namespace/import rules."),
+ )),
+ }
+}
+
+impl CSSGroupingRule {
+ pub(crate) fn new(native_rule: Rc<NativeRule>) -> Self {
+ Self {
+ rule: CSSRule::new(native_rule),
+ rules: GcRefCell::new(None),
+ }
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ &self.rule
+ }
+
+ pub(crate) fn existing_css_rules(&self) -> Option<Ref<CSSRuleList>> {
+ *self.rules.borrow()
+ }
+
+ pub(crate) fn child_rules(&self, vm: &Vm) -> Ref<CSSRuleList> {
+ if let Some(rules) = self.existing_css_rules() {
+ return rules;
+ }
+ let native_rules = self
+ .rule
+ .native_rule()
+ .cssom_children()
+ .expect("a grouping rule has child rules");
+ let rules = CSSRuleList::create_for_rule(vm, native_rules, self.rule.object());
+ *self.rules.borrow_mut(vm) = Some(rules);
+ rules
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssgroupingrule-cssrules
+ pub(crate) fn css_rules(&self, cx: &mut CallContext) -> WebIdlResult<Ref<CSSRuleList>> {
+ Ok(self.child_rules(cx.vm()))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssgroupingrule-insertrule
+ pub(crate) fn insert_rule(&self, cx: &mut CallContext, rule: Utf16String, index: u32) -> WebIdlResult<u32> {
+ // The insertRule(rule, index) method must return the result of invoking insert a CSS rule rule into the child
+ // CSS rules at index, with the nested flag set.
+ let vm = cx.vm();
+ let rules = self.child_rules(vm);
+
+ // https://drafts.csswg.org/cssom/#insert-a-css-rule
+ // 1. Set length to the number of items in list.
+ let length = rules.native_length();
+
+ // 2. If index is greater than length, then throw an IndexSizeError exception.
+ if index as usize > length {
+ return Err(Exception::index_size_error(Utf16String::from_utf8(
+ "CSS rule index out of bounds.",
+ )));
+ }
+
+ // 3. Set new rule to the results of performing parse a CSS rule on argument rule.
+ // 4. If new rule is a syntax error, and nested is set, perform the following substeps:
+ let object = self.rule.object();
+ let mut declarations_failed = false;
+ // SAFETY: The cell is that of this object, the text is handed over, and the out pointer is valid.
+ let new_rule =
+ unsafe { web_css_grouping_rule_parse_rule(object.cell(), rule.into_raw(), &raw mut declarations_failed) };
+
+ // 5. If new rule is a syntax error, throw a SyntaxError exception.
+ if new_rule.is_null() {
+ let message = if declarations_failed {
+ "Unable to parse CSS declarations block."
+ } else {
+ "Unable to parse CSS rule."
+ };
+ return Err(Exception::syntax_error(Utf16String::from_utf8(message)));
+ }
+ // SAFETY: LibWeb hands over a reference to the rule.
+ let new_rule = unsafe { Rc::from_raw(new_rule.cast::<NativeRule>()) };
+
+ insertion_error(
+ rules
+ .native_rules()
+ .cssom_insert_rule(index as usize, Rc::clone(&new_rule), true),
+ )?;
+
+ // SAFETY: The cell is that of this object, and the rule is live.
+ unsafe { web_css_grouping_rule_inserted(object.cell(), Rc::as_ptr(&new_rule).cast()) };
+ Ok(index)
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssgroupingrule-deleterule
+ pub(crate) fn delete_rule(&self, cx: &mut CallContext, index: u32) -> WebIdlResult<()> {
+ // The deleteRule(index) method must remove a CSS rule from the child CSS rules at index.
+ let vm = cx.vm();
+ let rules = self.child_rules(vm);
+ let index = index as usize;
+ validate_rule_removal(rules.native_rules().cssom_validate_removal(index))?;
+ let removed_rule = rules.native_rules().cssom_rule_at(index);
+ rules.remove_a_css_rule_without_validation(vm, index);
+
+ // SAFETY: The cell is that of this object, and the rule is live.
+ unsafe { web_css_grouping_rule_removed(self.rule.object().cell(), Rc::as_ptr(&removed_rule).cast()) };
+ Ok(())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_import_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_import_rule.rs
new file mode 100644
index 00000000000..1c620844d0f
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_import_rule.rs
@@ -0,0 +1,208 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSImportRule, https://drafts.csswg.org/cssom/#the-cssimportrule-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;
+
+use super::css_rule::{AnyCSSRule, CSSRule, RuleText, impl_rule_wrappable, selector_list_text, wrap_cpp_cell};
+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};
+
+unsafe extern "C" {
+ fn web_css_import_create(rule: *const c_void, document: *mut c_void) -> *mut c_void;
+ fn web_css_import_set_rule(import: *mut c_void, rule: *mut c_void);
+ fn web_css_import_set_parent_style_sheet(import: *mut c_void, sheet: *mut c_void);
+ fn web_css_import_href(import: *mut c_void) -> usize;
+ fn web_css_import_url_text(import: *mut c_void) -> usize;
+ fn web_css_import_media(import: *mut c_void) -> *mut c_void;
+ fn web_css_import_style_sheet(import: *mut c_void) -> *mut c_void;
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSImportRule {
+ rule: CSSRule,
+ /// The cell that holds the Web::CSS::StyleSheetImport, which loads the sheet.
+ import: CppCell,
+}
+
+impl_rule_wrappable!(CSSImportRule);
+
+impl Inherits<CSSRule> for CSSImportRule {
+ fn parent(&self) -> &CSSRule {
+ &self.rule
+ }
+}
+
+impl CSSImportRule {
+ /// The object of a rule that C++ does not load yet.
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>, document: Option<&CppCell>) -> Ref<Self> {
+ let document = document.map_or(null_mut(), CppCell::as_ptr);
+ // SAFETY: The rule is live, and the cell is that of a live Document, or null.
+ let import = unsafe { web_css_import_create(Rc::as_ptr(&native_rule).cast(), document) };
+ // SAFETY: LibWeb returns a live cell.
+ let import = unsafe { CppCell::from_raw(import) };
+ Self::create_for_import(vm, native_rule, import)
+ }
+
+ /// The object of a rule that the import loads.
+ pub(crate) fn create_for_import(vm: &Vm, native_rule: Rc<NativeRule>, import: CppCell) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ rule: CSSRule::new(native_rule),
+ import,
+ })
+ }
+
+ /// Tells the import of the object that the object is its rule.
+ pub(crate) fn finish(object: Ref<Self>, vm: &Vm) -> AnyCSSRule {
+ let any = AnyCSSRule::CSSImportRule(object);
+ any.set_object(vm, any);
+ // SAFETY: Both cells are live.
+ unsafe { web_css_import_set_rule(object.import.as_ptr(), any.cell()) };
+ any
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ &self.rule
+ }
+
+ pub(crate) fn import_cell(&self) -> *mut c_void {
+ self.import.as_ptr()
+ }
+
+ pub(crate) fn parent_style_sheet_changed(&self, sheet: Option<&CppCell>) {
+ let sheet = sheet.map_or(null_mut(), CppCell::as_ptr);
+ // SAFETY: The cells are live, or the sheet is null.
+ unsafe { web_css_import_set_parent_style_sheet(self.import.as_ptr(), sheet) };
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssimportrule-href
+ pub(crate) fn href(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ // SAFETY: The cell is live.
+ let href = unsafe { web_css_import_href(self.import.as_ptr()) };
+ // SAFETY: LibWeb hands over the string.
+ Ok(unsafe { Utf16String::from_raw_owned(href) })
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssimportrule-media
+ pub(crate) fn media(&self, _: &mut CallContext) -> WebIdlResult<Ref<MediaList>> {
+ // SAFETY: The cell is live.
+ let media = unsafe { web_css_import_media(self.import.as_ptr()) };
+ // SAFETY: LibWeb returns the live cell of a MediaList.
+ Ok(unsafe { cell_from_abi(media) })
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssimportrule-stylesheet
+ pub(crate) fn style_sheet(&self, cx: &mut CallContext) -> WebIdlResult<Option<CppInterface>> {
+ // 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)))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssimportrule-layername
+ pub(crate) fn layer_name(&self, _: &mut CallContext) -> WebIdlResult<Option<Utf16String>> {
+ // The layerName attribute must return the layer name declared in the at-rule itself, or an empty string if the
+ // layer is anonymous, or null if the at-rule does not declare a layer.
+ Ok(self.rule.native_rule().import_layer())
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssimportrule-supportstext
+ pub(crate) fn supports_text(&self, _: &mut CallContext) -> WebIdlResult<Option<Utf16String>> {
+ // The supportsText attribute must return the <supports-condition> declared in the at-rule itself, or null if
+ // the at-rule does not declare a supports condition.
+ Ok(self.rule.native_rule().import_supports_text())
+ }
+
+ // https://drafts.csswg.org/cssom/#serialize-a-css-rule
+ pub(crate) fn serialized(&self, _: &Vm) -> Utf16String {
+ let native_rule = self.rule.native_rule();
+
+ // The result of concatenating the following:
+
+ // 1. The string "@import" followed by a single SPACE (U+0020).
+ let mut text = RuleText::new("@import ");
+
+ // 2. The result of performing serialize a URL on the rule’s location.
+ // SAFETY: The cell is live.
+ let url = unsafe { web_css_import_url_text(self.import.as_ptr()) };
+ // SAFETY: LibWeb hands over the string.
+ text.push(&unsafe { Utf16String::from_raw_owned(url) });
+
+ // AD-HOC: Serialize the rule's layer if it exists.
+ if let Some(layer) = native_rule.import_layer() {
+ if layer.is_empty() {
+ text.push_str(" layer");
+ } else {
+ text.push_str(" layer(");
+ text.push(&layer);
+ text.push_str(")");
+ }
+ }
+
+ // AD-HOC: Serialize the rule's import scope if it exists.
+ if let Some((start, end)) = native_rule.scope_selector_lists() {
+ text.push_str(" scope");
+ if !start.is_null() || !end.is_null() {
+ text.push_str("(");
+ if !start.is_null() {
+ let start_text = selector_list_text(start, None);
+ if end.is_null() {
+ text.push(&start_text);
+ } else {
+ text.push_str("(");
+ text.push(&start_text);
+ text.push_str(")");
+ }
+ }
+ if !end.is_null() {
+ if !start.is_null() {
+ text.push_str(" ");
+ }
+ text.push_str("to (");
+ text.push(&selector_list_text(end, None));
+ text.push_str(")");
+ }
+ text.push_str(")");
+ }
+ }
+
+ // AD-HOC: Serialize the rule's supports condition if it exists.
+ // This isn't currently specified, but major browsers include this in their serialization of import
+ // rules
+ if let Some(supports) = native_rule.import_supports_text() {
+ text.push_str(" supports(");
+ text.push(&supports);
+ text.push_str(")");
+ }
+
+ // 3. If the rule’s associated media list is not empty, a single SPACE (U+0020) followed by the result of
+ // performing serialize a media query list on the media list.
+ let media = native_rule.media_list();
+ if media.length() != 0 {
+ text.push_str(" ");
+ text.push(&Utf16String::from_utf16(&media.media_text()));
+ }
+
+ // 4. The string ";", i.e., SEMICOLON (U+003B).
+ text.push_str(";");
+ text.finish()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_keyframe_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_keyframe_rule.rs
new file mode 100644
index 00000000000..9a668bcc632
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_keyframe_rule.rs
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSKeyframeRule, https://drafts.csswg.org/css-animations/#interface-csskeyframerule
+
+use super::css_rule::CSSRule;
+use super::css_rule::RuleText;
+use super::css_rule::impl_rule_wrappable;
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use libweb_rust::typed_om::serialize_a_number;
+use std::rc::Rc;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSKeyframeRule {
+ rule: CSSRule,
+}
+
+impl_rule_wrappable!(CSSKeyframeRule);
+
+impl Inherits<CSSRule> for CSSKeyframeRule {
+ fn parent(&self) -> &CSSRule {
+ &self.rule
+ }
+}
+
+impl CSSKeyframeRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ rule: CSSRule::new(native_rule),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ &self.rule
+ }
+
+ fn serialized_key_text(&self) -> Utf16String {
+ let mut text = String::new();
+ for (index, key) in self.rule.native_rule().keyframe_keys().iter().enumerate() {
+ if index != 0 {
+ text.push_str(", ");
+ }
+ serialize_a_number(&mut text, *key);
+ text.push('%');
+ }
+ Utf16String::from_utf8(&text)
+ }
+
+ // https://drafts.csswg.org/css-animations/#dom-csskeyframerule-keytext
+ pub(crate) fn key_text(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.serialized_key_text())
+ }
+
+ // https://drafts.csswg.org/css-animations/#dom-csskeyframerule-keytext
+ pub(crate) fn set_key_text(&self, _: &mut CallContext, _: Utf16String) -> WebIdlResult<()> {
+ // FIXME: Parse the value as a keyframe selector and replace the keys of the rule with it.
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/css-animations/#dom-csskeyframerule-style
+ pub(crate) fn style(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(self.rule.style_attribute(cx))
+ }
+
+ pub(crate) fn serialized(&self, vm: &Vm) -> Utf16String {
+ let mut text = RuleText::default();
+ text.push(&self.serialized_key_text());
+ text.push_str(" { ");
+ text.push(&self.rule.serialized_declarations(vm));
+ text.push_str(" }");
+ text.finish()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_keyframes_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_keyframes_rule.rs
new file mode 100644
index 00000000000..ff48c9a802d
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_keyframes_rule.rs
@@ -0,0 +1,212 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSKeyframesRule, https://drafts.csswg.org/css-animations/#interface-csskeyframesrule
+
+use super::css_keyframe_rule::CSSKeyframeRule;
+use super::css_rule::CSSRule;
+use super::css_rule::impl_rule_wrappable;
+use super::css_rule::{AnyCSSRule, RuleText};
+use super::css_rule_list::CSSRuleList;
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use core::ffi::c_void;
+use libjs_rust::api::GcRefCell;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use libweb_rust::cssom::{is_valid_animation_name, serialize_identifier, serialize_string_value};
+use std::rc::Rc;
+
+unsafe extern "C" {
+ fn web_css_keyframes_rule_changed(rule: *mut c_void);
+ fn web_css_keyframes_rule_will_rename(rule: *mut c_void);
+ fn web_css_keyframes_rule_renamed(rule: *mut c_void);
+ fn web_css_parse_keyframe_rule(text: usize) -> *const c_void;
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSKeyframesRule {
+ rule: CSSRule,
+ rules: GcRefCell<Option<Ref<CSSRuleList>>>,
+}
+
+impl_rule_wrappable!(CSSKeyframesRule);
+
+impl Inherits<CSSRule> for CSSKeyframesRule {
+ fn parent(&self) -> &CSSRule {
+ &self.rule
+ }
+}
+
+impl CSSKeyframesRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ rule: CSSRule::new(native_rule),
+ rules: GcRefCell::new(None),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ &self.rule
+ }
+
+ pub(crate) fn existing_css_rules(&self) -> Option<Ref<CSSRuleList>> {
+ *self.rules.borrow()
+ }
+
+ pub(crate) fn child_rules(&self, vm: &Vm) -> Ref<CSSRuleList> {
+ if let Some(rules) = self.existing_css_rules() {
+ return rules;
+ }
+ let native_rules = self
+ .rule
+ .native_rule()
+ .cssom_children()
+ .expect("a @keyframes rule has keyframes");
+ let rules = CSSRuleList::create_for_rule(vm, native_rules, self.rule.object());
+ *self.rules.borrow_mut(vm) = Some(rules);
+ rules
+ }
+
+ fn native_length(&self) -> usize {
+ self.rule
+ .native_rule()
+ .cssom_children()
+ .expect("a @keyframes rule has keyframes")
+ .cssom_length()
+ }
+
+ fn keyframe(&self, vm: &Vm, index: usize) -> Option<Ref<CSSKeyframeRule>> {
+ if index >= self.native_length() {
+ return None;
+ }
+ match self.child_rules(vm).rule_at(vm, index) {
+ AnyCSSRule::CSSKeyframeRule(keyframe) => Some(keyframe),
+ _ => None,
+ }
+ }
+
+ fn keyframes_changed(&self) {
+ if self.rule.parent_sheet().is_some() {
+ // SAFETY: The cell is that of this object, which is live.
+ unsafe { web_css_keyframes_rule_changed(self.rule.object().cell()) };
+ }
+ }
+
+ // https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-name
+ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().keyframes_name())
+ }
+
+ // https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-name
+ pub(crate) fn set_name(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ let native_rule = self.rule.native_rule();
+ if native_rule.keyframes_name() == value {
+ return Ok(());
+ }
+ let cell = self.rule.object().cell();
+ // SAFETY: The cell is that of this object, which is live.
+ unsafe { web_css_keyframes_rule_will_rename(cell) };
+ native_rule.set_keyframes_name(&value.to_utf16());
+ // SAFETY: The cell is that of this object, which is live.
+ unsafe { web_css_keyframes_rule_renamed(cell) };
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-cssrules
+ pub(crate) fn css_rules(&self, cx: &mut CallContext) -> WebIdlResult<Ref<CSSRuleList>> {
+ Ok(self.child_rules(cx.vm()))
+ }
+
+ // https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-length
+ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ Ok(u32::try_from(self.native_length()).expect("a rule has fewer than 2^32 keyframes"))
+ }
+
+ // https://drafts.csswg.org/css-animations/#interface-csskeyframesrule
+ pub(crate) fn item(&self, cx: &mut CallContext, index: u32) -> WebIdlResult<Ref<CSSKeyframeRule>> {
+ Ok(self
+ .keyframe(cx.vm(), index as usize)
+ .expect("the bindings check the index"))
+ }
+
+ // https://drafts.csswg.org/css-animations/#interface-csskeyframesrule-appendrule
+ pub(crate) fn append_rule(&self, _: &mut CallContext, rule: Utf16String) -> WebIdlResult<()> {
+ // The appendRule method appends the passed CSSKeyframeRule at the end of the keyframes rule.
+ // SAFETY: The string is handed over.
+ let parsed_rule = unsafe { web_css_parse_keyframe_rule(rule.into_raw()) };
+ if parsed_rule.is_null() {
+ return Ok(());
+ }
+ // SAFETY: LibWeb hands over a reference to the rule.
+ let parsed_rule = unsafe { Rc::from_raw(parsed_rule.cast::<NativeRule>()) };
+ let children = self
+ .rule
+ .native_rule()
+ .cssom_children()
+ .expect("a @keyframes rule has keyframes");
+ children.cssom_append_rule(parsed_rule);
+ self.keyframes_changed();
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/css-animations-1/#interface-csskeyframesrule-deleterule
+ pub(crate) fn delete_rule(&self, cx: &mut CallContext, select: Utf16String) -> WebIdlResult<()> {
+ // The deleteRule method deletes the last declared CSSKeyframeRule matching the specified keyframe selector. If
+ // no matching rule exists, the method does nothing.
+ let native_rule = self.rule.native_rule();
+ let Some(index) = native_rule.find_keyframe(&select.to_utf16()) else {
+ return Ok(());
+ };
+ if let Some(rules) = self.existing_css_rules() {
+ rules.remove_a_css_rule_without_validation(cx.vm(), index);
+ } else {
+ native_rule
+ .cssom_children()
+ .expect("a @keyframes rule has keyframes")
+ .cssom_remove(index);
+ }
+ self.keyframes_changed();
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/css-animations-1/#interface-csskeyframesrule-findrule
+ pub(crate) fn find_rule(
+ &self,
+ cx: &mut CallContext,
+ select: Utf16String,
+ ) -> WebIdlResult<Option<Ref<CSSKeyframeRule>>> {
+ // The findRule returns the last declared CSSKeyframeRule matching the specified keyframe selector. If no
+ // matching rule exists, the method does nothing.
+ let index = self.rule.native_rule().find_keyframe(&select.to_utf16());
+ Ok(index.and_then(|index| self.keyframe(cx.vm(), index)))
+ }
+
+ pub(crate) fn serialized(&self, vm: &Vm) -> Utf16String {
+ let mut text = RuleText::new("@keyframes ");
+
+ // https://drafts.csswg.org/css-animations-1/#keyframes
+ // When serialized, the value is serialized as an <ident> unless it’s a disallowed keyword, in which case
+ // it’s serialized as a <string>.
+ let name = self.rule.native_rule().keyframes_name();
+ if is_valid_animation_name(&name.to_utf16()) {
+ text.push(&serialize_identifier(&name.to_utf16()));
+ } else {
+ text.push(&serialize_string_value(&name.to_utf16()));
+ }
+
+ text.push_str(" { ");
+ let rules = self.child_rules(vm);
+ for index in 0..rules.native_length() {
+ text.push(&rules.rule_at(vm, index).serialized(vm));
+ text.push_str(" ");
+ }
+ text.push_str("}");
+ text.finish()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_layer_block_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_layer_block_rule.rs
new file mode 100644
index 00000000000..b2a577b182f
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_layer_block_rule.rs
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSLayerBlockRule, https://drafts.csswg.org/css-cascade-5/#the-csslayerblockrule-interface
+
+use super::css_grouping_rule::CSSGroupingRule;
+use super::css_rule::impl_rule_wrappable;
+use super::css_rule::{AnyCSSRule, CSSRule, RuleText};
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use std::rc::Rc;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSLayerBlockRule {
+ grouping_rule: CSSGroupingRule,
+}
+
+impl_rule_wrappable!(CSSLayerBlockRule);
+
+impl Inherits<CSSGroupingRule> for CSSLayerBlockRule {
+ fn parent(&self) -> &CSSGroupingRule {
+ &self.grouping_rule
+ }
+}
+
+impl CSSLayerBlockRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ grouping_rule: CSSGroupingRule::new(native_rule),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ self.grouping_rule.rule()
+ }
+
+ pub(crate) fn grouping_rule(&self) -> &CSSGroupingRule {
+ &self.grouping_rule
+ }
+
+ fn layer_name(&self) -> Utf16String {
+ self.rule().native_rule().layer_names().swap_remove(0)
+ }
+
+ // https://drafts.csswg.org/css-cascade-5/#dom-csslayerblockrule-name
+ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.layer_name())
+ }
+
+ pub(crate) fn serialized(&self, vm: &Vm) -> Utf16String {
+ // AD-HOC: No spec yet, so this is based on the @media serialization algorithm.
+ let mut text = RuleText::new("@layer");
+ let name = self.layer_name();
+ if !name.is_empty() {
+ text.push_str(" ");
+ text.push(&name);
+ }
+ text.push_str(" {\n");
+
+ // AD-HOC: All modern browsers omit the ending newline if there are no CSS rules, so let's do the same.
+ let rules = self.grouping_rule.child_rules(vm);
+ if rules.native_length() == 0 {
+ text.push_str("}");
+ return text.finish();
+ }
+ for index in 0..rules.native_length() {
+ if index != 0 {
+ text.push_str("\n");
+ }
+ text.push_str(" ");
+ text.push(&AnyCSSRule::serialized(rules.rule_at(vm, index), vm));
+ }
+ text.push_str("\n}");
+ text.finish()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_layer_statement_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_layer_statement_rule.rs
new file mode 100644
index 00000000000..d5ba2fbb7a9
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_layer_statement_rule.rs
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSLayerStatementRule, https://drafts.csswg.org/css-cascade-5/#the-csslayerstatementrule-interface
+
+use super::css_rule::CSSRule;
+use super::css_rule::RuleText;
+use super::css_rule::impl_rule_wrappable;
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use std::rc::Rc;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSLayerStatementRule {
+ rule: CSSRule,
+}
+
+impl_rule_wrappable!(CSSLayerStatementRule);
+
+impl Inherits<CSSRule> for CSSLayerStatementRule {
+ fn parent(&self) -> &CSSRule {
+ &self.rule
+ }
+}
+
+impl CSSLayerStatementRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ rule: CSSRule::new(native_rule),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ &self.rule
+ }
+
+ // https://drafts.csswg.org/css-cascade-5/#dom-csslayerstatementrule-namelist
+ pub(crate) fn name_list(&self, _: &mut CallContext) -> WebIdlResult<Vec<Utf16String>> {
+ Ok(self.rule.native_rule().layer_names())
+ }
+
+ pub(crate) fn serialized(&self, _: &Vm) -> Utf16String {
+ // AD-HOC: No spec yet.
+ let mut text = RuleText::new("@layer ");
+ for (index, name) in self.rule.native_rule().layer_names().iter().enumerate() {
+ if index != 0 {
+ text.push_str(", ");
+ }
+ text.push(name);
+ }
+ text.push_str(";");
+ text.finish()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_margin_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_margin_rule.rs
new file mode 100644
index 00000000000..d50b6b944c0
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_margin_rule.rs
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSMarginRule, https://drafts.csswg.org/cssom/#cssmarginrule
+
+use super::css_rule::CSSRule;
+use super::css_rule::RuleText;
+use super::css_rule::impl_rule_wrappable;
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use std::rc::Rc;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSMarginRule {
+ rule: CSSRule,
+}
+
+impl_rule_wrappable!(CSSMarginRule);
+
+impl Inherits<CSSRule> for CSSMarginRule {
+ fn parent(&self) -> &CSSRule {
+ &self.rule
+ }
+}
+
+impl CSSMarginRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ rule: CSSRule::new(native_rule),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ &self.rule
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssmarginrule-name
+ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().at_rule_name())
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssmarginrule-style
+ pub(crate) fn style(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(self.rule.style_attribute(cx))
+ }
+
+ pub(crate) fn serialized(&self, vm: &Vm) -> Utf16String {
+ // AD-HOC: There is currently no spec for serializing CSSMarginRule.
+ let mut text = RuleText::new("@");
+ text.push(&self.rule.native_rule().at_rule_name());
+ text.push_str(" { ");
+ if !self.rule.native_rule().has_no_declarations() {
+ text.push(&self.rule.serialized_declarations(vm));
+ text.push_str(" ");
+ }
+ text.push_str("}");
+ text.finish()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_media_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_media_rule.rs
new file mode 100644
index 00000000000..237a48b069b
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_media_rule.rs
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSMediaRule, https://drafts.csswg.org/cssom/#the-cssmediarule-interface
+
+use super::css_condition_rule::CSSConditionRule;
+use super::css_grouping_rule::CSSGroupingRule;
+use super::css_rule::impl_rule_wrappable;
+use super::css_rule::{CSSRule, RuleText, serialize_block_of_rules};
+use super::media_list::MediaList;
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use libjs_rust::api::GcRefCell;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use std::rc::Rc;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSMediaRule {
+ condition_rule: CSSConditionRule,
+ media: GcRefCell<Option<Ref<MediaList>>>,
+}
+
+impl_rule_wrappable!(CSSMediaRule);
+
+impl Inherits<CSSConditionRule> for CSSMediaRule {
+ fn parent(&self) -> &CSSConditionRule {
+ &self.condition_rule
+ }
+}
+
+impl CSSMediaRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ condition_rule: CSSConditionRule::new(native_rule),
+ media: GcRefCell::new(None),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ self.condition_rule.rule()
+ }
+
+ pub(crate) fn grouping_rule(&self) -> &CSSGroupingRule {
+ self.condition_rule.grouping_rule()
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssmediarule-media
+ pub(crate) fn media(&self, cx: &mut CallContext) -> WebIdlResult<Ref<MediaList>> {
+ if let Some(media) = *self.media.borrow() {
+ return Ok(media);
+ }
+ let vm = cx.vm();
+ let native_media = self.rule().native_rule().media_list();
+ let media = allocate(vm, |defer_gc| MediaList::new(defer_gc, native_media));
+ // SAFETY: The cell is that of this object, which is live.
+ media.set_associated_rule(vm, unsafe { CppCell::from_raw(self.rule().object().cell()) });
+ *self.media.borrow_mut(vm) = Some(media);
+ Ok(media)
+ }
+
+ // https://drafts.csswg.org/css-conditional-5/#dom-cssmediarule-matches
+ pub(crate) fn matches(&self, _: &mut CallContext) -> WebIdlResult<bool> {
+ Ok(self.rule().native_rule().media_list().matches())
+ }
+
+ pub(crate) fn serialized_condition_text(&self) -> Utf16String {
+ Utf16String::from_utf16(&self.rule().native_rule().media_list().media_text())
+ }
+
+ // https://drafts.csswg.org/cssom-1/#serialize-a-css-rule
+ pub(crate) fn serialized(&self, vm: &Vm) -> Utf16String {
+ // The result of concatenating the following:
+ // 1. The string "@media", followed by a single SPACE (U+0020).
+ let mut text = RuleText::new("@media ");
+
+ // 2. The result of performing serialize a media query list on rule’s media query list.
+ text.push(&self.serialized_condition_text());
+ serialize_block_of_rules(text, vm, self.grouping_rule().child_rules(vm))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_namespace_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_namespace_rule.rs
new file mode 100644
index 00000000000..6cada241b72
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_namespace_rule.rs
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSNamespaceRule, https://drafts.csswg.org/cssom/#the-cssnamespacerule-interface
+
+use super::css_rule::CSSRule;
+use super::css_rule::RuleText;
+use super::css_rule::impl_rule_wrappable;
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use libweb_rust::cssom::{serialize_identifier, serialize_string_value};
+use std::rc::Rc;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSNamespaceRule {
+ rule: CSSRule,
+}
+
+impl_rule_wrappable!(CSSNamespaceRule);
+
+impl Inherits<CSSRule> for CSSNamespaceRule {
+ fn parent(&self) -> &CSSRule {
+ &self.rule
+ }
+}
+
+impl CSSNamespaceRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ rule: CSSRule::new(native_rule),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ &self.rule
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssnamespacerule-namespaceuri
+ pub(crate) fn namespace_uri(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().namespace_uri())
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssnamespacerule-prefix
+ pub(crate) fn prefix(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().namespace_prefix())
+ }
+
+ // https://drafts.csswg.org/cssom/#serialize-a-css-rule
+ pub(crate) fn serialized(&self, _: &Vm) -> Utf16String {
+ let native_rule = self.rule.native_rule();
+
+ // The literal string "@namespace", followed by a single SPACE (U+0020),
+ let mut text = RuleText::new("@namespace ");
+
+ // followed by the serialization as an identifier of the prefix attribute (if any),
+ let prefix = native_rule.namespace_prefix();
+ if !prefix.is_empty() {
+ text.push(&serialize_identifier(&prefix.to_utf16()));
+ // followed by a single SPACE (U+0020) if there is a prefix,
+ text.push_str(" ");
+ }
+
+ // followed by the serialization as URL of the namespaceURI attribute,
+ text.push_str("url(");
+ text.push(&serialize_string_value(&native_rule.namespace_uri().to_utf16()));
+ text.push_str(")");
+
+ // followed the character ";" (U+003B).
+ text.push_str(";");
+ text.finish()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_nested_declarations.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_nested_declarations.rs
new file mode 100644
index 00000000000..3c17529bd5f
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_nested_declarations.rs
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSNestedDeclarations, https://drafts.csswg.org/css-nesting-1/#cssnesteddeclarations
+
+use super::css_rule::CSSRule;
+use super::css_rule::impl_rule_wrappable;
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use std::rc::Rc;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSNestedDeclarations {
+ rule: CSSRule,
+}
+
+impl_rule_wrappable!(CSSNestedDeclarations);
+
+impl Inherits<CSSRule> for CSSNestedDeclarations {
+ fn parent(&self) -> &CSSRule {
+ &self.rule
+ }
+}
+
+impl CSSNestedDeclarations {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ rule: CSSRule::new(native_rule),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ &self.rule
+ }
+
+ // https://drafts.csswg.org/css-nesting-1/#dom-cssnesteddeclarations-style
+ pub(crate) fn style(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(self.rule.style_attribute(cx))
+ }
+
+ pub(crate) fn serialized(&self, vm: &Vm) -> Utf16String {
+ // NB: There's no proper spec for this yet, only this note:
+ // "The CSSNestedDeclarations rule serializes as if its declaration block had been serialized directly."
+ // - https://drafts.csswg.org/css-nesting-1/#ref-for-cssnesteddeclarations%E2%91%A1
+ // So, we'll do the simple thing and hope it's good.
+ self.rule.serialized_declarations(vm)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_page_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_page_rule.rs
new file mode 100644
index 00000000000..fed02bfd8ea
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_page_rule.rs
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSPageRule, https://drafts.csswg.org/cssom/#the-csspagerule-interface
+
+use super::css_grouping_rule::CSSGroupingRule;
+use super::css_rule::impl_rule_wrappable;
+use super::css_rule::{CSSRule, RuleText, serialized_rules};
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use std::rc::Rc;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSPageRule {
+ grouping_rule: CSSGroupingRule,
+}
+
+impl_rule_wrappable!(CSSPageRule);
+
+impl Inherits<CSSGroupingRule> for CSSPageRule {
+ fn parent(&self) -> &CSSGroupingRule {
+ &self.grouping_rule
+ }
+}
+
+impl CSSPageRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ grouping_rule: CSSGroupingRule::new(native_rule),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ self.grouping_rule.rule()
+ }
+
+ pub(crate) fn grouping_rule(&self) -> &CSSGroupingRule {
+ &self.grouping_rule
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-csspagerule-selectortext
+ pub(crate) fn selector_text(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule().native_rule().page_selector_text())
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-csspagerule-selectortext
+ pub(crate) fn set_selector_text(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ // On setting the selectorText attribute these steps must be run:
+ // 1. Run the parse a list of CSS page selectors algorithm on the given value.
+ // 2. If the algorithm returns a non-null value replace the associated selector list with the returned value.
+ // 3. Otherwise, if the algorithm returns a null value, do nothing.
+ self.rule().native_rule().set_page_selector_text(&value.to_utf16());
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-csspagerule-style
+ pub(crate) fn style(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(self.rule().style_attribute(cx))
+ }
+
+ // https://drafts.csswg.org/cssom/#ref-for-csspagerule
+ pub(crate) fn serialized(&self, vm: &Vm) -> Utf16String {
+ // AD-HOC: There's no spec for this yet, but Chrome puts declarations before margin rules.
+ let mut text = RuleText::new("@page ");
+ let selector = self.rule().native_rule().page_selector_text();
+ if !selector.is_empty() {
+ text.push(&selector);
+ text.push_str(" ");
+ }
+ text.push_str("{ ");
+ if !self.rule().native_rule().has_no_declarations() {
+ text.push(&self.rule().serialized_declarations(vm));
+ text.push_str(" ");
+ }
+ for rule in serialized_rules(vm, self.grouping_rule.child_rules(vm)) {
+ text.push(&rule);
+ text.push_str(" ");
+ }
+ text.push_str("}");
+ text.finish()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_position_try_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_position_try_rule.rs
new file mode 100644
index 00000000000..bdf5cd228f3
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_position_try_rule.rs
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSPositionTryRule, https://drafts.csswg.org/css-anchor-position-1/#the-csspositiontryrule-interface
+
+use super::css_rule::CSSRule;
+use super::css_rule::RuleText;
+use super::css_rule::impl_rule_wrappable;
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use libweb_rust::cssom::serialize_identifier;
+use std::rc::Rc;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSPositionTryRule {
+ rule: CSSRule,
+}
+
+impl_rule_wrappable!(CSSPositionTryRule);
+
+impl Inherits<CSSRule> for CSSPositionTryRule {
+ fn parent(&self) -> &CSSRule {
+ &self.rule
+ }
+}
+
+impl CSSPositionTryRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ rule: CSSRule::new(native_rule),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ &self.rule
+ }
+
+ fn serialized_name(&self) -> Utf16String {
+ // Its name attribute represents the name declared in the rule's prelude.
+ // INTEROP: Other browsers return the name serialized as an identifier.
+ serialize_identifier(&self.rule.native_rule().at_rule_name().to_utf16())
+ }
+
+ // https://drafts.csswg.org/css-anchor-position-1/#dom-csspositiontryrule-name
+ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.serialized_name())
+ }
+
+ // https://drafts.csswg.org/css-anchor-position-1/#dom-csspositiontryrule-style
+ pub(crate) fn style(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ // On getting, it must return a CSSPositionTryDescriptors object for the @position-try at-rule, with the
+ // following properties:
+ // computed flag: Unset
+ // readonly flag: Unset
+ // declarations: The declared descriptors in the rule, in specified order.
+ // parent CSS rule: The context object
+ // owner node: Null
+ Ok(self.rule.style_attribute(cx))
+ }
+
+ pub(crate) fn serialized(&self, vm: &Vm) -> Utf16String {
+ // AD-HOC: There is no spec for serializing CSSPositionTryRule. This matches other browsers.
+ let mut text = RuleText::new("@position-try ");
+ text.push(&self.serialized_name());
+ text.push_str(" { ");
+ if !self.rule.native_rule().has_no_declarations() {
+ text.push(&self.rule.serialized_declarations(vm));
+ text.push_str(" ");
+ }
+ text.push_str("}");
+ text.finish()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_property_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_property_rule.rs
new file mode 100644
index 00000000000..cf8ec8ca119
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_property_rule.rs
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSPropertyRule, https://drafts.css-houdini.org/css-properties-values-api/#the-css-property-rule-interface
+
+use super::css_rule::CSSRule;
+use super::css_rule::RuleText;
+use super::css_rule::impl_rule_wrappable;
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use libweb_rust::cssom::{serialize_identifier, serialize_string_value};
+use std::rc::Rc;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSPropertyRule {
+ rule: CSSRule,
+}
+
+impl_rule_wrappable!(CSSPropertyRule);
+
+impl Inherits<CSSRule> for CSSPropertyRule {
+ fn parent(&self) -> &CSSRule {
+ &self.rule
+ }
+}
+
+impl CSSPropertyRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ rule: CSSRule::new(native_rule),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ &self.rule
+ }
+
+ // https://drafts.css-houdini.org/css-properties-values-api/#dom-csspropertyrule-name
+ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().property_name())
+ }
+
+ // https://drafts.css-houdini.org/css-properties-values-api/#dom-csspropertyrule-syntax
+ pub(crate) fn syntax(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.rule.native_rule().property_syntax())
+ }
+
+ // https://drafts.css-houdini.org/css-properties-values-api/#dom-csspropertyrule-inherits
+ pub(crate) fn inherits(&self, _: &mut CallContext) -> WebIdlResult<bool> {
+ Ok(self.rule.native_rule().property_inherits())
+ }
+
+ // https://drafts.css-houdini.org/css-properties-values-api/#dom-csspropertyrule-initialvalue
+ pub(crate) fn initial_value(&self, _: &mut CallContext) -> WebIdlResult<Option<Utf16String>> {
+ Ok(self.rule.native_rule().property_initial_value())
+ }
+
+ // https://drafts.css-houdini.org/css-properties-values-api/#the-css-property-rule-interface
+ pub(crate) fn serialized(&self, _: &Vm) -> Utf16String {
+ let native_rule = self.rule.native_rule();
+
+ // To serialize a CSSPropertyRule, return the concatenation of the following:
+
+ // 1. The string "@property" followed by a single SPACE (U+0020).
+ // 2. The result of performing serialize an identifier on the rule’s name, followed by a single SPACE (U+0020).
+ let mut text = RuleText::new("@property ");
+ text.push(&serialize_identifier(&native_rule.property_name().to_utf16()));
+ text.push_str(" ");
+
+ // 3. The string "{ ", i.e., a single LEFT CURLY BRACKET (U+007B), followed by a SPACE (U+0020).
+ text.push_str("{ ");
+
+ // 4. The string "syntax:", followed by a single SPACE (U+0020).
+ // 5. The result of performing serialize a string on the rule’s syntax, followed by a single SEMICOLON (U+003B),
+ // followed by a SPACE (U+0020).
+ text.push_str("syntax: ");
+ text.push(&serialize_string_value(&native_rule.property_syntax().to_utf16()));
+ text.push_str("; ");
+
+ // 6. The string "inherits:", followed by a single SPACE (U+0020).
+ // 7. For the rule’s inherits attribute, one of the following depending on the attribute’s value:
+ // true: The string "true" followed by a single SEMICOLON (U+003B), followed by a SPACE (U+0020).
+ // false: The string "false" followed by a single SEMICOLON (U+003B), followed by a SPACE (U+0020).
+ text.push_str(if native_rule.property_inherits() {
+ "inherits: true; "
+ } else {
+ "inherits: false; "
+ });
+
+ // 8. If the rule’s initial-value is present, follow these substeps:
+ if let Some(initial_value) = native_rule.property_initial_value() {
+ // 1. The string "initial-value:".
+ // 2. The result of performing serialize a CSS value in the rule’s initial-value followed by a single
+ // SEMICOLON (U+003B), followed by a SPACE (U+0020).
+ text.push_str("initial-value: ");
+ text.push(&initial_value);
+ text.push_str("; ");
+ }
+
+ // 9. A single RIGHT CURLY BRACKET (U+007D).
+ text.push_str("}");
+ text.finish()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs
new file mode 100644
index 00000000000..ccb24c7feeb
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs
@@ -0,0 +1,438 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSRule, https://drafts.csswg.org/cssom/#the-cssrule-interface
+
+use core::ffi::c_void;
+use core::ops::Deref;
+use core::ptr::{NonNull, null_mut};
+use std::rc::Rc;
+
+use ak::Utf16String;
+use libjs_rust::api::{Gc, GcRefCell, Object, ThrowCompletionOr, Trace, Value, Vm};
+use libweb_rust::{NativeRule, NativeRuleList, NativeRuleType};
+
+use super::css_condition_rule::CSSConditionRule;
+use super::css_container_rule::CSSContainerRule;
+use super::css_counter_style_rule::CSSCounterStyleRule;
+use super::css_font_face_rule::CSSFontFaceRule;
+use super::css_font_feature_values_rule::CSSFontFeatureValuesRule;
+use super::css_function_declarations::CSSFunctionDeclarations;
+use super::css_function_rule::CSSFunctionRule;
+use super::css_grouping_rule::CSSGroupingRule;
+use super::css_import_rule::CSSImportRule;
+use super::css_keyframe_rule::CSSKeyframeRule;
+use super::css_keyframes_rule::CSSKeyframesRule;
+use super::css_layer_block_rule::CSSLayerBlockRule;
+use super::css_layer_statement_rule::CSSLayerStatementRule;
+use super::css_margin_rule::CSSMarginRule;
+use super::css_media_rule::CSSMediaRule;
+use super::css_namespace_rule::CSSNamespaceRule;
+use super::css_nested_declarations::CSSNestedDeclarations;
+use super::css_page_rule::CSSPageRule;
+use super::css_position_try_rule::CSSPositionTryRule;
+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_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::{CallContext, WebIdlResult};
+
+unsafe extern "C" {
+ fn web_css_wrap_object(realm: *mut c_void, cell: *mut c_void) -> *mut c_void;
+ fn web_css_rule_create_declarations(rule: *mut c_void) -> *mut c_void;
+ fn web_css_declarations_serialized(declarations: *mut c_void) -> usize;
+ fn web_css_style_sheet_native_rules(sheet: *mut c_void) -> *const c_void;
+ fn web_css_selector_list_text(selectors: *const c_void, sheet: *mut c_void) -> usize;
+}
+
+/// The wrapper of the object of an interface implemented in C++ in the world of the call.
+pub(crate) fn wrap_cpp_cell(cx: &CallContext, cell: &CppCell) -> CppInterface {
+ // SAFETY: The realm is live, and the cell is that of an object of an interface implemented in C++.
+ let wrapper = unsafe { web_css_wrap_object(cx.realm().as_ptr().cast(), cell.as_ptr()) };
+ let wrapper = NonNull::new(wrapper.cast::<Object>()).expect("LibWeb returns the wrapper of the object");
+ // SAFETY: LibWeb returns a live wrapper of the object.
+ unsafe { CppInterface::from_wrapper(Gc::from_non_null(wrapper)) }
+}
+
+/// The text of the selector list that the pointer points to, which names the namespaces of the sheet.
+pub(crate) fn selector_list_text(selectors: *const c_void, sheet: Option<&CppCell>) -> Utf16String {
+ let sheet = sheet.map_or(null_mut(), CppCell::as_ptr);
+ // SAFETY: The caller passes a live list, and the sheet is the live cell of a CSSStyleSheet, or null.
+ let text = unsafe { web_css_selector_list_text(selectors, sheet) };
+ // SAFETY: LibWeb hands over the string.
+ unsafe { Utf16String::from_raw_owned(text) }
+}
+
+/// The native rules of the sheet, whose cell is that of a CSSStyleSheet.
+pub(crate) fn native_rules_of_sheet(sheet: &CppCell) -> Rc<NativeRuleList> {
+ // SAFETY: The cell is that of a live CSSStyleSheet.
+ let rules = unsafe { web_css_style_sheet_native_rules(sheet.as_ptr()) };
+ // SAFETY: LibWeb returns the live list of the sheet.
+ unsafe { NativeRuleList::retained_from_raw(rules.cast()) }
+}
+
+/// What an interface that inherits from CSSRule says about the memory of its objects outside the heap, which is that
+/// of the native rule.
+macro_rules! impl_rule_wrappable {
+ ($type:ty) => {
+ impl crate::bindings::interface::Wrappable for $type {
+ const OWNS_EXTERNAL_MEMORY: bool = true;
+
+ fn external_memory_size(&self) -> usize {
+ self.rule().native_rule().cssom_external_memory_size()
+ }
+ }
+ };
+}
+pub(crate) use impl_rule_wrappable;
+
+/// A rule's part of every rule, which the attributes of CSSRule run on.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSRule {
+ /// The rule of the sheet that the object represents.
+ #[gc(untraced)]
+ native_rule: Rc<NativeRule>,
+ /// The object that this is the part of, which the steps that differ between the interfaces run on.
+ object: GcRefCell<Option<AnyCSSRule>>,
+ /// https://drafts.csswg.org/cssom/#concept-css-rule-parent-css-rule
+ parent_rule: GcRefCell<Option<AnyCSSRule>>,
+ /// https://drafts.csswg.org/cssom/#concept-css-rule-parent-css-style-sheet, the cell of a CSSStyleSheet.
+ parent_style_sheet: GcRefCell<Option<CppCell>>,
+ /// The cell of the CSSStyleDeclaration of the declarations of the rule, once it is asked for.
+ declarations: GcRefCell<Option<CppCell>>,
+}
+
+impl Wrappable for CSSRule {}
+
+impl CSSRule {
+ pub(crate) fn new(native_rule: Rc<NativeRule>) -> Self {
+ Self {
+ native_rule,
+ object: GcRefCell::new(None),
+ parent_rule: GcRefCell::new(None),
+ parent_style_sheet: GcRefCell::new(None),
+ declarations: GcRefCell::new(None),
+ }
+ }
+
+ pub(crate) fn native_rule(&self) -> &Rc<NativeRule> {
+ &self.native_rule
+ }
+
+ pub(crate) fn set_object(&self, vm: &Vm, object: AnyCSSRule) {
+ *self.object.borrow_mut(vm) = Some(object);
+ }
+
+ pub(crate) fn object(&self) -> AnyCSSRule {
+ self.object.borrow().expect("an object knows what it is")
+ }
+
+ pub(crate) fn parent_rule_object(&self) -> Option<AnyCSSRule> {
+ *self.parent_rule.borrow()
+ }
+
+ pub(crate) fn parent_sheet(&self) -> Option<CppCell> {
+ self.parent_style_sheet.borrow().clone()
+ }
+
+ pub(crate) fn store_parent_rule(&self, vm: &Vm, parent_rule: Option<AnyCSSRule>) {
+ *self.parent_rule.borrow_mut(vm) = parent_rule;
+ }
+
+ pub(crate) fn store_parent_style_sheet(&self, vm: &Vm, parent_style_sheet: Option<CppCell>) {
+ *self.parent_style_sheet.borrow_mut(vm) = parent_style_sheet;
+ }
+
+ /// The CSSStyleDeclaration of the declarations of the rule, which the first call creates.
+ pub(crate) fn declarations(&self, vm: &Vm) -> CppCell {
+ if let Some(declarations) = self.declarations.borrow().as_ref() {
+ return declarations.clone();
+ }
+ // SAFETY: The cell is that of this object, which is live.
+ let declarations = unsafe { web_css_rule_create_declarations(self.object().cell()) };
+ // SAFETY: LibWeb returns a live cell.
+ let declarations = unsafe { CppCell::from_raw(declarations) };
+ *self.declarations.borrow_mut(vm) = Some(declarations.clone());
+ declarations
+ }
+
+ /// The text of the declarations of the rule, which is what the CSSStyleDeclaration of the rule serializes to.
+ pub(crate) fn serialized_declarations(&self, vm: &Vm) -> Utf16String {
+ let declarations = self.declarations(vm);
+ // SAFETY: The cell is that of a live CSSStyleDeclaration.
+ let text = unsafe { web_css_declarations_serialized(declarations.as_ptr()) };
+ // SAFETY: LibWeb hands over the string.
+ unsafe { Utf16String::from_raw_owned(text) }
+ }
+
+ /// The object that the `style` attribute of the rule returns.
+ pub(crate) fn style_attribute(&self, cx: &CallContext) -> CppInterface {
+ wrap_cpp_cell(cx, &self.declarations(cx.vm()))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssrule-csstext
+ pub(crate) fn css_text(&self, cx: &mut CallContext) -> WebIdlResult<Utf16String> {
+ // The cssText attribute must return a serialization of the CSS rule.
+ Ok(self.object().serialized(cx.vm()))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssrule-csstext
+ pub(crate) fn set_css_text(&self, _: &mut CallContext, _: Utf16String) -> WebIdlResult<()> {
+ // On setting the cssText attribute must do nothing.
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssrule-parentrule
+ pub(crate) fn parent_rule(&self, _: &mut CallContext) -> WebIdlResult<Option<AnyCSSRule>> {
+ Ok(self.parent_rule_object())
+ }
+
+ // 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)))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssrule-type
+ pub(crate) fn type_for_bindings(&self, _: &mut CallContext) -> WebIdlResult<u16> {
+ // NOTE: Types that aren't defined in the spec must return 0.
+ // To do this, we arbitrarily make non-spec ones start at 100.
+ let rule_type = self.native_rule.cssom_type() as u16;
+ Ok(if rule_type >= 100 { 0 } else { rule_type })
+ }
+}
+
+/// The object of a CSSRule, of an interface that inherits from it.
+#[derive(Clone, Copy, Trace)]
+#[gc(crate = libjs_rust)]
+#[expect(clippy::enum_variant_names, reason = "the variants are named after the interfaces")]
+#[expect(
+ dead_code,
+ reason = "the bindings match the variants of interfaces that only others inherit from"
+)]
+pub(crate) enum AnyCSSRule {
+ CSSRule(Ref<CSSRule>),
+ CSSConditionRule(Ref<CSSConditionRule>),
+ CSSContainerRule(Ref<CSSContainerRule>),
+ CSSCounterStyleRule(Ref<CSSCounterStyleRule>),
+ CSSFontFaceRule(Ref<CSSFontFaceRule>),
+ CSSFontFeatureValuesRule(Ref<CSSFontFeatureValuesRule>),
+ CSSFunctionDeclarations(Ref<CSSFunctionDeclarations>),
+ CSSFunctionRule(Ref<CSSFunctionRule>),
+ CSSGroupingRule(Ref<CSSGroupingRule>),
+ CSSImportRule(Ref<CSSImportRule>),
+ CSSKeyframeRule(Ref<CSSKeyframeRule>),
+ CSSKeyframesRule(Ref<CSSKeyframesRule>),
+ CSSLayerBlockRule(Ref<CSSLayerBlockRule>),
+ CSSLayerStatementRule(Ref<CSSLayerStatementRule>),
+ CSSMarginRule(Ref<CSSMarginRule>),
+ CSSMediaRule(Ref<CSSMediaRule>),
+ CSSNamespaceRule(Ref<CSSNamespaceRule>),
+ CSSNestedDeclarations(Ref<CSSNestedDeclarations>),
+ CSSPageRule(Ref<CSSPageRule>),
+ CSSPositionTryRule(Ref<CSSPositionTryRule>),
+ CSSPropertyRule(Ref<CSSPropertyRule>),
+ CSSScopeRule(Ref<CSSScopeRule>),
+ CSSStyleRule(Ref<CSSStyleRule>),
+ CSSSupportsRule(Ref<CSSSupportsRule>),
+}
+
+/// Runs the expression on the object of every interface that has objects of its own.
+macro_rules! for_each_rule {
+ ($any:expr, $object:ident => $expression:expr) => {
+ match $any {
+ AnyCSSRule::CSSContainerRule($object) => $expression,
+ AnyCSSRule::CSSCounterStyleRule($object) => $expression,
+ AnyCSSRule::CSSFontFaceRule($object) => $expression,
+ AnyCSSRule::CSSFontFeatureValuesRule($object) => $expression,
+ AnyCSSRule::CSSFunctionDeclarations($object) => $expression,
+ AnyCSSRule::CSSFunctionRule($object) => $expression,
+ AnyCSSRule::CSSImportRule($object) => $expression,
+ AnyCSSRule::CSSKeyframeRule($object) => $expression,
+ AnyCSSRule::CSSKeyframesRule($object) => $expression,
+ AnyCSSRule::CSSLayerBlockRule($object) => $expression,
+ AnyCSSRule::CSSLayerStatementRule($object) => $expression,
+ AnyCSSRule::CSSMarginRule($object) => $expression,
+ AnyCSSRule::CSSMediaRule($object) => $expression,
+ AnyCSSRule::CSSNamespaceRule($object) => $expression,
+ AnyCSSRule::CSSNestedDeclarations($object) => $expression,
+ AnyCSSRule::CSSPageRule($object) => $expression,
+ AnyCSSRule::CSSPositionTryRule($object) => $expression,
+ AnyCSSRule::CSSPropertyRule($object) => $expression,
+ AnyCSSRule::CSSScopeRule($object) => $expression,
+ AnyCSSRule::CSSStyleRule($object) => $expression,
+ AnyCSSRule::CSSSupportsRule($object) => $expression,
+ AnyCSSRule::CSSRule(_) | AnyCSSRule::CSSGroupingRule(_) | AnyCSSRule::CSSConditionRule(_) => {
+ unreachable!("nothing creates an object of an interface that only others inherit from")
+ }
+ }
+ };
+}
+
+impl Deref for AnyCSSRule {
+ type Target = CSSRule;
+
+ fn deref(&self) -> &CSSRule {
+ for_each_rule!(self, object => object.rule())
+ }
+}
+
+impl ToJs for AnyCSSRule {
+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {
+ Ok(Value::from_object(for_each_rule!(self, object => wrap(cx, object))))
+ }
+}
+
+impl AnyCSSRule {
+ /// The object for a rule of a sheet, which `document` loads what it imports for.
+ pub(crate) fn create(vm: &Vm, rule: Rc<NativeRule>, document: Option<&CppCell>) -> Self {
+ let object = match rule.cssom_type() {
+ NativeRuleType::Style => Self::CSSStyleRule(CSSStyleRule::create(vm, rule)),
+ NativeRuleType::Import => Self::CSSImportRule(CSSImportRule::create(vm, rule, document)),
+ NativeRuleType::Media => Self::CSSMediaRule(CSSMediaRule::create(vm, rule)),
+ NativeRuleType::FontFace => Self::CSSFontFaceRule(CSSFontFaceRule::create(vm, rule)),
+ NativeRuleType::Page => Self::CSSPageRule(CSSPageRule::create(vm, rule)),
+ NativeRuleType::Keyframes => Self::CSSKeyframesRule(CSSKeyframesRule::create(vm, rule)),
+ NativeRuleType::Keyframe => Self::CSSKeyframeRule(CSSKeyframeRule::create(vm, rule)),
+ NativeRuleType::Margin => Self::CSSMarginRule(CSSMarginRule::create(vm, rule)),
+ NativeRuleType::Namespace => Self::CSSNamespaceRule(CSSNamespaceRule::create(vm, rule)),
+ NativeRuleType::CounterStyle => Self::CSSCounterStyleRule(CSSCounterStyleRule::create(vm, rule)),
+ NativeRuleType::Supports => Self::CSSSupportsRule(CSSSupportsRule::create(vm, rule)),
+ NativeRuleType::FontFeatureValues => {
+ Self::CSSFontFeatureValuesRule(CSSFontFeatureValuesRule::create(vm, rule))
+ }
+ NativeRuleType::LayerBlock => Self::CSSLayerBlockRule(CSSLayerBlockRule::create(vm, rule)),
+ NativeRuleType::LayerStatement => Self::CSSLayerStatementRule(CSSLayerStatementRule::create(vm, rule)),
+ NativeRuleType::NestedDeclarations => Self::CSSNestedDeclarations(CSSNestedDeclarations::create(vm, rule)),
+ NativeRuleType::Property => Self::CSSPropertyRule(CSSPropertyRule::create(vm, rule)),
+ NativeRuleType::Function => Self::CSSFunctionRule(CSSFunctionRule::create(vm, rule)),
+ NativeRuleType::FunctionDeclarations => {
+ Self::CSSFunctionDeclarations(CSSFunctionDeclarations::create(vm, rule))
+ }
+ NativeRuleType::Container => Self::CSSContainerRule(CSSContainerRule::create(vm, rule)),
+ NativeRuleType::Scope => Self::CSSScopeRule(CSSScopeRule::create(vm, rule)),
+ NativeRuleType::PositionTry => Self::CSSPositionTryRule(CSSPositionTryRule::create(vm, rule)),
+ };
+ if let Self::CSSImportRule(import) = object {
+ return CSSImportRule::finish(import, vm);
+ }
+ object.set_object(vm, object);
+ object
+ }
+
+ /// The cell of the object, which C++ names through the handles of the rules.
+ pub(crate) fn cell(self) -> *mut c_void {
+ for_each_rule!(self, object => cell_into_abi(object))
+ }
+
+ /// The object as a rule with child rules that it manages itself, if it is one.
+ pub(crate) fn grouping_rule(&self) -> Option<&CSSGroupingRule> {
+ match self {
+ Self::CSSContainerRule(object) => Some(object.grouping_rule()),
+ Self::CSSFunctionRule(object) => Some(object.grouping_rule()),
+ Self::CSSLayerBlockRule(object) => Some(object.grouping_rule()),
+ Self::CSSMediaRule(object) => Some(object.grouping_rule()),
+ Self::CSSPageRule(object) => Some(object.grouping_rule()),
+ Self::CSSScopeRule(object) => Some(object.grouping_rule()),
+ Self::CSSStyleRule(object) => Some(object.grouping_rule()),
+ Self::CSSSupportsRule(object) => Some(object.grouping_rule()),
+ _ => None,
+ }
+ }
+
+ /// The list of child rules of the object, if it has made one.
+ pub(crate) fn existing_child_rules(&self) -> Option<Ref<CSSRuleList>> {
+ if let Self::CSSKeyframesRule(object) = self {
+ return object.existing_css_rules();
+ }
+ self.grouping_rule().and_then(CSSGroupingRule::existing_css_rules)
+ }
+
+ /// The list of child rules of the object, which the first call makes.
+ pub(crate) fn child_rules(self, vm: &Vm) -> Option<Ref<CSSRuleList>> {
+ if let Self::CSSKeyframesRule(object) = self {
+ return Some(object.child_rules(vm));
+ }
+ self.grouping_rule().map(|rule| rule.child_rules(vm))
+ }
+
+ /// https://drafts.csswg.org/cssom/#serialize-a-css-rule
+ pub(crate) fn serialized(self, vm: &Vm) -> Utf16String {
+ for_each_rule!(self, object => object.serialized(vm))
+ }
+
+ pub(crate) fn set_parent_rule(self, vm: &Vm, parent_rule: Option<Self>) {
+ self.store_parent_rule(vm, parent_rule);
+ self.set_parent_style_sheet(vm, parent_rule.and_then(|parent_rule| parent_rule.parent_sheet()));
+ }
+
+ pub(crate) fn set_parent_style_sheet(self, vm: &Vm, sheet: Option<CppCell>) {
+ self.store_parent_style_sheet(vm, sheet.clone());
+ if let Self::CSSImportRule(object) = self {
+ object.parent_style_sheet_changed(sheet.as_ref());
+ }
+ if let Some(rules) = self.existing_child_rules() {
+ rules.set_parent_style_sheet(vm, sheet);
+ }
+ }
+}
+
+/// The text of each of the rules of the list, without the empty ones.
+pub(crate) fn serialized_rules(vm: &Vm, rules: Ref<CSSRuleList>) -> Vec<Utf16String> {
+ (0..rules.native_length())
+ .map(|index| rules.rule_at(vm, index).serialized(vm))
+ .filter(|text| !text.is_empty())
+ .collect()
+}
+
+/// A string that grows by what the rules serialize to.
+#[derive(Default)]
+pub(crate) struct RuleText(Vec<u16>);
+
+impl RuleText {
+ pub(crate) fn new(text: &str) -> Self {
+ let mut result = Self::default();
+ result.push_str(text);
+ result
+ }
+
+ pub(crate) fn push_str(&mut self, text: &str) {
+ self.0.extend(text.encode_utf16());
+ }
+
+ pub(crate) fn push(&mut self, text: &Utf16String) {
+ self.0.extend_from_slice(&text.to_utf16());
+ }
+
+ pub(crate) fn finish(self) -> Utf16String {
+ Utf16String::from_utf16(&self.0)
+ }
+}
+
+/// `@<at-rule> {`, each rule on a line of its own indented by two spaces, and `}`, as @media, @scope and @container
+/// serialize, https://drafts.csswg.org/cssom/#serialize-a-css-rule
+pub(crate) fn serialize_block_of_rules(mut text: RuleText, vm: &Vm, rules: Ref<CSSRuleList>) -> Utf16String {
+ // 3. A single SPACE (U+0020), followed by the string "{", i.e., LEFT CURLY BRACKET (U+007B), followed by a newline.
+ text.push_str(" {\n");
+
+ // 4. The result of performing serialize a CSS rule on each rule in the rule’s cssRules list,
+ // filtering out empty strings, indenting each item with two spaces, all joined with newline.
+ for rule in serialized_rules(vm, rules) {
+ text.push_str(" ");
+ text.push(&rule);
+ text.push_str("\n");
+ }
+
+ // 5. A newline, followed by the string "}", i.e., RIGHT CURLY BRACKET (U+007D)
+ // AD-HOC: All modern browsers omit the ending newline if there are no CSS rules, so let's do the same.
+ // If there are rules, the required newline is appended in the loop above.
+ text.push_str("}");
+ text.finish()
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_rule_list.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_rule_list.rs
new file mode 100644
index 00000000000..7345c68e87a
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_rule_list.rs
@@ -0,0 +1,202 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSRuleList, https://drafts.csswg.org/cssom/#the-cssrulelist-interface
+
+use core::ffi::c_void;
+use core::ptr::null_mut;
+use std::collections::HashMap;
+use std::rc::Rc;
+
+use libjs_rust::api::{DeferGc, GcRefCell, MarkedVec, Trace, Visitor, Vm};
+use libweb_rust::NativeRuleList;
+
+use super::css_rule::AnyCSSRule;
+use super::exports::rule_from_abi;
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+
+unsafe extern "C" {
+ fn web_css_style_sheet_import_rule(sheet: *mut c_void, identity: u64) -> *mut c_void;
+ fn web_css_style_sheet_disconnect_font_faces(sheet: *mut c_void, rule: *const c_void);
+ fn web_css_style_sheet_rules_changed(sheet: *mut c_void);
+}
+
+/// The objects of the rules of a list that have one, by the identity of the rule.
+#[derive(Default)]
+struct RuleObjects(HashMap<u64, AnyCSSRule>);
+
+// SAFETY: Forwards to every object.
+unsafe impl Trace for RuleObjects {
+ fn trace(&self, visitor: &mut Visitor) {
+ for object in self.0.values() {
+ object.trace(visitor);
+ }
+ }
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSRuleList {
+ #[gc(untraced)]
+ rules: Rc<NativeRuleList>,
+ objects: GcRefCell<RuleObjects>,
+ owner_rule: GcRefCell<Option<AnyCSSRule>>,
+ /// The cell of the CSSStyleSheet.
+ parent_style_sheet: GcRefCell<Option<CppCell>>,
+ /// The cell of the Document that the @import rules of the list load for.
+ document: GcRefCell<Option<CppCell>>,
+}
+
+impl Wrappable for CSSRuleList {
+ const OWNS_EXTERNAL_MEMORY: bool = true;
+
+ fn external_memory_size(&self) -> usize {
+ self.rules.cssom_external_memory_size()
+ }
+}
+
+impl CSSRuleList {
+ pub(crate) fn new(_: &DeferGc<'_>, rules: Rc<NativeRuleList>, document: Option<CppCell>) -> Self {
+ Self {
+ rules,
+ objects: GcRefCell::new(RuleObjects::default()),
+ owner_rule: GcRefCell::new(None),
+ parent_style_sheet: GcRefCell::new(None),
+ document: GcRefCell::new(document),
+ }
+ }
+
+ /// The list of the child rules of `owner`.
+ pub(crate) fn create_for_rule(vm: &Vm, rules: Rc<NativeRuleList>, owner: AnyCSSRule) -> Ref<Self> {
+ let list = allocate(vm, |defer_gc| Self::new(defer_gc, rules, None));
+ *list.owner_rule.borrow_mut(vm) = Some(owner);
+ *list.parent_style_sheet.borrow_mut(vm) = owner.parent_sheet();
+ list
+ }
+
+ pub(crate) fn native_rules(&self) -> &Rc<NativeRuleList> {
+ &self.rules
+ }
+
+ pub(crate) fn native_length(&self) -> usize {
+ self.rules.cssom_length()
+ }
+
+ pub(crate) fn existing_object(&self, identity: u64) -> Option<AnyCSSRule> {
+ self.objects.borrow().0.get(&identity).copied()
+ }
+
+ /// The object of the rule at the index, which the first call creates.
+ pub(crate) fn rule_at(&self, vm: &Vm, index: usize) -> AnyCSSRule {
+ let identity = self.rules.cssom_identity_at(index);
+ if let Some(object) = self.existing_object(identity) {
+ return object;
+ }
+
+ let sheet = self.parent_style_sheet.borrow().clone();
+ // SAFETY: The cell is that of a live CSSStyleSheet.
+ let import = sheet.as_ref().map_or(null_mut(), |sheet| unsafe {
+ web_css_style_sheet_import_rule(sheet.as_ptr(), identity)
+ });
+ let object = if import.is_null() {
+ AnyCSSRule::create(vm, self.rules.cssom_rule_at(index), self.document.borrow().as_ref())
+ } else {
+ // SAFETY: LibWeb returns the live cell of the CSSImportRule of the rule.
+ unsafe { rule_from_abi(import) }
+ };
+ self.objects.borrow_mut(vm).0.insert(identity, object);
+ let owner = *self.owner_rule.borrow();
+ if owner.is_some() {
+ object.set_parent_rule(vm, owner);
+ } else {
+ object.set_parent_style_sheet(vm, sheet);
+ }
+ object
+ }
+
+ fn rule_objects<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, AnyCSSRule> {
+ let objects = MarkedVec::new(vm);
+ for object in self.objects.borrow().0.values() {
+ objects.push(*object);
+ }
+ objects
+ }
+
+ pub(crate) fn set_parent_style_sheet(&self, vm: &Vm, sheet: Option<CppCell>) {
+ *self.parent_style_sheet.borrow_mut(vm) = sheet.clone();
+ for object in self.rule_objects(vm).values().iter() {
+ object.set_parent_style_sheet(vm, sheet.clone());
+ }
+ }
+
+ /// Replaces the rules of the list with those of the other list, whose objects are new.
+ pub(crate) fn set_rules(&self, vm: &Vm, rules: &NativeRuleList, document: Option<CppCell>) {
+ for object in self.rule_objects(vm).values().iter() {
+ object.set_parent_style_sheet(vm, None);
+ }
+ self.rules.cssom_replace(rules);
+ self.objects.borrow_mut(vm).0.clear();
+ *self.document.borrow_mut(vm) = document;
+ }
+
+ /// What a change of the rules of a sheet means for the sheet: only the list of the sheet itself has no owner rule.
+ fn notify_change(&self) {
+ if self.owner_rule.borrow().is_some() {
+ return;
+ }
+ if let Some(sheet) = self.parent_style_sheet.borrow().as_ref() {
+ // SAFETY: The cell is that of a live CSSStyleSheet.
+ unsafe { web_css_style_sheet_rules_changed(sheet.as_ptr()) };
+ }
+ }
+
+ // https://drafts.csswg.org/cssom/#remove-a-css-rule
+ pub(crate) fn remove_a_css_rule_without_validation(&self, vm: &Vm, index: usize) {
+ assert!(index < self.native_length(), "the caller validated the index");
+
+ let old_rule = self.rules.cssom_rule_at(index);
+ let identity = old_rule.cssom_identity();
+ let old_object = self.existing_object(identity);
+
+ // https://drafts.csswg.org/css-font-loading/#font-face-css-connection
+ // If a @font-face rule is removed from the document, its corresponding FontFace object is no longer
+ // CSS-connected. The connection is not restorable by any means (but adding the @font-face back to the
+ // stylesheet will create a brand new FontFace object which is CSS-connected).
+ if let Some(sheet) = self.parent_style_sheet.borrow().as_ref() {
+ // SAFETY: The cell is that of a live CSSStyleSheet, and the rule is live.
+ unsafe { web_css_style_sheet_disconnect_font_faces(sheet.as_ptr(), Rc::as_ptr(&old_rule).cast()) };
+ }
+
+ // 5. Remove rule old rule from list at the zero-indexed position index.
+ self.rules.cssom_remove(index);
+ self.objects.borrow_mut(vm).0.remove(&identity);
+
+ // 6. Set old rule’s parent CSS rule and parent CSS style sheet to null.
+ // NOTE: We set the parent stylesheet to null within set_parent_rule.
+ if let Some(old_object) = old_object {
+ old_object.set_parent_rule(vm, None);
+ }
+
+ self.notify_change();
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssrulelist-item
+ pub(crate) fn item(&self, cx: &mut CallContext, index: u32) -> WebIdlResult<Option<AnyCSSRule>> {
+ let vm = cx.vm();
+ let index = index as usize;
+ if index >= self.native_length() {
+ return Ok(None);
+ }
+ Ok(Some(self.rule_at(vm, index)))
+ }
+
+ // https://drafts.csswg.org/cssom/#dom-cssrulelist-length
+ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ Ok(u32::try_from(self.native_length()).expect("a list has fewer than 2^32 rules"))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_scope_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_scope_rule.rs
new file mode 100644
index 00000000000..12b79dd81f8
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_scope_rule.rs
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSScopeRule, https://drafts.csswg.org/css-cascade-6/#the-cssscoperule-interface
+
+use super::css_grouping_rule::CSSGroupingRule;
+use super::css_rule::impl_rule_wrappable;
+use super::css_rule::{CSSRule, RuleText, selector_list_text, serialize_block_of_rules};
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use std::rc::Rc;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSScopeRule {
+ grouping_rule: CSSGroupingRule,
+}
+
+impl_rule_wrappable!(CSSScopeRule);
+
+impl Inherits<CSSGroupingRule> for CSSScopeRule {
+ fn parent(&self) -> &CSSGroupingRule {
+ &self.grouping_rule
+ }
+}
+
+impl CSSScopeRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ grouping_rule: CSSGroupingRule::new(native_rule),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ self.grouping_rule.rule()
+ }
+
+ pub(crate) fn grouping_rule(&self) -> &CSSGroupingRule {
+ &self.grouping_rule
+ }
+
+ fn scope_text(&self, selectors: *const core::ffi::c_void) -> Option<Utf16String> {
+ (!selectors.is_null()).then(|| selector_list_text(selectors, None))
+ }
+
+ fn start_text(&self) -> Option<Utf16String> {
+ let (start, _) = self
+ .rule()
+ .native_rule()
+ .scope_selector_lists()
+ .expect("a @scope rule has a scope");
+ self.scope_text(start)
+ }
+
+ fn end_text(&self) -> Option<Utf16String> {
+ let (_, end) = self
+ .rule()
+ .native_rule()
+ .scope_selector_lists()
+ .expect("a @scope rule has a scope");
+ self.scope_text(end)
+ }
+
+ // https://drafts.csswg.org/css-cascade-6/#dom-cssscoperule-start
+ pub(crate) fn start(&self, _: &mut CallContext) -> WebIdlResult<Option<Utf16String>> {
+ Ok(self.start_text())
+ }
+
+ // https://drafts.csswg.org/css-cascade-6/#dom-cssscoperule-end
+ pub(crate) fn end(&self, _: &mut CallContext) -> WebIdlResult<Option<Utf16String>> {
+ Ok(self.end_text())
+ }
+
+ // https://drafts.csswg.org/cssom/#serialize-a-css-rule
+ pub(crate) fn serialized(&self, vm: &Vm) -> Utf16String {
+ // AD-HOC: There is no spec for this yet.
+ let mut text = RuleText::new("@scope");
+ if let Some(start) = self.start_text() {
+ text.push_str(" (");
+ text.push(&start);
+ text.push_str(")");
+ }
+ if let Some(end) = self.end_text() {
+ text.push_str(" to (");
+ text.push(&end);
+ text.push_str(")");
+ }
+ serialize_block_of_rules(text, vm, self.grouping_rule.child_rules(vm))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_style_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_rule.rs
new file mode 100644
index 00000000000..a8405fe8fb8
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_rule.rs
@@ -0,0 +1,184 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSStyleRule, https://drafts.csswg.org/cssom/#the-cssstylerule-interface
+
+use super::css_grouping_rule::CSSGroupingRule;
+use super::css_rule::impl_rule_wrappable;
+use super::css_rule::{CSSRule, RuleText, native_rules_of_sheet, selector_list_text, wrap_cpp_cell};
+use crate::bindings::conversions::CppInterface;
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use core::ffi::c_void;
+use libjs_rust::api::GcRefCell;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use std::rc::Rc;
+
+unsafe extern "C" {
+ fn web_css_style_rule_selector_changed(rule: *mut c_void);
+ fn web_css_style_property_map_create(declarations: *mut c_void) -> *mut c_void;
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSStyleRule {
+ grouping_rule: CSSGroupingRule,
+ /// The cell of the StylePropertyMap of the rule, once it is asked for.
+ style_map: GcRefCell<Option<CppCell>>,
+}
+
+impl_rule_wrappable!(CSSStyleRule);
+
+impl Inherits<CSSGroupingRule> for CSSStyleRule {
+ fn parent(&self) -> &CSSGroupingRule {
+ &self.grouping_rule
+ }
+}
+
+impl CSSStyleRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ grouping_rule: CSSGroupingRule::new(native_rule),
+ style_map: GcRefCell::new(None),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ self.grouping_rule.rule()
+ }
+
+ pub(crate) fn grouping_rule(&self) -> &CSSGroupingRule {
+ &self.grouping_rule
+ }
+
+ fn serialized_selector_text(&self) -> Utf16String {
+ // The selectorText attribute, on getting, must return the result of serializing the associated group of
+ // selectors.
+ selector_list_text(
+ self.rule().native_rule().style_selector_list(),
+ self.rule().parent_sheet().as_ref(),
+ )
+ }
+
+ // https://drafts.csswg.org/cssom-1/#dom-cssstylerule-selectortext
+ pub(crate) fn selector_text(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.serialized_selector_text())
+ }
+
+ // https://drafts.csswg.org/cssom-1/#dom-cssstylerule-selectortext
+ pub(crate) fn set_selector_text(&self, _: &mut CallContext, value: Utf16String) -> WebIdlResult<()> {
+ self.replace_selectors(&value.to_utf16());
+ Ok(())
+ }
+
+ // https://drafts.csswg.org/cssom-1/#dom-cssstylerule-selectortext
+ pub(crate) fn replace_selectors(&self, value: &[u16]) {
+ // 1. Run the parse a group of selectors algorithm on the given value.
+ let sheet = self.rule().parent_sheet();
+ let sheet_rules = sheet.as_ref().map(native_rules_of_sheet);
+
+ // 2. If the algorithm returns a non-null value replace the associated group of selectors with the returned
+ // value.
+ let native_rule = self.rule().native_rule();
+ if native_rule.cssom_set_selector_text(value, sheet_rules.as_deref()) && sheet.is_some() {
+ // SAFETY: The cell is that of this object, which is live.
+ unsafe { web_css_style_rule_selector_changed(self.rule().object().cell()) };
+ }
+
+ // 3. Otherwise, if the algorithm returns a null value, do nothing.
+ }
+
+ // https://drafts.csswg.org/cssom-1/#dom-cssstylerule-style
+ pub(crate) fn style(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ Ok(self.rule().style_attribute(cx))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssstylerule-stylemap
+ pub(crate) fn style_map(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {
+ if let Some(style_map) = self.style_map.borrow().as_ref() {
+ return Ok(wrap_cpp_cell(cx, style_map));
+ }
+ let vm = cx.vm();
+ let declarations = self.rule().declarations(vm);
+ // SAFETY: The cell is that of a live CSSStyleProperties.
+ let style_map = unsafe { web_css_style_property_map_create(declarations.as_ptr()) };
+ // SAFETY: LibWeb returns a live cell.
+ let style_map = unsafe { CppCell::from_raw(style_map) };
+ let result = wrap_cpp_cell(cx, &style_map);
+ *self.style_map.borrow_mut(vm) = Some(style_map);
+ Ok(result)
+ }
+
+ // https://drafts.csswg.org/cssom-1/#serialize-a-css-rule
+ pub(crate) fn serialized(&self, vm: &Vm) -> Utf16String {
+ // 1. Let s initially be the result of performing serialize a group of selectors on the rule’s associated
+ // selectors, followed by the string " {", i.e., a single SPACE (U+0020), followed by LEFT CURLY BRACKET
+ // (U+007B).
+ let mut s = RuleText::default();
+ s.push(&self.serialized_selector_text());
+ s.push_str(" {");
+
+ // 2. Let decls be the result of performing serialize a CSS declaration block on the rule’s associated
+ // declarations, or null if there are no such declarations.
+ let decls = (!self.rule().native_rule().has_no_declarations()).then(|| self.rule().serialized_declarations(vm));
+
+ // 3. Let rules be the result of performing serialize a CSS rule on each rule in the rule’s cssRules list,
+ // or null if there are no such rules.
+ let child_rules = self.grouping_rule.child_rules(vm);
+ let has_rules = child_rules.native_length() != 0;
+ let mut rules = (0..child_rules.native_length())
+ .map(|index| child_rules.rule_at(vm, index).serialized(vm))
+ .collect::<Vec<_>>();
+
+ // 4. If decls and rules are both null, append " }" to s (i.e. a single SPACE (U+0020) followed by RIGHT CURLY
+ // BRACKET (U+007D)) and return s.
+ if decls.is_none() && !has_rules {
+ s.push_str(" }");
+ return s.finish();
+ }
+
+ // 5. If rules is null:
+ if !has_rules {
+ // 1. Append a single SPACE (U+0020) to s
+ s.push_str(" ");
+ // 2. Append decls to s
+ s.push(&decls.expect("step 4 returned if there are no declarations"));
+ // 3. Append " }" to s (i.e. a single SPACE (U+0020) followed by RIGHT CURLY BRACKET (U+007D)).
+ s.push_str(" }");
+ // 4. Return s.
+ return s.finish();
+ }
+
+ // 6. Otherwise:
+ // 1. If decls is not null, prepend it to rules.
+ if let Some(decls) = decls {
+ rules.insert(0, decls);
+ }
+
+ // 2. For each rule in rules:
+ for rule in &rules {
+ // * If rule is the empty string, do nothing.
+ if rule.is_empty() {
+ continue;
+ }
+
+ // * Otherwise:
+ // 1. Append a newline followed by two spaces to s.
+ // 2. Append rule to s.
+ s.push_str("\n ");
+ s.push(rule);
+ }
+
+ // 3. Append a newline followed by RIGHT CURLY BRACKET (U+007D) to s.
+ s.push_str("\n}");
+
+ // 4. Return s.
+ s.finish()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_supports_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_supports_rule.rs
new file mode 100644
index 00000000000..1da51d8eeb1
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_supports_rule.rs
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSSupportsRule, https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface
+
+use super::css_condition_rule::CSSConditionRule;
+use super::css_grouping_rule::CSSGroupingRule;
+use super::css_rule::impl_rule_wrappable;
+use super::css_rule::{AnyCSSRule, CSSRule, RuleText};
+use crate::bindings::interface::{Inherits, Ref, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::NativeRule;
+use std::rc::Rc;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSSupportsRule {
+ condition_rule: CSSConditionRule,
+}
+
+impl_rule_wrappable!(CSSSupportsRule);
+
+impl Inherits<CSSConditionRule> for CSSSupportsRule {
+ fn parent(&self) -> &CSSConditionRule {
+ &self.condition_rule
+ }
+}
+
+impl CSSSupportsRule {
+ pub(crate) fn create(vm: &Vm, native_rule: Rc<NativeRule>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ condition_rule: CSSConditionRule::new(native_rule),
+ })
+ }
+
+ pub(crate) fn rule(&self) -> &CSSRule {
+ self.condition_rule.rule()
+ }
+
+ pub(crate) fn grouping_rule(&self) -> &CSSGroupingRule {
+ self.condition_rule.grouping_rule()
+ }
+
+ // https://drafts.csswg.org/css-conditional-5/#dom-csssupportsrule-matches
+ pub(crate) fn matches(&self, _: &mut CallContext) -> WebIdlResult<bool> {
+ Ok(self.rule().native_rule().supports_condition_matches())
+ }
+
+ pub(crate) fn serialized_condition_text(&self) -> Utf16String {
+ self.rule().native_rule().supports_condition_text()
+ }
+
+ // https://drafts.csswg.org/cssom/#serialize-a-css-rule
+ pub(crate) fn serialized(&self, vm: &Vm) -> Utf16String {
+ // Note: The spec doesn't cover this yet, so I'm roughly following the spec for the @media rule.
+ // It should be pretty close!
+ let mut text = RuleText::new("@supports ");
+ text.push(&self.serialized_condition_text());
+ text.push_str(" {\n");
+ let rules = self.grouping_rule().child_rules(vm);
+ for index in 0..rules.native_length() {
+ if index != 0 {
+ text.push_str("\n");
+ }
+ text.push_str(" ");
+ text.push(&AnyCSSRule::serialized(rules.rule_at(vm, index), vm));
+ }
+ text.push_str("\n}");
+ text.finish()
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
index 5429feafe78..aef0dbc2ec8 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
@@ -8,17 +8,30 @@
//! Libraries/LibWeb/CSS/TypedOM.cpp.
use core::ffi::c_void;
-use core::ptr::NonNull;
+use core::ptr::{NonNull, null_mut};
+use std::rc::Rc;
use std::sync::Arc;
use ak::Utf16String;
use libjs_rust::api::{Gc, MarkedVec, Vm};
-use libweb_rust::NativeMediaList;
use libweb_rust::typed_om::{FfiNumericType, RetainedStyleValue};
+use libweb_rust::{NativeMediaList, NativeRule, NativeRuleList};
use super::animation_event::{AnimationEvent, AnimationEventInit};
+use super::css_container_rule::CSSContainerRule;
+use super::css_counter_style_rule::CSSCounterStyleRule;
+use super::css_font_face_rule::CSSFontFaceRule;
+use super::css_font_feature_values_rule::CSSFontFeatureValuesRule;
+use super::css_function_declarations::CSSFunctionDeclarations;
+use super::css_function_rule::CSSFunctionRule;
use super::css_image_value::CSSImageValue;
+use super::css_import_rule::CSSImportRule;
+use super::css_keyframe_rule::CSSKeyframeRule;
+use super::css_keyframes_rule::CSSKeyframesRule;
use super::css_keyword_value::CSSKeywordValue;
+use super::css_layer_block_rule::CSSLayerBlockRule;
+use super::css_layer_statement_rule::CSSLayerStatementRule;
+use super::css_margin_rule::CSSMarginRule;
use super::css_math_clamp::CSSMathClamp;
use super::css_math_invert::CSSMathInvert;
use super::css_math_max::CSSMathMax;
@@ -26,8 +39,19 @@ use super::css_math_min::CSSMathMin;
use super::css_math_negate::CSSMathNegate;
use super::css_math_product::CSSMathProduct;
use super::css_math_sum::CSSMathSum;
+use super::css_media_rule::CSSMediaRule;
+use super::css_namespace_rule::CSSNamespaceRule;
+use super::css_nested_declarations::CSSNestedDeclarations;
use super::css_numeric_value::AnyCSSNumericValue;
+use super::css_page_rule::CSSPageRule;
+use super::css_position_try_rule::CSSPositionTryRule;
+use super::css_property_rule::CSSPropertyRule;
+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_value::{AnyCSSStyleValue, CSSStyleValue, PerformTypeCheck};
+use super::css_supports_rule::CSSSupportsRule;
use super::css_transform_value::CSSTransformValue;
use super::css_unit_value::CSSUnitValue;
use super::css_unparsed_value::CSSUnparsedValue;
@@ -557,3 +581,289 @@ fn bubbling_event_init() -> EventInit {
composed: false,
}
}
+
+/// The object of the rule whose cell C++ holds, which C++ names by any of the interfaces it is an object of.
+///
+/// # Safety
+///
+/// `cell` must be the live cell of an object of an interface that inherits from CSSRule.
+pub(crate) unsafe fn rule_from_abi(cell: *mut c_void) -> AnyCSSRule {
+ macro_rules! decode {
+ ($($interface:ident),+ $(,)?) => {
+ $(
+ // SAFETY: The caller passes a live cell.
+ if let Some(object) = unsafe { cell_if_abi::<$interface>(cell) } {
+ return AnyCSSRule::$interface(object);
+ }
+ )+
+ };
+ }
+ decode!(
+ CSSStyleRule,
+ CSSNestedDeclarations,
+ CSSMediaRule,
+ CSSSupportsRule,
+ CSSContainerRule,
+ CSSScopeRule,
+ CSSLayerBlockRule,
+ CSSLayerStatementRule,
+ CSSImportRule,
+ CSSFontFaceRule,
+ CSSKeyframesRule,
+ CSSKeyframeRule,
+ CSSPageRule,
+ CSSMarginRule,
+ CSSNamespaceRule,
+ CSSPropertyRule,
+ CSSCounterStyleRule,
+ CSSFontFeatureValuesRule,
+ CSSFunctionRule,
+ CSSFunctionDeclarations,
+ CSSPositionTryRule,
+ );
+ unreachable!("nothing creates an object of an interface that only others inherit from")
+}
+
+/// The implementation of the CSSRuleList whose cell C++ lends, for as long as C++ keeps the cell alive.
+///
+/// # Safety
+///
+/// `list` must be the live cell of a CSSRuleList, and it must outlive `'a`.
+unsafe fn rule_list_from_abi<'a>(list: *mut c_void) -> &'a CSSRuleList {
+ // SAFETY: The caller passes a live cell of a CSSRuleList.
+ let list: Ref<CSSRuleList> = unsafe { cell_from_abi(list) };
+ // SAFETY: The caller keeps the cell alive for 'a.
+ unsafe { &*list.as_ptr() }
+}
+
+/// The cell that C++ passes, which it passes as null for nothing.
+///
+/// # Safety
+///
+/// `cell` must be a live cell, or null.
+unsafe fn optional_cpp_cell(cell: *mut c_void) -> Option<CppCell> {
+ // SAFETY: The caller passes a live cell.
+ (!cell.is_null()).then(|| unsafe { CppCell::from_raw(cell) })
+}
+
+/// The native rule of the rule, which the rule keeps alive.
+///
+/// # Safety
+///
+/// `rule` must be the live cell of a rule.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_rule_native(rule: *mut c_void) -> *const NativeRule {
+ // SAFETY: The caller passes a live cell.
+ Rc::as_ptr(unsafe { rule_from_abi(rule) }.native_rule())
+}
+
+/// # Safety
+///
+/// `rule` must be the live cell of a rule.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_rule_parent_rule(rule: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes a live cell.
+ let rule = unsafe { rule_from_abi(rule) };
+ rule.parent_rule_object().map_or(null_mut(), AnyCSSRule::cell)
+}
+
+/// The cell of the CSSStyleSheet that the rule is in.
+///
+/// # Safety
+///
+/// `rule` must be the live cell of a rule.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_rule_parent_style_sheet(rule: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes a live cell.
+ let rule = unsafe { rule_from_abi(rule) };
+ rule.parent_sheet().map_or(null_mut(), |sheet| sheet.as_ptr())
+}
+
+/// # Safety
+///
+/// `vm` must be the live VM, and `rule` the live cell of a rule.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_rule_serialized(vm: *mut c_void, rule: *mut c_void) -> usize {
+ // SAFETY: The caller passes the live VM and a live cell.
+ let (vm, rule) = unsafe { (vm_from_abi(vm), rule_from_abi(rule)) };
+ rule.serialized(vm).into_raw()
+}
+
+/// The cell of the CSSStyleDeclaration of the declarations of the rule.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `rule` the live cell of a rule with declarations.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_rule_declarations(vm: *mut c_void, rule: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes the live VM and a live cell.
+ let (vm, rule) = unsafe { (vm_from_abi(vm), rule_from_abi(rule)) };
+ rule.declarations(vm).as_ptr()
+}
+
+/// The cell of the list of child rules of the rule.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `rule` the live cell of a rule with child rules.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_rule_child_rules(vm: *mut c_void, rule: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes the live VM and a live cell.
+ let (vm, rule) = unsafe { (vm_from_abi(vm), rule_from_abi(rule)) };
+ cell_into_abi(rule.child_rules(vm).expect("C++ asks a rule with child rules"))
+}
+
+/// A new CSSRuleList of the native rules, whose @import rules `document` loads, if it is not null.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, `rules` a live list, and `document` the live cell of a Document, or null.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_rule_list_create(
+ vm: *mut c_void,
+ rules: *const NativeRuleList,
+ document: *mut c_void,
+) -> *mut c_void {
+ // SAFETY: The caller passes the live VM, a live list and a live cell, or null.
+ let (vm, rules, document) = unsafe {
+ (
+ vm_from_abi(vm),
+ NativeRuleList::retained_from_raw(rules),
+ optional_cpp_cell(document),
+ )
+ };
+ cell_into_abi(allocate(vm, |defer_gc| CSSRuleList::new(defer_gc, rules, document)))
+}
+
+/// The native rules of the list, which the list keeps alive.
+///
+/// # Safety
+///
+/// `list` must be the live cell of a CSSRuleList.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_rule_list_native_rules(list: *mut c_void) -> *const NativeRuleList {
+ // SAFETY: The caller passes a live cell, and keeps it alive for the call.
+ Rc::as_ptr(unsafe { rule_list_from_abi(list) }.native_rules())
+}
+
+/// # Safety
+///
+/// `list` must be the live cell of a CSSRuleList.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_rule_list_length(list: *mut c_void) -> usize {
+ // SAFETY: The caller passes a live cell, and keeps it alive for the call.
+ unsafe { rule_list_from_abi(list) }.native_length()
+}
+
+/// The cell of the rule at the index, which has to be in the list.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `list` the live cell of a CSSRuleList.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_rule_list_item(vm: *mut c_void, list: *mut c_void, index: usize) -> *mut c_void {
+ // SAFETY: The caller passes the live VM and a live cell, and keeps it alive for the call.
+ let (vm, list) = unsafe { (vm_from_abi(vm), rule_list_from_abi(list)) };
+ list.rule_at(vm, index).cell()
+}
+
+/// The cell of the object of the rule with the identity, if the rule has one yet.
+///
+/// # Safety
+///
+/// `list` must be the live cell of a CSSRuleList.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_rule_list_existing_rule(list: *mut c_void, identity: u64) -> *mut c_void {
+ // SAFETY: The caller passes a live cell, and keeps it alive for the call.
+ let list = unsafe { rule_list_from_abi(list) };
+ list.existing_object(identity).map_or(null_mut(), AnyCSSRule::cell)
+}
+
+/// # Safety
+///
+/// `vm` must be the live VM, `list` the live cell of a CSSRuleList, and `sheet` that of a CSSStyleSheet, or null.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_rule_list_set_parent_style_sheet(
+ vm: *mut c_void,
+ list: *mut c_void,
+ sheet: *mut c_void,
+) {
+ // SAFETY: The caller passes the live VM and live cells, and keeps them alive for the call.
+ let (vm, list, sheet) = unsafe { (vm_from_abi(vm), rule_list_from_abi(list), optional_cpp_cell(sheet)) };
+ list.set_parent_style_sheet(vm, sheet);
+}
+
+/// # Safety
+///
+/// `vm` must be the live VM, `list` the live cell of a CSSRuleList, `rules` a live list, and `document` the live cell
+/// of a Document, or null.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_rule_list_set_rules(
+ vm: *mut c_void,
+ list: *mut c_void,
+ rules: &NativeRuleList,
+ document: *mut c_void,
+) {
+ // SAFETY: The caller passes the live VM and live cells, and keeps them alive for the call.
+ let (vm, list, document) = unsafe { (vm_from_abi(vm), rule_list_from_abi(list), optional_cpp_cell(document)) };
+ list.set_rules(vm, rules, document);
+}
+
+/// # Safety
+///
+/// `vm` must be the live VM, and `list` the live cell of a CSSRuleList.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_rule_list_remove_rule(vm: *mut c_void, list: *mut c_void, index: usize) {
+ // SAFETY: The caller passes the live VM and a live cell, and keeps it alive for the call.
+ let (vm, list) = unsafe { (vm_from_abi(vm), rule_list_from_abi(list)) };
+ list.remove_a_css_rule_without_validation(vm, index);
+}
+
+/// A new CSSImportRule for the import that `import` holds, in the sheet `sheet`, if it is not null.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, `rule` a live rule, `import` the live cell of a StyleSheetImportCell, and `sheet` that of
+/// a CSSStyleSheet, or null.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_import_rule_create(
+ vm: *mut c_void,
+ rule: *const NativeRule,
+ import: *mut c_void,
+ sheet: *mut c_void,
+) -> *mut c_void {
+ // SAFETY: The caller passes the live VM, a live rule and live cells, or null for the sheet.
+ let (vm, rule, import, sheet) = unsafe {
+ (
+ vm_from_abi(vm),
+ NativeRule::retained_from_raw(rule),
+ CppCell::from_raw(import),
+ optional_cpp_cell(sheet),
+ )
+ };
+ let object = CSSImportRule::finish(CSSImportRule::create_for_import(vm, rule, import), vm);
+ object.store_parent_style_sheet(vm, sheet);
+ object.cell()
+}
+
+/// The cell of the StyleSheetImportCell of the rule.
+///
+/// # Safety
+///
+/// `rule` must be the live cell of a CSSImportRule.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_import_rule_import(rule: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes a live cell of a CSSImportRule.
+ let rule: Ref<CSSImportRule> = unsafe { cell_from_abi(rule) };
+ rule.import_cell()
+}
+
+/// # Safety
+///
+/// `rule` must be the live cell of a CSSStyleRule, and `text` a string that the caller hands over.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_style_rule_set_selector_text(rule: *mut c_void, text: usize) {
+ // SAFETY: The caller passes a live cell of a CSSStyleRule, and hands over the string.
+ let (rule, text): (Ref<CSSStyleRule>, _) = unsafe { (cell_from_abi(rule), Utf16String::from_raw_owned(text)) };
+ rule.replace_selectors(&text.to_utf16());
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
index 0ead0240d4e..a322678fa5c 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
@@ -7,8 +7,22 @@
//! The CSS Object Model, https://drafts.csswg.org/cssom/
pub(crate) mod animation_event;
+pub(crate) mod css_condition_rule;
+pub(crate) mod css_container_rule;
+pub(crate) mod css_counter_style_rule;
+pub(crate) mod css_font_face_rule;
+pub(crate) mod css_font_feature_values_rule;
+pub(crate) mod css_function_declarations;
+pub(crate) mod css_function_rule;
+pub(crate) mod css_grouping_rule;
pub(crate) mod css_image_value;
+pub(crate) mod css_import_rule;
+pub(crate) mod css_keyframe_rule;
+pub(crate) mod css_keyframes_rule;
pub(crate) mod css_keyword_value;
+pub(crate) mod css_layer_block_rule;
+pub(crate) mod css_layer_statement_rule;
+pub(crate) mod css_margin_rule;
pub(crate) mod css_math_clamp;
pub(crate) mod css_math_invert;
pub(crate) mod css_math_max;
@@ -18,15 +32,26 @@ pub(crate) mod css_math_product;
pub(crate) mod css_math_sum;
pub(crate) mod css_math_value;
pub(crate) mod css_matrix_component;
+pub(crate) mod css_media_rule;
+pub(crate) mod css_namespace_rule;
+pub(crate) mod css_nested_declarations;
pub(crate) mod css_numeric_array;
pub(crate) mod css_numeric_value;
+pub(crate) mod css_page_rule;
pub(crate) mod css_perspective;
+pub(crate) mod css_position_try_rule;
+pub(crate) mod css_property_rule;
pub(crate) mod css_rotate;
+pub(crate) mod css_rule;
+pub(crate) mod css_rule_list;
pub(crate) mod css_scale;
+pub(crate) mod css_scope_rule;
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_value;
+pub(crate) mod css_supports_rule;
pub(crate) mod css_transform_component;
pub(crate) mod css_transform_value;
pub(crate) mod css_translate;
diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
index 29155822914..66e6a322bcf 100644
--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
@@ -136,6 +136,8 @@ void web_bindings_message_port_transport_close_after_sending_all_pending_message
bool web_bindings_message_port_transport_send(IPC::Transport*, HTML::SerializedTransferRecord const*);
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_bindings_wrapper_world(void* realm, bool* is_main_world)
{
auto& wrapper_world = host_defined_wrapper_world(*static_cast<JS::Realm*>(realm));
@@ -156,6 +158,14 @@ void web_bindings_set_rust_wrapper(void* realm, void* cell, JSObject* wrapper)
host_defined_wrapper_world(*static_cast<JS::Realm*>(realm)).set_rust_wrapper(*static_cast<RustInterfaceCell*>(cell), host_object);
}
+void* web_css_wrap_object(void* realm, void* cell)
+{
+ auto& js_realm = *static_cast<JS::Realm*>(realm);
+ auto& wrappable = *static_cast<GCAllocatedWrappable*>(static_cast<GC::Cell*>(cell));
+ auto wrapper = wrap(host_defined_wrapper_world(js_realm), js_realm, GC::Ref<Wrappable> { wrappable });
+ return JS::HostABI::object_to_abi(wrapper.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 789edba3abe..acb5f0a4447 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -80,40 +80,24 @@ set(SOURCES
CSS/GeneratedContent.cpp
CSS/CSS.cpp
CSS/CSSAnimation.cpp
- CSS/CSSConditionRule.cpp
- CSS/CSSContainerRule.cpp
- CSS/CSSCounterStyleRule.cpp
CSS/CSSDescriptors.cpp
CSS/CSSFontFaceDescriptors.cpp
CSS/CSSFontFaceRule.cpp
CSS/CSSFontFeatureValuesMap.cpp
CSS/CSSFontFeatureValuesRule.cpp
- CSS/CSSFunctionDeclarations.cpp
CSS/CSSFunctionDescriptors.cpp
- CSS/CSSFunctionRule.cpp
CSS/CSSGroupingRule.cpp
CSS/CSSImportRule.cpp
- CSS/CSSKeyframeRule.cpp
CSS/CSSKeyframesRule.cpp
- CSS/CSSLayerBlockRule.cpp
- CSS/CSSLayerStatementRule.cpp
- CSS/CSSMarginRule.cpp
- CSS/CSSMediaRule.cpp
- CSS/CSSNamespaceRule.cpp
CSS/CSSNestedDeclarations.cpp
- CSS/CSSPageRule.cpp
CSS/CSSPageDescriptors.cpp
CSS/CSSPositionTryDescriptors.cpp
- CSS/CSSPositionTryRule.cpp
- CSS/CSSPropertyRule.cpp
CSS/CSSRule.cpp
CSS/CSSRuleList.cpp
- CSS/CSSScopeRule.cpp
CSS/CSSStyleDeclaration.cpp
CSS/CSSStyleProperties.cpp
CSS/CSSStyleRule.cpp
CSS/CSSStyleSheet.cpp
- CSS/CSSSupportsRule.cpp
CSS/CSSTransition.cpp
CSS/ColorFunctionDescriptor.cpp
CSS/CustomPropertyData.cpp
diff --git a/Libraries/LibWeb/CSS/CSSConditionRule.cpp b/Libraries/LibWeb/CSS/CSSConditionRule.cpp
deleted file mode 100644
index 5c2a4d889ea..00000000000
--- a/Libraries/LibWeb/CSS/CSSConditionRule.cpp
+++ /dev/null
@@ -1,17 +0,0 @@
-/*
- * Copyright (c) 2021-2024, Sam Atkins <[email protected]>
- * Copyright (c) 2022, Andreas Kling <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibWeb/CSS/CSSConditionRule.h>
-
-namespace Web::CSS {
-
-CSSConditionRule::CSSConditionRule(CSSRuleList& rules, RustRule rule)
- : CSSGroupingRule(rules, move(rule))
-{
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSConditionRule.h b/Libraries/LibWeb/CSS/CSSConditionRule.h
deleted file mode 100644
index d4e38e78f90..00000000000
--- a/Libraries/LibWeb/CSS/CSSConditionRule.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2021-2024, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/NonnullRefPtr.h>
-#include <AK/Utf16String.h>
-#include <LibWeb/CSS/CSSGroupingRule.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::CSS {
-
-class CSSConditionRule : public CSSGroupingRule {
- WEB_WRAPPABLE(CSSConditionRule, CSSGroupingRule);
-
-public:
- virtual ~CSSConditionRule() = default;
-
- Utf16String condition_text() const { return serialized_condition_text(); }
- virtual Utf16String serialized_condition_text() const = 0;
-
-protected:
- CSSConditionRule(CSSRuleList&, RustRule);
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSConditionRule.idl b/Libraries/LibWeb/CSS/CSSConditionRule.idl
index 013fc5dcfa4..3786b80c34a 100644
--- a/Libraries/LibWeb/CSS/CSSConditionRule.idl
+++ b/Libraries/LibWeb/CSS/CSSConditionRule.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/css-conditional-3/#the-cssconditionrule-interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSConditionRule : CSSGroupingRule {
readonly attribute CSSOMString conditionText;
};
diff --git a/Libraries/LibWeb/CSS/CSSContainerRule.cpp b/Libraries/LibWeb/CSS/CSSContainerRule.cpp
deleted file mode 100644
index f6f2b3048a0..00000000000
--- a/Libraries/LibWeb/CSS/CSSContainerRule.cpp
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * Copyright (c) 2026, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSContainerRule.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/ContainerQuery.h>
-#include <LibWeb/CSS/Serialize.h>
-#include <LibWeb/DOM/AbstractElement.h>
-#include <LibWeb/DOM/Element.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSContainerRule);
-
-GC::Ref<CSSContainerRule> CSSContainerRule::create(RustRule rule, CSSRuleList& rules)
-{
- return GC::Heap::the().allocate<CSSContainerRule>(move(rule), rules);
-}
-
-CSSContainerRule::CSSContainerRule(RustRule rule, CSSRuleList& rules)
- : CSSConditionRule(rules, move(rule))
- , m_conditions(ContainerConditions::create(native_rule().payload().container))
-{
-}
-
-CSSContainerRule::~CSSContainerRule() = default;
-
-static Utf16String serialized_condition_name(ContainerConditions::Condition const& condition)
-{
- if (!condition.container_name.has_value())
- return {};
-
- Utf16StringBuilder builder;
- serialize_an_identifier(builder, *condition.container_name);
- return builder.to_string();
-}
-
-static Utf16String serialized_condition_query(ContainerConditions::Condition const& condition)
-{
- return condition.container_query ? condition.container_query->to_string() : Utf16String {};
-}
-
-static void append_condition_text(Utf16StringBuilder& result, ContainerConditions::Condition const& condition)
-{
- auto name = serialized_condition_name(condition);
- auto query = serialized_condition_query(condition);
-
- if (!name.is_empty()) {
- result.append(name.utf16_view());
-
- if (!query.is_empty())
- result.append_ascii(' ');
- }
-
- result.append(query.utf16_view());
-}
-
-// https://drafts.csswg.org/css-conditional-5/#the-csscontainerrule-interface
-Utf16String CSSContainerRule::serialized_condition_text() const
-{
- // The conditionText attribute (defined on the CSSConditionRule parent rule), on getting, must return a value as
- // follows:
-
- // 1. Let conditions be the result of getting the conditions attribute.
- auto const& conditions = m_conditions->entries();
-
- // 2. Let first be true.
- auto first = true;
-
- // 2. Let result be the empty string.
- Utf16StringBuilder result;
-
- // 3. For each condition in conditions:
- for (auto const& condition : conditions) {
- // 1. If first is false, append ", " to result.
- if (!first)
- result.append_ascii(", "sv);
-
- // 2. Set first to false.
- first = false;
-
- // 3. If condition's name is not empty:
- // 1. Append condition's name to result.
- // 2. If condition's query is not empty, append a single space to result.
- //
- // 4. Append condition's query to result.
- append_condition_text(result, condition);
- }
-
- // 5. Return result.
- return result.to_string();
-}
-
-// https://drafts.csswg.org/cssom-1/#serialize-a-css-rule
-Utf16String CSSContainerRule::serialized() const
-{
- // AD-HOC: The spec does not define @container serialization, so this is based on CSSMediaRule::serialized().
- Utf16StringBuilder builder;
- builder.append_ascii("@container "sv);
-
- builder.append(serialized_condition_text());
-
- builder.append_ascii(" {\n"sv);
-
- for (size_t i = 0; i < css_rules().length(); i++) {
- auto rule = css_rules().item(i);
- auto result = rule->serialized();
-
- if (result.is_empty())
- continue;
-
- builder.append_ascii(" "sv);
- builder.append(result);
- builder.append_ascii('\n');
- }
-
- builder.append_ascii('}');
-
- return builder.to_string();
-}
-
-// https://drafts.csswg.org/css-conditional-5/#dom-csscontainerrule-containername
-Utf16String CSSContainerRule::container_name() const
-{
- // The containerName attribute, on getting, must return a value as follows:
-
- // 1. Let conditions be the result of getting the conditions attribute.
- auto const& conditions = m_conditions->entries();
-
- // 2. If the length of conditions is 1:
- if (conditions.size() == 1) {
- // 1. Return the only condition's name.
- return serialized_condition_name(conditions.first());
- }
-
- // 3. Return "".
- return {};
-}
-
-// https://drafts.csswg.org/css-conditional-5/#dom-csscontainerrule-containerquery
-Utf16String CSSContainerRule::container_query() const
-{
- // The containerQuery attribute, on getting, must return a value as follows:
-
- // 1. Let conditions be the result of getting the conditions attribute.
- auto const& conditions = m_conditions->entries();
-
- // 2. If the length of conditions is 1:
- if (conditions.size() == 1) {
- // 1. Return the only condition's query.
- return serialized_condition_query(conditions.first());
- }
-
- // 3. Return "".
- return {};
-}
-
-// https://drafts.csswg.org/css-conditional-5/#dom-csscontainerrule-conditions
-Vector<CSSContainerCondition> CSSContainerRule::conditions() const
-{
- // The conditions attribute, on getting, must return a value as follows:
-
- // 1. Let result be an empty list.
- Vector<CSSContainerCondition> result;
-
- // 2. For each <container-condition> condition specified in the rule:
- result.ensure_capacity(m_conditions->entries().size());
- for (auto const& condition : m_conditions->entries()) {
- // 1. Let dict be a new CSSContainerCondition with name set to the serialized <container-name> of condition if
- // specified, or "" otherwise, and query set to the <container-query> specified in condition without any
- // logical simplifications, so that the returned query will evaluate to the same result as the specified
- // query in any conformant implementation of this specification (including implementations that implement
- // future extensions allowed by the <general-enclosed> extensibility mechanism in this specification). In
- // other words, token stream simplifications are allowed (such as reducing whitespace to a single space or
- // omitting it in cases where it is known to be optional), but logical simplifications (such as removal of
- // unneeded parentheses, or simplification based on evaluating results) are not allowed.
- CSSContainerCondition dict {
- .name = serialized_condition_name(condition),
- .query = serialized_condition_query(condition),
- };
-
- // 2. Append dict to result.
- result.unchecked_append(move(dict));
- }
-
- // 3. Return result.
- return result;
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSContainerRule.h b/Libraries/LibWeb/CSS/CSSContainerRule.h
deleted file mode 100644
index fac65811b35..00000000000
--- a/Libraries/LibWeb/CSS/CSSContainerRule.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 2026, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <AK/Utf16FlyString.h>
-#include <AK/Utf16String.h>
-#include <LibWeb/CSS/CSSConditionRule.h>
-#include <LibWeb/CSS/ContainerQuery.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::CSS {
-
-// https://drafts.csswg.org/css-conditional-5/#dictdef-csscontainercondition
-struct CSSContainerCondition {
- Utf16String name;
- Utf16String query;
-};
-
-// https://drafts.csswg.org/css-conditional-5/#the-csscontainerrule-interface
-class CSSContainerRule final : public CSSConditionRule {
- WEB_WRAPPABLE(CSSContainerRule, CSSConditionRule);
- GC_DECLARE_ALLOCATOR(CSSContainerRule);
-
-public:
- [[nodiscard]] static GC::Ref<CSSContainerRule> create(RustRule, CSSRuleList&);
-
- virtual ~CSSContainerRule() override;
-
- virtual Utf16String serialized_condition_text() const override;
-
- Utf16String container_name() const;
- Utf16String container_query() const;
-
- // FIXME: Should be FrozenArray
- Vector<CSSContainerCondition> conditions() const;
-
-private:
- CSSContainerRule(RustRule, CSSRuleList&);
- virtual Utf16String serialized() const override;
-
- NonnullRefPtr<ContainerConditions> m_conditions;
-};
-
-template<>
-inline bool CSSRule::fast_is<CSSContainerRule>() const { return type() == CSSRule::Type::Container; }
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSContainerRule.idl b/Libraries/LibWeb/CSS/CSSContainerRule.idl
index cb9a02ecaa3..72fb32248a2 100644
--- a/Libraries/LibWeb/CSS/CSSContainerRule.idl
+++ b/Libraries/LibWeb/CSS/CSSContainerRule.idl
@@ -5,7 +5,7 @@ dictionary CSSContainerCondition {
};
// https://drafts.csswg.org/css-conditional-5/#csscontainerrule
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSContainerRule : CSSConditionRule {
readonly attribute CSSOMString containerName;
readonly attribute CSSOMString containerQuery;
diff --git a/Libraries/LibWeb/CSS/CSSCounterStyleRule.cpp b/Libraries/LibWeb/CSS/CSSCounterStyleRule.cpp
deleted file mode 100644
index 7b459d90062..00000000000
--- a/Libraries/LibWeb/CSS/CSSCounterStyleRule.cpp
+++ /dev/null
@@ -1,285 +0,0 @@
-/*
- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSCounterStyleRule.h>
-#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/Serialize.h>
-#include <LibWeb/CSS/StyleEngineInput.h>
-#include <LibWeb/CSS/StyleScope.h>
-#include <LibWeb/CSS/StyleSheetState.h>
-#include <LibWeb/CSS/StyleValues/StyleValueList.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSCounterStyleRule);
-
-static Utf16String serialize_counter_style_descriptor(RefPtr<StyleValue const> const& descriptor)
-{
- if (!descriptor)
- return {};
-
- return descriptor->to_utf16_string(SerializationMode::Normal);
-}
-
-GC::Ref<CSSCounterStyleRule> CSSCounterStyleRule::create(RustRule rule)
-{
- return GC::Heap::the().allocate<CSSCounterStyleRule>(move(rule));
-}
-
-CSSCounterStyleRule::CSSCounterStyleRule(RustRule rule)
- : CSSRule(move(rule))
- , m_rule(*native_rule().payload().counter_style)
- , m_descriptors(Parser::ValueParserFFI::rust_counter_style_descriptors(&m_rule))
-{
-}
-
-Utf16String CSSCounterStyleRule::serialized() const
-{
- Utf16StringBuilder builder;
- builder.appendff("@counter-style {} {{", serialize_an_identifier(name()));
-
- for (auto id : { DescriptorID::System, DescriptorID::Negative, DescriptorID::Prefix, DescriptorID::Suffix, DescriptorID::Range, DescriptorID::Pad, DescriptorID::Fallback, DescriptorID::Symbols, DescriptorID::AdditiveSymbols, DescriptorID::SpeakAs }) {
- auto name = DescriptorNameAndID::from_id(id);
- if (auto value = m_descriptors.descriptor(name)) {
- builder.appendff(" {}: ", name.name());
- value->serialize(builder, SerializationMode::Normal);
- builder.append_ascii(';');
- }
- }
-
- builder.append_ascii(" }"sv);
- return builder.to_string();
-}
-
-Utf16View CSSCounterStyleRule::name() const
-{
- auto view = Parser::ValueParserFFI::rust_counter_style_name(&m_rule);
- return { reinterpret_cast<char16_t const*>(view.utf16), view.length };
-}
-
-void CSSCounterStyleRule::set_name(Utf16String const& name)
-{
- if (Parser::ValueParserFFI::rust_counter_style_set_name(&m_rule, Parser::ffi_utf16_view(name)))
- clear_caches();
-}
-
-Utf16String CSSCounterStyleRule::system() const
-{
- return serialize_counter_style_descriptor(m_descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::System)));
-}
-
-// https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-system
-void CSSCounterStyleRule::set_system(Utf16String const& system)
-{
- // 1. parse the given value as the descriptor associated with the attribute.
- Parser::ParsingParams parsing_params;
- auto value = parse_css_descriptor(parsing_params, CSS::AtRuleID::CounterStyle, DescriptorNameAndID::from_id(CSS::DescriptorID::System), system);
-
- // 2. If the result is invalid according to the given descriptor’s grammar, or would cause the @counter-style rule
- // to not define a counter style, do nothing and abort these steps. (For example, some systems require the
- // symbols descriptor to contain two values.)
- // NB: Since we only allow changing parameters of the system, not the algorithm itself (see below), we know this
- // change can't cause the @counter-style to not define a counter style.
- if (!value)
- return;
-
- // 3. If the attribute being set is system, and the new value would change the algorithm used, do nothing and abort
- // these steps.
- // Note: It’s okay to change an aspect of the algorithm, like the first symbol value of a fixed system.
- auto current_system = system_style_value();
- if (!current_system || Parser::ValueParserFFI::rust_counter_style_system_changes_algorithm(current_system->rust_style_value_data(), value->rust_style_value_data()))
- return;
-
- // 4. Set the descriptor to the value.
- m_descriptors.set(DescriptorNameAndID::from_id(DescriptorID::System), *value);
-
- clear_caches();
-}
-
-Utf16String CSSCounterStyleRule::negative() const
-{
- return serialize_counter_style_descriptor(m_descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::Negative)));
-}
-
-void CSSCounterStyleRule::set_negative(Utf16String const& negative)
-{
- Parser::ParsingParams parsing_params;
-
- if (auto value = parse_css_descriptor(parsing_params, CSS::AtRuleID::CounterStyle, DescriptorNameAndID::from_id(CSS::DescriptorID::Negative), negative)) {
- m_descriptors.set(DescriptorNameAndID::from_id(DescriptorID::Negative), *value);
- clear_caches();
- }
-}
-
-Utf16String CSSCounterStyleRule::prefix() const
-{
- return serialize_counter_style_descriptor(m_descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::Prefix)));
-}
-
-void CSSCounterStyleRule::set_prefix(Utf16String const& prefix)
-{
- Parser::ParsingParams parsing_params;
-
- if (auto value = parse_css_descriptor(parsing_params, CSS::AtRuleID::CounterStyle, DescriptorNameAndID::from_id(CSS::DescriptorID::Prefix), prefix)) {
- m_descriptors.set(DescriptorNameAndID::from_id(DescriptorID::Prefix), *value);
- clear_caches();
- }
-}
-
-Utf16String CSSCounterStyleRule::suffix() const
-{
- return serialize_counter_style_descriptor(m_descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::Suffix)));
-}
-
-void CSSCounterStyleRule::set_suffix(Utf16String const& suffix)
-{
- Parser::ParsingParams parsing_params;
-
- if (auto value = parse_css_descriptor(parsing_params, CSS::AtRuleID::CounterStyle, DescriptorNameAndID::from_id(CSS::DescriptorID::Suffix), suffix)) {
- m_descriptors.set(DescriptorNameAndID::from_id(DescriptorID::Suffix), *value);
- clear_caches();
- }
-}
-
-Utf16String CSSCounterStyleRule::range() const
-{
- return serialize_counter_style_descriptor(m_descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::Range)));
-}
-
-void CSSCounterStyleRule::set_range(Utf16String const& range)
-{
- Parser::ParsingParams parsing_params;
-
- if (auto value = parse_css_descriptor(parsing_params, CSS::AtRuleID::CounterStyle, DescriptorNameAndID::from_id(CSS::DescriptorID::Range), range)) {
- m_descriptors.set(DescriptorNameAndID::from_id(DescriptorID::Range), *value);
- clear_caches();
- }
-}
-
-Utf16String CSSCounterStyleRule::pad() const
-{
- return serialize_counter_style_descriptor(m_descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::Pad)));
-}
-
-void CSSCounterStyleRule::set_pad(Utf16String const& pad)
-{
- Parser::ParsingParams parsing_params;
-
- if (auto value = parse_css_descriptor(parsing_params, CSS::AtRuleID::CounterStyle, DescriptorNameAndID::from_id(CSS::DescriptorID::Pad), pad)) {
- m_descriptors.set(DescriptorNameAndID::from_id(DescriptorID::Pad), *value);
- clear_caches();
- }
-}
-
-Utf16String CSSCounterStyleRule::fallback() const
-{
- return serialize_counter_style_descriptor(m_descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::Fallback)));
-}
-
-void CSSCounterStyleRule::set_fallback(Utf16String const& fallback)
-{
- Parser::ParsingParams parsing_params;
-
- if (auto value = parse_css_descriptor(parsing_params, CSS::AtRuleID::CounterStyle, DescriptorNameAndID::from_id(CSS::DescriptorID::Fallback), fallback)) {
- m_descriptors.set(DescriptorNameAndID::from_id(DescriptorID::Fallback), *value);
- clear_caches();
- }
-}
-
-Utf16String CSSCounterStyleRule::symbols() const
-{
- return serialize_counter_style_descriptor(m_descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::Symbols)));
-}
-
-// https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-symbols
-void CSSCounterStyleRule::set_symbols(Utf16String const& symbols)
-{
- // On setting, run the following steps:
-
- // 1. parse the given value as the descriptor associated with the attribute.
- Parser::ParsingParams parsing_params;
-
- auto value = parse_css_descriptor(parsing_params, CSS::AtRuleID::CounterStyle, DescriptorNameAndID::from_id(CSS::DescriptorID::Symbols), symbols);
-
- // 2. If the result is invalid according to the given descriptor’s grammar, or would cause the @counter-style rule
- // to not define a counter style, do nothing and abort these steps. (For example, some systems require the
- // symbols descriptor to contain two values.)
- auto current_system = system_style_value();
- if (!value || (current_system && !Parser::ValueParserFFI::rust_counter_style_system_accepts_symbols(current_system->rust_style_value_data(), false, value->as_value_list().size())))
- return;
-
- // 3. If the attribute being set is system, and the new value would change the algorithm used, do nothing and abort
- // these steps. It’s okay to change an aspect of the algorithm, like the first symbol value of a fixed system.
-
- // 4. Set the descriptor to the value.
- m_descriptors.set(DescriptorNameAndID::from_id(DescriptorID::Symbols), *value);
-
- clear_caches();
-}
-
-Utf16String CSSCounterStyleRule::additive_symbols() const
-{
- return serialize_counter_style_descriptor(m_descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::AdditiveSymbols)));
-}
-
-// https://drafts.csswg.org/css-counter-styles-3/#dom-csscounterstylerule-additivesymbols
-void CSSCounterStyleRule::set_additive_symbols(Utf16String const& additive_symbols)
-{
- // On setting, run the following steps:
-
- // 1. parse the given value as the descriptor associated with the attribute.
- Parser::ParsingParams parsing_params;
-
- auto value = parse_css_descriptor(parsing_params, CSS::AtRuleID::CounterStyle, DescriptorNameAndID::from_id(CSS::DescriptorID::AdditiveSymbols), additive_symbols);
-
- // 2. If the result is invalid according to the given descriptor’s grammar, or would cause the @counter-style rule
- // to not define a counter style, do nothing and abort these steps. (For example, some systems require the
- // symbols descriptor to contain two values.)
- auto current_system = system_style_value();
- if (!value || (current_system && !Parser::ValueParserFFI::rust_counter_style_system_accepts_symbols(current_system->rust_style_value_data(), true, value->as_value_list().size())))
- return;
-
- // 3. If the attribute being set is system, and the new value would change the algorithm used, do nothing and abort
- // these steps. It’s okay to change an aspect of the algorithm, like the first symbol value of a fixed system.
-
- // 4. Set the descriptor to the value.
- m_descriptors.set(DescriptorNameAndID::from_id(DescriptorID::AdditiveSymbols), *value);
-
- clear_caches();
-}
-
-Utf16String CSSCounterStyleRule::speak_as() const
-{
- return serialize_counter_style_descriptor(m_descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::SpeakAs)));
-}
-
-void CSSCounterStyleRule::set_speak_as(Utf16String const& speak_as)
-{
- Parser::ParsingParams parsing_params;
-
- if (auto value = parse_css_descriptor(parsing_params, CSS::AtRuleID::CounterStyle, DescriptorNameAndID::from_id(CSS::DescriptorID::SpeakAs), speak_as)) {
- m_descriptors.set(DescriptorNameAndID::from_id(DescriptorID::SpeakAs), *value);
- clear_caches();
- }
-}
-
-void CSSCounterStyleRule::clear_caches()
-{
- Base::clear_caches();
-
- auto* parent_style_sheet = this->parent_style_sheet();
-
- if (!parent_style_sheet)
- return;
-
- parent_style_sheet->for_each_owning_style_scope([&](StyleScope& style_scope) {
- style_scope.invalidate_counter_style_cache();
- });
- record_style_rule_declarations_changed(*this);
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSCounterStyleRule.h b/Libraries/LibWeb/CSS/CSSCounterStyleRule.h
deleted file mode 100644
index e66f4ec7b9b..00000000000
--- a/Libraries/LibWeb/CSS/CSSCounterStyleRule.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16FlyString.h>
-#include <LibWeb/CSS/CSSRule.h>
-#include <LibWeb/CSS/RustDescriptorBlock.h>
-
-namespace Web::CSS {
-
-class CSSCounterStyleRule : public CSSRule {
- WEB_WRAPPABLE(CSSCounterStyleRule, CSSRule);
- GC_DECLARE_ALLOCATOR(CSSCounterStyleRule);
-
-public:
- static GC::Ref<CSSCounterStyleRule> create(RustRule);
- virtual ~CSSCounterStyleRule() = default;
-
- virtual Utf16String serialized() const override;
-
- Utf16View name() const;
- void set_name(Utf16String const& name);
-
- Utf16String system() const;
- void set_system(Utf16String const& system);
- RefPtr<StyleValue const> system_style_value() const { return m_descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::System)); }
-
- Utf16String negative() const;
- void set_negative(Utf16String const& negative);
-
- Utf16String prefix() const;
- void set_prefix(Utf16String const& prefix);
-
- Utf16String suffix() const;
- void set_suffix(Utf16String const& suffix);
-
- Utf16String range() const;
- void set_range(Utf16String const& range);
-
- Utf16String pad() const;
- void set_pad(Utf16String const& pad);
-
- Utf16String fallback() const;
- void set_fallback(Utf16String const& fallback);
-
- Utf16String symbols() const;
- void set_symbols(Utf16String const& symbols);
-
- Utf16String additive_symbols() const;
- void set_additive_symbols(Utf16String const& additive_symbols);
-
- Utf16String speak_as() const;
- void set_speak_as(Utf16String const& speak_as);
-
- virtual void clear_caches() override;
-
-protected:
- CSSCounterStyleRule(RustRule);
-
- Parser::ValueParserFFI::FfiCounterStyle const& m_rule;
- RustDescriptorBlock m_descriptors;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSCounterStyleRule.idl b/Libraries/LibWeb/CSS/CSSCounterStyleRule.idl
index c63845210a3..86990bc5458 100644
--- a/Libraries/LibWeb/CSS/CSSCounterStyleRule.idl
+++ b/Libraries/LibWeb/CSS/CSSCounterStyleRule.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/css-counter-styles/#the-csscounterstylerule-interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSCounterStyleRule : CSSRule {
attribute CSSOMString name;
attribute CSSOMString system;
diff --git a/Libraries/LibWeb/CSS/CSSFontFaceRule.cpp b/Libraries/LibWeb/CSS/CSSFontFaceRule.cpp
index edbfa93a85a..5cbc0defdd2 100644
--- a/Libraries/LibWeb/CSS/CSSFontFaceRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSFontFaceRule.cpp
@@ -5,47 +5,21 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibGC/Heap.h>
#include <LibGfx/Font/Font.h>
#include <LibGfx/Font/FontStyleMapping.h>
-#include <LibJS/Runtime/ExternalMemory.h>
#include <LibWeb/CSS/CSSFontFaceRule.h>
#include <LibWeb/CSS/FontComputer.h>
#include <LibWeb/CSS/FontFaceSet.h>
#include <LibWeb/CSS/FontFaceState.h>
-#include <LibWeb/CSS/Serialize.h>
#include <LibWeb/CSS/StyleSheetState.h>
#include <LibWeb/DOM/Document.h>
-#include <LibWeb/Dump.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::CSS {
-GC_DEFINE_ALLOCATOR(CSSFontFaceRule);
-
-GC::Ref<CSSFontFaceRule> CSSFontFaceRule::create(RustRule rule)
-{
- return GC::Heap::the().allocate<CSSFontFaceRule>(move(rule));
-}
-
-CSSFontFaceRule::CSSFontFaceRule(RustRule rule)
- : CSSRule(move(rule))
- , m_descriptors(Parser::ValueParserFFI::rust_descriptor_block_retain(native_rule().payload().descriptors))
-{
-}
-
-size_t CSSFontFaceRule::external_memory_size() const
-{
- return JS::saturating_add_external_memory_size(Base::external_memory_size(), m_descriptors.external_memory_size());
-}
-
GC::Ref<CSSFontFaceDescriptors> CSSFontFaceRule::descriptors() const
{
- if (!m_style) {
- m_style = CSSFontFaceDescriptors::create(m_descriptors.retain());
- m_style->set_parent_rule(const_cast<CSSFontFaceRule&>(*this));
- }
- return *m_style;
+ return static_cast<CSSFontFaceDescriptors&>(*declarations());
}
bool CSSFontFaceRule::is_valid() const
@@ -53,108 +27,9 @@ bool CSSFontFaceRule::is_valid() const
// @font-face rules require a font-family and src descriptor; if either of these are missing, the @font-face rule
// must not be considered when performing the font matching algorithm.
// https://drafts.csswg.org/css-fonts-4/#font-face-rule
- return !m_descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::FontFamily)).is_null()
- && !m_descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::Src)).is_null();
-}
-
-// https://drafts.csswg.org/cssom/#ref-for-cssfontfacerule
-Utf16String CSSFontFaceRule::serialized() const
-{
- auto const& descriptors = m_descriptors;
-
- Utf16StringBuilder builder;
- // The result of concatenating the following:
-
- // 1. The string "@font-face {".
- builder.append_ascii("@font-face {"sv);
-
- // 2. If the font-family descriptor is present:
- if (auto font_family = descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::FontFamily)); !font_family.is_null()) {
- // 1. A single SPACE (U+0020), followed by the string "font-family:", followed by a single SPACE (U+0020).
- builder.append_ascii(" font-family: "sv);
-
- // 2. The result of performing serialize a string on the rule’s font family name.
- descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::FontFamily))->serialize(builder, SerializationMode::Normal);
-
- // 3. The string ";", i.e., SEMICOLON (U+003B).
- builder.append_ascii(';');
- }
-
- // 3. If the rule’s associated source list is not empty, follow these substeps:
- if (auto sources = descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::Src))) {
- // 1. A single SPACE (U+0020), followed by the string "src:", followed by a single SPACE (U+0020).
- builder.append_ascii(" src: "sv);
-
- // 2. The result of invoking serialize a comma-separated list on performing serialize a URL or serialize a LOCAL for each source on the source list.
- sources->serialize(builder, SerializationMode::Normal);
-
- // 3. The string ";", i.e., SEMICOLON (U+003B).
- builder.append_ascii(';');
- }
-
- // 4. If rule’s associated unicode-range descriptor is present, a single SPACE (U+0020), followed by the string "unicode-range:", followed by a single SPACE (U+0020), followed by the result of performing serialize a <'unicode-range'>, followed by the string ";", i.e., SEMICOLON (U+003B).
- if (auto unicode_range = descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::UnicodeRange))) {
- builder.append_ascii(" unicode-range: "sv);
- unicode_range->serialize(builder, SerializationMode::Normal);
- builder.append_ascii(';');
- }
-
- // FIXME: 5. If rule’s associated font-variant descriptor is present, a single SPACE (U+0020),
- // followed by the string "font-variant:", followed by a single SPACE (U+0020),
- // followed by the result of performing serialize a <'font-variant'>,
- // followed by the string ";", i.e., SEMICOLON (U+003B).
-
- // 6. If rule’s associated font-feature-settings descriptor is present, a single SPACE (U+0020),
- // followed by the string "font-feature-settings:", followed by a single SPACE (U+0020),
- // followed by the result of performing serialize a <'font-feature-settings'>,
- // followed by the string ";", i.e., SEMICOLON (U+003B).
- if (auto font_feature_settings = descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::FontFeatureSettings))) {
- builder.append_ascii(" font-feature-settings: "sv);
- font_feature_settings->serialize(builder, SerializationMode::Normal);
- builder.append_ascii(";"sv);
- }
-
- // 7. If rule’s associated font-stretch descriptor is present, a single SPACE (U+0020),
- // followed by the string "font-stretch:", followed by a single SPACE (U+0020),
- // followed by the result of performing serialize a <'font-stretch'>,
- // followed by the string ";", i.e., SEMICOLON (U+003B).
- // NOTE: font-stretch is now an alias for font-width, so we use that instead.
- if (auto font_width = descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::FontWidth))) {
- builder.append_ascii(" font-stretch: "sv);
- font_width->serialize(builder, SerializationMode::Normal);
- builder.append_ascii(";"sv);
- }
-
- // 8. If rule’s associated font-weight descriptor is present, a single SPACE (U+0020),
- // followed by the string "font-weight:", followed by a single SPACE (U+0020),
- // followed by the result of performing serialize a <'font-weight'>,
- // followed by the string ";", i.e., SEMICOLON (U+003B).
- if (auto font_weight = descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::FontWeight))) {
- builder.append_ascii(" font-weight: "sv);
- font_weight->serialize(builder, SerializationMode::Normal);
- builder.append_ascii(";"sv);
- }
-
- // 9. If rule’s associated font-style descriptor is present, a single SPACE (U+0020),
- // followed by the string "font-style:", followed by a single SPACE (U+0020),
- // followed by the result of performing serialize a <'font-style'>,
- // followed by the string ";", i.e., SEMICOLON (U+003B).
- if (auto font_style = descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::FontStyle))) {
- builder.append_ascii(" font-style: "sv);
- font_style->serialize(builder, SerializationMode::Normal);
- builder.append_ascii(";"sv);
- }
-
- // 10. A single SPACE (U+0020), followed by the string "}", i.e., RIGHT CURLY BRACKET (U+007D).
- builder.append_ascii(" }"sv);
-
- return builder.to_string();
-}
-
-void CSSFontFaceRule::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_style);
+ RustDescriptorBlock descriptors { Parser::ValueParserFFI::rust_descriptor_block_retain(native_rule().payload().descriptors) };
+ return !descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::FontFamily)).is_null()
+ && !descriptors.descriptor(DescriptorNameAndID::from_id(DescriptorID::Src)).is_null();
}
RefPtr<FontFaceState> CSSFontFaceRule::css_connected_font_face() const
@@ -248,13 +123,4 @@ void CSSFontFaceRule::disconnect_font_face()
font_face->disconnect_from_css_rule();
}
-void CSSFontFaceRule::dump(StringBuilder& builder, int indent_levels) const
-{
- Base::dump(builder, indent_levels);
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Valid: {}\n", is_valid());
- dump_descriptors(builder, descriptors(), indent_levels + 1);
-}
-
}
diff --git a/Libraries/LibWeb/CSS/CSSFontFaceRule.h b/Libraries/LibWeb/CSS/CSSFontFaceRule.h
index f3a5642839d..50be3b4436d 100644
--- a/Libraries/LibWeb/CSS/CSSFontFaceRule.h
+++ b/Libraries/LibWeb/CSS/CSSFontFaceRule.h
@@ -7,6 +7,7 @@
#pragma once
+#include <LibWeb/Bindings/CSSFontFaceRule.h>
#include <LibWeb/CSS/CSSFontFaceDescriptors.h>
#include <LibWeb/CSS/CSSRule.h>
@@ -15,14 +16,9 @@ namespace Web::CSS {
class FontFaceState;
class CSSFontFaceRule final : public CSSRule {
- WEB_WRAPPABLE(CSSFontFaceRule, CSSRule);
- GC_DECLARE_ALLOCATOR(CSSFontFaceRule);
+ WEB_RUST_INTERFACE(CSSFontFaceRule, css_font_face_rule)
public:
- [[nodiscard]] static GC::Ref<CSSFontFaceRule> create(RustRule);
-
- virtual ~CSSFontFaceRule() override = default;
-
bool is_valid() const;
GC::Ref<CSSFontFaceDescriptors> descriptors() const;
@@ -31,17 +27,7 @@ public:
void disconnect_font_face();
private:
- CSSFontFaceRule(RustRule);
-
- virtual size_t external_memory_size() const override;
- virtual Utf16String serialized() const override;
- virtual void visit_edges(Visitor&) override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
-
void handle_src_descriptor_change();
-
- RustDescriptorBlock m_descriptors;
- mutable GC::Ptr<CSSFontFaceDescriptors> m_style;
};
template<>
diff --git a/Libraries/LibWeb/CSS/CSSFontFaceRule.idl b/Libraries/LibWeb/CSS/CSSFontFaceRule.idl
index 0455ed939b4..c5f5ba5165a 100644
--- a/Libraries/LibWeb/CSS/CSSFontFaceRule.idl
+++ b/Libraries/LibWeb/CSS/CSSFontFaceRule.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/css-fonts/#om-fontface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSFontFaceRule : CSSRule {
- [SameObject, PutForwards=cssText, ImplementedAs=descriptors] readonly attribute CSSFontFaceDescriptors style;
+ [SameObject, PutForwards=cssText] readonly attribute CSSFontFaceDescriptors style;
};
diff --git a/Libraries/LibWeb/CSS/CSSFontFeatureValuesRule.cpp b/Libraries/LibWeb/CSS/CSSFontFeatureValuesRule.cpp
index 5690bd90198..0f46697d02a 100644
--- a/Libraries/LibWeb/CSS/CSSFontFeatureValuesRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSFontFeatureValuesRule.cpp
@@ -4,134 +4,27 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include "CSSFontFeatureValuesRule.h"
-#include <AK/QuickSort.h>
-#include <LibGC/Heap.h>
+#include <LibWeb/CSS/CSSFontFeatureValuesRule.h>
#include <LibWeb/CSS/FontComputer.h>
-#include <LibWeb/CSS/Parser/RustSyntaxParsing.h>
-#include <LibWeb/CSS/Serialize.h>
#include <LibWeb/CSS/StyleSheetState.h>
#include <LibWeb/DOM/Document.h>
-#include <LibWebCommon/Infra/CharacterTypes.h>
namespace Web::CSS {
-GC_DEFINE_ALLOCATOR(CSSFontFeatureValuesRule);
-
-GC::Ref<CSSFontFeatureValuesRule> CSSFontFeatureValuesRule::create(RustRule rule)
-{
- return GC::Heap::the().allocate<CSSFontFeatureValuesRule>(move(rule));
-}
-
-CSSFontFeatureValuesRule::CSSFontFeatureValuesRule(RustRule rule)
- : CSSRule(move(rule))
- , m_values(*native_rule().payload().font_feature_values)
-{
-}
-
-GC::Ref<CSSFontFeatureValuesMap> CSSFontFeatureValuesRule::map(FontFeatureValuesRuleKind kind) const
-{
- auto& wrapper = m_maps[to_underlying(kind)];
- if (!wrapper)
- wrapper = CSSFontFeatureValuesMap::create(kind, const_cast<CSSFontFeatureValuesRule&>(*this));
- return *wrapper;
-}
-
Vector<Utf16FlyString> CSSFontFeatureValuesRule::font_families() const
{
+ auto const* rule_values = &values();
Vector<Utf16FlyString> families;
- auto count = Parser::ValueParserFFI::rust_font_feature_values_family_count(&m_values);
- for (size_t index = 0; index < count; ++index)
- families.append(Utf16FlyString::from_utf16(family_at(index)));
- return families;
-}
-
-Utf16View CSSFontFeatureValuesRule::family_at(size_t index) const
-{
- auto family = Parser::ValueParserFFI::rust_font_feature_values_family_at(&m_values, index);
- return { reinterpret_cast<char16_t const*>(family.utf16), family.length };
-}
-
-Utf16String CSSFontFeatureValuesRule::serialized_font_family() const
-{
- Utf16StringBuilder builder;
-
- bool first = true;
- auto count = Parser::ValueParserFFI::rust_font_feature_values_family_count(&m_values);
+ auto count = Parser::ValueParserFFI::rust_font_feature_values_family_count(rule_values);
for (size_t index = 0; index < count; ++index) {
- auto family = family_at(index);
- if (first)
- first = false;
- else
- builder.append(", "sv);
-
- if (family.contains_any_of(Infra::ASCII_WHITESPACE_CODE_POINTS))
- serialize_a_string(builder, family);
- else
- serialize_an_identifier(builder, family);
+ auto family = Parser::ValueParserFFI::rust_font_feature_values_family_at(rule_values, index);
+ families.append(Utf16FlyString::from_utf16({ reinterpret_cast<char16_t const*>(family.utf16), family.length }));
}
-
- return builder.to_string();
-}
-
-Utf16String CSSFontFeatureValuesRule::font_family() const
-{
- return serialized_font_family();
-}
-
-void CSSFontFeatureValuesRule::set_font_family(Utf16View value)
-{
- Vector<Parser::ValueParserFFI::FfiUtf16View> family_names;
-
- value.for_each_split_view(u',', SplitBehavior::Nothing, [&](Utf16View family_name) {
- family_names.append(Parser::ffi_utf16_view(family_name.trim(Infra::ASCII_WHITESPACE)));
- return IterationDecision::Continue;
- });
-
- Parser::ValueParserFFI::rust_font_feature_values_set_families(&m_values, family_names.data(), family_names.size());
-}
-
-Utf16String CSSFontFeatureValuesRule::serialized() const
-{
- Utf16StringBuilder builder;
-
- auto serialize_font_feature_values_map = [&](FontFeatureValuesRuleKind kind, StringView const& at_rule_name) {
- auto count = Parser::ValueParserFFI::rust_font_feature_values_count(&m_values, kind);
- if (count != 0) {
- builder.appendff(" @{} {{"sv, at_rule_name);
-
- for (size_t index = 0; index < count; ++index) {
- auto entry = Parser::ValueParserFFI::rust_font_feature_values_at(&m_values, kind, index);
- builder.append_ascii(' ');
- serialize_an_identifier(builder, { reinterpret_cast<char16_t const*>(entry.name.utf16), entry.name.length });
- builder.append_ascii(':');
-
- for (size_t i = 0; i < entry.count; ++i)
- builder.appendff(" {}", entry.values[i]);
-
- builder.append_ascii(";"sv);
- }
- builder.append_ascii(" }"sv);
- }
- };
-
- builder.appendff("@font-feature-values {} {{"sv, serialized_font_family());
-
- serialize_font_feature_values_map(FontFeatureValuesRuleKind::Annotation, "annotation"sv);
- serialize_font_feature_values_map(FontFeatureValuesRuleKind::Ornaments, "ornaments"sv);
- serialize_font_feature_values_map(FontFeatureValuesRuleKind::Stylistic, "stylistic"sv);
- serialize_font_feature_values_map(FontFeatureValuesRuleKind::Swash, "swash"sv);
- serialize_font_feature_values_map(FontFeatureValuesRuleKind::CharacterVariant, "character-variant"sv);
- serialize_font_feature_values_map(FontFeatureValuesRuleKind::Styleset, "styleset"sv);
- serialize_font_feature_values_map(FontFeatureValuesRuleKind::HistoricalForms, "historical-forms"sv);
- builder.append_ascii(" }"sv);
-
- return builder.to_string();
+ return families;
}
void CSSFontFeatureValuesRule::clear_caches()
{
- Base::clear_caches();
auto const* parent_style_sheet = this->parent_style_sheet();
if (!parent_style_sheet)
@@ -148,16 +41,4 @@ void CSSFontFeatureValuesRule::clear_caches()
}
}
-void CSSFontFeatureValuesRule::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- for (auto const& map : m_maps)
- visitor.visit(map);
-}
-
-size_t CSSFontFeatureValuesRule::external_memory_size() const
-{
- return Base::external_memory_size() + Parser::ValueParserFFI::rust_font_feature_values_external_memory_size(&m_values);
-}
-
}
diff --git a/Libraries/LibWeb/CSS/CSSFontFeatureValuesRule.h b/Libraries/LibWeb/CSS/CSSFontFeatureValuesRule.h
index 326d11e3023..2cfb3a43788 100644
--- a/Libraries/LibWeb/CSS/CSSFontFeatureValuesRule.h
+++ b/Libraries/LibWeb/CSS/CSSFontFeatureValuesRule.h
@@ -6,12 +6,8 @@
#pragma once
-#include <AK/Array.h>
#include <AK/Utf16FlyString.h>
-#include <AK/Utf16String.h>
-#include <AK/Utf16View.h>
-#include <LibJS/Runtime/MapIterator.h>
-#include <LibWeb/CSS/CSSFontFeatureValuesMap.h>
+#include <LibWeb/Bindings/CSSFontFeatureValuesRule.h>
#include <LibWeb/CSS/CSSRule.h>
#include <LibWeb/CSS/RustFontFeatureValues.h>
#include <LibWeb/Forward.h>
@@ -19,41 +15,15 @@
namespace Web::CSS {
class CSSFontFeatureValuesRule final : public CSSRule {
- WEB_WRAPPABLE(CSSFontFeatureValuesRule, CSSRule);
- GC_DECLARE_ALLOCATOR(CSSFontFeatureValuesRule);
+ WEB_RUST_INTERFACE(CSSFontFeatureValuesRule, css_font_feature_values_rule)
public:
- static GC::Ref<CSSFontFeatureValuesRule> create(RustRule);
-
- Utf16String font_family() const;
- void set_font_family(Utf16View);
- GC::Ref<CSSFontFeatureValuesMap> annotation() const { return map(FontFeatureValuesRuleKind::Annotation); }
- GC::Ref<CSSFontFeatureValuesMap> ornaments() const { return map(FontFeatureValuesRuleKind::Ornaments); }
- GC::Ref<CSSFontFeatureValuesMap> stylistic() const { return map(FontFeatureValuesRuleKind::Stylistic); }
- GC::Ref<CSSFontFeatureValuesMap> swash() const { return map(FontFeatureValuesRuleKind::Swash); }
- GC::Ref<CSSFontFeatureValuesMap> character_variant() const { return map(FontFeatureValuesRuleKind::CharacterVariant); }
- GC::Ref<CSSFontFeatureValuesMap> styleset() const { return map(FontFeatureValuesRuleKind::Styleset); }
- GC::Ref<CSSFontFeatureValuesMap> historical_forms() const { return map(FontFeatureValuesRuleKind::HistoricalForms); }
+ Parser::ValueParserFFI::FontFeatureValuesRule const& values() const { return *native_rule().payload().font_feature_values; }
- Vector<Utf16FlyString> font_families() const;
- Parser::ValueParserFFI::FontFeatureValuesRule const& values() const { return m_values; }
-
- virtual void clear_caches() override;
-
- virtual Utf16String serialized() const override;
+ void clear_caches();
private:
- Utf16String serialized_font_family() const;
- Utf16View family_at(size_t) const;
-
- CSSFontFeatureValuesRule(RustRule);
- GC::Ref<CSSFontFeatureValuesMap> map(FontFeatureValuesRuleKind) const;
-
- virtual void visit_edges(Cell::Visitor&) override;
- virtual size_t external_memory_size() const override;
-
- Parser::ValueParserFFI::FontFeatureValuesRule const& m_values;
- mutable Array<GC::Ptr<CSSFontFeatureValuesMap>, 7> m_maps;
+ Vector<Utf16FlyString> font_families() const;
};
}
diff --git a/Libraries/LibWeb/CSS/CSSFontFeatureValuesRule.idl b/Libraries/LibWeb/CSS/CSSFontFeatureValuesRule.idl
index a21e4256ee4..a1e43b6e6b1 100644
--- a/Libraries/LibWeb/CSS/CSSFontFeatureValuesRule.idl
+++ b/Libraries/LibWeb/CSS/CSSFontFeatureValuesRule.idl
@@ -1,4 +1,4 @@
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSFontFeatureValuesRule : CSSRule {
attribute CSSOMString fontFamily;
readonly attribute CSSFontFeatureValuesMap annotation;
diff --git a/Libraries/LibWeb/CSS/CSSFunctionDeclarations.cpp b/Libraries/LibWeb/CSS/CSSFunctionDeclarations.cpp
deleted file mode 100644
index 7e0debf4e3a..00000000000
--- a/Libraries/LibWeb/CSS/CSSFunctionDeclarations.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (c) 2026, Callum Law <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSFunctionDeclarations.h"
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/ExternalMemory.h>
-#include <LibWeb/Dump.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSFunctionDeclarations);
-
-GC::Ref<CSSFunctionDeclarations> CSSFunctionDeclarations::create(RustRule rule)
-{
- return GC::Heap::the().allocate<CSSFunctionDeclarations>(move(rule));
-}
-
-CSSFunctionDeclarations::CSSFunctionDeclarations(RustRule rule)
- : CSSRule(move(rule))
- , m_descriptors(Parser::ValueParserFFI::rust_descriptor_block_retain(native_rule().payload().descriptors))
-{
-}
-
-size_t CSSFunctionDeclarations::external_memory_size() const
-{
- return JS::saturating_add_external_memory_size(Base::external_memory_size(), m_descriptors.external_memory_size());
-}
-
-GC::Ref<CSSFunctionDescriptors> CSSFunctionDeclarations::style() const
-{
- if (!m_style) {
- m_style = CSSFunctionDescriptors::create(m_descriptors.retain());
- m_style->set_parent_rule(const_cast<CSSFunctionDeclarations&>(*this));
- }
- return *m_style;
-}
-
-void CSSFunctionDeclarations::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_style);
-}
-
-Utf16String CSSFunctionDeclarations::serialized() const
-{
- // https://drafts.csswg.org/css-mixins-1/#the-function-declarations-interface
- // The CSSFunctionDeclarations rule, like CSSNestedDeclarations, serializes as if its declaration block had been
- // serialized directly.
- return style()->serialized();
-}
-
-void CSSFunctionDeclarations::dump(StringBuilder& builder, int indent_levels) const
-{
- Base::dump(builder, indent_levels);
-
- dump_descriptors(builder, style(), indent_levels + 1);
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSFunctionDeclarations.h b/Libraries/LibWeb/CSS/CSSFunctionDeclarations.h
deleted file mode 100644
index cd597de0147..00000000000
--- a/Libraries/LibWeb/CSS/CSSFunctionDeclarations.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2026, Callum Law <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSFunctionDescriptors.h>
-#include <LibWeb/CSS/CSSRule.h>
-
-namespace Web::CSS {
-
-// https://drafts.csswg.org/css-mixins-1/#cssfunctiondeclarations
-class CSSFunctionDeclarations final : public CSSRule {
- WEB_WRAPPABLE(CSSFunctionDeclarations, CSSRule);
- GC_DECLARE_ALLOCATOR(CSSFunctionDeclarations);
-
-public:
- [[nodiscard]] static GC::Ref<CSSFunctionDeclarations> create(RustRule);
-
- virtual ~CSSFunctionDeclarations() override = default;
-
- GC::Ref<CSSFunctionDescriptors> style() const;
-
-private:
- CSSFunctionDeclarations(RustRule);
-
- virtual size_t external_memory_size() const override;
- virtual void visit_edges(Cell::Visitor&) override;
- virtual Utf16String serialized() const override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
-
- RustDescriptorBlock m_descriptors;
- mutable GC::Ptr<CSSFunctionDescriptors> m_style;
-};
-
-template<>
-inline bool CSSRule::fast_is<CSSFunctionDeclarations>() const { return type() == CSSRule::Type::FunctionDeclarations; }
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSFunctionDeclarations.idl b/Libraries/LibWeb/CSS/CSSFunctionDeclarations.idl
index b459261904b..368b9f989a8 100644
--- a/Libraries/LibWeb/CSS/CSSFunctionDeclarations.idl
+++ b/Libraries/LibWeb/CSS/CSSFunctionDeclarations.idl
@@ -1,4 +1,4 @@
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSFunctionDeclarations : CSSRule {
[SameObject, PutForwards=cssText] readonly attribute CSSFunctionDescriptors style;
};
diff --git a/Libraries/LibWeb/CSS/CSSFunctionRule.cpp b/Libraries/LibWeb/CSS/CSSFunctionRule.cpp
deleted file mode 100644
index e1b34d69ef0..00000000000
--- a/Libraries/LibWeb/CSS/CSSFunctionRule.cpp
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * Copyright (c) 2026, Callum Law <[email protected]
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSFunctionRule.h"
-#include <AK/Utf16StringBuilder.h>
-#include <LibWeb/Bindings/CSSFunctionRule.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/CSS/CustomPropertyRegistration.h>
-#include <LibWeb/CSS/HypotheticalElement.h>
-#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/Parser/SyntaxParsing.h>
-#include <LibWeb/CSS/Serialize.h>
-#include <LibWeb/CSS/StyleComputer.h>
-#include <LibWeb/CSS/StyleValues/UnresolvedStyleValue.h>
-#include <LibWeb/DOM/Document.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSFunctionRule);
-
-static Utf16View parameter_name(Parser::ValueParserFFI::FfiFunctionParameterView const& parameter)
-{
- if (parameter.name.latin1)
- return Utf16View::from_latin1({ parameter.name.latin1, parameter.name.length }, false);
- return { reinterpret_cast<char16_t const*>(parameter.name.utf16), parameter.name.length };
-}
-
-static RefPtr<StyleValue const> parameter_default_value(Parser::ValueParserFFI::FfiFunctionParameterView const& parameter)
-{
- if (!parameter.default_value)
- return {};
- return StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(static_cast<StyleValueFFI::StyleValueData const*>(parameter.default_value)));
-}
-
-// https://drafts.csswg.org/css-mixins-1/#dictdef-functionparameter
-FunctionParameter FunctionParameter::from_native_parameter(Parser::ValueParserFFI::FfiFunctionParameterView const& parameter)
-{
- auto type = Parser::RustSyntaxHandle { Parser::ValueParserFFI::rust_syntax_retain(parameter.syntax) };
- auto default_value = parameter_default_value(parameter);
- return {
- // name
- // The name of the function parameter.
- Utf16FlyString::from_utf16(parameter_name(parameter)),
-
- // type
- // The type of the function parameter, represented as a syntax string, or "*" if the parameter has no type.
- type.serialize(),
-
- // defaultValue
- // The default value of the function parameter, or `null` if the argument does not have a default.
- default_value
- ? default_value->to_utf16_string(SerializationMode::Normal)
- : Optional<Utf16String> {},
- };
-}
-
-// https://drafts.csswg.org/css-mixins-1/#serialize-a-css-type
-static void serialize_a_css_type(Utf16StringBuilder& builder, Parser::RustSyntaxHandle const& type)
-{
- // To serialize a CSS type, return the concatenation of the following:
-
- // If the <css-type> consists of a single <syntax-component>, return the corresponding syntax string.
- if (type.is_single_component()) {
- builder.append(type.serialize());
- return;
- }
-
- // Otherwise, return the concatenation of the following:
- // The string "type(", i.e. "type" followed by a single LEFT PARENTHESIS (U+0028).
- builder.append_ascii("type("sv);
-
- // The corresponding syntax string.
- builder.append(type.serialize());
-
- // The string ")", i.e. a single RIGHT PARENTHESIS (U+0029).
- builder.append_ascii(')');
-}
-
-// https://drafts.csswg.org/css-mixins-1/#serialize-a-function-parameter
-static void serialize_function_parameter(Utf16StringBuilder& builder, Parser::ValueParserFFI::FfiFunctionParameterView const& parameter)
-{
- auto type = Parser::RustSyntaxHandle { Parser::ValueParserFFI::rust_syntax_retain(parameter.syntax) };
- // To serialize a function parameter, return the concatenation of the following:
-
- // The result of performing serialize an identifier on the name of the function parameter.
- serialize_an_identifier(builder, parameter_name(parameter));
-
- // If the function parameter has a type, and that type is not the universal syntax definition:
- if (!type.is_universal()) {
- // - A single SPACE (U+0020), followed by the result of performing serialize a CSS type on that type.
- builder.append_ascii(' ');
- serialize_a_css_type(builder, type);
- }
-
- // If the function parameter has a default value:
- if (auto default_value = parameter_default_value(parameter)) {
- // - A single COLON (U+003A), followed by a single SPACE (U+0020), followed by the result of performing
- // serialize a CSS value on that value.
- builder.append_ascii(": "sv);
- default_value->serialize(builder, SerializationMode::Normal);
- }
-}
-
-GC::Ref<CSSFunctionRule> CSSFunctionRule::create(RustRule rule, CSSRuleList& rules)
-{
- return GC::Heap::the().allocate<CSSFunctionRule>(move(rule), rules);
-}
-
-CSSFunctionRule::CSSFunctionRule(RustRule rule, CSSRuleList& rules)
- : CSSGroupingRule(rules, move(rule))
- , m_signature(*native_rule().payload().function_signature)
-{
-}
-
-Utf16String CSSFunctionRule::name() const
-{
- auto name = Parser::ValueParserFFI::rust_function_signature_view(&m_signature).name;
- return Utf16String::from_utf16({ reinterpret_cast<char16_t const*>(name.utf16), name.length });
-}
-
-// https://drafts.csswg.org/css-mixins-1/#dom-cssfunctionrule-getparameters
-Vector<FunctionParameter> CSSFunctionRule::get_parameters() const
-{
- Vector<FunctionParameter> parameters;
- auto count = Parser::ValueParserFFI::rust_function_signature_view(&m_signature).parameter_count;
- parameters.ensure_capacity(count);
-
- for (size_t index = 0; index < count; ++index)
- parameters.append(FunctionParameter::from_native_parameter(Parser::ValueParserFFI::rust_function_signature_parameter(&m_signature, index)));
-
- return parameters;
-}
-
-// https://drafts.csswg.org/css-mixins-1/#dom-cssfunctionrule-returntype
-Utf16String CSSFunctionRule::return_type() const
-{
- // The return type of the custom function, represented as a syntax string. If the custom function has no return
- // type, returns "*".
- // NB: We always store a return type (defaulting to "*")
- return Parser::RustSyntaxHandle { Parser::ValueParserFFI::rust_syntax_retain(Parser::ValueParserFFI::rust_function_signature_view(&m_signature).return_type) }.serialize();
-}
-
-// https://drafts.csswg.org/css-mixins-1/#serialize-a-cssfunctionrule
-Utf16String CSSFunctionRule::serialized() const
-{
- auto signature = Parser::ValueParserFFI::rust_function_signature_view(&m_signature);
- // To serialize a CSSFunctionRule, return the concatenation of the following:
- Utf16StringBuilder builder;
-
- // 1. The string "@function" followed by a single SPACE (U+0020).
- builder.append_ascii("@function "sv);
-
- // 2. The result of performing serialize an identifier on the name of the custom function, followed by a single LEFT
- // PARENTHESIS (U+0028).
- serialize_an_identifier(builder, { reinterpret_cast<char16_t const*>(signature.name.utf16), signature.name.length });
- builder.append_ascii('(');
-
- // 3. The result of serialize a function parameter on each of the custom function’s parameters, all joined by ", "
- // (COMMA U+002C, followed by a single SPACE U+0020).
- for (size_t i = 0; i < signature.parameter_count; ++i) {
- if (i > 0)
- builder.append_ascii(", "sv);
- serialize_function_parameter(builder, Parser::ValueParserFFI::rust_function_signature_parameter(&m_signature, i));
- }
-
- // 4. A single RIGHT PARENTHESIS (U+0029).
- builder.append_ascii(')');
-
- // 5. If the custom function has return type, and that return type is not the universal syntax definition ("*"):
- if (auto return_type = Parser::RustSyntaxHandle { Parser::ValueParserFFI::rust_syntax_retain(signature.return_type) }; !return_type.is_universal()) {
- // - A single SPACE (U+0020), followed by the string "returns", followed by a single SPACE (U+0020).
- builder.append_ascii(" returns "sv);
-
- // - The result of performing serialize a CSS type on that type.
- serialize_a_css_type(builder, return_type);
- }
-
- // 6. A single SPACE (U+0020), followed by a LEFT CURLY BRACKET (U+007B).
- builder.append_ascii(" {"sv);
-
- // 7. The result of performing serialize a CSS rule on each rule in cssRules, filtering out empty strings, each
- // preceded by a single SPACE (U+0020).
- auto const& rules = css_rules();
-
- for (size_t i = 0; i < rules.length(); ++i) {
- auto const& rule = rules.item(i);
-
- auto serialized_rule = rule->serialized();
-
- if (!serialized_rule.is_empty()) {
- builder.append_ascii(' ');
- builder.append(serialized_rule);
- }
- }
-
- // 8. A single SPACE (U+0020), followed by a single RIGHT CURLY BRACKET (U+007D).
- builder.append_ascii(" }"sv);
-
- return builder.to_string();
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSFunctionRule.h b/Libraries/LibWeb/CSS/CSSFunctionRule.h
deleted file mode 100644
index 2c08ec7f5f7..00000000000
--- a/Libraries/LibWeb/CSS/CSSFunctionRule.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2026, Callum Law <[email protected]
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16FlyString.h>
-#include <LibWeb/CSS/CSSGroupingRule.h>
-
-namespace Web::CSS {
-
-// https://drafts.csswg.org/css-mixins-1/#dictdef-functionparameter
-struct FunctionParameter {
- Utf16FlyString name;
- Utf16String type;
- Optional<Utf16String> default_value;
-
- static FunctionParameter from_native_parameter(Parser::ValueParserFFI::FfiFunctionParameterView const&);
-};
-
-// https://drafts.csswg.org/css-mixins-1/#cssfunctionrule
-class CSSFunctionRule : public CSSGroupingRule {
- WEB_WRAPPABLE(CSSFunctionRule, CSSGroupingRule);
- GC_DECLARE_ALLOCATOR(CSSFunctionRule);
-
-public:
- static GC::Ref<CSSFunctionRule> create(RustRule, CSSRuleList&);
- virtual ~CSSFunctionRule() override = default;
-
- Utf16String name() const;
- Vector<FunctionParameter> get_parameters() const;
- Utf16String return_type() const;
-
- Utf16String serialized() const override;
-
-private:
- CSSFunctionRule(RustRule, CSSRuleList&);
-
- Parser::ValueParserFFI::FunctionSignature const& m_signature;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSFunctionRule.idl b/Libraries/LibWeb/CSS/CSSFunctionRule.idl
index b427f087e83..8310f6b167d 100644
--- a/Libraries/LibWeb/CSS/CSSFunctionRule.idl
+++ b/Libraries/LibWeb/CSS/CSSFunctionRule.idl
@@ -1,12 +1,12 @@
// https://drafts.csswg.org/css-mixins-1/#dictdef-functionparameter
dictionary FunctionParameter {
required CSSOMString name;
- [ImplementedAs=type_for_bindings]required CSSOMString type;
+ required CSSOMString type;
CSSOMString defaultValue;
};
// https://drafts.csswg.org/css-mixins-1/#cssfunctionrule
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSFunctionRule : CSSGroupingRule {
readonly attribute CSSOMString name;
sequence<FunctionParameter> getParameters();
diff --git a/Libraries/LibWeb/CSS/CSSGroupingRule.cpp b/Libraries/LibWeb/CSS/CSSGroupingRule.cpp
index d89eef69df4..16307896276 100644
--- a/Libraries/LibWeb/CSS/CSSGroupingRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSGroupingRule.cpp
@@ -5,92 +5,119 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
#include <LibWeb/CSS/CSSGroupingRule.h>
#include <LibWeb/CSS/CSSRuleList.h>
+#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/StyleEngineInput.h>
#include <LibWeb/CSS/StyleSheetState.h>
-#include <LibWeb/HTML/Window.h>
namespace Web::CSS {
-CSSGroupingRule::CSSGroupingRule(GC::Ptr<CSSRuleList> rules, RustRule rule)
- : CSSRule(move(rule))
- , m_rules(rules)
-{
- if (!m_rules)
- return;
- VERIFY(Parser::ValueParserFFI::rust_rule_children(native_rule().handle()) == m_rules->native_rules().handle());
- m_rules->set_owner_rule(*this);
+using Parser::ValueParserFFI::NativeRule;
+
+// NB: Implemented in Libraries/LibWeb/Bindings/Rust/src/css/exports.rs.
+extern "C" void* web_css_rule_child_rules(void* vm, void* rule);
+
+// NB: What the implementation of CSSGroupingRule in Rust asks of the C++ code of LibWeb.
+extern "C" {
+NativeRule const* web_css_grouping_rule_parse_rule(void* rule, FlatPtr text, bool* declarations_failed);
+void web_css_grouping_rule_inserted(void* rule, NativeRule const* inserted);
+void web_css_grouping_rule_removed(void* rule, NativeRule const* removed);
}
-CSSRuleList& CSSGroupingRule::ensure_rules() const
+CSSRuleList& CSSGroupingRule::css_rules() const
{
- if (!m_rules) {
- auto& rule = const_cast<CSSGroupingRule&>(*this);
- auto* sheet = rule.parent_style_sheet();
- m_rules = CSSRuleList::create(RustRuleList { Parser::ValueParserFFI::rust_rule_list_retain(Parser::ValueParserFFI::rust_rule_children(native_rule().handle())) }, sheet ? sheet->parsing_document() : nullptr);
- m_rules->set_owner_rule(rule);
- m_rules->set_parent_style_sheet(sheet);
- }
- return *m_rules;
+ return *static_cast<CSSRuleList*>(web_css_rule_child_rules(JS::HostABI::vm_to_abi(JS::VM::the()), const_cast<CSSGroupingRule*>(this)));
}
-void CSSGroupingRule::visit_edges(GC::Cell::Visitor& visitor)
+static CSSRule& rule_from_cell(void* cell)
{
- Base::visit_edges(visitor);
- visitor.visit(m_rules);
+ return *static_cast<CSSRule*>(cell);
}
-void CSSGroupingRule::clear_caches()
+static Vector<Parser::RuleContext> rule_context(CSSRule& owner_rule)
{
- Base::clear_caches();
- if (!m_rules)
- return;
- m_rules->for_each_existing_rule([](CSSRule& rule) { rule.clear_caches(); });
+ Vector<Parser::RuleContext> context;
+ for (auto* rule = &owner_rule; rule; rule = rule->parent_rule())
+ context.append(Parser::rule_context_type_for_rule(rule->type()));
+ context.reverse();
+ return context;
}
-// https://drafts.csswg.org/cssom/#dom-cssgroupingrule-insertrule
-WebIDL::ExceptionOr<u32> CSSGroupingRule::insert_rule(Utf16View rule, u32 index)
+// https://drafts.csswg.org/cssom/#insert-a-css-rule
+NativeRule const* web_css_grouping_rule_parse_rule(void* cell, FlatPtr raw_text, bool* declarations_failed)
{
- // The insertRule(rule, index) method must return the result of invoking insert a CSS rule rule into the child CSS
- // rules at index, with the nested flag set.
+ auto& owner_rule = rule_from_cell(cell);
+ auto text = Utf16String::from_raw(raw_text);
+ auto rule = text.utf16_view();
+
+ // AD-HOC: The spec doesn't include a declared_namespaces parameter, but we need it to handle parsing of namespaced
+ // selectors.
RustNamespaceContext declared_namespaces;
- if (auto* sheet = parent_style_sheet())
+ if (auto* sheet = owner_rule.parent_style_sheet())
declared_namespaces = sheet->declared_namespaces();
- auto& rules = css_rules();
- TRY(rules.insert_a_css_rule(rule, index, CSSRuleList::Nested::Yes, declared_namespaces));
-
- if (auto* sheet = parent_style_sheet()) {
- sheet->invalidate_image_resource_registration();
- if (auto* function = Parser::ValueParserFFI::rust_rule_containing_function(native_rule().handle()))
- record_style_rule_declarations_changed(RustRule { function }, *sheet);
- else
- record_style_rule_inserted(rules.native_rules().at(index), *sheet);
- sheet->invalidate_owners();
- sheet->synchronize_fonts_after_rule_change();
+
+ // 3. Set new rule to the results of performing parse a CSS rule on argument rule.
+ Parser::ParsingParams parsing_params {};
+ parsing_params.rule_context = rule_context(owner_rule);
+ parsing_params.declared_namespaces = declared_namespaces;
+ auto new_rule = parse_css_rule(parsing_params, rule, true);
+ if (!new_rule.has_value()) {
+ auto trimmed_rule = rule.trim(" \t\n\f\r"sv, TrimMode::Left);
+ if (trimmed_rule.starts_with("@import"sv) || trimmed_rule.starts_with("@namespace"sv)) {
+ auto top_level_params = parsing_params;
+ top_level_params.rule_context.clear();
+ new_rule = parse_css_rule(top_level_params, rule);
+ }
}
- return index;
+
+ // 4. If new rule is a syntax error, and nested is set, perform the following substeps:
+ if (!new_rule.has_value()) {
+ // - Set declarations to the results of performing parse a CSS declaration block, on argument rule.
+ auto declarations = parse_css_property_declaration_block(parsing_params, rule);
+
+ // - If declarations is empty, throw a SyntaxError exception.
+ if (declarations.is_empty()) {
+ *declarations_failed = true;
+ return nullptr;
+ }
+
+ // - Otherwise, set new rule to a new nested declarations rule with declarations as it contents.
+ new_rule = RustRule { declarations };
+ }
+
+ return Parser::ValueParserFFI::rust_rule_retain(new_rule->handle());
}
-WebIDL::ExceptionOr<void> CSSGroupingRule::delete_rule(u32 index)
+void web_css_grouping_rule_inserted(void* cell, NativeRule const* inserted)
{
- auto removed_rule = TRY(css_rules().remove_a_css_rule(index));
- if (auto* sheet = parent_style_sheet()) {
- if (auto* function = Parser::ValueParserFFI::rust_rule_containing_function(native_rule().handle()))
- record_style_rule_declarations_changed(RustRule { function }, *sheet);
- else
- record_style_rule_removed(*sheet, removed_rule);
- sheet->invalidate_owners();
- sheet->synchronize_fonts_after_rule_change();
- }
- return {};
+ auto& rule = rule_from_cell(cell);
+ auto* sheet = rule.parent_style_sheet();
+ if (!sheet)
+ return;
+ sheet->invalidate_image_resource_registration();
+ if (auto* function = Parser::ValueParserFFI::rust_rule_containing_function(rule.native_rule().handle()))
+ record_style_rule_declarations_changed(RustRule { function }, *sheet);
+ else
+ record_style_rule_inserted(RustRule { inserted }, *sheet);
+ sheet->invalidate_owners();
+ sheet->synchronize_fonts_after_rule_change();
}
-void CSSGroupingRule::set_parent_style_sheet(StyleSheetState* parent_style_sheet)
+void web_css_grouping_rule_removed(void* cell, NativeRule const* removed)
{
- CSSRule::set_parent_style_sheet(parent_style_sheet);
- if (m_rules)
- m_rules->set_parent_style_sheet(parent_style_sheet);
+ auto& rule = rule_from_cell(cell);
+ auto* sheet = rule.parent_style_sheet();
+ if (!sheet)
+ return;
+ if (auto* function = Parser::ValueParserFFI::rust_rule_containing_function(rule.native_rule().handle()))
+ record_style_rule_declarations_changed(RustRule { function }, *sheet);
+ else
+ record_style_rule_removed(*sheet, RustRule { removed });
+ sheet->invalidate_owners();
+ sheet->synchronize_fonts_after_rule_change();
}
}
diff --git a/Libraries/LibWeb/CSS/CSSGroupingRule.h b/Libraries/LibWeb/CSS/CSSGroupingRule.h
index 4e713068e20..e9a066df3de 100644
--- a/Libraries/LibWeb/CSS/CSSGroupingRule.h
+++ b/Libraries/LibWeb/CSS/CSSGroupingRule.h
@@ -6,8 +6,7 @@
#pragma once
-#include <AK/Function.h>
-#include <AK/NonnullRefPtr.h>
+#include <LibWeb/Bindings/CSSGroupingRule.h>
#include <LibWeb/CSS/CSSRule.h>
#include <LibWeb/CSS/CSSRuleList.h>
#include <LibWeb/Forward.h>
@@ -15,29 +14,28 @@
namespace Web::CSS {
class CSSGroupingRule : public CSSRule {
- WEB_WRAPPABLE(CSSGroupingRule, CSSRule);
+ WEB_RUST_INTERFACE(CSSGroupingRule, css_grouping_rule)
public:
- virtual ~CSSGroupingRule() = default;
-
- CSSRuleList const& css_rules() const { return ensure_rules(); }
- CSSRuleList& css_rules() { return ensure_rules(); }
- CSSRuleList* css_rules_for_bindings() { return &ensure_rules(); }
- WebIDL::ExceptionOr<u32> insert_rule(Utf16View rule, u32 index = 0);
- WebIDL::ExceptionOr<void> delete_rule(u32 index);
-
- virtual void set_parent_style_sheet(StyleSheetState*) override;
-
-protected:
- // NB: A rule given no list, as a style rule is, makes its list when it is first read.
- CSSGroupingRule(GC::Ptr<CSSRuleList>, RustRule);
- virtual void visit_edges(GC::Cell::Visitor&) override;
- virtual void clear_caches() override;
-
-private:
- CSSRuleList& ensure_rules() const;
-
- mutable GC::Ptr<CSSRuleList> m_rules;
+ CSSRuleList& css_rules() const;
};
+template<>
+inline bool CSSRule::fast_is<CSSGroupingRule>() const
+{
+ switch (type()) {
+ case Type::Style:
+ case Type::Media:
+ case Type::Supports:
+ case Type::Container:
+ case Type::Scope:
+ case Type::LayerBlock:
+ case Type::Page:
+ case Type::Function:
+ return true;
+ default:
+ return false;
+ }
+}
+
}
diff --git a/Libraries/LibWeb/CSS/CSSGroupingRule.idl b/Libraries/LibWeb/CSS/CSSGroupingRule.idl
index bdfef838184..dd1c80a3bea 100644
--- a/Libraries/LibWeb/CSS/CSSGroupingRule.idl
+++ b/Libraries/LibWeb/CSS/CSSGroupingRule.idl
@@ -1,7 +1,7 @@
// https://drafts.csswg.org/cssom/#the-cssgroupingrule-interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSGroupingRule : CSSRule {
- [SameObject, ImplementedAs=css_rules_for_bindings] readonly attribute CSSRuleList cssRules;
+ [SameObject] readonly attribute CSSRuleList cssRules;
unsigned long insertRule(CSSOMString rule, optional unsigned long index = 0);
undefined deleteRule(unsigned long index);
};
diff --git a/Libraries/LibWeb/CSS/CSSImportRule.cpp b/Libraries/LibWeb/CSS/CSSImportRule.cpp
index 5c4148566ea..e71fffd1802 100644
--- a/Libraries/LibWeb/CSS/CSSImportRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSImportRule.cpp
@@ -7,201 +7,16 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/Utf16StringBuilder.h>
#include <LibWeb/CSS/CSSImportRule.h>
-#include <LibWeb/CSS/Supports.h>
-#include <LibWeb/Dump.h>
namespace Web::CSS {
-GC_DEFINE_ALLOCATOR(CSSImportRule);
+// NB: Implemented in Libraries/LibWeb/Bindings/Rust/src/css/exports.rs.
+extern "C" void* web_css_import_rule_import(void* rule);
-GC::Ref<CSSImportRule> CSSImportRule::create(StyleSheetImport& import)
+StyleSheetImport& CSSImportRule::import() const
{
- return GC::Heap::the().allocate<CSSImportRule>(import);
-}
-
-CSSImportRule::CSSImportRule(StyleSheetImport& import)
- : CSSRule(import.native_rule())
- , m_rule(native_rule().payload().import_rule)
- , m_import(import)
- , m_scope(native_rule().payload().scope ? RefPtr<RustScopeSelectors> { RustScopeSelectors::create(native_rule().payload().scope) } : nullptr)
- , m_supports(m_rule.supports())
-{
- m_import->set_cssom_rule(*this);
- CSSRule::set_parent_style_sheet(import.parent_style_sheet());
-}
-
-Optional<Utf16FlyString> CSSImportRule::internal_layer_name() const
-{
- if (!m_rule.layer().has_value())
- return {};
- return m_layer_internal.ensure([&] {
- auto name = native_rule().internal_layer_name().release_value();
- return Utf16FlyString::from_utf16(name.utf16_view());
- });
-}
-
-CSSImportRule::~CSSImportRule() = default;
-
-URL const& CSSImportRule::url() const
-{
- return m_import->url();
-}
-
-GC::Ref<MediaList> CSSImportRule::media() const
-{
- return m_import->media();
-}
-
-void CSSImportRule::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- m_import->visit_edges(visitor);
-}
-
-void CSSImportRule::set_parent_style_sheet(StyleSheetState* parent_style_sheet)
-{
- Base::set_parent_style_sheet(parent_style_sheet);
- if (m_import->parent_style_sheet() != parent_style_sheet)
- m_import->set_parent_style_sheet(parent_style_sheet);
-}
-
-// https://www.w3.org/TR/cssom/#serialize-a-css-rule
-Utf16String CSSImportRule::serialized() const
-{
- Utf16StringBuilder builder;
- // The result of concatenating the following:
-
- // 1. The string "@import" followed by a single SPACE (U+0020).
- builder.append_ascii("@import "sv);
-
- // 2. The result of performing serialize a URL on the rule’s location.
- builder.append(url().to_utf16_string());
-
- // AD-HOC: Serialize the rule's layer if it exists.
- if (auto layer = m_rule.layer(); layer.has_value()) {
- if (layer->is_empty()) {
- builder.append_ascii(" layer"sv);
- } else {
- builder.append_ascii(" layer("sv);
- builder.append(*layer);
- builder.append_ascii(')');
- }
- }
-
- // AD-HOC: Serialize the rule's import scope if it exists.
- if (has_scope()) {
- builder.append_ascii(" scope"sv);
- if (m_scope->start().has_value() || m_scope->end().has_value()) {
- builder.append_ascii('(');
- if (m_scope->start().has_value()) {
- if (m_scope->end().has_value())
- builder.appendff("({})", serialize_a_group_of_selectors(*m_scope->start()));
- else
- builder.append(serialize_a_group_of_selectors(*m_scope->start()));
- }
- if (m_scope->end().has_value()) {
- if (m_scope->start().has_value())
- builder.append_ascii(' ');
- builder.appendff("to ({})", serialize_a_group_of_selectors(*m_scope->end()));
- }
- builder.append_ascii(')');
- }
- }
-
- // AD-HOC: Serialize the rule's supports condition if it exists.
- // This isn't currently specified, but major browsers include this in their serialization of import rules
- if (m_supports.has_value()) {
- builder.append_ascii(" supports("sv);
- builder.append(serialize_supports_condition(*m_supports));
- builder.append_ascii(')');
- }
-
- // 3. If the rule’s associated media list is not empty, a single SPACE (U+0020) followed by the result of performing serialize a media query list on the media list.
- if (m_import->native_media_list().length() != 0) {
- builder.append_ascii(' ');
- builder.append(m_import->native_media_list().media_text());
- }
-
- // 4. The string ";", i.e., SEMICOLON (U+003B).
- builder.append_ascii(';');
-
- return builder.to_string();
-}
-
-// https://drafts.csswg.org/cssom/#dom-cssimportrule-layername
-Optional<Utf16FlyString> CSSImportRule::layer_name() const
-{
- // The layerName attribute must return the layer name declared in the at-rule itself, or an empty string if the
- // layer is anonymous, or null if the at-rule does not declare a layer.
- auto layer = m_rule.layer();
- if (!layer.has_value())
- return {};
- return Utf16FlyString::from_utf16(*layer);
-}
-
-// https://drafts.csswg.org/cssom/#dom-cssimportrule-supportstext
-Optional<Utf16String> CSSImportRule::supports_text() const
-{
- // The supportsText attribute must return the <supports-condition> declared in the at-rule itself, or null if the
- // at-rule does not declare a supports condition.
- if (!m_supports.has_value())
- return {};
- return serialize_supports_condition(*m_supports);
-}
-
-bool CSSImportRule::matches() const
-{
- if (m_supports.has_value() && !supports_condition_matches(*m_supports))
- return false;
- return m_import->native_media_list().matches();
-}
-
-void CSSImportRule::dump(StringBuilder& builder, int indent_levels) const
-{
- Base::dump(builder, indent_levels);
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Document URL: {}\n", url().to_string());
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Loading state: {}\n", StyleSheetState::loading_state_name(m_import->loading_state()));
-
- if (auto layer = layer_name(); layer.has_value()) {
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Layer: `{}` (internal: `{}`)\n", *layer, *internal_layer_name());
- }
-
- if (m_import->native_media_list().length() != 0)
- m_import->native_media_list().dump(builder, indent_levels + 1);
-
- if (m_supports.has_value())
- dump_supports_condition(builder, *m_supports, indent_levels + 1);
-
- if (has_scope()) {
- dump_indent(builder, indent_levels + 1);
- builder.append("Scope:\n"sv);
-
- dump_indent(builder, indent_levels + 2);
- if (m_scope->start().has_value())
- builder.appendff("Start selectors: {}\n", serialize_a_group_of_selectors(*m_scope->start()));
- else
- builder.append("Start selectors: <none>\n"sv);
-
- dump_indent(builder, indent_levels + 2);
- if (m_scope->end().has_value())
- builder.appendff("End selectors: {}\n", serialize_a_group_of_selectors(*m_scope->end()));
- else
- builder.append("End selectors: <none>\n"sv);
- }
-
- if (auto* sheet = loaded_style_sheet()) {
- dump_sheet(builder, *sheet, indent_levels + 1);
- } else {
- dump_indent(builder, indent_levels + 1);
- builder.append("Style sheet not loaded\n"sv);
- }
+ return static_cast<StyleSheetImportCell*>(static_cast<GC::Cell*>(web_css_import_rule_import(const_cast<CSSImportRule*>(this))))->import();
}
}
diff --git a/Libraries/LibWeb/CSS/CSSImportRule.h b/Libraries/LibWeb/CSS/CSSImportRule.h
index 966c76bca17..aec9839b010 100644
--- a/Libraries/LibWeb/CSS/CSSImportRule.h
+++ b/Libraries/LibWeb/CSS/CSSImportRule.h
@@ -8,64 +8,20 @@
#pragma once
-#include <AK/Utf16String.h>
+#include <LibWeb/Bindings/CSSImportRule.h>
#include <LibWeb/CSS/CSSRule.h>
-#include <LibWeb/CSS/RustImportRule.h>
-#include <LibWeb/CSS/RustScopeSelectors.h>
-#include <LibWeb/CSS/Selector.h>
#include <LibWeb/CSS/StyleSheetImport.h>
-#include <LibWeb/CSS/URL.h>
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
namespace Web::CSS {
class WEB_API CSSImportRule final : public CSSRule {
- WEB_WRAPPABLE(CSSImportRule, CSSRule);
- GC_DECLARE_ALLOCATOR(CSSImportRule);
+ WEB_RUST_INTERFACE(CSSImportRule, css_import_rule)
public:
- [[nodiscard]] static GC::Ref<CSSImportRule> create(StyleSheetImport&);
-
- virtual ~CSSImportRule() override;
-
- URL const& url() const;
- Utf16String const& href() const { return url().url(); }
- Utf16String href_for_bindings() const { return href(); }
-
- StyleSheetState* loaded_style_sheet() { return m_import->loaded_style_sheet(); }
- StyleSheetState const* loaded_style_sheet() const { return m_import->loaded_style_sheet(); }
- GC::Ref<MediaList> media() const;
- CSSStyleSheet* style_sheet_for_bindings()
- {
- auto* sheet = loaded_style_sheet();
- return sheet ? &sheet->cssom_sheet() : nullptr;
- }
- StyleSheetImport& import() const { return *m_import; }
-
- Optional<Utf16FlyString> layer_name() const;
- Optional<Utf16String> supports_text() const;
-
- bool matches() const;
- bool has_scope() const { return m_scope; }
-
- Optional<Utf16FlyString> internal_layer_name() const;
-
-private:
- explicit CSSImportRule(StyleSheetImport&);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
-
- virtual void set_parent_style_sheet(StyleSheetState*) override;
-
- virtual Utf16String serialized() const override;
-
- RustImportRule m_rule;
- NonnullRefPtr<StyleSheetImport> m_import;
- mutable Optional<Utf16FlyString> m_layer_internal;
- RefPtr<RustScopeSelectors> m_scope;
- Optional<RustQueryHandle> m_supports;
+ StyleSheetState* loaded_style_sheet() const { return import().loaded_style_sheet(); }
+ StyleSheetImport& import() const;
};
template<>
diff --git a/Libraries/LibWeb/CSS/CSSImportRule.idl b/Libraries/LibWeb/CSS/CSSImportRule.idl
index 9753dffcd3b..3a76d1855cf 100644
--- a/Libraries/LibWeb/CSS/CSSImportRule.idl
+++ b/Libraries/LibWeb/CSS/CSSImportRule.idl
@@ -1,9 +1,9 @@
// https://drafts.csswg.org/cssom/#the-cssimportrule-interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSImportRule : CSSRule {
- [ImplementedAs=href_for_bindings] readonly attribute USVString href;
+ readonly attribute USVString href;
[SameObject, PutForwards=mediaText] readonly attribute MediaList media;
- [SameObject, ImplementedAs=style_sheet_for_bindings] readonly attribute CSSStyleSheet? styleSheet;
+ [SameObject] readonly attribute CSSStyleSheet? styleSheet;
readonly attribute CSSOMString? layerName;
readonly attribute CSSOMString? supportsText;
};
diff --git a/Libraries/LibWeb/CSS/CSSKeyframeRule.cpp b/Libraries/LibWeb/CSS/CSSKeyframeRule.cpp
deleted file mode 100644
index 1ff4fa7f8d8..00000000000
--- a/Libraries/LibWeb/CSS/CSSKeyframeRule.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (c) 2023, Ali Mohammad Pur <[email protected]>
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSKeyframeRule.h"
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/ExternalMemory.h>
-#include <LibWeb/CSS/CSSRuleList.h>
-#include <LibWeb/Dump.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSKeyframeRule);
-
-GC::Ref<CSSKeyframeRule> CSSKeyframeRule::create(RustRule rule)
-{
- return GC::Heap::the().allocate<CSSKeyframeRule>(move(rule));
-}
-
-CSSKeyframeRule::CSSKeyframeRule(RustRule rule)
- : CSSRule(move(rule))
- , m_frame(*native_rule().payload().keyframe)
- , m_declarations(Parser::ValueParserFFI::rust_keyframe_declarations(&m_frame))
-{
-}
-
-size_t CSSKeyframeRule::external_memory_size() const
-{
- return JS::saturating_add_external_memory_size(Base::external_memory_size(), m_declarations.external_memory_size());
-}
-
-GC::Ref<CSSStyleProperties> CSSKeyframeRule::style() const
-{
- if (!m_style) {
- m_style = CSSStyleProperties::create(m_declarations.retain());
- m_style->set_parent_rule(const_cast<CSSKeyframeRule&>(*this));
- }
- return *m_style;
-}
-
-void CSSKeyframeRule::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_style);
-}
-
-Utf16String CSSKeyframeRule::serialized() const
-{
- Utf16StringBuilder builder;
- builder.appendff("{} {{ {} }}", key_text(), style()->serialized());
- return builder.to_string();
-}
-
-void CSSKeyframeRule::dump(StringBuilder& builder, int indent_levels) const
-{
- Base::dump(builder, indent_levels);
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Keys: {}\n"sv, key_text());
- dump_style_properties(builder, style(), indent_levels + 1);
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSKeyframeRule.h b/Libraries/LibWeb/CSS/CSSKeyframeRule.h
deleted file mode 100644
index d769bbbebd9..00000000000
--- a/Libraries/LibWeb/CSS/CSSKeyframeRule.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (c) 2023, Ali Mohammad Pur <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/NonnullRefPtr.h>
-#include <AK/Utf16String.h>
-#include <AK/Utf16View.h>
-#include <LibWeb/CSS/CSSRule.h>
-#include <LibWeb/CSS/CSSStyleProperties.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-// https://drafts.csswg.org/css-animations/#interface-csskeyframerule
-class CSSKeyframeRule final : public CSSRule {
- WEB_WRAPPABLE(CSSKeyframeRule, CSSRule);
- GC_DECLARE_ALLOCATOR(CSSKeyframeRule);
-
-public:
- static GC::Ref<CSSKeyframeRule> create(RustRule);
-
- virtual ~CSSKeyframeRule() = default;
-
- GC::Ref<CSSStyleProperties> style() const;
-
- Utf16String key_text() const
- {
- Utf16StringBuilder builder;
- auto keys = Parser::ValueParserFFI::rust_keyframe_keys(&m_frame);
- for (auto key : ReadonlySpan<double> { keys.values, keys.count }) {
- if (!builder.is_empty())
- builder.append(", "sv);
- builder.appendff("{}%"sv, key);
- }
-
- return builder.to_string();
- }
-
- void set_key_text(Utf16View)
- {
- dbgln("FIXME: CSSKeyframeRule::set_key_text is not implemented");
- }
-
-private:
- CSSKeyframeRule(RustRule);
-
- virtual size_t external_memory_size() const override;
- virtual void visit_edges(Visitor&) override;
- virtual Utf16String serialized() const override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
-
- Parser::ValueParserFFI::FfiKeyframe const& m_frame;
- RustDeclarationBlock m_declarations;
- mutable GC::Ptr<CSSStyleProperties> m_style;
-};
-
-template<>
-inline bool CSSRule::fast_is<CSSKeyframeRule>() const { return type() == CSSRule::Type::Keyframe; }
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSKeyframeRule.idl b/Libraries/LibWeb/CSS/CSSKeyframeRule.idl
index 3f1b1060bc3..0108709e4be 100644
--- a/Libraries/LibWeb/CSS/CSSKeyframeRule.idl
+++ b/Libraries/LibWeb/CSS/CSSKeyframeRule.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/css-animations-1/#interface-csskeyframerule-idl
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSKeyframeRule : CSSRule {
attribute CSSOMString keyText;
[SameObject, PutForwards=cssText] readonly attribute CSSStyleProperties style;
diff --git a/Libraries/LibWeb/CSS/CSSKeyframesRule.cpp b/Libraries/LibWeb/CSS/CSSKeyframesRule.cpp
index 68ece9c983c..aac13dd82b7 100644
--- a/Libraries/LibWeb/CSS/CSSKeyframesRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSKeyframesRule.cpp
@@ -6,163 +6,54 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibGC/Heap.h>
#include <LibWeb/CSS/CSSKeyframesRule.h>
-#include <LibWeb/CSS/CSSRuleList.h>
#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/Percentage.h>
#include <LibWeb/CSS/StyleEngineInput.h>
#include <LibWeb/CSS/StyleSheetState.h>
-#include <LibWeb/Dump.h>
namespace Web::CSS {
-GC_DEFINE_ALLOCATOR(CSSKeyframesRule);
+using Parser::ValueParserFFI::NativeRule;
-GC::Ref<CSSKeyframesRule> CSSKeyframesRule::create(RustRule rule)
-{
- return GC::Heap::the().allocate<CSSKeyframesRule>(move(rule));
-}
-
-CSSKeyframesRule::CSSKeyframesRule(RustRule rule)
- : CSSRule(move(rule))
-{
- auto name = native_rule().payload().name;
- m_name = Utf16FlyString::from_utf16({ reinterpret_cast<char16_t const*>(name.utf16), name.length });
-}
-
-GC::Ref<CSSRuleList> CSSKeyframesRule::css_rules() const
-{
- if (!m_rules) {
- RustRuleList rules { Parser::ValueParserFFI::rust_rule_list_retain(Parser::ValueParserFFI::rust_rule_children(native_rule().handle())) };
- m_rules = CSSRuleList::create(move(rules), nullptr);
- m_rules->set_owner_rule(*const_cast<CSSKeyframesRule*>(this));
- m_rules->set_parent_style_sheet(const_cast<CSSKeyframesRule*>(this)->parent_style_sheet());
- }
- return *m_rules;
+// NB: What the implementation of CSSKeyframesRule in Rust asks of the C++ code of LibWeb.
+extern "C" {
+void web_css_keyframes_rule_changed(void* rule);
+void web_css_keyframes_rule_will_rename(void* rule);
+void web_css_keyframes_rule_renamed(void* rule);
+NativeRule const* web_css_parse_keyframe_rule(FlatPtr text);
}
-void CSSKeyframesRule::set_parent_style_sheet(StyleSheetState* parent_style_sheet)
+static CSSRule& rule_from_cell(void* cell)
{
- CSSRule::set_parent_style_sheet(parent_style_sheet);
- if (m_rules) {
- m_rules->set_parent_style_sheet(parent_style_sheet);
- }
+ return *static_cast<CSSRule*>(cell);
}
-void CSSKeyframesRule::visit_edges(Visitor& visitor)
+void web_css_keyframes_rule_changed(void* cell)
{
- Base::visit_edges(visitor);
- visitor.visit(m_rules);
+ auto& rule = rule_from_cell(cell);
+ record_style_rule_declarations_changed(rule);
+ rule.parent_style_sheet()->invalidate_owners();
}
-Utf16String CSSKeyframesRule::serialized() const
+void web_css_keyframes_rule_will_rename(void* cell)
{
- Utf16StringBuilder builder;
-
- builder.append("@keyframes "sv);
-
- // https://drafts.csswg.org/css-animations-1/#keyframes
- // When serialized, the value is serialized as an <ident> unless it’s a disallowed keyword, in which case
- // it’s serialized as a <string>.
- if (!is_valid_animation_name_custom_ident(m_name))
- serialize_a_string(builder, m_name);
- else
- serialize_an_identifier(builder, m_name);
-
- builder.append_ascii(" { "sv);
- for (auto const& keyframe : *css_rules()) {
- builder.append(keyframe->serialized());
- builder.append_ascii(' ');
- }
- builder.append_ascii('}');
- return builder.to_string();
+ record_style_rule_removed(rule_from_cell(cell));
}
-WebIDL::UnsignedLong CSSKeyframesRule::length() const
+void web_css_keyframes_rule_renamed(void* cell)
{
- return Parser::ValueParserFFI::rust_rule_list_count(Parser::ValueParserFFI::rust_rule_children(native_rule().handle()));
-}
-
-GC::Ptr<CSSKeyframeRule> CSSKeyframesRule::item(size_t index) const
-{
- if (index >= length())
- return nullptr;
- return as_if<CSSKeyframeRule>(css_rules()->item(index));
-}
-
-void CSSKeyframesRule::set_name(Utf16String const& name)
-{
- Utf16FlyString new_name { name };
- if (new_name == m_name)
- return;
-
- record_style_rule_removed(*this);
- m_name = move(new_name);
- Parser::ValueParserFFI::rust_keyframes_set_name(native_rule().handle(), Parser::ffi_utf16_view(name));
- record_style_rule_inserted(*this);
-
- if (auto* sheet = parent_style_sheet())
+ auto& rule = rule_from_cell(cell);
+ record_style_rule_inserted(rule);
+ if (auto* sheet = rule.parent_style_sheet())
sheet->invalidate_owners();
}
-// https://drafts.csswg.org/css-animations/#interface-csskeyframesrule-appendrule
-void CSSKeyframesRule::append_rule(Utf16String const& rule)
+NativeRule const* web_css_parse_keyframe_rule(FlatPtr text)
{
- // The appendRule method appends the passed CSSKeyframeRule at the end of the keyframes rule.
- auto parsed_rule = Parser::parse_keyframe_rule(Parser::ParsingParams {}, rule);
-
+ auto parsed_rule = Parser::parse_keyframe_rule(Parser::ParsingParams {}, Utf16String::from_raw(text));
if (!parsed_rule.has_value())
- return;
-
- RustRuleList rules { Parser::ValueParserFFI::rust_rule_list_retain(Parser::ValueParserFFI::rust_rule_children(native_rule().handle())) };
- rules.insert(rules.size(), *parsed_rule);
-
- if (auto* sheet = parent_style_sheet()) {
- record_style_rule_declarations_changed(*this);
- sheet->invalidate_owners();
- }
-}
-
-// https://drafts.csswg.org/css-animations-1/#interface-csskeyframesrule-deleterule
-void CSSKeyframesRule::delete_rule(Utf16String const& select)
-{
- // The deleteRule method deletes the last declared CSSKeyframeRule matching the specified keyframe selector. If no
- // matching rule exists, the method does nothing.
- auto index = Parser::ValueParserFFI::rust_keyframes_find_rule(native_rule().handle(), Parser::ffi_utf16_view(select));
- if (index == NumericLimits<size_t>::max())
- return;
-
- if (m_rules)
- MUST(m_rules->remove_a_css_rule(index));
- else
- Parser::ValueParserFFI::rust_rule_list_remove(Parser::ValueParserFFI::rust_rule_children(native_rule().handle()), index);
-
- if (auto* sheet = parent_style_sheet()) {
- record_style_rule_declarations_changed(*this);
- sheet->invalidate_owners();
- }
-}
-
-// https://drafts.csswg.org/css-animations-1/#interface-csskeyframesrule-findrule
-GC::Ptr<CSSKeyframeRule> CSSKeyframesRule::find_rule(Utf16String const& select)
-{
- // The findRule returns the last declared CSSKeyframeRule matching the specified keyframe selector. If no matching
- // rule exists, the method does nothing.
- auto index = Parser::ValueParserFFI::rust_keyframes_find_rule(native_rule().handle(), Parser::ffi_utf16_view(select));
- return index == NumericLimits<size_t>::max() ? nullptr : item(index);
-}
-
-void CSSKeyframesRule::dump(StringBuilder& builder, int indent_levels) const
-{
- Base::dump(builder, indent_levels);
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Name: {}\n", name());
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Keyframes ({}):\n", length());
- for (auto& rule : *css_rules())
- dump_rule(builder, rule, indent_levels + 2);
+ return nullptr;
+ return Parser::ValueParserFFI::rust_rule_retain(parsed_rule->handle());
}
}
diff --git a/Libraries/LibWeb/CSS/CSSKeyframesRule.h b/Libraries/LibWeb/CSS/CSSKeyframesRule.h
index 433797a0a4e..45e031c706c 100644
--- a/Libraries/LibWeb/CSS/CSSKeyframesRule.h
+++ b/Libraries/LibWeb/CSS/CSSKeyframesRule.h
@@ -7,52 +7,16 @@
#pragma once
-#include <AK/NonnullRefPtr.h>
-#include <AK/Utf16FlyString.h>
#include <LibGC/Ptr.h>
-#include <LibWeb/CSS/CSSKeyframeRule.h>
+#include <LibWeb/Bindings/CSSKeyframesRule.h>
#include <LibWeb/CSS/CSSRule.h>
#include <LibWeb/Forward.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-#include <LibWebCommon/WebIDL/Types.h>
namespace Web::CSS {
// https://drafts.csswg.org/css-animations/#interface-csskeyframesrule
class CSSKeyframesRule final : public CSSRule {
- WEB_WRAPPABLE(CSSKeyframesRule, CSSRule);
- GC_DECLARE_ALLOCATOR(CSSKeyframesRule);
-
-public:
- [[nodiscard]] static GC::Ref<CSSKeyframesRule> create(RustRule);
-
- virtual ~CSSKeyframesRule() = default;
-
- GC::Ref<CSSRuleList> css_rules() const;
- Utf16FlyString const& name() const { return m_name; }
- [[nodiscard]] WebIDL::UnsignedLong length() const;
- GC::Ptr<CSSKeyframeRule> item(size_t index) const;
-
- void set_name(Utf16String const& name);
-
- void append_rule(Utf16String const& rule);
- void delete_rule(Utf16String const& select);
- GC::Ptr<CSSKeyframeRule> find_rule(Utf16String const& select);
-
- // A keyframes rule holds rules without being a grouping rule, so its keyframes have to be handed
- // the sheet themselves. A keyframe edited through the CSSOM reports against the sheet it belongs
- // to, and one that never learned its sheet reports against nothing at all.
- virtual void set_parent_style_sheet(StyleSheetState*) override;
-
-private:
- CSSKeyframesRule(RustRule);
- virtual void visit_edges(Visitor&) override;
-
- virtual Utf16String serialized() const override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
-
- Utf16FlyString m_name;
- mutable GC::Ptr<CSSRuleList> m_rules;
+ WEB_RUST_INTERFACE(CSSKeyframesRule, css_keyframes_rule)
};
template<>
diff --git a/Libraries/LibWeb/CSS/CSSKeyframesRule.idl b/Libraries/LibWeb/CSS/CSSKeyframesRule.idl
index 7d649ed0d44..0e28c3c1722 100644
--- a/Libraries/LibWeb/CSS/CSSKeyframesRule.idl
+++ b/Libraries/LibWeb/CSS/CSSKeyframesRule.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/css-animations-1/#interface-csskeyframesrule
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSKeyframesRule : CSSRule {
attribute CSSOMString name;
readonly attribute CSSRuleList cssRules;
diff --git a/Libraries/LibWeb/CSS/CSSLayerBlockRule.cpp b/Libraries/LibWeb/CSS/CSSLayerBlockRule.cpp
deleted file mode 100644
index da08b313836..00000000000
--- a/Libraries/LibWeb/CSS/CSSLayerBlockRule.cpp
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (c) 2024-2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSLayerBlockRule.h"
-#include <AK/Utf16StringBuilder.h>
-#include <LibWeb/Bindings/CSSLayerBlockRule.h>
-#include <LibWeb/CSS/Serialize.h>
-#include <LibWeb/Dump.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSLayerBlockRule);
-
-GC::Ref<CSSLayerBlockRule> CSSLayerBlockRule::create(RustRule rule, CSSRuleList& rules)
-{
- return GC::Heap::the().allocate<CSSLayerBlockRule>(move(rule), rules);
-}
-
-CSSLayerBlockRule::CSSLayerBlockRule(RustRule rule, CSSRuleList& rules)
- : CSSGroupingRule(rules, move(rule))
- , m_names(*native_rule().payload().layer_names)
-{
- VERIFY(Parser::ValueParserFFI::rust_layer_names_count(&m_names) == 1);
-}
-
-Utf16View CSSLayerBlockRule::name() const
-{
- auto view = Parser::ValueParserFFI::rust_layer_names_at(&m_names, 0);
- return { reinterpret_cast<char16_t const*>(view.utf16), view.length };
-}
-
-Utf16FlyString const& CSSLayerBlockRule::internal_name() const
-{
- return m_name_internal.ensure([&] {
- auto name = native_rule().internal_layer_name().release_value();
- return Utf16FlyString::from_utf16(name.utf16_view());
- });
-}
-
-size_t CSSLayerBlockRule::external_memory_size() const
-{
- return Base::external_memory_size() + Parser::ValueParserFFI::rust_layer_names_external_memory_size(&m_names);
-}
-
-Utf16String CSSLayerBlockRule::serialized() const
-{
- // AD-HOC: No spec yet, so this is based on the @media serialization algorithm.
- Utf16StringBuilder builder;
- builder.append_ascii("@layer"sv);
- if (!name().is_empty())
- builder.appendff(" {}", name());
-
- builder.append_ascii(" {\n"sv);
- // AD-HOC: All modern browsers omit the ending newline if there are no CSS rules, so let's do the same.
- if (css_rules().length() == 0) {
- builder.append_ascii('}');
- return builder.to_string();
- }
-
- for (size_t i = 0; i < css_rules().length(); i++) {
- auto rule = css_rules().item(i);
- if (i != 0)
- builder.append_ascii("\n"sv);
- builder.append_ascii(" "sv);
- builder.append(rule->serialized());
- }
-
- builder.append_ascii("\n}"sv);
-
- return builder.to_string();
-}
-
-void CSSLayerBlockRule::dump(StringBuilder& builder, int indent_levels) const
-{
- Base::dump(builder, indent_levels);
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Name: `{}` (internal `{}`)\n", name(), internal_name());
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Rules ({}):\n", css_rules().length());
- for (auto& rule : css_rules())
- dump_rule(builder, rule, indent_levels + 2);
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSLayerBlockRule.h b/Libraries/LibWeb/CSS/CSSLayerBlockRule.h
deleted file mode 100644
index e583c3253dc..00000000000
--- a/Libraries/LibWeb/CSS/CSSLayerBlockRule.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (c) 2024, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSGroupingRule.h>
-
-namespace Web::CSS {
-
-// https://drafts.csswg.org/css-cascade-5/#the-csslayerblockrule-interface
-class CSSLayerBlockRule final : public CSSGroupingRule {
- WEB_WRAPPABLE(CSSLayerBlockRule, CSSGroupingRule);
- GC_DECLARE_ALLOCATOR(CSSLayerBlockRule);
-
-public:
- [[nodiscard]] static GC::Ref<CSSLayerBlockRule> create(RustRule, CSSRuleList&);
-
- virtual ~CSSLayerBlockRule() = default;
-
- Utf16View name() const;
- Utf16FlyString const& internal_name() const;
-
-private:
- CSSLayerBlockRule(RustRule, CSSRuleList&);
-
- virtual Utf16String serialized() const override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
- virtual size_t external_memory_size() const override;
-
- Parser::ValueParserFFI::LayerNames const& m_names;
- mutable Optional<Utf16FlyString> m_name_internal;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSLayerBlockRule.idl b/Libraries/LibWeb/CSS/CSSLayerBlockRule.idl
index b36263060a2..3d3e685af7a 100644
--- a/Libraries/LibWeb/CSS/CSSLayerBlockRule.idl
+++ b/Libraries/LibWeb/CSS/CSSLayerBlockRule.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/css-cascade-5/#the-csslayerblockrule-interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSLayerBlockRule : CSSGroupingRule {
readonly attribute CSSOMString name;
};
diff --git a/Libraries/LibWeb/CSS/CSSLayerStatementRule.cpp b/Libraries/LibWeb/CSS/CSSLayerStatementRule.cpp
deleted file mode 100644
index 7bc9da0e706..00000000000
--- a/Libraries/LibWeb/CSS/CSSLayerStatementRule.cpp
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (c) 2024, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSLayerStatementRule.h"
-#include <AK/Utf16StringBuilder.h>
-#include <LibWeb/Bindings/CSSLayerStatementRule.h>
-#include <LibWeb/CSS/CSSLayerBlockRule.h>
-#include <LibWeb/Dump.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSLayerStatementRule);
-
-GC::Ref<CSSLayerStatementRule> CSSLayerStatementRule::create(RustRule rule)
-{
- return GC::Heap::the().allocate<CSSLayerStatementRule>(move(rule));
-}
-
-CSSLayerStatementRule::CSSLayerStatementRule(RustRule rule)
- : CSSRule(move(rule))
- , m_names(*native_rule().payload().layer_names)
-{
-}
-
-Vector<Utf16String> CSSLayerStatementRule::name_list() const
-{
- Vector<Utf16String> names;
- auto count = Parser::ValueParserFFI::rust_layer_names_count(&m_names);
- names.ensure_capacity(count);
- for (size_t index = 0; index < count; ++index)
- names.unchecked_append(Utf16String::from_utf16(name_at(index)));
- return names;
-}
-
-Utf16View CSSLayerStatementRule::name_at(size_t index) const
-{
- auto view = Parser::ValueParserFFI::rust_layer_names_at(&m_names, index);
- return { reinterpret_cast<char16_t const*>(view.utf16), view.length };
-}
-
-size_t CSSLayerStatementRule::external_memory_size() const
-{
- return Base::external_memory_size() + Parser::ValueParserFFI::rust_layer_names_external_memory_size(&m_names);
-}
-
-Utf16String CSSLayerStatementRule::serialized() const
-{
- // AD-HOC: No spec yet.
- Utf16StringBuilder builder;
- builder.append_ascii("@layer "sv);
- auto count = Parser::ValueParserFFI::rust_layer_names_count(&m_names);
- for (size_t i = 0; i < count; ++i) {
- if (i > 0)
- builder.append_ascii(", "sv);
- builder.append(name_at(i));
- }
- builder.append_ascii(';');
- return builder.to_string();
-}
-
-void CSSLayerStatementRule::dump(StringBuilder& builder, int indent_levels) const
-{
- Base::dump(builder, indent_levels);
-
- dump_indent(builder, indent_levels + 1);
- builder.append("Names: "sv);
- builder.join(", "sv, name_list());
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSLayerStatementRule.h b/Libraries/LibWeb/CSS/CSSLayerStatementRule.h
deleted file mode 100644
index 18eea54c3a0..00000000000
--- a/Libraries/LibWeb/CSS/CSSLayerStatementRule.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (c) 2024, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSRule.h>
-
-namespace Web::CSS {
-
-// https://drafts.csswg.org/css-cascade-5/#the-csslayerstatementrule-interface
-class CSSLayerStatementRule final : public CSSRule {
- WEB_WRAPPABLE(CSSLayerStatementRule, CSSRule);
- GC_DECLARE_ALLOCATOR(CSSLayerStatementRule);
-
-public:
- [[nodiscard]] static GC::Ref<CSSLayerStatementRule> create(RustRule);
-
- virtual ~CSSLayerStatementRule() = default;
-
- // FIXME: Should be FrozenArray
- Vector<Utf16String> name_list() const;
-
-private:
- CSSLayerStatementRule(RustRule);
-
- virtual Utf16String serialized() const override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
- virtual size_t external_memory_size() const override;
-
- Utf16View name_at(size_t) const;
- Parser::ValueParserFFI::LayerNames const& m_names;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSLayerStatementRule.idl b/Libraries/LibWeb/CSS/CSSLayerStatementRule.idl
index ba8f8ef9014..67600067c88 100644
--- a/Libraries/LibWeb/CSS/CSSLayerStatementRule.idl
+++ b/Libraries/LibWeb/CSS/CSSLayerStatementRule.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/css-cascade-5/#the-csslayerstatementrule-interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSLayerStatementRule : CSSRule {
readonly attribute FrozenArray<CSSOMString> nameList;
};
diff --git a/Libraries/LibWeb/CSS/CSSMarginRule.cpp b/Libraries/LibWeb/CSS/CSSMarginRule.cpp
deleted file mode 100644
index 848f2bbc191..00000000000
--- a/Libraries/LibWeb/CSS/CSSMarginRule.cpp
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/ExternalMemory.h>
-#include <LibWeb/CSS/CSSMarginRule.h>
-#include <LibWeb/CSS/CSSStyleProperties.h>
-#include <LibWeb/Dump.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSMarginRule);
-
-GC::Ref<CSSMarginRule> CSSMarginRule::create(RustRule rule)
-{
- return GC::Heap::the().allocate<CSSMarginRule>(move(rule));
-}
-
-CSSMarginRule::CSSMarginRule(RustRule rule)
- : CSSRule(move(rule))
- , m_name([&] {
- auto name = native_rule().payload().name;
- auto view = name.latin1 ? Utf16View::from_latin1({ name.latin1, name.length }, false) : Utf16View { reinterpret_cast<char16_t const*>(name.utf16), name.length };
- return Utf16FlyString::from_utf16(view);
- }())
- , m_declarations(Parser::ValueParserFFI::rust_declaration_block_retain(native_rule().payload().declarations))
-{
-}
-
-size_t CSSMarginRule::external_memory_size() const
-{
- return JS::saturating_add_external_memory_size(Base::external_memory_size(), m_declarations.external_memory_size());
-}
-
-GC::Ref<CSSStyleProperties> CSSMarginRule::style() const
-{
- if (!m_style) {
- m_style = CSSStyleProperties::create(m_declarations.retain());
- m_style->set_parent_rule(const_cast<CSSMarginRule&>(*this));
- }
- return *m_style;
-}
-
-Utf16String CSSMarginRule::serialized() const
-{
- // AD-HOC: There is currently no spec for serializing CSSMarginRule.
- Utf16StringBuilder builder;
- builder.appendff("@{} {{ ", m_name);
- if (!m_declarations.is_empty()) {
- builder.append(style()->serialized());
- builder.append_ascii(' ');
- }
- builder.append_ascii('}');
-
- return builder.to_string();
-}
-
-void CSSMarginRule::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_style);
-}
-
-void CSSMarginRule::dump(StringBuilder& builder, int indent_levels) const
-{
- Base::dump(builder, indent_levels);
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Name: {}\n", name());
- dump_style_properties(builder, style(), indent_levels + 1);
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMarginRule.h b/Libraries/LibWeb/CSS/CSSMarginRule.h
deleted file mode 100644
index 7eb6a825b9e..00000000000
--- a/Libraries/LibWeb/CSS/CSSMarginRule.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16View.h>
-#include <LibWeb/CSS/CSSRule.h>
-#include <LibWeb/CSS/RustDeclarationBlock.h>
-
-namespace Web::CSS {
-
-// https://drafts.csswg.org/cssom/#cssmarginrule
-class CSSMarginRule final : public CSSRule {
- WEB_WRAPPABLE(CSSMarginRule, CSSRule);
- GC_DECLARE_ALLOCATOR(CSSMarginRule);
-
-public:
- [[nodiscard]] static GC::Ref<CSSMarginRule> create(RustRule);
-
- virtual ~CSSMarginRule() override = default;
-
- Utf16FlyString const& name() const { return m_name; }
- GC::Ref<CSSStyleProperties> style() const;
-
-private:
- CSSMarginRule(RustRule);
-
- virtual size_t external_memory_size() const override;
- virtual Utf16String serialized() const override;
- virtual void visit_edges(Visitor&) override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
-
- Utf16FlyString m_name;
- RustDeclarationBlock m_declarations;
- mutable GC::Ptr<CSSStyleProperties> m_style;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMarginRule.idl b/Libraries/LibWeb/CSS/CSSMarginRule.idl
index 95a99f2eacb..428fcd65169 100644
--- a/Libraries/LibWeb/CSS/CSSMarginRule.idl
+++ b/Libraries/LibWeb/CSS/CSSMarginRule.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/cssom/#cssmarginrule
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSMarginRule : CSSRule {
readonly attribute CSSOMString name;
// FIXME: This should be CSSMarginDescriptors, but that has no spec. https://github.com/w3c/csswg-drafts/issues/10106
diff --git a/Libraries/LibWeb/CSS/CSSMediaRule.cpp b/Libraries/LibWeb/CSS/CSSMediaRule.cpp
deleted file mode 100644
index f9a16f60c56..00000000000
--- a/Libraries/LibWeb/CSS/CSSMediaRule.cpp
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (c) 2021-2025, Sam Atkins <[email protected]>
- * Copyright (c) 2022, Andreas Kling <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSMediaRule.h>
-#include <LibWeb/Dump.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSMediaRule);
-
-GC::Ref<CSSMediaRule> CSSMediaRule::create(RustRule rule, CSSRuleList& rules)
-{
- return GC::Heap::the().allocate<CSSMediaRule>(move(rule), rules);
-}
-
-CSSMediaRule::CSSMediaRule(RustRule rule, CSSRuleList& rules)
- : CSSConditionRule(rules, move(rule))
- , m_media_list(Parser::ValueParserFFI::rust_media_list_retain(native_rule().payload().media))
-{
-}
-
-GC::Ref<MediaList> CSSMediaRule::media() const
-{
- if (!m_media) {
- m_media = MediaList::create(m_media_list);
- m_media->set_associated_rule(const_cast<CSSMediaRule&>(*this));
- }
- return *m_media;
-}
-
-void CSSMediaRule::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_media);
-}
-
-Utf16String CSSMediaRule::serialized_condition_text() const
-{
- return m_media_list.media_text();
-}
-
-// https://www.w3.org/TR/cssom-1/#serialize-a-css-rule
-Utf16String CSSMediaRule::serialized() const
-{
- // The result of concatenating the following:
- Utf16StringBuilder builder;
-
- // 1. The string "@media", followed by a single SPACE (U+0020).
- builder.append_ascii("@media "sv);
- // 2. The result of performing serialize a media query list on rule’s media query list.
- builder.append(serialized_condition_text());
- // 3. A single SPACE (U+0020), followed by the string "{", i.e., LEFT CURLY BRACKET (U+007B), followed by a newline.
- builder.append_ascii(" {\n"sv);
- // 4. The result of performing serialize a CSS rule on each rule in the rule’s cssRules list,
- // filtering out empty strings, indenting each item with two spaces, all joined with newline.
- for (size_t i = 0; i < css_rules().length(); i++) {
- auto rule = css_rules().item(i);
- auto result = rule->serialized();
-
- if (result.is_empty())
- continue;
-
- builder.append_ascii(" "sv);
- builder.append(result);
- builder.append_ascii('\n');
- }
- // 5. A newline, followed by the string "}", i.e., RIGHT CURLY BRACKET (U+007D)
- // AD-HOC: All modern browsers omit the ending newline if there are no CSS rules, so let's do the same.
- // If there are rules, the required newline will be appended in the for-loop above.
- builder.append_ascii('}');
-
- return builder.to_string();
-}
-
-void CSSMediaRule::dump(StringBuilder& builder, int indent_levels) const
-{
- Base::dump(builder, indent_levels);
-
- m_media_list.dump(builder, indent_levels + 1);
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Rules ({}):\n", css_rules().length());
- for (auto& rule : css_rules())
- dump_rule(builder, rule, indent_levels + 2);
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMediaRule.h b/Libraries/LibWeb/CSS/CSSMediaRule.h
deleted file mode 100644
index f347ae6adb3..00000000000
--- a/Libraries/LibWeb/CSS/CSSMediaRule.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2021-2022, Sam Atkins <[email protected]>
- * Copyright (c) 2022, Andreas Kling <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSConditionRule.h>
-#include <LibWeb/CSS/MediaList.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::CSS {
-
-// https://www.w3.org/TR/css-conditional-3/#the-cssmediarule-interface
-class CSSMediaRule final : public CSSConditionRule {
- WEB_WRAPPABLE(CSSMediaRule, CSSConditionRule);
- GC_DECLARE_ALLOCATOR(CSSMediaRule);
-
-public:
- [[nodiscard]] static GC::Ref<CSSMediaRule> create(RustRule, CSSRuleList&);
-
- virtual ~CSSMediaRule() = default;
-
- virtual Utf16String serialized_condition_text() const override;
- bool matches() const { return m_media_list.matches(); }
-
- GC::Ref<MediaList> media() const;
- RustMediaList const& native_media_list() const { return m_media_list; }
-
-private:
- CSSMediaRule(RustRule, CSSRuleList&);
-
- virtual void visit_edges(Cell::Visitor&) override;
- virtual Utf16String serialized() const override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
-
- RustMediaList m_media_list;
- mutable GC::Ptr<MediaList> m_media;
-};
-
-template<>
-inline bool CSSRule::fast_is<CSSMediaRule>() const { return type() == CSSRule::Type::Media; }
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMediaRule.idl b/Libraries/LibWeb/CSS/CSSMediaRule.idl
index fed6a42dc42..e9c3797ed9e 100644
--- a/Libraries/LibWeb/CSS/CSSMediaRule.idl
+++ b/Libraries/LibWeb/CSS/CSSMediaRule.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/css-conditional-3/#the-cssmediarule-interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSMediaRule : CSSConditionRule {
[SameObject, PutForwards=mediaText] readonly attribute MediaList media;
readonly attribute boolean matches;
diff --git a/Libraries/LibWeb/CSS/CSSNamespaceRule.cpp b/Libraries/LibWeb/CSS/CSSNamespaceRule.cpp
deleted file mode 100644
index 2ada991615f..00000000000
--- a/Libraries/LibWeb/CSS/CSSNamespaceRule.cpp
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (c) 2023, Jonah Shafran <[email protected]>
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Utf16StringBuilder.h>
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSNamespaceRule.h>
-#include <LibWeb/CSS/Serialize.h>
-#include <LibWeb/Dump.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSNamespaceRule);
-
-CSSNamespaceRule::CSSNamespaceRule(RustRule rule)
- : CSSRule(move(rule))
- , m_rule(*native_rule().payload().namespace_rule)
-{
-}
-
-GC::Ref<CSSNamespaceRule> CSSNamespaceRule::create(RustRule rule)
-{
- return GC::Heap::the().allocate<CSSNamespaceRule>(move(rule));
-}
-
-Utf16View CSSNamespaceRule::prefix() const
-{
- auto view = Parser::ValueParserFFI::rust_namespace_rule_prefix(&m_rule);
- return { reinterpret_cast<char16_t const*>(view.utf16), view.length };
-}
-
-Utf16View CSSNamespaceRule::namespace_uri() const
-{
- auto view = Parser::ValueParserFFI::rust_namespace_rule_uri(&m_rule);
- return { reinterpret_cast<char16_t const*>(view.utf16), view.length };
-}
-
-// https://www.w3.org/TR/cssom/#serialize-a-css-rule
-Utf16String CSSNamespaceRule::serialized() const
-{
- Utf16StringBuilder builder;
- // The literal string "@namespace", followed by a single SPACE (U+0020),
- builder.append_ascii("@namespace "sv);
-
- // followed by the serialization as an identifier of the prefix attribute (if any),
- if (!prefix().is_empty()) {
- serialize_an_identifier(builder, prefix());
- // followed by a single SPACE (U+0020) if there is a prefix,
- builder.append_ascii(' ');
- }
-
- // followed by the serialization as URL of the namespaceURI attribute,
- serialize_a_url(builder, namespace_uri());
-
- // followed the character ";" (U+003B).
- builder.append_ascii(';');
-
- return builder.to_string();
-}
-
-void CSSNamespaceRule::dump(StringBuilder& builder, int indent_levels) const
-{
- Base::dump(builder, indent_levels);
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Namespace: {}\n", namespace_uri());
- if (!prefix().is_empty()) {
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Prefix: {}\n", prefix());
- }
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSNamespaceRule.h b/Libraries/LibWeb/CSS/CSSNamespaceRule.h
deleted file mode 100644
index 2a7a1160106..00000000000
--- a/Libraries/LibWeb/CSS/CSSNamespaceRule.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2023, Jonah Shafran <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16FlyString.h>
-#include <LibWeb/CSS/CSSRule.h>
-
-namespace Web::CSS {
-
-class CSSNamespaceRule final : public CSSRule {
- WEB_WRAPPABLE(CSSNamespaceRule, CSSRule);
- GC_DECLARE_ALLOCATOR(CSSNamespaceRule);
-
-public:
- [[nodiscard]] static GC::Ref<CSSNamespaceRule> create(RustRule);
-
- virtual ~CSSNamespaceRule() = default;
-
- Utf16View namespace_uri() const;
- Utf16View prefix() const;
-
-private:
- explicit CSSNamespaceRule(RustRule);
-
- virtual Utf16String serialized() const override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
-
- Parser::ValueParserFFI::NamespaceRuleData const& m_rule;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSNamespaceRule.idl b/Libraries/LibWeb/CSS/CSSNamespaceRule.idl
index 070cee4dd2d..8fad3c8f0b6 100644
--- a/Libraries/LibWeb/CSS/CSSNamespaceRule.idl
+++ b/Libraries/LibWeb/CSS/CSSNamespaceRule.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/cssom/#the-cssnamespacerule-interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSNamespaceRule : CSSRule {
readonly attribute CSSOMString namespaceURI;
readonly attribute CSSOMString prefix;
diff --git a/Libraries/LibWeb/CSS/CSSNestedDeclarations.cpp b/Libraries/LibWeb/CSS/CSSNestedDeclarations.cpp
index d0b6a1eb8af..0e5bafec354 100644
--- a/Libraries/LibWeb/CSS/CSSNestedDeclarations.cpp
+++ b/Libraries/LibWeb/CSS/CSSNestedDeclarations.cpp
@@ -5,98 +5,34 @@
*/
#include "CSSNestedDeclarations.h"
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/ExternalMemory.h>
#include <LibWeb/CSS/CSSStyleRule.h>
-#include <LibWeb/Dump.h>
namespace Web::CSS {
-GC_DEFINE_ALLOCATOR(CSSNestedDeclarations);
-
-GC::Ref<CSSNestedDeclarations> CSSNestedDeclarations::create(RustRule rule)
-{
- return GC::Heap::the().allocate<CSSNestedDeclarations>(move(rule));
-}
-
-CSSNestedDeclarations::CSSNestedDeclarations(RustRule rule)
- : CSSRule(move(rule))
- , m_declarations(Parser::ValueParserFFI::rust_declaration_block_retain(native_rule().payload().declarations))
-{
-}
-
-size_t CSSNestedDeclarations::external_memory_size() const
-{
- return JS::saturating_add_external_memory_size(Base::external_memory_size(), m_declarations.external_memory_size());
-}
-
-GC::Ref<CSSStyleProperties> CSSNestedDeclarations::ensure_style_properties() const
-{
- if (!m_declaration) {
- m_declaration = CSSStyleProperties::create(m_declarations.retain());
- m_declaration->set_parent_rule(const_cast<CSSNestedDeclarations&>(*this));
- }
- return *m_declaration;
-}
-
-void CSSNestedDeclarations::visit_edges(GC::Cell::Visitor& visitor)
+SelectorList CSSNestedDeclarations::absolutized_selectors() const
{
- Base::visit_edges(visitor);
- visitor.visit(m_declaration);
- visitor.visit(m_parent_style_rule);
+ return matching_selectors_for_rule(native_rule());
}
-SelectorList const& CSSNestedDeclarations::absolutized_selectors() const
+RustDeclarationBlock CSSNestedDeclarations::declaration() const
{
- if (m_cached_absolutized_selectors.has_value())
- return m_cached_absolutized_selectors.value();
-
- m_cached_absolutized_selectors = matching_selectors_for_rule(native_rule());
- return m_cached_absolutized_selectors.value();
+ return RustDeclarationBlock { Parser::ValueParserFFI::rust_declaration_block_retain(native_rule().payload().declarations) };
}
GC::Ref<CSSStyleProperties> CSSNestedDeclarations::style() const
{
- return ensure_style_properties();
+ return static_cast<CSSStyleProperties&>(*declarations());
}
CSSStyleRule const& CSSNestedDeclarations::parent_style_rule() const
{
- if (m_parent_style_rule)
- return *m_parent_style_rule;
-
for (auto* parent = parent_rule(); parent; parent = parent->parent_rule()) {
- if (is<CSSStyleRule>(parent)) {
- m_parent_style_rule = static_cast<CSSStyleRule const*>(parent);
- return *m_parent_style_rule;
- }
+ if (auto* style_rule = as_if<CSSStyleRule>(parent))
+ return *style_rule;
}
dbgln("CSSNestedDeclarations has no parent style rule!");
VERIFY_NOT_REACHED();
}
-Utf16String CSSNestedDeclarations::serialized() const
-{
- // NOTE: There's no proper spec for this yet, only this note:
- // "The CSSNestedDeclarations rule serializes as if its declaration block had been serialized directly."
- // - https://drafts.csswg.org/css-nesting-1/#ref-for-cssnesteddeclarations%E2%91%A1
- // So, we'll do the simple thing and hope it's good.
- return ensure_style_properties()->serialized();
-}
-
-void CSSNestedDeclarations::clear_caches()
-{
- Base::clear_caches();
- m_parent_style_rule = nullptr;
- m_cached_absolutized_selectors.clear();
-}
-
-void CSSNestedDeclarations::dump(StringBuilder& builder, int indent_levels) const
-{
- Base::dump(builder, indent_levels);
-
- dump_style_properties(builder, *ensure_style_properties(), indent_levels + 1);
-}
-
}
diff --git a/Libraries/LibWeb/CSS/CSSNestedDeclarations.h b/Libraries/LibWeb/CSS/CSSNestedDeclarations.h
index ee4bdc5b061..768f012116e 100644
--- a/Libraries/LibWeb/CSS/CSSNestedDeclarations.h
+++ b/Libraries/LibWeb/CSS/CSSNestedDeclarations.h
@@ -6,6 +6,7 @@
#pragma once
+#include <LibWeb/Bindings/CSSNestedDeclarations.h>
#include <LibWeb/CSS/CSSRule.h>
#include <LibWeb/CSS/CSSStyleProperties.h>
#include <LibWeb/CSS/Selector.h>
@@ -13,35 +14,15 @@
namespace Web::CSS {
class CSSNestedDeclarations final : public CSSRule {
- WEB_WRAPPABLE(CSSNestedDeclarations, CSSRule);
- GC_DECLARE_ALLOCATOR(CSSNestedDeclarations);
+ WEB_RUST_INTERFACE(CSSNestedDeclarations, css_nested_declarations)
public:
- [[nodiscard]] static GC::Ref<CSSNestedDeclarations> create(RustRule);
-
- virtual ~CSSNestedDeclarations() override = default;
-
- SelectorList const& absolutized_selectors() const;
- RustDeclarationBlock const& declaration() const { return m_declarations; }
+ SelectorList absolutized_selectors() const;
+ RustDeclarationBlock declaration() const;
GC::Ref<CSSStyleProperties> style() const;
CSSStyleRule const& parent_style_rule() const;
-
-private:
- CSSNestedDeclarations(RustRule);
- GC::Ref<CSSStyleProperties> ensure_style_properties() const;
- virtual size_t external_memory_size() const override;
-
- virtual void visit_edges(Cell::Visitor&) override;
- virtual Utf16String serialized() const override;
- virtual void clear_caches() override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
-
- RustDeclarationBlock m_declarations;
- mutable GC::Ptr<CSSStyleProperties> m_declaration;
- GC::Ptr<CSSStyleRule const> mutable m_parent_style_rule;
- mutable Optional<SelectorList> m_cached_absolutized_selectors;
};
template<>
diff --git a/Libraries/LibWeb/CSS/CSSNestedDeclarations.idl b/Libraries/LibWeb/CSS/CSSNestedDeclarations.idl
index 520e0998a33..2132d50e112 100644
--- a/Libraries/LibWeb/CSS/CSSNestedDeclarations.idl
+++ b/Libraries/LibWeb/CSS/CSSNestedDeclarations.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/css-nesting-1/#cssnesteddeclarations
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSNestedDeclarations : CSSRule {
[SameObject, PutForwards=cssText] readonly attribute CSSStyleProperties style;
};
diff --git a/Libraries/LibWeb/CSS/CSSPageRule.cpp b/Libraries/LibWeb/CSS/CSSPageRule.cpp
deleted file mode 100644
index 717f6a436af..00000000000
--- a/Libraries/LibWeb/CSS/CSSPageRule.cpp
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/ExternalMemory.h>
-#include <LibWeb/CSS/CSSPageRule.h>
-#include <LibWeb/CSS/Serialize.h>
-#include <LibWeb/Dump.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-#include <AK/Utf16StringBuilder.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSPageRule);
-
-GC::Ref<CSSPageRule> CSSPageRule::create(RustRule rule, CSSRuleList& rules)
-{
- return GC::Heap::the().allocate<CSSPageRule>(move(rule), rules);
-}
-
-CSSPageRule::CSSPageRule(RustRule rule, CSSRuleList& rules)
- : CSSGroupingRule(rules, move(rule))
- , m_descriptors(Parser::ValueParserFFI::rust_descriptor_block_retain(native_rule().payload().descriptors))
-{
-}
-
-size_t CSSPageRule::external_memory_size() const
-{
- return JS::saturating_add_external_memory_size(Base::external_memory_size(), m_descriptors.external_memory_size());
-}
-
-GC::Ref<CSSPageDescriptors> CSSPageRule::style() const
-{
- if (!m_style) {
- m_style = CSSPageDescriptors::create(m_descriptors.retain());
- m_style->set_parent_rule(const_cast<CSSPageRule&>(*this));
- }
- return *m_style;
-}
-
-// https://drafts.csswg.org/cssom/#dom-csspagerule-selectortext
-Utf16String CSSPageRule::selector_text() const
-{
- return RustPageSelectors { native_rule().payload().page_selectors }.serialize();
-}
-
-// https://drafts.csswg.org/cssom/#dom-csspagerule-selectortext
-void CSSPageRule::set_selector_text(Utf16View text)
-{
- // On setting the selectorText attribute these steps must be run:
- // 1. Run the parse a list of CSS page selectors algorithm on the given value.
- auto page_selector_list = RustPageSelectors::parse(text);
-
- // 2. If the algorithm returns a non-null value replace the associated selector list with the returned value.
- if (page_selector_list.has_value())
- Parser::ValueParserFFI::rust_rule_set_page_selectors(native_rule().handle(), page_selector_list->handle());
-
- // 3. Otherwise, if the algorithm returns a null value, do nothing.
-}
-
-// https://drafts.csswg.org/cssom/#ref-for-csspagerule
-Utf16String CSSPageRule::serialized() const
-{
- Utf16StringBuilder builder;
-
- // AD-HOC: There's no spec for this yet, but Chrome puts declarations before margin rules.
- builder.append_ascii("@page "sv);
- if (auto selector = selector_text(); !selector.is_empty()) {
- builder.append(selector);
- builder.append_ascii(' ');
- }
- builder.append_ascii("{ "sv);
- if (m_descriptors.size() > 0) {
- builder.append(style()->serialized());
- builder.append_ascii(' ');
- }
- for (size_t i = 0; i < css_rules().length(); i++) {
- auto rule = css_rules().item(i);
- auto result = rule->serialized();
-
- if (result.is_empty())
- continue;
-
- builder.appendff("{} ", result);
- }
- builder.append_ascii("}"sv);
-
- return builder.to_string();
-}
-
-void CSSPageRule::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_style);
-}
-
-void CSSPageRule::dump(StringBuilder& builder, int indent_levels) const
-{
- Base::dump(builder, indent_levels);
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Selector: {}\n", selector_text().to_utf8());
- dump_descriptors(builder, style(), indent_levels + 1);
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Rules ({}):\n", css_rules().length());
- for (auto& rule : css_rules())
- dump_rule(builder, rule, indent_levels + 2);
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSPageRule.h b/Libraries/LibWeb/CSS/CSSPageRule.h
deleted file mode 100644
index 5ee070cd958..00000000000
--- a/Libraries/LibWeb/CSS/CSSPageRule.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16String.h>
-#include <AK/Utf16View.h>
-#include <LibWeb/CSS/CSSGroupingRule.h>
-#include <LibWeb/CSS/CSSPageDescriptors.h>
-#include <LibWeb/CSS/RustPageSelectors.h>
-
-namespace Web::CSS {
-
-// https://drafts.csswg.org/css-page-3/#at-ruledef-page
-class CSSPageRule final : public CSSGroupingRule {
- WEB_WRAPPABLE(CSSPageRule, CSSGroupingRule);
- GC_DECLARE_ALLOCATOR(CSSPageRule);
-
-public:
- [[nodiscard]] static GC::Ref<CSSPageRule> create(RustRule, CSSRuleList&);
-
- virtual ~CSSPageRule() override = default;
-
- Utf16String selector_text() const;
- void set_selector_text(Utf16View);
-
- GC::Ref<CSSPageDescriptors> style() const;
-
-private:
- CSSPageRule(RustRule, CSSRuleList&);
-
- virtual size_t external_memory_size() const override;
- virtual Utf16String serialized() const override;
- virtual void visit_edges(Visitor&) override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
-
- RustDescriptorBlock m_descriptors;
- mutable GC::Ptr<CSSPageDescriptors> m_style;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSPageRule.idl b/Libraries/LibWeb/CSS/CSSPageRule.idl
index 1838af10ebc..2eb4c344140 100644
--- a/Libraries/LibWeb/CSS/CSSPageRule.idl
+++ b/Libraries/LibWeb/CSS/CSSPageRule.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/cssom/#csspagerule
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSPageRule : CSSGroupingRule {
attribute CSSOMString selectorText;
[SameObject, PutForwards=cssText] readonly attribute CSSPageDescriptors style;
diff --git a/Libraries/LibWeb/CSS/CSSPositionTryRule.cpp b/Libraries/LibWeb/CSS/CSSPositionTryRule.cpp
deleted file mode 100644
index a7f3c8e909d..00000000000
--- a/Libraries/LibWeb/CSS/CSSPositionTryRule.cpp
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Utf16StringBuilder.h>
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/ExternalMemory.h>
-#include <LibWeb/CSS/CSSPositionTryDescriptors.h>
-#include <LibWeb/CSS/CSSPositionTryRule.h>
-#include <LibWeb/CSS/Serialize.h>
-#include <LibWeb/Dump.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSPositionTryRule);
-
-GC::Ref<CSSPositionTryRule> CSSPositionTryRule::create(RustRule rule)
-{
- return GC::Heap::the().allocate<CSSPositionTryRule>(move(rule));
-}
-
-CSSPositionTryRule::CSSPositionTryRule(RustRule rule)
- : CSSRule(move(rule))
- , m_name([&] {
- auto name = native_rule().payload().name;
- auto view = name.latin1 ? Utf16View::from_latin1({ name.latin1, name.length }, false) : Utf16View { reinterpret_cast<char16_t const*>(name.utf16), name.length };
- return Utf16FlyString::from_utf16(view);
- }())
- , m_declarations(Parser::ValueParserFFI::rust_declaration_block_retain(native_rule().payload().declarations))
-{
-}
-
-size_t CSSPositionTryRule::external_memory_size() const
-{
- return JS::saturating_add_external_memory_size(Base::external_memory_size(), m_declarations.external_memory_size());
-}
-
-// https://drafts.csswg.org/css-anchor-position-1/#dom-csspositiontryrule-name
-Utf16String CSSPositionTryRule::name() const
-{
- // Its name attribute represents the name declared in the rule's prelude.
- // INTEROP: Other browsers return the name serialized as an identifier.
- return serialize_an_identifier_to_utf16(m_name);
-}
-
-// https://drafts.csswg.org/css-anchor-position-1/#dom-csspositiontryrule-style
-GC::Ref<CSSPositionTryDescriptors> CSSPositionTryRule::style() const
-{
- // On getting, it must return a CSSPositionTryDescriptors object for the @position-try at-rule, with the following
- // properties:
- // computed flag: Unset
- // readonly flag: Unset
- // declarations: The declared descriptors in the rule, in specified order.
- // parent CSS rule: The context object
- // owner node: Null
- if (!m_style) {
- m_style = CSSPositionTryDescriptors::create(m_declarations.retain());
- m_style->set_parent_rule(const_cast<CSSPositionTryRule&>(*this));
- }
- return *m_style;
-}
-
-Utf16String CSSPositionTryRule::serialized() const
-{
- // AD-HOC: There is no spec for serializing CSSPositionTryRule. This matches other browsers.
- Utf16StringBuilder builder;
- builder.append_ascii("@position-try "sv);
- builder.append(name());
- builder.append_ascii(" { "sv);
- if (!m_declarations.is_empty()) {
- builder.append(style()->serialized());
- builder.append_ascii(' ');
- }
- builder.append_ascii('}');
- return builder.to_string();
-}
-
-void CSSPositionTryRule::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_style);
-}
-
-void CSSPositionTryRule::dump(StringBuilder& builder, int indent_levels) const
-{
- Base::dump(builder, indent_levels);
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Name: {}\n", m_name);
- dump_style_properties(builder, style(), indent_levels + 1);
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSPositionTryRule.h b/Libraries/LibWeb/CSS/CSSPositionTryRule.h
deleted file mode 100644
index d6d619f9d03..00000000000
--- a/Libraries/LibWeb/CSS/CSSPositionTryRule.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16FlyString.h>
-#include <LibWeb/CSS/CSSRule.h>
-#include <LibWeb/CSS/RustDeclarationBlock.h>
-
-namespace Web::CSS {
-
-// https://drafts.csswg.org/css-anchor-position-1/#om-position-try
-class CSSPositionTryRule final : public CSSRule {
- WEB_WRAPPABLE(CSSPositionTryRule, CSSRule);
- GC_DECLARE_ALLOCATOR(CSSPositionTryRule);
-
-public:
- [[nodiscard]] static GC::Ref<CSSPositionTryRule> create(RustRule);
-
- virtual ~CSSPositionTryRule() override = default;
-
- Utf16String name() const;
- GC::Ref<CSSPositionTryDescriptors> style() const;
-
-private:
- explicit CSSPositionTryRule(RustRule);
-
- virtual size_t external_memory_size() const override;
- virtual Utf16String serialized() const override;
- virtual void visit_edges(Visitor&) override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
-
- Utf16FlyString m_name;
- RustDeclarationBlock m_declarations;
- mutable GC::Ptr<CSSPositionTryDescriptors> m_style;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSPositionTryRule.idl b/Libraries/LibWeb/CSS/CSSPositionTryRule.idl
index 3c3e330293f..47484d27b3b 100644
--- a/Libraries/LibWeb/CSS/CSSPositionTryRule.idl
+++ b/Libraries/LibWeb/CSS/CSSPositionTryRule.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/css-anchor-position-1/#om-position-try
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSPositionTryRule : CSSRule {
readonly attribute CSSOMString name;
[SameObject, PutForwards=cssText] readonly attribute CSSPositionTryDescriptors style;
diff --git a/Libraries/LibWeb/CSS/CSSPropertyRule.cpp b/Libraries/LibWeb/CSS/CSSPropertyRule.cpp
deleted file mode 100644
index 62e11d630e5..00000000000
--- a/Libraries/LibWeb/CSS/CSSPropertyRule.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (c) 2024, Alex Ungurianu <[email protected]>
- * Copyright (c) 2025-2026, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSPropertyRule.h>
-#include <LibWeb/CSS/Parser/RustSyntaxHandle.h>
-#include <LibWeb/CSS/Serialize.h>
-#include <LibWeb/CSS/StyleValues/StyleValue.h>
-#include <LibWeb/Dump.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSPropertyRule);
-
-GC::Ref<CSSPropertyRule> CSSPropertyRule::create(RustRule rule)
-{
- return GC::Heap::the().allocate<CSSPropertyRule>(move(rule));
-}
-
-CSSPropertyRule::CSSPropertyRule(RustRule rule)
- : CSSRule(move(rule))
- , m_rule(*native_rule().payload().property)
-{
-}
-
-CSSPropertyRule::~CSSPropertyRule() = default;
-
-Utf16View CSSPropertyRule::name() const
-{
- auto name = Parser::ValueParserFFI::rust_property_rule_view(&m_rule).name;
- return { reinterpret_cast<char16_t const*>(name.utf16), name.length };
-}
-
-Utf16View CSSPropertyRule::syntax() const
-{
- auto syntax = Parser::ValueParserFFI::rust_property_rule_view(&m_rule).syntax_source;
- return { reinterpret_cast<char16_t const*>(syntax.utf16), syntax.length };
-}
-
-bool CSSPropertyRule::inherits() const
-{
- return Parser::ValueParserFFI::rust_property_rule_view(&m_rule).inherits;
-}
-
-RefPtr<StyleValue const> CSSPropertyRule::initial_style_value() const
-{
- auto* value = Parser::ValueParserFFI::rust_property_rule_view(&m_rule).initial_value;
- if (!value)
- return {};
- return StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(static_cast<StyleValueFFI::StyleValueData const*>(value)));
-}
-
-Optional<Utf16String> CSSPropertyRule::initial_value() const
-{
- if (auto initial_value = initial_style_value())
- return initial_value->to_utf16_string(SerializationMode::Normal);
- return {};
-}
-
-// https://www.w3.org/TR/cssom-1/#serialize-a-css-rule
-Utf16String CSSPropertyRule::serialized() const
-{
- Utf16StringBuilder builder;
-
- // Serialization algorithm is defined in the spec below
- // https://drafts.css-houdini.org/css-properties-values-api/#the-css-property-rule-interface
-
- // To serialize a CSSPropertyRule, return the concatenation of the following:
-
- // 1. The string "@property" followed by a single SPACE (U+0020).
- // 2. The result of performing serialize an identifier on the rule’s name, followed by a single SPACE (U+0020).
- builder.append_ascii("@property "sv);
- serialize_an_identifier(builder, name());
- builder.append_ascii(' ');
-
- // 3. The string "{ ", i.e., a single LEFT CURLY BRACKET (U+007B), followed by a SPACE (U+0020).
- builder.append_ascii("{ "sv);
-
- // 4. The string "syntax:", followed by a single SPACE (U+0020).
- // 5. The result of performing serialize a string on the rule’s syntax, followed by a single SEMICOLON (U+003B), followed by a SPACE (U+0020).
- builder.append_ascii("syntax: "sv);
- serialize_a_string(builder, syntax());
- builder.append_ascii("; "sv);
-
- // 6. The string "inherits:", followed by a single SPACE (U+0020).
- // 7. For the rule’s inherits attribute, one of the following depending on the attribute’s value:
- // true: The string "true" followed by a single SEMICOLON (U+003B), followed by a SPACE (U+0020).
- // false: The string "false" followed by a single SEMICOLON (U+003B), followed by a SPACE (U+0020).
- builder.appendff("inherits: {}; ", inherits());
-
- // 8. If the rule’s initial-value is present, follow these substeps:
- if (auto initial_value = initial_style_value()) {
- // 1. The string "initial-value:".
- // 2. The result of performing serialize a CSS value in the rule’s initial-value followed by a single SEMICOLON
- // (U+003B), followed by a SPACE (U+0020).
- builder.append_ascii("initial-value: "sv);
- initial_value->serialize(builder, SerializationMode::Normal);
- builder.append_ascii("; "sv);
- }
- // 9. A single RIGHT CURLY BRACKET (U+007D).
- builder.append_ascii("}"sv);
-
- return builder.to_string();
-}
-
-void CSSPropertyRule::dump(StringBuilder& builder, int indent_levels) const
-{
- Base::dump(builder, indent_levels);
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Name: {}\n", name());
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Syntax: `{}`\n", syntax());
- dump_indent(builder, indent_levels + 2);
- builder.appendff("Parsed syntax: {}\n", Parser::RustSyntaxHandle { Parser::ValueParserFFI::rust_syntax_retain(Parser::ValueParserFFI::rust_property_rule_view(&m_rule).syntax) }.serialize());
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Inherits: {}\n", inherits());
-
- if (auto initial_value = initial_style_value()) {
- dump_indent(builder, indent_levels + 1);
- builder.append("Initial value: "sv);
- initial_value->serialize(builder, SerializationMode::Normal);
- builder.append('\n');
- }
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSPropertyRule.h b/Libraries/LibWeb/CSS/CSSPropertyRule.h
deleted file mode 100644
index 1dbf326bfac..00000000000
--- a/Libraries/LibWeb/CSS/CSSPropertyRule.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2024, Alex Ungurianu <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <AK/RefPtr.h>
-#include <AK/Utf16String.h>
-#include <AK/Utf16View.h>
-#include <LibWeb/CSS/CSSRule.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-properties-values-api/#the-css-property-rule-interface
-class CSSPropertyRule final : public CSSRule {
- WEB_WRAPPABLE(CSSPropertyRule, CSSRule);
- GC_DECLARE_ALLOCATOR(CSSPropertyRule);
-
-public:
- static GC::Ref<CSSPropertyRule> create(RustRule);
-
- virtual ~CSSPropertyRule();
-
- Utf16View name() const;
- Utf16View syntax() const;
- bool inherits() const;
- Optional<Utf16String> initial_value() const;
-
-private:
- explicit CSSPropertyRule(RustRule);
-
- virtual Utf16String serialized() const override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
-
- RefPtr<StyleValue const> initial_style_value() const;
- Parser::ValueParserFFI::PropertyRuleData const& m_rule;
-};
-
-template<>
-inline bool CSSRule::fast_is<CSSPropertyRule>() const { return type() == CSSRule::Type::Property; }
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSPropertyRule.idl b/Libraries/LibWeb/CSS/CSSPropertyRule.idl
index e4ab1b43756..8abc5f32da5 100644
--- a/Libraries/LibWeb/CSS/CSSPropertyRule.idl
+++ b/Libraries/LibWeb/CSS/CSSPropertyRule.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-properties-values-api/#the-css-property-rule-interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSPropertyRule : CSSRule {
readonly attribute CSSOMString name;
readonly attribute CSSOMString syntax;
diff --git a/Libraries/LibWeb/CSS/CSSRule.cpp b/Libraries/LibWeb/CSS/CSSRule.cpp
index b09f4ee3c8b..34b1e860ef6 100644
--- a/Libraries/LibWeb/CSS/CSSRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSRule.cpp
@@ -6,54 +6,86 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibJS/Runtime/ExternalMemory.h>
-#include <LibWeb/Bindings/CSSRule.h>
-#include <LibWeb/CSS/CSSContainerRule.h>
-#include <LibWeb/CSS/CSSCounterStyleRule.h>
-#include <LibWeb/CSS/CSSFontFaceRule.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/CSS/CSSFontFaceDescriptors.h>
+#include <LibWeb/CSS/CSSFontFeatureValuesMap.h>
#include <LibWeb/CSS/CSSFontFeatureValuesRule.h>
-#include <LibWeb/CSS/CSSFunctionDeclarations.h>
-#include <LibWeb/CSS/CSSFunctionRule.h>
-#include <LibWeb/CSS/CSSImportRule.h>
-#include <LibWeb/CSS/CSSKeyframeRule.h>
-#include <LibWeb/CSS/CSSKeyframesRule.h>
-#include <LibWeb/CSS/CSSLayerBlockRule.h>
-#include <LibWeb/CSS/CSSLayerStatementRule.h>
-#include <LibWeb/CSS/CSSMarginRule.h>
-#include <LibWeb/CSS/CSSMediaRule.h>
-#include <LibWeb/CSS/CSSNamespaceRule.h>
-#include <LibWeb/CSS/CSSNestedDeclarations.h>
-#include <LibWeb/CSS/CSSPageRule.h>
-#include <LibWeb/CSS/CSSPositionTryRule.h>
-#include <LibWeb/CSS/CSSPropertyRule.h>
+#include <LibWeb/CSS/CSSFunctionDescriptors.h>
+#include <LibWeb/CSS/CSSPageDescriptors.h>
+#include <LibWeb/CSS/CSSPositionTryDescriptors.h>
#include <LibWeb/CSS/CSSRule.h>
-#include <LibWeb/CSS/CSSRuleList.h>
-#include <LibWeb/CSS/CSSScopeRule.h>
-#include <LibWeb/CSS/CSSStyleRule.h>
+#include <LibWeb/CSS/CSSStyleProperties.h>
#include <LibWeb/CSS/CSSStyleSheet.h>
-#include <LibWeb/CSS/CSSSupportsRule.h>
+#include <LibWeb/CSS/Parser/Parser.h>
+#include <LibWeb/CSS/Selector.h>
+#include <LibWeb/CSS/Serialize.h>
+#include <LibWeb/CSS/StyleEngineInput.h>
+#include <LibWeb/CSS/StylePropertyMap.h>
+#include <LibWeb/CSS/StyleScope.h>
+#include <LibWeb/CSS/StyleSheetImport.h>
#include <LibWeb/CSS/StyleSheetState.h>
-#include <LibWeb/Dump.h>
namespace Web::CSS {
-CSSRule::~CSSRule() = default;
+using Parser::ValueParserFFI::NativeRule;
+using Parser::ValueParserFFI::NativeRuleList;
-CSSStyleSheet* CSSRule::parent_style_sheet_for_bindings() const
+// NB: Implemented in Libraries/LibWeb/Bindings/Rust/src/css/exports.rs.
+extern "C" {
+NativeRule const* web_css_rule_native(void* rule);
+void* web_css_rule_parent_rule(void* rule);
+void* web_css_rule_parent_style_sheet(void* rule);
+FlatPtr web_css_rule_serialized(void* vm, void* rule);
+void* web_css_rule_declarations(void* vm, void* rule);
+}
+
+// NB: What the implementation of the rules in Rust asks of the C++ code of LibWeb.
+extern "C" {
+void* web_css_rule_create_declarations(void* rule);
+FlatPtr web_css_declarations_serialized(void* declarations);
+NativeRuleList const* web_css_style_sheet_native_rules(void* sheet);
+FlatPtr web_css_selector_list_text(void const* selectors, void* sheet);
+void* web_css_style_sheet_import_rule(void* sheet, u64 identity);
+void web_css_style_sheet_disconnect_font_faces(void* sheet, NativeRule const* rule);
+void web_css_style_sheet_rules_changed(void* sheet);
+void web_css_counter_style_rule_changed(void* rule);
+void* web_css_style_property_map_create(void* declarations);
+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();
+}
+
+CSSRule::Type CSSRule::type() const
+{
+ return Parser::ValueParserFFI::rust_rule_type(native_handle());
+}
+
+NativeRule const* CSSRule::native_handle() const
{
- return m_parent_style_sheet ? &m_parent_style_sheet->cssom_sheet() : nullptr;
+ return web_css_rule_native(const_cast<CSSRule*>(this));
}
-CSSRule::CSSRule(RustRule rule)
- : m_type(rule.type())
- , m_native_rule(move(rule))
+CSSRule* CSSRule::parent_rule() const
{
+ return static_cast<CSSRule*>(web_css_rule_parent_rule(const_cast<CSSRule*>(this)));
+}
+
+StyleSheetState* CSSRule::parent_style_sheet() const
+{
+ auto* sheet = web_css_rule_parent_style_sheet(const_cast<CSSRule*>(this));
+ return sheet ? &state_of_sheet(sheet) : nullptr;
}
// NB: Read from the native rule when asked, as only DevTools asks.
Optional<SourcePosition> CSSRule::source_location() const
{
- auto payload = m_native_rule.payload();
+ auto payload = native_rule().payload();
if (!payload.has_source_position)
return {};
VERIFY(payload.start_line <= NumericLimits<u32>::max());
@@ -61,126 +93,106 @@ Optional<SourcePosition> CSSRule::source_location() const
return SourcePosition { static_cast<u32>(payload.start_line), static_cast<u32>(payload.start_column) };
}
-GC::Ref<CSSRule> CSSRule::create(RustRule rule, GC::Ptr<DOM::Document> document)
-{
- // NB: A style rule makes its list of nested rules when it is first read, as most style rules nest none.
- if (rule.type() == Type::Style)
- return CSSStyleRule::create(move(rule));
- GC::Ptr<CSSRuleList> children;
- if (auto* native_children = Parser::ValueParserFFI::rust_rule_children(rule.handle()); native_children && rule.type() != Type::Keyframes)
- children = CSSRuleList::create(RustRuleList { Parser::ValueParserFFI::rust_rule_list_retain(native_children) }, document);
- switch (rule.type()) {
- case Type::Style:
- VERIFY_NOT_REACHED();
- case Type::Media:
- return CSSMediaRule::create(move(rule), *children);
- case Type::Supports:
- return CSSSupportsRule::create(move(rule), *children);
- case Type::Container:
- return CSSContainerRule::create(move(rule), *children);
- case Type::Scope:
- return CSSScopeRule::create(move(rule), *children);
- case Type::LayerBlock:
- return CSSLayerBlockRule::create(move(rule), *children);
- case Type::Page:
- return CSSPageRule::create(move(rule), *children);
- case Type::Function:
- return CSSFunctionRule::create(move(rule), *children);
- case Type::Import:
- return CSSImportRule::create(*StyleSheetImport::create(move(rule), document));
- case Type::FontFace:
- return CSSFontFaceRule::create(move(rule));
- case Type::Keyframes:
- return CSSKeyframesRule::create(move(rule));
- case Type::Keyframe:
- return CSSKeyframeRule::create(move(rule));
- case Type::Margin:
- return CSSMarginRule::create(move(rule));
- case Type::PositionTry:
- return CSSPositionTryRule::create(move(rule));
- case Type::Namespace:
- return CSSNamespaceRule::create(move(rule));
- case Type::CounterStyle:
- return CSSCounterStyleRule::create(move(rule));
- case Type::FontFeatureValues:
- return CSSFontFeatureValuesRule::create(move(rule));
- case Type::LayerStatement:
- return CSSLayerStatementRule::create(move(rule));
- case Type::NestedDeclarations:
- return CSSNestedDeclarations::create(move(rule));
- case Type::Property:
- return CSSPropertyRule::create(move(rule));
- case Type::FunctionDeclarations:
- return CSSFunctionDeclarations::create(move(rule));
- }
- VERIFY_NOT_REACHED();
+Utf16String CSSRule::serialized() const
+{
+ return Utf16String::from_raw(web_css_rule_serialized(JS::HostABI::vm_to_abi(JS::VM::the()), const_cast<CSSRule*>(this)));
+}
+
+GC::Ref<CSSStyleDeclaration> CSSRule::declarations() const
+{
+ auto* declarations = web_css_rule_declarations(JS::HostABI::vm_to_abi(JS::VM::the()), const_cast<CSSRule*>(this));
+ return *static_cast<CSSStyleDeclaration*>(static_cast<GC::Cell*>(declarations));
}
-void CSSRule::visit_edges(GC::Cell::Visitor& visitor)
+void* web_css_rule_create_declarations(void* cell)
{
- Base::visit_edges(visitor);
- visitor.visit(m_parent_style_sheet);
- visitor.visit(m_parent_cssom_sheet);
- visitor.visit(m_parent_rule);
+ using namespace Parser::ValueParserFFI;
+
+ auto& rule = *static_cast<CSSRule*>(cell);
+ auto native_rule = rule.native_rule();
+ auto payload = native_rule.payload();
+
+ auto declarations = [&]() -> GC::Ref<CSSStyleDeclaration> {
+ switch (native_rule.type()) {
+ case CSSRule::Type::Style:
+ return CSSStyleProperties::create(RustDeclarationBlock { rust_rule_declarations(native_rule.handle()) });
+ case CSSRule::Type::NestedDeclarations:
+ case CSSRule::Type::Margin:
+ return CSSStyleProperties::create(RustDeclarationBlock { rust_declaration_block_retain(payload.declarations) });
+ case CSSRule::Type::Keyframe:
+ return CSSStyleProperties::create(RustDeclarationBlock { rust_keyframe_declarations(payload.keyframe) });
+ case CSSRule::Type::PositionTry:
+ return CSSPositionTryDescriptors::create(RustDeclarationBlock { rust_declaration_block_retain(payload.declarations) });
+ case CSSRule::Type::FontFace:
+ return CSSFontFaceDescriptors::create(RustDescriptorBlock { rust_descriptor_block_retain(payload.descriptors) });
+ case CSSRule::Type::Page:
+ return CSSPageDescriptors::create(RustDescriptorBlock { rust_descriptor_block_retain(payload.descriptors) });
+ case CSSRule::Type::FunctionDeclarations:
+ return CSSFunctionDescriptors::create(RustDescriptorBlock { rust_descriptor_block_retain(payload.descriptors) });
+ default:
+ VERIFY_NOT_REACHED();
+ }
+ }();
+ declarations->set_parent_rule(rule);
+ return static_cast<GC::Cell*>(declarations.ptr());
}
-size_t CSSRule::external_memory_size() const
+FlatPtr web_css_declarations_serialized(void* declarations)
{
- return JS::saturating_add_external_memory_size(Base::external_memory_size(), m_native_rule.external_memory_size());
+ return static_cast<CSSStyleDeclaration*>(static_cast<GC::Cell*>(declarations))->serialized().into_raw();
}
-// https://www.w3.org/TR/cssom/#dom-cssrule-type
-WebIDL::UnsignedShort CSSRule::type_for_bindings() const
+NativeRuleList const* web_css_style_sheet_native_rules(void* sheet)
{
- // NOTE: Types that aren't defined in the spec must return 0.
- // To do this, we arbitrarily make non-spec ones start at 100.
- auto type = to_underlying(m_type);
- if (type >= 100)
- return 0;
- return type;
+ return state_of_sheet(sheet).native_rules().handle();
}
-// https://www.w3.org/TR/cssom/#dom-cssrule-csstext
-Utf16String CSSRule::css_text() const
+FlatPtr web_css_selector_list_text(void const* selectors, void* sheet)
{
- // The cssText attribute must return a serialization of the CSS rule.
- return serialized();
+ auto list = selector_list_from_rust(static_cast<SelectorFFI::RustParsedSelectorList const*>(selectors));
+ return serialize_a_group_of_selectors(list, sheet ? &state_of_sheet(sheet) : nullptr).into_raw();
}
-// https://www.w3.org/TR/cssom/#dom-cssrule-csstext
-void CSSRule::set_css_text(Utf16View)
+void* web_css_style_sheet_import_rule(void* sheet, u64 identity)
{
- // On setting the cssText attribute must do nothing.
+ auto* import = state_of_sheet(sheet).import_for_rule(identity);
+ return import ? &import->cssom_rule() : nullptr;
}
-void CSSRule::set_parent_rule(CSSRule* parent_rule)
+void web_css_style_sheet_disconnect_font_faces(void* sheet, NativeRule const* rule)
{
- clear_caches();
- m_parent_rule = parent_rule;
+ state_of_sheet(sheet).disconnect_font_faces_in_rule(RustRule { rule });
+}
- if (parent_rule == nullptr)
- set_parent_style_sheet(nullptr);
- else
- set_parent_style_sheet(parent_rule->parent_style_sheet());
- clear_caches();
-}
-
-void CSSRule::set_parent_style_sheet(StyleSheetState* parent_style_sheet)
+void web_css_style_sheet_rules_changed(void* sheet)
{
- clear_caches();
- m_parent_style_sheet = parent_style_sheet;
- m_parent_cssom_sheet = parent_style_sheet ? &parent_style_sheet->cssom_sheet() : nullptr;
- clear_caches();
+ state_of_sheet(sheet).recalculate_rule_caches();
+}
+
+void web_css_counter_style_rule_changed(void* cell)
+{
+ auto& rule = *static_cast<CSSRule*>(cell);
+ auto* parent_style_sheet = rule.parent_style_sheet();
+
+ if (!parent_style_sheet)
+ return;
+
+ parent_style_sheet->for_each_owning_style_scope([&](StyleScope& style_scope) {
+ style_scope.invalidate_counter_style_cache();
+ });
+ record_style_rule_declarations_changed(rule);
}
-void CSSRule::dump(StringBuilder& builder, int indent_levels) const
+void* web_css_style_property_map_create(void* declarations)
{
- dump_indent(builder, indent_levels);
- builder.appendff("{}:\n", class_name());
+ auto& style_properties = *static_cast<CSSStyleProperties*>(static_cast<GC::Cell*>(declarations));
+ return static_cast<GC::Cell*>(StylePropertyMap::create(style_properties).ptr());
}
-void CSSRule::clear_caches()
+void* web_css_font_feature_values_map_create(void* rule, u8 kind)
{
+ auto& parent_rule = *static_cast<CSSFontFeatureValuesRule*>(rule);
+ return static_cast<GC::Cell*>(CSSFontFeatureValuesMap::create(static_cast<FontFeatureValuesRuleKind>(kind), parent_rule).ptr());
}
}
diff --git a/Libraries/LibWeb/CSS/CSSRule.h b/Libraries/LibWeb/CSS/CSSRule.h
index 68109d7926b..3aad228ad34 100644
--- a/Libraries/LibWeb/CSS/CSSRule.h
+++ b/Libraries/LibWeb/CSS/CSSRule.h
@@ -7,44 +7,32 @@
#pragma once
-#include <AK/String.h>
#include <AK/Utf16String.h>
-#include <AK/Utf16View.h>
#include <LibGC/Ptr.h>
+#include <LibWeb/Bindings/CSSRule.h>
+#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/CSS/CSSStyleDeclaration.h>
#include <LibWeb/CSS/Parser/SourcePosition.h>
#include <LibWeb/CSS/RustRule.h>
#include <LibWeb/Export.h>
-#include <LibWebCommon/WebIDL/Types.h>
+#include <LibWeb/Forward.h>
namespace Web::CSS {
-class WEB_API CSSRule : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(CSSRule, Bindings::GCAllocatedWrappable);
+class WEB_API CSSRule : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(CSSRule, css_rule)
public:
- static GC::Ref<CSSRule> create(RustRule, GC::Ptr<DOM::Document>);
- virtual ~CSSRule() override;
-
using Type = RustRule::Type;
- Type type() const { return m_type; }
- RustRule const& native_rule() const { return m_native_rule; }
- WebIDL::UnsignedShort type_for_bindings() const;
-
- Utf16String css_text() const;
- void set_css_text(Utf16View);
+ Type type() const;
+ RustRule native_rule() const { return RustRule { native_handle() }; }
- CSSRule* parent_rule() { return m_parent_rule.ptr(); }
- CSSRule const* parent_rule() const { return m_parent_rule.ptr(); }
- void set_parent_rule(CSSRule*);
- static constexpr size_t parent_rule_offset() { return offsetof(CSSRule, m_parent_rule); }
+ Utf16String css_text() const { return serialized(); }
- StyleSheetState* parent_style_sheet() { return m_parent_style_sheet.ptr(); }
- StyleSheetState const* parent_style_sheet() const { return m_parent_style_sheet.ptr(); }
- MUST_UPCALL virtual void set_parent_style_sheet(StyleSheetState*);
- CSSStyleSheet* parent_style_sheet_for_bindings() const;
+ CSSRule* parent_rule() const;
+ StyleSheetState* parent_style_sheet() const;
Optional<SourcePosition> source_location() const;
@@ -52,23 +40,14 @@ public:
bool fast_is() const = delete;
// https://drafts.csswg.org/cssom-1/#serialize-a-css-rule
- virtual Utf16String serialized() const = 0;
-
- MUST_UPCALL virtual void dump(StringBuilder&, int indent_levels = 0) const;
-
- MUST_UPCALL virtual void clear_caches();
+ Utf16String serialized() const;
protected:
- explicit CSSRule(RustRule);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
- virtual size_t external_memory_size() const override;
+ // The CSSStyleDeclaration of the declarations of the rule, which the first call creates.
+ GC::Ref<CSSStyleDeclaration> declarations() const;
- Type m_type;
- RustRule m_native_rule;
- GC::Ptr<CSSRule> m_parent_rule;
- RefPtr<StyleSheetState> m_parent_style_sheet;
- GC::Ptr<CSSStyleSheet> m_parent_cssom_sheet;
+private:
+ Parser::ValueParserFFI::NativeRule const* native_handle() const;
};
}
diff --git a/Libraries/LibWeb/CSS/CSSRule.idl b/Libraries/LibWeb/CSS/CSSRule.idl
index 941ec83c6af..87727208077 100644
--- a/Libraries/LibWeb/CSS/CSSRule.idl
+++ b/Libraries/LibWeb/CSS/CSSRule.idl
@@ -1,10 +1,10 @@
// https://drafts.csswg.org/cssom/#the-cssrule-interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSRule {
attribute CSSOMString cssText;
- [DirectGetter] readonly attribute CSSRule? parentRule;
- [ImplementedAs=parent_style_sheet_for_bindings] readonly attribute CSSStyleSheet? parentStyleSheet;
+ readonly attribute CSSRule? parentRule;
+ readonly attribute CSSStyleSheet? parentStyleSheet;
// the following attribute and constants are historical
[ImplementedAs=type_for_bindings] readonly attribute unsigned short type;
diff --git a/Libraries/LibWeb/CSS/CSSRuleList.cpp b/Libraries/LibWeb/CSS/CSSRuleList.cpp
index 64d46bbfb50..1fa3c922f76 100644
--- a/Libraries/LibWeb/CSS/CSSRuleList.cpp
+++ b/Libraries/LibWeb/CSS/CSSRuleList.cpp
@@ -5,89 +5,78 @@
*/
#include <AK/TypeCasts.h>
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/ExternalMemory.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/CSS/CSSFontFeatureValuesRule.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
#include <LibWeb/CSS/CSSGroupingRule.h>
-#include <LibWeb/CSS/CSSImportRule.h>
-#include <LibWeb/CSS/CSSKeyframesRule.h>
#include <LibWeb/CSS/CSSRule.h>
#include <LibWeb/CSS/CSSRuleList.h>
#include <LibWeb/CSS/CSSStyleSheet.h>
-#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/StyleSheetImport.h>
#include <LibWeb/CSS/StyleSheetState.h>
-#include <LibWeb/HTML/Window.h>
+#include <LibWeb/DOM/Document.h>
namespace Web::CSS {
-CSSRuleList::~CSSRuleList() = default;
+using Parser::ValueParserFFI::NativeRuleList;
-GC_DEFINE_ALLOCATOR(CSSRuleList);
+// NB: Implemented in Libraries/LibWeb/Bindings/Rust/src/css/exports.rs.
+extern "C" {
+void* web_css_rule_list_create(void* vm, NativeRuleList const* rules, void* document);
+NativeRuleList const* web_css_rule_list_native_rules(void* list);
+size_t web_css_rule_list_length(void* list);
+void* web_css_rule_list_item(void* vm, void* list, size_t index);
+void* web_css_rule_list_existing_rule(void* list, u64 identity);
+void web_css_rule_list_set_parent_style_sheet(void* vm, void* list, void* sheet);
+void web_css_rule_list_set_rules(void* vm, void* list, NativeRuleList const* rules, void* document);
+void web_css_rule_list_remove_rule(void* vm, void* list, size_t index);
+}
-GC::Ref<CSSRuleList> CSSRuleList::create(RustRuleList rules, GC::Ptr<DOM::Document> document)
+static void* vm_abi()
{
- return GC::Heap::the().allocate<CSSRuleList>(move(rules), document);
+ return JS::HostABI::vm_to_abi(JS::VM::the());
}
-CSSRuleList::CSSRuleList(RustRuleList rules, GC::Ptr<DOM::Document> document)
- : m_rules(move(rules))
- , m_document(document)
+static void* document_cell(GC::Ptr<DOM::Document> document)
{
+ return document ? static_cast<GC::Cell*>(document.ptr()) : nullptr;
}
-CSSRule* CSSRuleList::existing_wrapper(u64 identity) const
+GC::Ref<CSSRuleList> CSSRuleList::create(RustRuleList const& rules, GC::Ptr<DOM::Document> document)
+{
+ return *static_cast<CSSRuleList*>(web_css_rule_list_create(vm_abi(), rules.handle(), document_cell(document)));
+}
+
+CSSRule* CSSRuleList::item(size_t index) const
{
- auto iterator = m_wrappers.find(identity);
- return iterator == m_wrappers.end() ? nullptr : iterator->value.ptr();
+ if (index >= length())
+ return nullptr;
+ return static_cast<CSSRule*>(web_css_rule_list_item(vm_abi(), const_cast<CSSRuleList*>(this), index));
}
-GC::Ref<CSSRule> const& CSSRuleList::wrapper_at(size_t index) const
+size_t CSSRuleList::length() const
{
- auto identity = m_rules.identity_at(index);
- if (auto iterator = m_wrappers.find(identity); iterator != m_wrappers.end())
- return iterator->value;
-
- auto rule = [&]() -> GC::Ref<CSSRule> {
- if (m_parent_style_sheet) {
- if (auto* import = m_parent_style_sheet->import_for_rule(identity))
- return import->cssom_rule();
- }
- return CSSRule::create(m_rules.at(index), m_document);
- }();
- m_wrappers.set(identity, rule);
- if (m_owner_rule)
- rule->set_parent_rule(m_owner_rule.ptr());
- else
- rule->set_parent_style_sheet(m_parent_style_sheet.ptr());
- return m_wrappers.find(identity)->value;
+ return web_css_rule_list_length(const_cast<CSSRuleList*>(this));
}
-void CSSRuleList::for_each_existing_rule(Function<void(CSSRule&)> const& callback) const
+RustRuleList CSSRuleList::native_rules() const
{
- for (auto const& entry : m_wrappers)
- callback(*entry.value);
+ return RustRuleList { Parser::ValueParserFFI::rust_rule_list_retain(web_css_rule_list_native_rules(const_cast<CSSRuleList*>(this))) };
}
-void CSSRuleList::set_owner_rule(GC::Ref<CSSRule> owner)
+CSSRule* CSSRuleList::existing_wrapper(u64 identity) const
{
- m_owner_rule = owner;
- for_each_existing_rule([&](CSSRule& rule) { rule.set_parent_rule(owner.ptr()); });
+ return static_cast<CSSRule*>(web_css_rule_list_existing_rule(const_cast<CSSRuleList*>(this), identity));
}
void CSSRuleList::set_parent_style_sheet(StyleSheetState* sheet)
{
- m_parent_style_sheet = sheet;
- m_parent_cssom_sheet = sheet ? &sheet->cssom_sheet() : nullptr;
- for_each_existing_rule([&](CSSRule& rule) { rule.set_parent_style_sheet(sheet); });
+ web_css_rule_list_set_parent_style_sheet(vm_abi(), this, sheet ? static_cast<GC::Cell*>(&sheet->cssom_sheet()) : nullptr);
}
-CSSRule const* CSSRuleList::rule_for_identity(u64 identity) const
+CSSRule* CSSRuleList::rule_for_identity(u64 identity) const
{
- auto path = m_rules.path_to_rule(identity);
+ auto path = native_rules().path_to_rule(identity);
auto const* list = this;
- CSSRule const* rule = nullptr;
+ CSSRule* rule = nullptr;
for (size_t depth = 0; depth < path.size(); ++depth) {
rule = list->item(path[depth]);
VERIFY(rule);
@@ -97,28 +86,9 @@ CSSRule const* CSSRuleList::rule_for_identity(u64 identity) const
return rule;
}
-void CSSRuleList::set_rules(Badge<StyleSheetState>, RustRuleList rules, GC::Ptr<DOM::Document> document)
+void CSSRuleList::set_rules(Badge<StyleSheetState>, RustRuleList const& rules, GC::Ptr<DOM::Document> document)
{
- for_each_existing_rule([](CSSRule& rule) { rule.set_parent_style_sheet(nullptr); });
-
- m_rules.replace(rules);
- m_wrappers.clear();
- m_document = document;
-}
-
-void CSSRuleList::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_wrappers);
- visitor.visit(m_owner_rule);
- visitor.visit(m_parent_style_sheet);
- visitor.visit(m_parent_cssom_sheet);
- visitor.visit(m_document);
-}
-
-size_t CSSRuleList::external_memory_size() const
-{
- return JS::saturating_add_external_memory_size(Base::external_memory_size(), JS::saturating_add_external_memory_size(m_rules.external_memory_size(), JS::hash_map_external_memory_size(m_wrappers)));
+ web_css_rule_list_set_rules(vm_abi(), this, rules.handle(), document_cell(document));
}
// https://drafts.csswg.org/cssom/#insert-a-css-rule
@@ -138,54 +108,6 @@ WebIDL::ExceptionOr<unsigned> CSSRuleList::insert_a_css_rule(RustRuleList& rules
VERIFY_NOT_REACHED();
}
-// AD-HOC: The spec doesn't include a declared_namespaces parameter, but we need it to handle parsing of namespaced selectors.
-// https://drafts.csswg.org/cssom/#insert-a-css-rule
-WebIDL::ExceptionOr<unsigned> CSSRuleList::insert_a_css_rule(Utf16View rule, u32 index, Nested nested, RustNamespaceContext const& declared_namespaces)
-{
- // 1. Set length to the number of items in list.
- auto length = m_rules.size();
-
- // 2. If index is greater than length, then throw an IndexSizeError exception.
- if (index > length)
- return WebIDL::IndexSizeError::create("CSS rule index out of bounds."_utf16);
-
- // 3. Set new rule to the results of performing parse a CSS rule on argument rule.
- Parser::ParsingParams parsing_params {};
- parsing_params.rule_context = rule_context();
- parsing_params.declared_namespaces = declared_namespaces;
- auto new_rule = parse_css_rule(parsing_params, rule, nested == Nested::Yes);
- if (!new_rule.has_value() && nested == Nested::Yes) {
- auto trimmed_rule = rule.trim(" \t\n\f\r"sv, TrimMode::Left);
- if (trimmed_rule.starts_with("@import"sv) || trimmed_rule.starts_with("@namespace"sv)) {
- auto top_level_params = parsing_params;
- top_level_params.rule_context.clear();
- new_rule = parse_css_rule(top_level_params, rule);
- }
- }
-
- // 4. If new rule is a syntax error, and nested is set, perform the following substeps:
- if (!new_rule.has_value() && nested == Nested::Yes) {
- // - Set declarations to the results of performing parse a CSS declaration block, on argument rule.
- auto declarations = parse_css_property_declaration_block(parsing_params, rule);
-
- // - If declarations is empty, throw a SyntaxError exception.
- if (declarations.is_empty())
- return WebIDL::SyntaxError::create("Unable to parse CSS declarations block."_utf16);
-
- // - Otherwise, set new rule to a new nested declarations rule with declarations as it contents.
- new_rule = RustRule { declarations };
- }
-
- // 5. If new rule is a syntax error, throw a SyntaxError exception.
- if (!new_rule.has_value())
- return WebIDL::SyntaxError::create("Unable to parse CSS rule."_utf16);
-
- auto result = TRY(insert_a_css_rule(m_rules, *new_rule, index, nested));
- if (on_change)
- on_change();
- return result;
-}
-
// https://www.w3.org/TR/cssom/#remove-a-css-rule
WebIDL::ExceptionOr<void> CSSRuleList::validate_rule_removal(RustRuleList const& rules, u32 index)
{
@@ -201,53 +123,9 @@ WebIDL::ExceptionOr<void> CSSRuleList::validate_rule_removal(RustRuleList const&
VERIFY_NOT_REACHED();
}
-WebIDL::ExceptionOr<RustRule> CSSRuleList::remove_a_css_rule(u32 index)
-{
- TRY(validate_rule_removal(m_rules, index));
- auto old_rule = m_rules.at(index);
- remove_a_css_rule_without_validation(index);
- return old_rule;
-}
-
void CSSRuleList::remove_a_css_rule_without_validation(Badge<StyleSheetState>, u32 index)
{
- remove_a_css_rule_without_validation(index);
-}
-
-void CSSRuleList::remove_a_css_rule_without_validation(u32 index)
-{
- VERIFY(index < m_rules.size());
-
- auto old_native_rule = m_rules.at(index);
- auto old_rule = GC::make_root(existing_wrapper(old_native_rule.identity()));
-
- // https://drafts.csswg.org/css-font-loading/#font-face-css-connection
- // If a @font-face rule is removed from the document, its corresponding FontFace object is no longer CSS-connected.
- // The connection is not restorable by any means (but adding the @font-face back to the stylesheet will create a
- // brand new FontFace object which is CSS-connected).
- if (m_parent_style_sheet)
- m_parent_style_sheet->disconnect_font_faces_in_rule(old_native_rule);
-
- // 5. Remove rule old rule from list at the zero-indexed position index.
- m_rules.remove(index);
- m_wrappers.remove(old_native_rule.identity());
-
- // 6. Set old rule’s parent CSS rule and parent CSS style sheet to null.
- // NOTE: We set the parent stylesheet to null within set_parent_rule.
- if (old_rule)
- old_rule->set_parent_rule(nullptr);
-
- if (on_change)
- on_change();
-}
-
-Vector<Parser::RuleContext> CSSRuleList::rule_context() const
-{
- Vector<Parser::RuleContext> context;
- for (auto* rule = m_owner_rule.ptr(); rule; rule = rule->parent_rule())
- context.append(Parser::rule_context_type_for_rule(rule->type()));
- context.reverse();
- return context;
+ web_css_rule_list_remove_rule(vm_abi(), this, index);
}
}
diff --git a/Libraries/LibWeb/CSS/CSSRuleList.h b/Libraries/LibWeb/CSS/CSSRuleList.h
index 0bc594d9004..166b22edd08 100644
--- a/Libraries/LibWeb/CSS/CSSRuleList.h
+++ b/Libraries/LibWeb/CSS/CSSRuleList.h
@@ -9,13 +9,11 @@
#pragma once
#include <AK/Badge.h>
-#include <AK/Function.h>
-#include <AK/HashMap.h>
-#include <AK/Utf16FlyString.h>
-#include <AK/Utf16View.h>
-#include <LibWeb/Bindings/PlatformObject.h>
+#include <LibGC/Ptr.h>
+#include <LibWeb/Bindings/CSSRuleList.h>
+#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/CSS/CSSRule.h>
-#include <LibWeb/CSS/Parser/RuleContext.h>
+#include <LibWeb/CSS/RustRule.h>
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
@@ -23,36 +21,18 @@
namespace Web::CSS {
// https://www.w3.org/TR/cssom/#the-cssrulelist-interface
-class WEB_API CSSRuleList : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(CSSRuleList, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(CSSRuleList);
+class WEB_API CSSRuleList final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(CSSRuleList, css_rule_list)
public:
- [[nodiscard]] static GC::Ref<CSSRuleList> create(RustRuleList, GC::Ptr<DOM::Document>);
+ [[nodiscard]] static GC::Ref<CSSRuleList> create(RustRuleList const&, GC::Ptr<DOM::Document>);
- virtual ~CSSRuleList() override;
-
- CSSRule const* item(size_t index) const
- {
- if (index >= length())
- return nullptr;
- return wrapper_at(index).ptr();
- }
-
- CSSRule* item(size_t index)
- {
- if (index >= length())
- return nullptr;
- return wrapper_at(index).ptr();
- }
-
- size_t length() const { return m_rules.size(); }
- RustRuleList const& native_rules() const { return m_rules; }
+ CSSRule* item(size_t index) const;
+ size_t length() const;
+ RustRuleList native_rules() const;
CSSRule* existing_wrapper(u64 identity) const;
- void for_each_existing_rule(Function<void(CSSRule&)> const&) const;
void set_parent_style_sheet(StyleSheetState*);
- CSSRule const* rule_for_identity(u64) const;
- CSSRule* rule_for_identity(u64 identity) { return const_cast<CSSRule*>(std::as_const(*this).rule_for_identity(identity)); }
+ CSSRule* rule_for_identity(u64) const;
class Iterator {
public:
@@ -61,7 +41,7 @@ public:
, m_index(index)
{
}
- GC::Ref<CSSRule> const& operator*() const { return m_list->wrapper_at(m_index); }
+ GC::Ref<CSSRule> operator*() const { return *m_list->item(m_index); }
Iterator& operator++()
{
++m_index;
@@ -78,36 +58,14 @@ public:
Iterator end() const { return { *this, length() }; }
static WebIDL::ExceptionOr<void> validate_rule_removal(RustRuleList const&, u32 index);
- WebIDL::ExceptionOr<RustRule> remove_a_css_rule(u32 index);
void remove_a_css_rule_without_validation(Badge<StyleSheetState>, u32 index);
enum class Nested {
No,
Yes,
};
static WebIDL::ExceptionOr<unsigned> insert_a_css_rule(RustRuleList&, RustRule const&, u32 index, Nested);
- WebIDL::ExceptionOr<unsigned> insert_a_css_rule(Utf16View, u32 index, Nested, RustNamespaceContext const& declared_namespaces);
-
- void set_owner_rule(GC::Ref<CSSRule>);
- void set_rules(Badge<StyleSheetState>, RustRuleList, GC::Ptr<DOM::Document>);
-
- Function<void()> on_change;
-
-private:
- CSSRuleList(RustRuleList, GC::Ptr<DOM::Document>);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
- virtual size_t external_memory_size() const override;
-
- void remove_a_css_rule_without_validation(u32 index);
- Vector<Parser::RuleContext> rule_context() const;
- GC::Ref<CSSRule> const& wrapper_at(size_t index) const;
- RustRuleList m_rules;
- mutable HashMap<u64, GC::Ref<CSSRule>> m_wrappers;
- GC::Ptr<CSSRule> m_owner_rule;
- RefPtr<StyleSheetState> m_parent_style_sheet;
- GC::Ptr<CSSStyleSheet> m_parent_cssom_sheet;
- GC::Ptr<DOM::Document> m_document;
+ void set_rules(Badge<StyleSheetState>, RustRuleList const&, GC::Ptr<DOM::Document>);
};
}
diff --git a/Libraries/LibWeb/CSS/CSSRuleList.idl b/Libraries/LibWeb/CSS/CSSRuleList.idl
index 95b1e8cd977..bd54a414cc4 100644
--- a/Libraries/LibWeb/CSS/CSSRuleList.idl
+++ b/Libraries/LibWeb/CSS/CSSRuleList.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/cssom/#the-cssrulelist-interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSRuleList {
getter CSSRule? item(unsigned long index);
diff --git a/Libraries/LibWeb/CSS/CSSScopeRule.cpp b/Libraries/LibWeb/CSS/CSSScopeRule.cpp
deleted file mode 100644
index caf922963b9..00000000000
--- a/Libraries/LibWeb/CSS/CSSScopeRule.cpp
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (c) 2026, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSScopeRule.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSRuleList.h>
-#include <LibWeb/Dump.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSScopeRule);
-
-GC::Ref<CSSScopeRule> CSSScopeRule::create(RustRule rule, CSSRuleList& rules)
-{
- return GC::Heap::the().allocate<CSSScopeRule>(move(rule), rules);
-}
-
-CSSScopeRule::CSSScopeRule(RustRule rule, CSSRuleList& rules)
- : CSSGroupingRule(rules, move(rule))
- , m_selectors(RustScopeSelectors::create(native_rule().payload().scope))
-{
-}
-
-CSSScopeRule::~CSSScopeRule() = default;
-
-void CSSScopeRule::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
-}
-
-Optional<Utf16String> CSSScopeRule::start() const
-{
- if (start_selectors().has_value())
- return serialize_a_group_of_selectors(*start_selectors());
- return {};
-}
-
-Optional<Utf16String> CSSScopeRule::end() const
-{
- if (end_selectors().has_value())
- return serialize_a_group_of_selectors(*end_selectors());
- return {};
-}
-
-// https://drafts.csswg.org/cssom-1/#serialize-a-css-rule
-Utf16String CSSScopeRule::serialized() const
-{
- // AD-HOC: There is no spec for this yet.
- Utf16StringBuilder builder;
- builder.append_ascii("@scope"sv);
-
- if (auto start = this->start(); start.has_value())
- builder.appendff(" ({})", *start);
-
- if (auto end = this->end(); end.has_value())
- builder.appendff(" to ({})", *end);
-
- builder.append_ascii(" {\n"sv);
-
- for (size_t i = 0; i < css_rules().length(); i++) {
- auto rule = css_rules().item(i);
- auto result = rule->serialized();
-
- if (result.is_empty())
- continue;
-
- builder.append_ascii(" "sv);
- builder.append(result);
- builder.append_ascii('\n');
- }
-
- builder.append_ascii('}');
-
- return builder.to_string();
-}
-
-void CSSScopeRule::dump(StringBuilder& builder, int indent_levels) const
-{
- Base::dump(builder, indent_levels);
-
- dump_indent(builder, indent_levels + 1);
- if (start_selectors().has_value()) {
- builder.appendff("Start selectors ({}):\n", start_selectors()->size());
- for (auto& selector : *start_selectors())
- dump_selector(builder, selector, indent_levels + 2);
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Absolutized start selectors:\n");
- auto matching_selectors = scope_start_selectors_for_rule(native_rule());
- for (auto& selector : matching_selectors.value()) {
- dump_selector(builder, selector, indent_levels + 2);
- }
- } else {
- builder.append("Start selectors: <none>\n"sv);
- }
-
- dump_indent(builder, indent_levels + 1);
- if (end_selectors().has_value()) {
- builder.appendff("End selectors ({}):\n", end_selectors()->size());
- for (auto& selector : *end_selectors())
- dump_selector(builder, selector, indent_levels + 2);
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Absolutized end selectors:\n");
- auto matching_selectors = scope_end_selectors_for_rule(native_rule());
- for (auto& selector : matching_selectors.value()) {
- dump_selector(builder, selector, indent_levels + 2);
- }
- } else {
- builder.append("End selectors: <none>\n"sv);
- }
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Rules ({}):\n", css_rules().length());
- for (auto& rule : css_rules())
- dump_rule(builder, rule, indent_levels + 2);
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSScopeRule.h b/Libraries/LibWeb/CSS/CSSScopeRule.h
deleted file mode 100644
index 5853e9ac711..00000000000
--- a/Libraries/LibWeb/CSS/CSSScopeRule.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2026, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <AK/Utf16String.h>
-#include <LibWeb/CSS/CSSGroupingRule.h>
-#include <LibWeb/CSS/RustScopeSelectors.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::CSS {
-
-// https://drafts.csswg.org/css-cascade-6/#the-cssscoperule-interface
-class CSSScopeRule final : public CSSGroupingRule {
- WEB_WRAPPABLE(CSSScopeRule, CSSGroupingRule);
- GC_DECLARE_ALLOCATOR(CSSScopeRule);
-
-public:
- [[nodiscard]] static GC::Ref<CSSScopeRule> create(RustRule, CSSRuleList&);
-
- virtual ~CSSScopeRule() override;
-
- Optional<SelectorList> const& start_selectors() const { return m_selectors->start(); }
- Optional<SelectorList> const& end_selectors() const { return m_selectors->end(); }
- Optional<Utf16String> start() const;
- Optional<Utf16String> end() const;
-
-private:
- CSSScopeRule(RustRule, CSSRuleList&);
- virtual void visit_edges(GC::Cell::Visitor&) override;
- virtual Utf16String serialized() const override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
-
- NonnullRefPtr<RustScopeSelectors> m_selectors;
-};
-
-template<>
-inline bool CSSRule::fast_is<CSSScopeRule>() const { return type() == CSSRule::Type::Scope; }
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSScopeRule.idl b/Libraries/LibWeb/CSS/CSSScopeRule.idl
index 89169ff0516..c02f245b8db 100644
--- a/Libraries/LibWeb/CSS/CSSScopeRule.idl
+++ b/Libraries/LibWeb/CSS/CSSScopeRule.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/css-cascade-6/#the-cssscoperule-interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSScopeRule : CSSGroupingRule {
readonly attribute CSSOMString? start;
readonly attribute CSSOMString? end;
diff --git a/Libraries/LibWeb/CSS/CSSStyleDeclaration.h b/Libraries/LibWeb/CSS/CSSStyleDeclaration.h
index f1b0b9d0175..1b036ee2842 100644
--- a/Libraries/LibWeb/CSS/CSSStyleDeclaration.h
+++ b/Libraries/LibWeb/CSS/CSSStyleDeclaration.h
@@ -51,7 +51,6 @@ public:
// https://drafts.csswg.org/cssom/#cssstyledeclaration-parent-css-rule
GC::Ptr<CSSRule> parent_rule() const { return m_parent_rule; }
void set_parent_rule(GC::Ptr<CSSRule> parent) { m_parent_rule = parent; }
- static constexpr GC::MemberOffset parent_rule_offset() { return GC_FIELD_OFFSET(CSSStyleDeclaration, m_parent_rule); }
// https://drafts.csswg.org/cssom/#cssstyledeclaration-owner-node
Optional<DOM::AbstractElement> owner_node() const
diff --git a/Libraries/LibWeb/CSS/CSSStyleDeclaration.idl b/Libraries/LibWeb/CSS/CSSStyleDeclaration.idl
index 9a8a843853a..95c87cbd7db 100644
--- a/Libraries/LibWeb/CSS/CSSStyleDeclaration.idl
+++ b/Libraries/LibWeb/CSS/CSSStyleDeclaration.idl
@@ -12,5 +12,5 @@ interface CSSStyleDeclaration {
[CEReactions] undefined setProperty(CSSOMString property, [LegacyNullToEmptyString] CSSOMString value, optional [LegacyNullToEmptyString] CSSOMString priority = "");
[CEReactions] CSSOMString removeProperty(CSSOMString property);
- [DirectGetter] readonly attribute CSSRule? parentRule;
+ readonly attribute CSSRule? parentRule;
};
diff --git a/Libraries/LibWeb/CSS/CSSStyleRule.cpp b/Libraries/LibWeb/CSS/CSSStyleRule.cpp
index 769fb6ea20d..f327ad89e54 100644
--- a/Libraries/LibWeb/CSS/CSSStyleRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSStyleRule.cpp
@@ -5,151 +5,32 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/ExternalMemory.h>
-#include <LibWeb/CSS/CSSRuleList.h>
#include <LibWeb/CSS/CSSStyleRule.h>
-#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/StyleComputer.h>
+#include <LibWeb/CSS/Serialize.h>
#include <LibWeb/CSS/StyleEngineInput.h>
-#include <LibWeb/CSS/StylePropertyMap.h>
#include <LibWeb/CSS/StyleSheetState.h>
-#include <LibWeb/Dump.h>
namespace Web::CSS {
-GC_DEFINE_ALLOCATOR(CSSStyleRule);
+// NB: Implemented in Libraries/LibWeb/Bindings/Rust/src/css/exports.rs.
+extern "C" void web_css_style_rule_set_selector_text(void* rule, FlatPtr text);
-// NB: The CSSOM wraps every style rule a script reads, so its wrapper stays small.
-#if ARCH(X86_64) && !defined(AK_OS_WINDOWS)
-static_assert(sizeof(CSSRule) <= 64);
-static_assert(sizeof(CSSStyleRule) <= 112);
-#endif
+// NB: What the implementation of CSSStyleRule in Rust asks of the C++ code of LibWeb.
+extern "C" void web_css_style_rule_selector_changed(void* rule);
-GC::Ref<CSSStyleRule> CSSStyleRule::create(RustRule rule)
+SelectorList CSSStyleRule::selectors() const
{
- return GC::Heap::the().allocate<CSSStyleRule>(move(rule));
+ return selector_list_from_rust(static_cast<SelectorFFI::RustParsedSelectorList const*>(Parser::ValueParserFFI::rust_rule_selectors(native_rule().handle())));
}
-CSSStyleRule::CSSStyleRule(RustRule rule)
- : CSSGroupingRule(nullptr, move(rule))
- , m_declarations(Parser::ValueParserFFI::rust_rule_declarations(native_rule().handle()))
+SelectorList CSSStyleRule::absolutized_selectors() const
{
+ return matching_selectors_for_rule(native_rule());
}
-CSSStyleRule::SelectorCaches& CSSStyleRule::selector_caches() const
+RustDeclarationBlock CSSStyleRule::declaration() const
{
- if (!m_selector_caches)
- m_selector_caches = make<SelectorCaches>();
- return *m_selector_caches;
-}
-
-SelectorList const& CSSStyleRule::selectors() const
-{
- auto& caches = selector_caches();
- if (!caches.selectors.has_value())
- caches.selectors = selector_list_from_rust(static_cast<SelectorFFI::RustParsedSelectorList const*>(Parser::ValueParserFFI::rust_rule_selectors(native_rule().handle())));
- return *caches.selectors;
-}
-
-size_t CSSStyleRule::external_memory_size() const
-{
- return JS::saturating_add_external_memory_size(Base::external_memory_size(), m_declarations.external_memory_size());
-}
-
-GC::Ref<CSSStyleProperties> CSSStyleRule::ensure_style_properties() const
-{
- if (!m_declaration) {
- m_declaration = CSSStyleProperties::create(m_declarations.retain());
- m_declaration->set_parent_rule(const_cast<CSSStyleRule&>(*this));
- }
- return *m_declaration;
-}
-
-void CSSStyleRule::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_declaration);
- visitor.visit(m_style_map);
-}
-
-// https://drafts.csswg.org/cssom-1/#dom-cssstylerule-style
-GC::Ref<CSSStyleProperties> CSSStyleRule::style() const
-{
- return ensure_style_properties();
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssstylerule-stylemap
-GC::Ref<StylePropertyMap> CSSStyleRule::style_map()
-{
- if (!m_style_map)
- m_style_map = StylePropertyMap::create(ensure_style_properties());
- return *m_style_map;
-}
-
-// https://drafts.csswg.org/cssom-1/#serialize-a-css-rule
-Utf16String CSSStyleRule::serialized() const
-{
- Utf16StringBuilder builder;
-
- // 1. Let s initially be the result of performing serialize a group of selectors on the rule’s associated selectors,
- // followed by the string " {", i.e., a single SPACE (U+0020), followed by LEFT CURLY BRACKET (U+007B).
- builder.append(selector_text());
- builder.append_ascii(" {"sv);
-
- // 2. Let decls be the result of performing serialize a CSS declaration block on the rule’s associated declarations,
- // or null if there are no such declarations.
- auto decls = !m_declarations.is_empty() ? Optional<Utf16String> { ensure_style_properties()->serialized() } : Optional<Utf16String> {};
-
- // 3. Let rules be the result of performing serialize a CSS rule on each rule in the rule’s cssRules list,
- // or null if there are no such rules.
- Vector<Utf16String> rules;
- for (auto& rule : css_rules()) {
- rules.append(rule->serialized());
- }
-
- // 4. If decls and rules are both null, append " }" to s (i.e. a single SPACE (U+0020) followed by RIGHT CURLY BRACKET (U+007D)) and return s.
- if (!decls.has_value() && rules.is_empty()) {
- builder.append_ascii(" }"sv);
- return builder.to_string();
- }
-
- // 5. If rules is null:
- if (rules.is_empty()) {
- // 1. Append a single SPACE (U+0020) to s
- builder.append_ascii(' ');
- // 2. Append decls to s
- builder.append(*decls);
- // 3. Append " }" to s (i.e. a single SPACE (U+0020) followed by RIGHT CURLY BRACKET (U+007D)).
- builder.append_ascii(" }"sv);
- // 4. Return s.
- return builder.to_string();
- }
-
- // 6. Otherwise:
- else {
- // 1. If decls is not null, prepend it to rules.
- if (decls.has_value())
- rules.prepend(decls.value());
-
- // 2. For each rule in rules:
- for (auto& rule : rules) {
- // * If rule is the empty string, do nothing.
- if (rule.is_empty())
- continue;
-
- // * Otherwise:
- // 1. Append a newline followed by two spaces to s.
- // 2. Append rule to s.
- builder.appendff("\n {}", rule);
- }
-
- // 3. Append a newline followed by RIGHT CURLY BRACKET (U+007D) to s.
- builder.append_ascii("\n}"sv);
-
- // 4. Return s.
- return builder.to_string();
- }
+ return RustDeclarationBlock { Parser::ValueParserFFI::rust_rule_declarations(native_rule().handle()) };
}
// https://drafts.csswg.org/cssom-1/#dom-cssstylerule-selectortext
@@ -159,59 +40,21 @@ Utf16String CSSStyleRule::selector_text() const
return serialize_a_group_of_selectors(selectors(), parent_style_sheet());
}
-// https://drafts.csswg.org/cssom-1/#dom-cssstylerule-selectortext
void CSSStyleRule::set_selector_text(Utf16View selector_text)
{
- // 1. Run the parse a group of selectors algorithm on the given value.
- auto* sheet = parent_style_sheet();
-
- // 2. If the algorithm returns a non-null value replace the associated group of selectors with the returned value.
- if (Parser::ValueParserFFI::rust_rule_set_selector_text(native_rule().handle(), Parser::ffi_utf16_view(selector_text), sheet ? sheet->native_rules().handle() : nullptr)) {
- if (m_selector_caches)
- m_selector_caches->selectors.clear();
- clear_caches();
- if (sheet) {
- record_style_rule_selector_changed(*this);
- sheet->invalidate_owners();
- }
- }
-
- // 3. Otherwise, if the algorithm returns a null value, do nothing.
-}
-
-SelectorList const& CSSStyleRule::absolutized_selectors() const
-{
- auto& caches = selector_caches();
- if (!caches.absolutized_selectors.has_value())
- caches.absolutized_selectors = matching_selectors_for_rule(native_rule());
- return *caches.absolutized_selectors;
+ web_css_style_rule_set_selector_text(this, Utf16String::from_utf16(selector_text).into_raw());
}
-void CSSStyleRule::clear_caches()
+GC::Ref<CSSStyleProperties> CSSStyleRule::style() const
{
- Base::clear_caches();
- if (m_selector_caches)
- m_selector_caches->absolutized_selectors.clear();
+ return static_cast<CSSStyleProperties&>(*declarations());
}
-void CSSStyleRule::dump(StringBuilder& builder, int indent_levels) const
+void web_css_style_rule_selector_changed(void* cell)
{
- Base::dump(builder, indent_levels);
-
- for (auto& selector : selectors()) {
- dump_selector(builder, selector, indent_levels + 1);
- }
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Absolutized selectors:\n");
- for (auto& selector : absolutized_selectors()) {
- dump_selector(builder, selector, indent_levels + 2);
- }
- dump_style_properties(builder, *ensure_style_properties(), indent_levels + 1);
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Child rules ({}):\n", css_rules().length());
- for (auto& child_rule : css_rules())
- dump_rule(builder, child_rule, indent_levels + 2);
+ auto& rule = *static_cast<CSSStyleRule*>(cell);
+ record_style_rule_selector_changed(rule);
+ rule.parent_style_sheet()->invalidate_owners();
}
}
diff --git a/Libraries/LibWeb/CSS/CSSStyleRule.h b/Libraries/LibWeb/CSS/CSSStyleRule.h
index ee8ee77acb7..00a4b7c937d 100644
--- a/Libraries/LibWeb/CSS/CSSStyleRule.h
+++ b/Libraries/LibWeb/CSS/CSSStyleRule.h
@@ -7,10 +7,7 @@
#pragma once
-#include <AK/NonnullRefPtr.h>
-#include <AK/OwnPtr.h>
-#include <AK/Utf16String.h>
-#include <AK/Utf16View.h>
+#include <LibWeb/Bindings/CSSStyleRule.h>
#include <LibWeb/CSS/CSSGroupingRule.h>
#include <LibWeb/CSS/CSSStyleProperties.h>
#include <LibWeb/CSS/Selector.h>
@@ -18,45 +15,17 @@
namespace Web::CSS {
class CSSStyleRule final : public CSSGroupingRule {
- WEB_WRAPPABLE(CSSStyleRule, CSSGroupingRule);
- GC_DECLARE_ALLOCATOR(CSSStyleRule);
+ WEB_RUST_INTERFACE(CSSStyleRule, css_style_rule)
public:
- [[nodiscard]] static GC::Ref<CSSStyleRule> create(RustRule);
-
- virtual ~CSSStyleRule() override = default;
-
- SelectorList const& selectors() const;
- SelectorList const& absolutized_selectors() const;
- RustDeclarationBlock const& declaration() const { return m_declarations; }
+ SelectorList selectors() const;
+ SelectorList absolutized_selectors() const;
+ RustDeclarationBlock declaration() const;
Utf16String selector_text() const;
void set_selector_text(Utf16View);
GC::Ref<CSSStyleProperties> style() const;
- GC::Ref<StylePropertyMap> style_map();
-
-private:
- explicit CSSStyleRule(RustRule);
- GC::Ref<CSSStyleProperties> ensure_style_properties() const;
- virtual size_t external_memory_size() const override;
- virtual void visit_edges(GC::Cell::Visitor&) override;
- virtual void clear_caches() override;
- virtual Utf16String serialized() const override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
-
- // What the rule makes of its selectors when they are first read; boxed, as most rules never make it.
- struct SelectorCaches {
- AK_ALLOC_WITH_KMALLOC;
- Optional<SelectorList> selectors;
- Optional<SelectorList> absolutized_selectors;
- };
- SelectorCaches& selector_caches() const;
-
- mutable OwnPtr<SelectorCaches> m_selector_caches;
- RustDeclarationBlock m_declarations;
- mutable GC::Ptr<CSSStyleProperties> m_declaration;
- GC::Ptr<StylePropertyMap> m_style_map;
};
template<>
diff --git a/Libraries/LibWeb/CSS/CSSStyleRule.idl b/Libraries/LibWeb/CSS/CSSStyleRule.idl
index 995eb91ee12..91daaf8ae03 100644
--- a/Libraries/LibWeb/CSS/CSSStyleRule.idl
+++ b/Libraries/LibWeb/CSS/CSSStyleRule.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/cssom/#the-cssstylerule-interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSStyleRule : CSSGroupingRule {
attribute CSSOMString selectorText;
[SameObject, PutForwards=cssText] readonly attribute CSSStyleProperties style;
diff --git a/Libraries/LibWeb/CSS/CSSSupportsRule.cpp b/Libraries/LibWeb/CSS/CSSSupportsRule.cpp
deleted file mode 100644
index 203481ffbf5..00000000000
--- a/Libraries/LibWeb/CSS/CSSSupportsRule.cpp
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (c) 2021-2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSSupportsRule.h>
-#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/Dump.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSSupportsRule);
-
-GC::Ref<CSSSupportsRule> CSSSupportsRule::create(RustRule rule, CSSRuleList& rules)
-{
- return GC::Heap::the().allocate<CSSSupportsRule>(move(rule), rules);
-}
-
-CSSSupportsRule::CSSSupportsRule(RustRule rule, CSSRuleList& rules)
- : CSSConditionRule(rules, move(rule))
- , m_supports(RustQueryHandle::retained(native_rule().payload().supports))
-{
-}
-
-Utf16String CSSSupportsRule::serialized_condition_text() const
-{
- return serialize_supports_condition(m_supports);
-}
-
-// https://www.w3.org/TR/cssom-1/#serialize-a-css-rule
-Utf16String CSSSupportsRule::serialized() const
-{
- // Note: The spec doesn't cover this yet, so I'm roughly following the spec for the @media rule.
- // It should be pretty close!
-
- Utf16StringBuilder builder;
-
- builder.append_ascii("@supports "sv);
- builder.append(serialized_condition_text());
- builder.append_ascii(" {\n"sv);
- for (size_t i = 0; i < css_rules().length(); i++) {
- auto rule = css_rules().item(i);
- if (i != 0)
- builder.append_ascii("\n"sv);
- builder.append_ascii(" "sv);
- builder.append(rule->serialized());
- }
- builder.append_ascii("\n}"sv);
-
- return builder.to_string();
-}
-
-void CSSSupportsRule::dump(StringBuilder& builder, int indent_levels) const
-{
- Base::dump(builder, indent_levels);
-
- dump_supports_condition(builder, supports(), indent_levels + 1);
-
- dump_indent(builder, indent_levels + 1);
- builder.appendff("Rules ({}):\n", css_rules().length());
- for (auto& rule : css_rules())
- dump_rule(builder, rule, indent_levels + 2);
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSSupportsRule.h b/Libraries/LibWeb/CSS/CSSSupportsRule.h
deleted file mode 100644
index 773678fe390..00000000000
--- a/Libraries/LibWeb/CSS/CSSSupportsRule.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2021-2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/NonnullRefPtr.h>
-#include <LibWeb/CSS/CSSConditionRule.h>
-#include <LibWeb/CSS/CSSRule.h>
-#include <LibWeb/CSS/Supports.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::CSS {
-
-// https://www.w3.org/TR/css-conditional-3/#the-csssupportsrule-interface
-class CSSSupportsRule final : public CSSConditionRule {
- WEB_WRAPPABLE(CSSSupportsRule, CSSConditionRule);
- GC_DECLARE_ALLOCATOR(CSSSupportsRule);
-
-public:
- static GC::Ref<CSSSupportsRule> create(RustRule, CSSRuleList&);
-
- virtual ~CSSSupportsRule() = default;
-
- virtual Utf16String serialized_condition_text() const override;
- bool matches() const { return supports_condition_matches(m_supports); }
-
- RustQueryHandle const& supports() const { return m_supports; }
-
-private:
- CSSSupportsRule(RustRule, CSSRuleList&);
-
- virtual Utf16String serialized() const override;
- virtual void dump(StringBuilder&, int indent_levels) const override;
-
- RustQueryHandle m_supports;
-};
-
-template<>
-inline bool CSSRule::fast_is<CSSSupportsRule>() const { return type() == CSSRule::Type::Supports; }
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSSupportsRule.idl b/Libraries/LibWeb/CSS/CSSSupportsRule.idl
index 1d74b8b2e09..47dd7152329 100644
--- a/Libraries/LibWeb/CSS/CSSSupportsRule.idl
+++ b/Libraries/LibWeb/CSS/CSSSupportsRule.idl
@@ -1,5 +1,5 @@
// https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface CSSSupportsRule : CSSConditionRule {
readonly attribute boolean matches;
};
diff --git a/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp b/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp
index 465e64e035a..01058f45372 100644
--- a/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp
+++ b/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp
@@ -31,10 +31,7 @@
#include <LibWeb/Bindings/PrincipalHostDefined.h>
#include <LibWeb/CSS/CSSAnimation.h>
#include <LibWeb/CSS/CSSImportRule.h>
-#include <LibWeb/CSS/CSSLayerBlockRule.h>
-#include <LibWeb/CSS/CSSLayerStatementRule.h>
#include <LibWeb/CSS/CSSNestedDeclarations.h>
-#include <LibWeb/CSS/CSSScopeRule.h>
#include <LibWeb/CSS/CSSStyleProperties.h>
#include <LibWeb/CSS/CSSStyleRule.h>
#include <LibWeb/CSS/CSSTransition.h>
@@ -107,7 +104,7 @@
namespace Web::CSS {
// What a rule contributes, for the two rule types that carry a declaration block.
-static RustDeclarationBlock const& declaration_of_rule(CSSRule const& rule)
+static RustDeclarationBlock declaration_of_rule(CSSRule const& rule)
{
if (rule.type() == CSSRule::Type::Style)
return static_cast<CSSStyleRule const&>(rule).declaration();
@@ -377,15 +374,13 @@ static JsonObject serialize_devtools_style_sheet_identifier(StyleSheetIdentifier
// the entry, and a panel can afford to match each selector again.
static JsonObject serialize_devtools_applied_rule(DOM::Document& document, CSSRule const& rule, DOM::AbstractElement const& element)
{
- auto const& declaration = declaration_of_rule(rule);
+ auto declaration = declaration_of_rule(rule);
auto authored_text = extract_css_declaration_block_from_source(rule);
- SelectorList const* selector_list = nullptr;
+ SelectorList selectors;
if (auto const* style_rule = as_if<CSSStyleRule>(rule))
- selector_list = &style_rule->absolutized_selectors();
+ selectors = style_rule->absolutized_selectors();
else if (auto const* nested = as_if<CSSNestedDeclarations>(rule))
- selector_list = &nested->absolutized_selectors();
- SelectorList const empty_selectors;
- auto const& selectors = selector_list ? *selector_list : empty_selectors;
+ selectors = nested->absolutized_selectors();
JsonArray serialized_selectors;
JsonArray specificities;
diff --git a/Libraries/LibWeb/CSS/MediaList.cpp b/Libraries/LibWeb/CSS/MediaList.cpp
index 7810b9a53c1..6ce66b1b62d 100644
--- a/Libraries/LibWeb/CSS/MediaList.cpp
+++ b/Libraries/LibWeb/CSS/MediaList.cpp
@@ -49,13 +49,13 @@ void MediaList::set_associated_style_sheet(NonnullRefPtr<StyleSheetState> sheet)
void MediaList::set_associated_rule(GC::Ref<CSSRule> rule)
{
- web_media_list_set_associated_rule(JS::HostABI::vm_to_abi(JS::VM::the()), this, static_cast<GC::Cell*>(rule.ptr()));
+ web_media_list_set_associated_rule(JS::HostABI::vm_to_abi(JS::VM::the()), this, rule.ptr());
}
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* rule = static_cast<CSSRule*>(static_cast<GC::Cell*>(rule_cell));
+ auto* rule = static_cast<CSSRule*>(rule_cell);
// Both owners reach the same place: the sheet whose rules the gate belongs to.
RefPtr<StyleSheetState> sheet;
diff --git a/Libraries/LibWeb/CSS/RustScopeSelectors.h b/Libraries/LibWeb/CSS/RustScopeSelectors.h
deleted file mode 100644
index 354f35b54f5..00000000000
--- a/Libraries/LibWeb/CSS/RustScopeSelectors.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/Selector.h>
-#include <LibWeb/ValueParserRustFFI.h>
-
-namespace Web::CSS {
-
-// Document-thread bindings of the immutable, worker-parsed scope selector pair.
-class RustScopeSelectors final : public RefCounted<RustScopeSelectors> {
-public:
- static NonnullRefPtr<RustScopeSelectors> create(Parser::ValueParserFFI::ScopeSelectors const* selectors)
- {
- return adopt_ref(*new RustScopeSelectors(selectors));
- }
- ~RustScopeSelectors() { Parser::ValueParserFFI::rust_scope_selectors_release(m_selectors); }
-
- Parser::ValueParserFFI::ScopeSelectors const* handle() const { return m_selectors; }
- Optional<SelectorList> const& start() const
- {
- if (!m_start.has_value()) {
- if (auto* selectors = Parser::ValueParserFFI::rust_scope_selectors_start(m_selectors))
- m_start = selector_list_from_rust(static_cast<SelectorFFI::RustParsedSelectorList const*>(selectors));
- }
- return m_start;
- }
- Optional<SelectorList> const& end() const
- {
- if (!m_end.has_value()) {
- if (auto* selectors = Parser::ValueParserFFI::rust_scope_selectors_end(m_selectors))
- m_end = selector_list_from_rust(static_cast<SelectorFFI::RustParsedSelectorList const*>(selectors));
- }
- return m_end;
- }
-
-private:
- explicit RustScopeSelectors(Parser::ValueParserFFI::ScopeSelectors const* selectors)
- : m_selectors(Parser::ValueParserFFI::rust_scope_selectors_retain(selectors))
- {
- }
-
- Parser::ValueParserFFI::ScopeSelectors const* m_selectors;
- mutable Optional<SelectorList> m_start;
- mutable Optional<SelectorList> m_end;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/StyleComputer.cpp b/Libraries/LibWeb/CSS/StyleComputer.cpp
index c50cccd2c1a..91e33852d8a 100644
--- a/Libraries/LibWeb/CSS/StyleComputer.cpp
+++ b/Libraries/LibWeb/CSS/StyleComputer.cpp
@@ -34,10 +34,7 @@
#include <LibWeb/Bindings/PrincipalHostDefined.h>
#include <LibWeb/CSS/CSSAnimation.h>
#include <LibWeb/CSS/CSSImportRule.h>
-#include <LibWeb/CSS/CSSLayerBlockRule.h>
-#include <LibWeb/CSS/CSSLayerStatementRule.h>
#include <LibWeb/CSS/CSSNestedDeclarations.h>
-#include <LibWeb/CSS/CSSScopeRule.h>
#include <LibWeb/CSS/CSSStyleProperties.h>
#include <LibWeb/CSS/CSSStyleRule.h>
#include <LibWeb/CSS/CSSTransition.h>
diff --git a/Libraries/LibWeb/CSS/StyleEngineInput.cpp b/Libraries/LibWeb/CSS/StyleEngineInput.cpp
index 2c628bb1b3e..c8a11855f51 100644
--- a/Libraries/LibWeb/CSS/StyleEngineInput.cpp
+++ b/Libraries/LibWeb/CSS/StyleEngineInput.cpp
@@ -11,7 +11,6 @@
#include <LibGC/RootHashTable.h>
#include <LibWeb/Animations/KeyframeEffect.h>
#include <LibWeb/CSS/CSSAnimation.h>
-#include <LibWeb/CSS/CSSPropertyRule.h>
#include <LibWeb/CSS/CSSStyleRule.h>
#include <LibWeb/CSS/CSSTransition.h>
#include <LibWeb/CSS/ElementBoxKind.h>
diff --git a/Libraries/LibWeb/CSS/StyleSheetImport.cpp b/Libraries/LibWeb/CSS/StyleSheetImport.cpp
index 6bb6edfe54e..05fd0fdcae2 100644
--- a/Libraries/LibWeb/CSS/StyleSheetImport.cpp
+++ b/Libraries/LibWeb/CSS/StyleSheetImport.cpp
@@ -10,8 +10,12 @@
#include <AK/Debug.h>
#include <AK/ScopeGuard.h>
+#include <LibGC/Heap.h>
#include <LibGC/Root.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
#include <LibWeb/CSS/CSSImportRule.h>
+#include <LibWeb/CSS/CSSStyleSheet.h>
#include <LibWeb/CSS/Fetch.h>
#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/StyleEngineInput.h>
@@ -27,6 +31,80 @@
namespace Web::CSS {
+using Parser::ValueParserFFI::NativeRule;
+
+// NB: Implemented in Libraries/LibWeb/Bindings/Rust/src/css/exports.rs.
+extern "C" void* web_css_import_rule_create(void* vm, NativeRule const* rule, void* import, void* sheet);
+
+// NB: What the implementation of CSSImportRule in Rust asks of the C++ code of LibWeb.
+extern "C" {
+void* web_css_import_create(NativeRule const* rule, void* document);
+void web_css_import_set_rule(void* import, void* rule);
+void web_css_import_set_parent_style_sheet(void* import, void* sheet);
+FlatPtr web_css_import_href(void* import);
+FlatPtr web_css_import_url_text(void* import);
+void* web_css_import_media(void* import);
+void* web_css_import_style_sheet(void* import);
+}
+
+GC_DEFINE_ALLOCATOR(StyleSheetImportCell);
+
+GC::Ref<StyleSheetImportCell> StyleSheetImportCell::create(NonnullRefPtr<StyleSheetImport> import)
+{
+ return GC::Heap::the().allocate<StyleSheetImportCell>(move(import));
+}
+
+void StyleSheetImportCell::visit_edges(GC::Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ m_import->visit_edges(visitor);
+}
+
+static StyleSheetImport& import_from_cell(void* import)
+{
+ return static_cast<StyleSheetImportCell*>(static_cast<GC::Cell*>(import))->import();
+}
+
+void* web_css_import_create(NativeRule const* rule, void* document)
+{
+ auto* document_object = static_cast<DOM::Document*>(static_cast<GC::Cell*>(document));
+ return static_cast<GC::Cell*>(StyleSheetImportCell::create(StyleSheetImport::create(RustRule { rule }, document_object)).ptr());
+}
+
+void web_css_import_set_rule(void* import, void* rule)
+{
+ import_from_cell(import).set_cssom_rule(*static_cast<CSSImportRule*>(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;
+ if (import.parent_style_sheet() != state)
+ import.set_parent_style_sheet(state);
+}
+
+FlatPtr web_css_import_href(void* import)
+{
+ return Utf16String { import_from_cell(import).href() }.into_raw();
+}
+
+FlatPtr web_css_import_url_text(void* import)
+{
+ return import_from_cell(import).url().to_utf16_string().into_raw();
+}
+
+void* web_css_import_media(void* import)
+{
+ return import_from_cell(import).media().ptr();
+}
+
+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;
+}
+
NonnullRefPtr<StyleSheetImport> StyleSheetImport::create(RustRule rule, GC::Ptr<DOM::Document> document)
{
auto import = adopt_ref(*new StyleSheetImport(rule.identity(), RustImportRule { rule.payload().import_rule }, RustMediaList { Parser::ValueParserFFI::rust_media_list_retain(rule.payload().media) }, document));
@@ -78,8 +156,12 @@ void StyleSheetImport::visit_edges(GC::Cell::Visitor& visitor)
CSSImportRule& StyleSheetImport::cssom_rule() const
{
- if (!m_cssom_rule)
- m_cssom_rule = CSSImportRule::create(const_cast<StyleSheetImport&>(*this));
+ if (!m_cssom_rule) {
+ 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);
+ }
return *m_cssom_rule;
}
diff --git a/Libraries/LibWeb/CSS/StyleSheetImport.h b/Libraries/LibWeb/CSS/StyleSheetImport.h
index 940067ea8a0..ecedc572987 100644
--- a/Libraries/LibWeb/CSS/StyleSheetImport.h
+++ b/Libraries/LibWeb/CSS/StyleSheetImport.h
@@ -7,6 +7,7 @@
#pragma once
#include <AK/RefCounted.h>
+#include <LibGC/Cell.h>
#include <LibWeb/CSS/RustImportRule.h>
#include <LibWeb/CSS/StyleSheetState.h>
#include <LibWeb/CSS/URL.h>
@@ -59,4 +60,25 @@ private:
mutable GC::Weak<CSSImportRule> m_cssom_rule;
};
+// What the CSSImportRule of an import holds it by, as the object is a cell that keeps it alive and traces its edges.
+class StyleSheetImportCell final : public GC::Cell {
+ GC_CELL(StyleSheetImportCell, GC::Cell);
+ GC_DECLARE_ALLOCATOR(StyleSheetImportCell);
+
+public:
+ [[nodiscard]] static GC::Ref<StyleSheetImportCell> create(NonnullRefPtr<StyleSheetImport>);
+
+ StyleSheetImport& import() const { return *m_import; }
+
+private:
+ explicit StyleSheetImportCell(NonnullRefPtr<StyleSheetImport> import)
+ : m_import(move(import))
+ {
+ }
+
+ virtual void visit_edges(GC::Cell::Visitor&) override;
+
+ NonnullRefPtr<StyleSheetImport> m_import;
+};
+
}
diff --git a/Libraries/LibWeb/CSS/StyleSheetState.cpp b/Libraries/LibWeb/CSS/StyleSheetState.cpp
index a4d9a9a40c0..5f534c5e3c2 100644
--- a/Libraries/LibWeb/CSS/StyleSheetState.cpp
+++ b/Libraries/LibWeb/CSS/StyleSheetState.cpp
@@ -11,7 +11,6 @@
#include <LibJS/Runtime/ExternalMemory.h>
#include <LibWeb/CSS/CSSImportRule.h>
#include <LibWeb/CSS/CSSNestedDeclarations.h>
-#include <LibWeb/CSS/CSSScopeRule.h>
#include <LibWeb/CSS/CSSStyleRule.h>
#include <LibWeb/CSS/CSSStyleSheet.h>
#include <LibWeb/CSS/FontComputer.h>
@@ -168,7 +167,7 @@ void StyleSheetState::set_rules(RustRuleList rules)
// brand new FontFace object which is CSS-connected).
disconnect_font_faces_in_rules(m_native_sheet.rules().handle());
if (m_rules)
- m_rules->set_rules({}, move(rules), m_parsing_document);
+ m_rules->set_rules({}, rules, m_parsing_document);
else
m_native_sheet.rules().replace(rules);
}
@@ -186,9 +185,8 @@ CSSRuleList const& StyleSheetState::rules() const
{
if (!m_rules) {
auto& sheet = const_cast<StyleSheetState&>(*this);
- m_rules = CSSRuleList::create(RustRuleList { Parser::ValueParserFFI::rust_rule_list_retain(m_native_sheet.rules().handle()) }, m_parsing_document);
+ m_rules = CSSRuleList::create(m_native_sheet.rules(), m_parsing_document);
m_rules->set_parent_style_sheet(&sheet);
- m_rules->on_change = [&sheet]() { sheet.recalculate_rule_caches(); };
}
return *m_rules;
}
diff --git a/Libraries/LibWeb/CSS/StyleSheetState.h b/Libraries/LibWeb/CSS/StyleSheetState.h
index 9183f824ff4..379c89a94f8 100644
--- a/Libraries/LibWeb/CSS/StyleSheetState.h
+++ b/Libraries/LibWeb/CSS/StyleSheetState.h
@@ -105,6 +105,7 @@ public:
bool evaluate_media_queries(DOM::Document const&, Parser::ValueParserFFI::NativeStyleSheetMediaEvaluation&);
void reload_fonts_after_media_query_change();
void synchronize_fonts_after_rule_change();
+ void recalculate_rule_caches();
void record_conditions_for_owners();
HashTable<GC::Ptr<DOM::Node>> const& owning_documents_or_shadow_roots() const { return m_owning_documents_or_shadow_roots; }
@@ -205,7 +206,6 @@ public:
private:
StyleSheetState(RustRuleList, GC::Ptr<DOM::Document>, RustMediaList, Optional<::URL::URL> location, Optional<ReferrerPolicy::ReferrerPolicy> fetched_referrer_policy);
- void recalculate_rule_caches();
void set_rules(RustRuleList);
bool has_document_owner() const;
void forget_font_feature_values();
diff --git a/Libraries/LibWeb/Dump.cpp b/Libraries/LibWeb/Dump.cpp
index e7f4ba4cd8a..b1f2e0040fa 100644
--- a/Libraries/LibWeb/Dump.cpp
+++ b/Libraries/LibWeb/Dump.cpp
@@ -7,23 +7,12 @@
*/
#include <AK/StringBuilder.h>
-#include <LibWeb/CSS/CSSDescriptors.h>
#include <LibWeb/CSS/CSSFontFaceRule.h>
#include <LibWeb/CSS/CSSImportRule.h>
-#include <LibWeb/CSS/CSSKeyframeRule.h>
#include <LibWeb/CSS/CSSKeyframesRule.h>
-#include <LibWeb/CSS/CSSLayerBlockRule.h>
-#include <LibWeb/CSS/CSSLayerStatementRule.h>
-#include <LibWeb/CSS/CSSMarginRule.h>
-#include <LibWeb/CSS/CSSMediaRule.h>
-#include <LibWeb/CSS/CSSNamespaceRule.h>
#include <LibWeb/CSS/CSSNestedDeclarations.h>
-#include <LibWeb/CSS/CSSPageRule.h>
-#include <LibWeb/CSS/CSSPropertyRule.h>
#include <LibWeb/CSS/CSSRule.h>
-#include <LibWeb/CSS/CSSStyleProperties.h>
#include <LibWeb/CSS/CSSStyleRule.h>
-#include <LibWeb/CSS/CSSSupportsRule.h>
#include <LibWeb/CSS/PropertyID.h>
#include <LibWeb/CSS/StyleSheetState.h>
#include <LibWeb/DOM/Document.h>
@@ -167,39 +156,17 @@ void dump_rule(CSS::CSSRule const& rule)
}
void dump_rule(StringBuilder& builder, CSS::CSSRule const& rule, int indent_levels)
-{
- rule.dump(builder, indent_levels);
-}
-
-void dump_style_properties(StringBuilder& builder, CSS::CSSStyleProperties const& declaration, int indent_levels)
-{
- dump_indent(builder, indent_levels);
- builder.appendff("Declarations ({}):\n", declaration.length());
- for (auto& property : declaration.properties()) {
- dump_indent(builder, indent_levels);
- builder.appendff(" {}: '{}'", CSS::string_from_property_id(property.property_id), property.value->to_string(CSS::SerializationMode::Normal));
- if (property.important == CSS::Important::Yes)
- builder.append(" \033[31;1m!important\033[0m"sv);
- builder.append('\n');
- }
- for (auto& property : declaration.custom_properties()) {
- dump_indent(builder, indent_levels);
- builder.appendff(" {}: '{}'", property.key, property.value.value->to_string(CSS::SerializationMode::Normal));
- if (property.value.important == CSS::Important::Yes)
- builder.append(" \033[31;1m!important\033[0m"sv);
- builder.append('\n');
- }
-}
-
-void dump_descriptors(StringBuilder& builder, CSS::CSSDescriptors const& descriptors, int indent_levels)
{
dump_indent(builder, indent_levels);
- builder.appendff("Declarations ({}):\n", descriptors.length());
- for (size_t index = 0; index < descriptors.length(); ++index) {
- auto name = descriptors.item(index);
- dump_indent(builder, indent_levels);
- builder.appendff(" {}: '{}'", name, descriptors.get_property_value(Utf16FlyString::from_utf16(name.utf16_view())));
- builder.append('\n');
+ builder.appendff("{}\n", rule.serialized());
+
+ if (auto const* style_rule = as_if<CSS::CSSStyleRule>(rule)) {
+ for (auto const& selector : style_rule->selectors())
+ dump_selector(builder, selector, indent_levels + 1);
+ dump_indent(builder, indent_levels + 1);
+ builder.append("Absolutized selectors:\n"sv);
+ for (auto const& selector : style_rule->absolutized_selectors())
+ dump_selector(builder, selector, indent_levels + 2);
}
}
@@ -215,7 +182,7 @@ void dump_sheet(StringBuilder& builder, CSS::StyleSheetState const& sheet, int i
dump_indent(builder, indent_levels);
builder.appendff("CSSStyleSheet{{{}}}: {} rule(s)\n", &sheet, sheet.rules().length());
- for (auto& rule : sheet.rules())
+ for (auto rule : sheet.rules())
dump_rule(builder, rule, indent_levels + 1);
}
diff --git a/Libraries/LibWeb/Dump.h b/Libraries/LibWeb/Dump.h
index 385200215e8..8fc112d70f9 100644
--- a/Libraries/LibWeb/Dump.h
+++ b/Libraries/LibWeb/Dump.h
@@ -23,8 +23,6 @@ void dump_sheet(StringBuilder&, CSS::StyleSheetState const&, int indent_levels =
WEB_API void dump_sheet(CSS::StyleSheetState const&);
void dump_rule(StringBuilder&, CSS::CSSRule const&, int indent_levels = 0);
void dump_rule(CSS::CSSRule const&);
-void dump_style_properties(StringBuilder&, CSS::CSSStyleProperties const&, int indent_levels = 0);
-void dump_descriptors(StringBuilder&, CSS::CSSDescriptors const&, int indent_levels = 0);
void dump_selector(StringBuilder&, CSS::Selector const&, int indent_levels = 0);
void dump_selector(CSS::Selector const&);
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index b17f46b2673..34ebc7d4c93 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -256,9 +256,6 @@ class ContentStyleValue;
class CounterDefinitionsStyleValue;
class CounterStyleStyleValue;
class CSSAnimation;
-class CSSConditionRule;
-class CSSContainerRule;
-class CSSCounterStyleRule;
class CSSDescriptors;
class CSSFontFaceDescriptors;
class CSSFontFaceRule;
@@ -268,31 +265,20 @@ class CSSFunctionDescriptors;
class CSSFunctionRule;
class CSSGroupingRule;
class CSSImportRule;
-class CSSKeyframeRule;
class CSSKeyframesRule;
class CSSKeywordValue;
-class CSSLayerBlockRule;
-class CSSLayerStatementRule;
-class CSSMarginRule;
-class CSSMediaRule;
-class CSSNamespaceRule;
class CSSNestedDeclarations;
class CSSNumericValue;
-class CSSPageRule;
class CSSPageDescriptors;
class CSSPositionTryDescriptors;
-class CSSPositionTryRule;
-class CSSPropertyRule;
class CSSRule;
class CSSRuleList;
-class CSSScopeRule;
class CSSStyleDeclaration;
class CSSStyleProperties;
class CSSStyleRule;
class CSSStyleSheet;
class StyleSheetState;
class CSSStyleValue;
-class CSSSupportsRule;
class CSSUnitValue;
class CursorStyleValue;
class CustomIdentStyleValue;
diff --git a/Libraries/LibWeb/Rust/src/css/counter_style.rs b/Libraries/LibWeb/Rust/src/css/counter_style.rs
index 6cac9989ae9..3c50bf62b87 100644
--- a/Libraries/LibWeb/Rust/src/css/counter_style.rs
+++ b/Libraries/LibWeb/Rust/src/css/counter_style.rs
@@ -13,12 +13,14 @@ use crate::css::css_enums::{
};
use crate::css::css_string::CssString;
use crate::css::descriptor_block::{DescriptorBlockData, FfiDescriptorBlock, rust_descriptor_block_retain};
+use crate::css::descriptor_metadata::descriptor_metadata;
use crate::css::ffi_support::{FfiUtf16View, ascii_lowercase};
use crate::css::parser::descriptor_parser::resolve_descriptor_integer;
use crate::css::parser::value_parser::equals_ascii_case_insensitive;
use crate::css::style_compute::FfiLengthResolutionContext;
use crate::css::style_value::CounterStyleSystemPayload;
use crate::css::style_value::{RetainedStyleValueData, StyleValueData};
+use crate::css::style_value_arc::StyleValueArc;
use std::cell::RefCell;
use std::collections::HashMap;
use std::ffi::c_void;
@@ -35,6 +37,9 @@ const _: () = {
assert_send_sync::<CounterStyleData>();
};
+/// The id of @counter-style among the at-rules with descriptors, AtRuleID::CounterStyle.
+const COUNTER_STYLE_AT_RULE: u8 = 3;
+
pub struct FfiCounterStyle {
name: RefCell<CssString>,
descriptors: FfiDescriptorBlock,
@@ -49,6 +54,54 @@ impl FfiCounterStyle {
self.descriptors.data()
}
+ pub(crate) fn descriptor_block(&self) -> &FfiDescriptorBlock {
+ &self.descriptors
+ }
+
+ pub(crate) fn name_text(&self) -> ak::Utf16String {
+ ak::Utf16String::from_utf16(self.name.borrow().units())
+ }
+
+ pub(crate) fn set_name_text(&self, name: &[u16]) -> bool {
+ rust_counter_style_set_name(self, FfiUtf16View::from_utf16(name))
+ }
+
+ /// The value of the `system` descriptor, if the rule has one.
+ fn system(&self) -> Option<StyleValueArc> {
+ let data = self.descriptors.data();
+ let id = descriptor_metadata(COUNTER_STYLE_AT_RULE, &"system".encode_utf16().collect::<Vec<_>>())?.id;
+ data.descriptors
+ .iter()
+ .find(|descriptor| descriptor.id == id)
+ .map(|descriptor| descriptor.value.clone())
+ }
+
+ /// Whether the rule still defines a counter style with the value as its `symbols` descriptor, or as its
+ /// `additive-symbols` one when `additive`.
+ pub(crate) fn system_accepts_symbols(&self, additive: bool, value: &StyleValueData) -> bool {
+ let Some(system) = self.system() else {
+ return true;
+ };
+ rust_counter_style_system_accepts_symbols(
+ Some(&system),
+ additive,
+ value.child_values().map_or(0, |values| values.len()),
+ )
+ }
+
+ /// Whether the value of the `system` descriptor would change the algorithm that the rule uses.
+ pub(crate) fn system_change_alters_algorithm(&self, new: &StyleValueData) -> bool {
+ self.system()
+ .is_none_or(|current| rust_counter_style_system_changes_algorithm(&current, new))
+ }
+
+ pub(crate) fn set_descriptor(&self, name: &[u16], value: StyleValueArc) {
+ let id = descriptor_metadata(COUNTER_STYLE_AT_RULE, name)
+ .expect("the descriptor exists")
+ .id;
+ self.descriptors.set_value(id, name, value);
+ }
+
pub(crate) fn new(data: Arc<CounterStyleData>) -> Self {
Self {
name: RefCell::new(data.name.clone()),
@@ -62,15 +115,6 @@ pub extern "C" fn rust_counter_style_descriptors(rule: &FfiCounterStyle) -> *mut
rust_descriptor_block_retain(&rule.descriptors)
}
-/// # Safety
-/// The caller must not set the rule's name while it uses the returned view.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_counter_style_name(rule: &FfiCounterStyle) -> FfiUtf16View<'_> {
- // SAFETY: The caller reads the name before it next sets one.
- let name = unsafe { rule.name.try_borrow_unguarded() }.expect("the name is not being set");
- FfiUtf16View::from_utf16(name.units())
-}
-
#[unsafe(no_mangle)]
pub extern "C" fn rust_counter_style_set_name(rule: &FfiCounterStyle, name: FfiUtf16View) -> bool {
let Some(mut name) = name.to_utf16() else {
diff --git a/Libraries/LibWeb/Rust/src/css/descriptor_block.rs b/Libraries/LibWeb/Rust/src/css/descriptor_block.rs
index 8cb839d09b9..8d1e887b693 100644
--- a/Libraries/LibWeb/Rust/src/css/descriptor_block.rs
+++ b/Libraries/LibWeb/Rust/src/css/descriptor_block.rs
@@ -71,6 +71,23 @@ impl DescriptorData {
}
impl FfiDescriptorBlock {
+ /// Sets the descriptor with the id and the name to the value.
+ pub(crate) fn set_value(&self, id: u8, name: &[u16], value: StyleValueArc) {
+ let descriptor = DescriptorData {
+ name: CssString::from_utf16(name),
+ id,
+ value,
+ };
+ self.mutate(|data| {
+ if let Some(index) = data.descriptors.iter().position(|existing| existing.id == id) {
+ data.descriptors[index] = descriptor;
+ } else {
+ data.descriptors.push(descriptor);
+ }
+ true
+ });
+ }
+
pub(crate) fn data(&self) -> Arc<DescriptorBlockData> {
match &*self.state.borrow() {
DescriptorBlockState::Immutable(data) => data.clone(),
@@ -97,7 +114,7 @@ impl FfiDescriptorBlock {
owner.clone()
}
- fn mutate(&mut self, mutation: impl FnOnce(&mut DescriptorBlockData) -> bool) -> bool {
+ fn mutate(&self, mutation: impl FnOnce(&mut DescriptorBlockData) -> bool) -> bool {
let owner = self.owner();
let mut owner = owner.borrow_mut();
mutation(Arc::make_mut(&mut owner))
diff --git a/Libraries/LibWeb/Rust/src/css/font_feature_values.rs b/Libraries/LibWeb/Rust/src/css/font_feature_values.rs
index c5f02811d47..91e35f6fe16 100644
--- a/Libraries/LibWeb/Rust/src/css/font_feature_values.rs
+++ b/Libraries/LibWeb/Rust/src/css/font_feature_values.rs
@@ -72,6 +72,28 @@ impl FontFeatureValuesRule {
pub(crate) fn snapshot(&self) -> Arc<FontFeatureValuesData> {
self.data.borrow().clone()
}
+ pub(crate) fn families_text(&self) -> Vec<ak::Utf16String> {
+ let data = self.data.borrow();
+ data.families
+ .iter()
+ .map(|family| ak::Utf16String::from_utf16(family.units()))
+ .collect()
+ }
+
+ pub(crate) fn set_families_text(&self, families: Vec<Vec<u16>>) {
+ let families = families.iter().map(|family| CssString::from_utf16(family)).collect();
+ Arc::make_mut(&mut self.data.borrow_mut()).families = families;
+ }
+
+ pub(crate) fn entries_of(&self, kind: FontFeatureValuesRuleKind) -> Vec<(Vec<u16>, Vec<u32>)> {
+ let data = self.data.borrow();
+ data.maps[kind as usize]
+ .entries
+ .iter()
+ .map(|entry| (entry.name.to_vec(), entry.values.clone()))
+ .collect()
+ }
+
pub(crate) fn new(data: Arc<FontFeatureValuesData>) -> Self {
Self {
data: RefCell::new(data),
@@ -241,26 +263,6 @@ pub extern "C" fn rust_font_feature_values_clear(owner: &FontFeatureValuesRule,
}
}
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_font_feature_values_external_memory_size(owner: &FontFeatureValuesRule) -> usize {
- let data = owner.data.borrow();
- let mut size = size_of::<FontFeatureValuesRule>().saturating_add(size_of::<FontFeatureValuesData>());
- size = size.saturating_add(data.families.capacity().saturating_mul(size_of::<CssString>()));
- for family in &data.families {
- size = size.saturating_add(size_of_val(family.units()));
- }
- for map in &data.maps {
- size = size.saturating_add(map.entries.capacity().saturating_mul(size_of::<FeatureValueEntry>()));
- size = size.saturating_add(map.indices.capacity().saturating_mul(size_of::<(Arc<[u16]>, usize)>()));
- for entry in &map.entries {
- size = size
- .saturating_add(size_of_val(&*entry.name))
- .saturating_add(entry.values.capacity().saturating_mul(size_of::<u32>()));
- }
- }
- size
-}
-
/// The OpenType features a style asks of a font, by tag, the later setting of a tag winning.
#[derive(Default)]
struct ShapeFeatures(Vec<(u32, u32)>);
diff --git a/Libraries/LibWeb/Rust/src/css/function_signature.rs b/Libraries/LibWeb/Rust/src/css/function_signature.rs
index fe5cb2d2432..3bc202a52bc 100644
--- a/Libraries/LibWeb/Rust/src/css/function_signature.rs
+++ b/Libraries/LibWeb/Rust/src/css/function_signature.rs
@@ -5,10 +5,8 @@
*/
use crate::css::css_string::CssString;
-use crate::css::ffi_support::FfiUtf16View;
use crate::css::parser::syntax::SyntaxNode;
use crate::css::style_value_arc::StyleValueArc;
-use std::ffi::c_void;
use std::sync::Arc;
pub(crate) struct FunctionParameterData {
@@ -27,44 +25,3 @@ const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<FunctionSignature>();
};
-
-#[repr(C)]
-pub struct FfiFunctionSignatureView<'a> {
- pub name: FfiUtf16View<'a>,
- pub parameter_count: usize,
- pub return_type: *const c_void,
-}
-
-#[repr(C)]
-pub struct FfiFunctionParameterView<'a> {
- pub name: FfiUtf16View<'a>,
- pub syntax: *const c_void,
- pub default_value: *const c_void,
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_function_signature_view(signature: &FunctionSignature) -> FfiFunctionSignatureView<'_> {
- let name = signature.name.units();
- FfiFunctionSignatureView {
- name: FfiUtf16View::from_utf16(name),
- parameter_count: signature.parameters.len(),
- return_type: Arc::as_ptr(&signature.return_type).cast(),
- }
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_function_signature_parameter(
- signature: &FunctionSignature,
- index: usize,
-) -> FfiFunctionParameterView<'_> {
- let parameter = &signature.parameters[index];
- let name = parameter.name.as_units();
- FfiFunctionParameterView {
- name: FfiUtf16View::from_input(name.into()),
- syntax: Arc::as_ptr(&parameter.syntax).cast(),
- default_value: parameter
- .default_value
- .as_ref()
- .map_or(std::ptr::null(), |value| StyleValueArc::as_ptr(value).cast()),
- }
-}
diff --git a/Libraries/LibWeb/Rust/src/css/keyframes.rs b/Libraries/LibWeb/Rust/src/css/keyframes.rs
index 67689063ddd..38fc5e4280b 100644
--- a/Libraries/LibWeb/Rust/src/css/keyframes.rs
+++ b/Libraries/LibWeb/Rust/src/css/keyframes.rs
@@ -38,20 +38,6 @@ impl FfiKeyframe {
}
}
-#[repr(C)]
-pub struct FfiKeyframeKeys {
- pub values: *const f64,
- pub count: usize,
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_keyframe_keys(frame: &FfiKeyframe) -> FfiKeyframeKeys {
- FfiKeyframeKeys {
- values: frame.keys().as_ptr(),
- count: frame.keys().len(),
- }
-}
-
#[unsafe(no_mangle)]
pub extern "C" fn rust_keyframe_declarations(frame: &FfiKeyframe) -> *mut DeclarationBlock {
Box::into_raw(Box::new(frame.declaration_block().clone()))
diff --git a/Libraries/LibWeb/Rust/src/css/layer_names.rs b/Libraries/LibWeb/Rust/src/css/layer_names.rs
index 5b85b60a3bf..f4f71f0ea04 100644
--- a/Libraries/LibWeb/Rust/src/css/layer_names.rs
+++ b/Libraries/LibWeb/Rust/src/css/layer_names.rs
@@ -5,7 +5,6 @@
*/
use crate::css::css_string::CssString;
-use crate::css::ffi_support::FfiUtf16View;
// Anonymous layer identities and qualified names belong to the document, not
// this immutable, shareable representation of the names written in a rule.
@@ -17,21 +16,3 @@ const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<LayerNames>();
};
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_layer_names_count(names: &LayerNames) -> usize {
- names.names.len()
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_layer_names_at(names: &LayerNames, index: usize) -> FfiUtf16View<'_> {
- FfiUtf16View::from_utf16(names.names[index].units())
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_layer_names_external_memory_size(names: &LayerNames) -> usize {
- names.names.iter().fold(
- size_of::<LayerNames>().saturating_add(size_of_val(&*names.names)),
- |size, name| size.saturating_add(size_of_val(name.units())),
- )
-}
diff --git a/Libraries/LibWeb/Rust/src/css/media_list.rs b/Libraries/LibWeb/Rust/src/css/media_list.rs
index b0ebef9a7a0..e14e082d440 100644
--- a/Libraries/LibWeb/Rust/src/css/media_list.rs
+++ b/Libraries/LibWeb/Rust/src/css/media_list.rs
@@ -150,7 +150,7 @@ impl MediaList {
};
}
- pub(crate) fn matches(&self) -> bool {
+ pub fn matches(&self) -> bool {
let state = self.owner.borrow();
state.matches.is_empty() || state.matches.iter().any(|matches| *matches)
}
diff --git a/Libraries/LibWeb/Rust/src/css/namespace_rule.rs b/Libraries/LibWeb/Rust/src/css/namespace_rule.rs
index 0c9671ce064..0667bf69ff6 100644
--- a/Libraries/LibWeb/Rust/src/css/namespace_rule.rs
+++ b/Libraries/LibWeb/Rust/src/css/namespace_rule.rs
@@ -5,7 +5,6 @@
*/
use crate::css::css_string::CssString;
-use crate::css::ffi_support::FfiUtf16View;
pub struct NamespaceRuleData {
pub(crate) prefix: CssString,
@@ -16,15 +15,3 @@ const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<NamespaceRuleData>();
};
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_namespace_rule_prefix(rule: &NamespaceRuleData) -> FfiUtf16View<'_> {
- let units = rule.prefix.units();
- FfiUtf16View::from_utf16(units)
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_namespace_rule_uri(rule: &NamespaceRuleData) -> FfiUtf16View<'_> {
- let units = rule.uri.units();
- FfiUtf16View::from_utf16(units)
-}
diff --git a/Libraries/LibWeb/Rust/src/css/parser/descriptor_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/descriptor_parser.rs
index dd8dd7a3261..4dde8374b88 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/descriptor_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/descriptor_parser.rs
@@ -548,6 +548,12 @@ pub extern "C" fn rust_parse_css_descriptor(
.unwrap_or(std::ptr::null())
}
+/// The value of the descriptor of the at-rule that the text parses to, in an empty context.
+pub(crate) fn parse_descriptor_text(at_rule: u8, name: &[u16], source: &[u16]) -> Option<StyleValueArc> {
+ let values = consume_a_list_of_component_values(tokenize_for_parser(source)).ok()?;
+ parse_descriptor(&ParseContext::default(), at_rule, name, &values, source).map(|descriptor| descriptor.value)
+}
+
#[cfg(test)]
mod tests {
use super::{consume_a_list_of_component_values, parse_descriptor, tokenize_for_parser};
diff --git a/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs
index 84a0d3b1351..1be657526e8 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/query_parser.rs
@@ -3079,6 +3079,21 @@ pub(crate) unsafe fn evaluate_container_query(
evaluate_container_expression(expression, facts, length_context, style)
}
+/// The text of a retained query condition.
+pub(crate) fn serialized_query_condition(handle: &FfiQueryHandle) -> Vec<u16> {
+ let QueryTree::Expression { expression, kind } = &handle.tree else {
+ unreachable!("the condition of a rule is an expression")
+ };
+ let mut sink = TextSink::new();
+ serialize_expression(&mut sink, expression, *kind);
+ sink.into_utf16()
+}
+
+/// Whether a retained supports condition matches.
+pub(crate) fn supports_query_matches(handle: &FfiQueryHandle) -> bool {
+ css_query_evaluate_supports(Some(handle)) == 1
+}
+
/// Serializes a retained query condition without changing its UTF-16 representation.
///
/// # Safety
diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax.rs
index 781e78cf6e9..5e3fd0fd7ac 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/syntax.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax.rs
@@ -518,6 +518,22 @@ pub unsafe extern "C" fn rust_parse_with_syntax(
crate::css::style_value_arc::StyleValueArc::into_raw(crate::css::style_value_arc::StyleValueArc::new(parsed)).cast()
}
+impl SyntaxNode {
+ pub(crate) fn is_universal(&self) -> bool {
+ rust_syntax_is_universal(self)
+ }
+
+ pub(crate) fn is_single_component(&self) -> bool {
+ rust_syntax_is_single_component(self)
+ }
+
+ pub(crate) fn serialize_to_utf16(&self) -> Vec<u16> {
+ let mut sink = TextSink::new();
+ serialize_syntax(self, &mut sink);
+ sink.into_utf16()
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs
index b9e48d65836..0aed1e2b19b 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser.rs
@@ -225,7 +225,7 @@ enum ParsedRulePrelude {
}
#[derive(Clone, Debug, PartialEq)]
-struct ParsedPageSelector {
+pub(crate) struct ParsedPageSelector {
name: Option<ParserString>,
pseudo_classes: Vec<PagePseudoClass>,
}
@@ -443,7 +443,7 @@ fn parse_page_selectors(values: &[ComponentValue]) -> ParsedRulePrelude {
}
// https://drafts.csswg.org/cssom/#parse-a-list-of-css-page-selectors
-fn parse_page_selector_list<'a>(source: impl Into<TokenizerInput<'a>>) -> Option<Vec<ParsedPageSelector>> {
+pub(crate) fn parse_page_selector_list<'a>(source: impl Into<TokenizerInput<'a>>) -> Option<Vec<ParsedPageSelector>> {
// NB: This replaces the C++ path that wrapped the source in `@page <source> {}` and parsed
// exactly one rule. Consuming the complete component-value list
// preserves rejection of trailing tokens without constructing synthetic CSS.
@@ -455,7 +455,7 @@ fn parse_page_selector_list<'a>(source: impl Into<TokenizerInput<'a>>) -> Option
}
impl PageSelectorList {
- fn new(parsed_selectors: Vec<ParsedPageSelector>) -> Self {
+ pub(crate) fn new(parsed_selectors: Vec<ParsedPageSelector>) -> Self {
Self {
selectors: parsed_selectors.into_boxed_slice(),
}
@@ -4381,6 +4381,12 @@ pub unsafe extern "C" fn rust_page_selector_list_serialize(
context: *mut c_void,
visit: crate::css::parser::query_parser::VisitQuerySerialization,
) {
+ let text = serialized_page_selectors(list);
+ unsafe { visit(context, text.as_ptr(), text.len()) };
+}
+
+/// The text of a list of page selectors.
+pub(crate) fn serialized_page_selectors(list: &PageSelectorList) -> Vec<u16> {
let mut text = Vec::new();
for (index, selector) in list.selectors.iter().enumerate() {
if index != 0 {
@@ -4399,7 +4405,7 @@ pub unsafe extern "C" fn rust_page_selector_list_serialize(
text.extend(name.bytes().map(u16::from));
}
}
- unsafe { visit(context, text.as_ptr(), text.len()) };
+ text
}
/// Retains a normalized declaration block from parsed block contents, ignoring rules.
diff --git a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs
index 56b51468350..7b7241c2a7f 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/syntax_parser/ownership_tests.rs
@@ -319,8 +319,8 @@ fn keyframe_mutation_preserves_exposed_declarations_and_snapshots() {
let children = &*rust_rule_children(&frames);
let originals = &*rust_rule_children(&original_frames);
let owners = RULE_OWNER_ALLOCATIONS.get();
- assert_eq!(rust_keyframes_find_rule(&frames, view(&utf16("from, 50%"))), 0);
- assert_eq!(rust_keyframes_find_rule(&frames, view(&utf16("50%"))), usize::MAX);
+ assert_eq!(frames.find_keyframe(&utf16("from, 50%")), Some(0));
+ assert_eq!(frames.find_keyframe(&utf16("50%")), None);
assert_eq!(RULE_OWNER_ALLOCATIONS.get(), owners);
let mut early = declarations_at(children, 1);
let later = children.rule_at(1);
@@ -348,7 +348,7 @@ fn keyframe_mutation_preserves_exposed_declarations_and_snapshots() {
serialize_style_value_to_utf16(&snapshot.properties().get(0).unwrap().value),
utf16("31px")
);
- rust_keyframes_set_name(&frames, view(&utf16("新しい名前")));
+ frames.set_keyframes_name(&utf16("新しい名前"));
assert_eq!(
rust_rule_payload(&retained).name.to_utf16().unwrap(),
utf16("新しい名前")
@@ -364,7 +364,7 @@ fn keyframe_mutation_preserves_exposed_declarations_and_snapshots() {
rust_rule_list_remove(children, 0);
assert_eq!(rust_rule_list_count(&*rust_rule_children(&retained)), 1);
assert_eq!(first_value(&later_declarations), utf16("23px"));
- assert_eq!(rust_keyframes_find_rule(&retained, view(&utf16("to"))), 0);
+ assert_eq!(retained.find_keyframe(&utf16("to")), Some(0));
assert_eq!(first_value(&exposed_declarations), utf16("29px"));
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs
index d493fd7ae2d..4e7039f9206 100644
--- a/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs
+++ b/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs
@@ -6646,9 +6646,10 @@ pub unsafe extern "C" fn rust_parse_entire_css_primitive_from_source(
#[unsafe(no_mangle)]
pub extern "C" fn rust_is_valid_animation_name_custom_ident(source: FfiUtf16View) -> bool {
- let Some(source) = source.units() else {
- return false;
- };
+ source.units().is_some_and(is_valid_animation_name)
+}
+
+pub(crate) fn is_valid_animation_name(source: TokenizerInput<'_>) -> bool {
is_valid_custom_ident_matching(
|expected| {
source.len() == expected.len()
diff --git a/Libraries/LibWeb/Rust/src/css/rule.rs b/Libraries/LibWeb/Rust/src/css/rule.rs
index 6c6a375bd9b..0e14fde1500 100644
--- a/Libraries/LibWeb/Rust/src/css/rule.rs
+++ b/Libraries/LibWeb/Rust/src/css/rule.rs
@@ -38,6 +38,7 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
mod compilation;
+pub mod cssom;
mod function;
pub(crate) use function::CompiledFunction;
#[cfg(test)]
@@ -872,44 +873,6 @@ pub extern "C" fn rust_namespace_context_release(context: OwnedArc<NativeNamespa
drop(context);
}
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_keyframes_set_name(rule: &NativeRule, name: FfiUtf16View) {
- let RulePayload::Keyframes(current) = &rule.payload else {
- unreachable!()
- };
- *current.borrow_mut() = CssString::from_utf16(&name.to_utf16().unwrap());
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_keyframes_find_rule(rule: &NativeRule, selector: FfiUtf16View) -> usize {
- let Some(selectors) = selector
- .units()
- .and_then(crate::css::parser::syntax_parser::parse_keyframe_selector_list)
- else {
- return usize::MAX;
- };
- let matches = |frame: &NativeRule| {
- let RulePayload::Keyframe(frame) = &frame.payload else {
- unreachable!()
- };
- frame.keys() == selectors
- };
- let children = rule.child_rules().unwrap();
- if let Some(rules) = children.rules.borrow().as_ref() {
- return rules.iter().rposition(|frame| matches(frame)).unwrap_or(usize::MAX);
- }
- let parsed = children.parsed_source.borrow();
- let parsed = parsed.as_ref().unwrap();
- let exposed = children.exposed_rules.borrow();
- (0..parsed.len())
- .rev()
- .find(|index| match exposed.get(index) {
- Some(frame) => matches(frame),
- None => *parsed.rule_at(*index).keyframe().unwrap().keys == selectors,
- })
- .unwrap_or(usize::MAX)
-}
-
static NEXT_RULE_IDENTITY: AtomicU64 = AtomicU64::new(1);
fn reserve_rule_identities(count: u64) -> u64 {
diff --git a/Libraries/LibWeb/Rust/src/css/rule/cssom.rs b/Libraries/LibWeb/Rust/src/css/rule/cssom.rs
new file mode 100644
index 00000000000..f7c249a1e0f
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/rule/cssom.rs
@@ -0,0 +1,611 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! What the CSSOM reads and changes of a rule, for libweb_bindings_rust, whose interfaces are implemented in Rust.
+
+use std::rc::Rc;
+use std::sync::Arc;
+
+use ak::Utf16String;
+
+use super::{NativeRule, NativeRuleList, NativeRuleType, RuleInsertionResult, RulePayload, RuleRemovalResult};
+use crate::css::css_string::CssString;
+use crate::css::css_tokenizer::TokenizerInput;
+use crate::css::descriptor_block::FfiDescriptorBlock;
+use crate::css::descriptor_metadata::descriptor_metadata;
+use crate::css::font_feature_values::FontFeatureValuesRuleKind;
+use crate::css::parser::descriptor_parser::parse_descriptor_text;
+use crate::css::parser::query_parser::{FfiQueryHandle, serialized_query_condition, supports_query_matches};
+use crate::css::parser::syntax::SyntaxNode;
+use crate::css::parser::syntax_parser::{
+ PageSelectorList, parse_keyframe_selector_list, parse_page_selector_list, serialized_page_selectors,
+};
+use crate::css::serialize::{
+ SerializationMode, StringUnits, TextSink, serialize_a_string, serialize_an_identifier, serialize_style_value,
+};
+use crate::css::style_value_arc::StyleValueArc;
+
+/// The at-rule id of @counter-style, as the descriptors of the generated metadata know it.
+const COUNTER_STYLE_AT_RULE: u8 = 3;
+
+fn utf16(units: &[u16]) -> Utf16String {
+ Utf16String::from_utf16(units)
+}
+
+fn css_utf16(string: &CssString) -> Utf16String {
+ utf16(string.units())
+}
+
+fn sink_to_string(sink: TextSink) -> Utf16String {
+ utf16(&sink.into_utf16())
+}
+
+/// https://drafts.csswg.org/cssom/#serialize-an-identifier
+pub fn serialize_identifier(units: &[u16]) -> Utf16String {
+ let mut sink = TextSink::new();
+ serialize_an_identifier(&mut sink, &StringUnits::Utf16(units));
+ sink_to_string(sink)
+}
+
+/// https://drafts.csswg.org/cssom/#serialize-a-string
+pub fn serialize_string_value(units: &[u16]) -> Utf16String {
+ let mut sink = TextSink::new();
+ serialize_a_string(&mut sink, &StringUnits::Utf16(units));
+ sink_to_string(sink)
+}
+
+fn value_text(value: &StyleValueArc) -> Utf16String {
+ let mut sink = TextSink::new();
+ serialize_style_value(&mut sink, value, SerializationMode::Normal);
+ sink_to_string(sink)
+}
+
+fn syntax_text(syntax: &SyntaxNode) -> Utf16String {
+ utf16(&syntax.serialize_to_utf16())
+}
+
+/// https://drafts.csswg.org/css-mixins-1/#serialize-a-css-type
+fn serialize_a_css_type(syntax: &SyntaxNode) -> Vec<u16> {
+ // To serialize a CSS type, return the concatenation of the following:
+ let text = syntax.serialize_to_utf16();
+
+ // If the <css-type> consists of a single <syntax-component>, return the corresponding syntax string.
+ if syntax.is_single_component() {
+ return text;
+ }
+
+ // Otherwise, return the concatenation of the following:
+ // The string "type(", i.e. "type" followed by a single LEFT PARENTHESIS (U+0028).
+ let mut result: Vec<u16> = "type(".encode_utf16().collect();
+
+ // The corresponding syntax string.
+ result.extend(text);
+
+ // The string ")", i.e. a single RIGHT PARENTHESIS (U+0029).
+ result.push(u16::from(b')'));
+ result
+}
+
+/// The name, type and default value of a parameter of a custom function, https://drafts.csswg.org/css-mixins-1/#dictdef-functionparameter
+pub struct FunctionParameter {
+ pub name: Utf16String,
+ pub parameter_type: Utf16String,
+ pub default_value: Option<Utf16String>,
+}
+
+/// The name and the query of a <container-condition>, each empty when the condition does not have it.
+pub struct ContainerCondition {
+ pub name: Utf16String,
+ pub query: Utf16String,
+}
+
+/// The kinds of feature values of a @font-feature-values rule, in the order of the rule's serialization.
+pub const FONT_FEATURE_VALUES_KINDS: [(FontFeatureValuesRuleKind, &str); 7] = [
+ (FontFeatureValuesRuleKind::Annotation, "annotation"),
+ (FontFeatureValuesRuleKind::Ornaments, "ornaments"),
+ (FontFeatureValuesRuleKind::Stylistic, "stylistic"),
+ (FontFeatureValuesRuleKind::Swash, "swash"),
+ (FontFeatureValuesRuleKind::CharacterVariant, "character-variant"),
+ (FontFeatureValuesRuleKind::Styleset, "styleset"),
+ (FontFeatureValuesRuleKind::HistoricalForms, "historical-forms"),
+];
+
+/// Whether the name of a @keyframes rule serializes as an identifier, and not as a string.
+pub fn is_valid_animation_name(name: &[u16]) -> bool {
+ crate::css::parser::value_parser::is_valid_animation_name(TokenizerInput::from(name))
+}
+
+impl NativeRule {
+ /// The rule that the pointer points to, which keeps its reference.
+ ///
+ /// # Safety
+ ///
+ /// `rule` must point to a live rule that an `Rc` owns.
+ pub unsafe fn retained_from_raw(rule: *const Self) -> Rc<Self> {
+ // SAFETY: The caller passes a pointer into a live Rc.
+ unsafe {
+ Rc::increment_strong_count(rule);
+ Rc::from_raw(rule)
+ }
+ }
+
+ pub fn cssom_identity(&self) -> u64 {
+ self.identity
+ }
+
+ pub fn cssom_type(&self) -> NativeRuleType {
+ self.rule_type
+ }
+
+ /// The list of child rules of a rule that has one, which a style rule makes when it is asked.
+ pub fn cssom_children(&self) -> Option<Rc<NativeRuleList>> {
+ self.child_rules().cloned()
+ }
+
+ /// The memory the rule owns outside the heap.
+ pub fn cssom_external_memory_size(&self) -> usize {
+ super::rust_rule_external_memory_size(self)
+ }
+
+ pub fn cssom_set_selector_text(&self, text: &[u16], sheet_rules: Option<&NativeRuleList>) -> bool {
+ self.set_selector_text(TokenizerInput::from(text), sheet_rules)
+ }
+
+ /// Whether the rule has an empty block of declarations or descriptors.
+ pub fn has_no_declarations(&self) -> bool {
+ match &self.payload {
+ RulePayload::FontFace(block)
+ | RulePayload::FunctionDeclarations(block)
+ | RulePayload::Page { descriptors: block, .. } => block.data().descriptors.is_empty(),
+ _ => self.declaration_block().is_none_or(|block| block.data().is_empty()),
+ }
+ }
+
+ fn descriptor_block(&self) -> &FfiDescriptorBlock {
+ match &self.payload {
+ RulePayload::FontFace(block)
+ | RulePayload::FunctionDeclarations(block)
+ | RulePayload::Page { descriptors: block, .. } => block,
+ RulePayload::CounterStyle(rule) => rule.descriptor_block(),
+ _ => unreachable!("expected a rule with descriptors"),
+ }
+ }
+
+ /// The value of the descriptor with the name, serialized.
+ pub fn descriptor_text(&self, at_rule: u8, name: &str) -> Option<Utf16String> {
+ let name: Vec<u16> = name.encode_utf16().collect();
+ let id = descriptor_metadata(at_rule, &name)?.id;
+ let data = self.descriptor_block().data();
+ let descriptor = data.descriptors.iter().find(|descriptor| descriptor.id == id)?;
+ Some(value_text(&descriptor.value))
+ }
+
+ /// https://drafts.csswg.org/css-animations-1/#dom-csskeyframesrule-name
+ pub fn keyframes_name(&self) -> Utf16String {
+ let RulePayload::Keyframes(name) = &self.payload else {
+ unreachable!("expected a @keyframes rule")
+ };
+ css_utf16(&name.borrow())
+ }
+
+ pub fn set_keyframes_name(&self, name: &[u16]) {
+ let RulePayload::Keyframes(current) = &self.payload else {
+ unreachable!("expected a @keyframes rule")
+ };
+ *current.borrow_mut() = CssString::from_utf16(name);
+ }
+
+ /// The index of the last keyframe with the selector.
+ pub fn find_keyframe(&self, selector: &[u16]) -> Option<usize> {
+ let selectors = parse_keyframe_selector_list(TokenizerInput::from(selector))?;
+ let matches = |frame: &Self| {
+ let RulePayload::Keyframe(frame) = &frame.payload else {
+ unreachable!("a @keyframes rule holds keyframes")
+ };
+ frame.keys() == selectors
+ };
+ let children = self.child_rules()?;
+ if let Some(rules) = children.rules.borrow().as_ref() {
+ return rules.iter().rposition(|frame| matches(frame));
+ }
+ // NB: Most keyframes are not exposed yet, and reading the parsed source leaves them that way.
+ let parsed = children.parsed_source.borrow();
+ let parsed = parsed.as_ref()?;
+ let exposed = children.exposed_rules.borrow();
+ (0..parsed.len()).rev().find(|index| match exposed.get(index) {
+ Some(frame) => matches(frame),
+ None => *parsed.rule_at(*index).keyframe().unwrap().keys == selectors,
+ })
+ }
+
+ pub fn keyframe_keys(&self) -> Vec<f64> {
+ let RulePayload::Keyframe(frame) = &self.payload else {
+ unreachable!("expected a keyframe rule")
+ };
+ frame.keys().to_vec()
+ }
+
+ pub fn page_selector_text(&self) -> Utf16String {
+ let RulePayload::Page { selectors, .. } = &self.payload else {
+ unreachable!("expected a @page rule")
+ };
+ utf16(&serialized_page_selectors(&selectors.borrow()))
+ }
+
+ /// Replaces the selectors of a @page rule with what the text parses to, and returns whether it parsed.
+ pub fn set_page_selector_text(&self, text: &[u16]) -> bool {
+ let RulePayload::Page { selectors, .. } = &self.payload else {
+ unreachable!("expected a @page rule")
+ };
+ let Some(parsed) = parse_page_selector_list(TokenizerInput::from(text)) else {
+ return false;
+ };
+ *selectors.borrow_mut() = Arc::new(PageSelectorList::new(parsed));
+ true
+ }
+
+ /// The name of a margin rule or of a @position-try rule.
+ pub fn at_rule_name(&self) -> Utf16String {
+ match &self.payload {
+ RulePayload::Margin { name, .. } | RulePayload::PositionTry { name, .. } => css_utf16(name),
+ _ => unreachable!("expected a margin or @position-try rule"),
+ }
+ }
+
+ pub fn namespace_prefix(&self) -> Utf16String {
+ let RulePayload::Namespace(data) = &self.payload else {
+ unreachable!("expected a @namespace rule")
+ };
+ css_utf16(&data.prefix)
+ }
+
+ pub fn namespace_uri(&self) -> Utf16String {
+ let RulePayload::Namespace(data) = &self.payload else {
+ unreachable!("expected a @namespace rule")
+ };
+ css_utf16(&data.uri)
+ }
+
+ pub fn layer_names(&self) -> Vec<Utf16String> {
+ let RulePayload::LayerNames(names) = &self.payload else {
+ unreachable!("expected a @layer rule")
+ };
+ names.names.iter().map(css_utf16).collect()
+ }
+
+ fn property(&self) -> &crate::css::property_rule::PropertyRuleData {
+ let RulePayload::Property(data) = &self.payload else {
+ unreachable!("expected a @property rule")
+ };
+ data
+ }
+
+ pub fn property_name(&self) -> Utf16String {
+ css_utf16(&self.property().name)
+ }
+
+ pub fn property_syntax(&self) -> Utf16String {
+ css_utf16(&self.property().syntax_source)
+ }
+
+ pub fn property_inherits(&self) -> bool {
+ self.property().inherits
+ }
+
+ pub fn property_initial_value(&self) -> Option<Utf16String> {
+ self.property().initial_value.as_ref().map(value_text)
+ }
+
+ fn function(&self) -> &crate::css::function_signature::FunctionSignature {
+ let RulePayload::Function(signature) = &self.payload else {
+ unreachable!("expected a @function rule")
+ };
+ signature
+ }
+
+ pub fn function_name(&self) -> Utf16String {
+ css_utf16(&self.function().name)
+ }
+
+ // https://drafts.csswg.org/css-mixins-1/#dom-cssfunctionrule-getparameters
+ pub fn function_parameters(&self) -> Vec<FunctionParameter> {
+ self.function()
+ .parameters
+ .iter()
+ .map(|parameter| FunctionParameter {
+ // name
+ // The name of the function parameter.
+ name: Utf16String::from_utf16(&parameter.name.to_utf16()),
+
+ // type
+ // The type of the function parameter, represented as a syntax string, or "*" if the parameter has no
+ // type.
+ parameter_type: syntax_text(&parameter.syntax),
+
+ // defaultValue
+ // The default value of the function parameter, or `null` if the argument does not have a default.
+ default_value: parameter.default_value.as_ref().map(value_text),
+ })
+ .collect()
+ }
+
+ // https://drafts.csswg.org/css-mixins-1/#dom-cssfunctionrule-returntype
+ pub fn function_return_type(&self) -> Utf16String {
+ // The return type of the custom function, represented as a syntax string. If the custom function has no return
+ // type, returns "*".
+ // NB: We always store a return type (defaulting to "*")
+ syntax_text(&self.function().return_type)
+ }
+
+ /// The text of the prelude of a @function rule, as the steps 1 to 5 of
+ /// https://drafts.csswg.org/css-mixins-1/#serialize-a-cssfunctionrule make it.
+ pub fn function_prelude_text(&self) -> Utf16String {
+ let signature = self.function();
+ // To serialize a CSSFunctionRule, return the concatenation of the following:
+ let mut sink = TextSink::new();
+
+ // 1. The string "@function" followed by a single SPACE (U+0020).
+ sink.push_ascii("@function ");
+
+ // 2. The result of performing serialize an identifier on the name of the custom function, followed by a single
+ // LEFT PARENTHESIS (U+0028).
+ serialize_an_identifier(&mut sink, &StringUnits::Utf16(signature.name.units()));
+ sink.push_ascii("(");
+
+ // 3. The result of serialize a function parameter on each of the custom function’s parameters, all joined by
+ // ", " (COMMA U+002C, followed by a single SPACE U+0020).
+ for (index, parameter) in signature.parameters.iter().enumerate() {
+ if index != 0 {
+ sink.push_ascii(", ");
+ }
+
+ // https://drafts.csswg.org/css-mixins-1/#serialize-a-function-parameter
+ // To serialize a function parameter, return the concatenation of the following:
+
+ // The result of performing serialize an identifier on the name of the function parameter.
+ serialize_an_identifier(&mut sink, &StringUnits::Utf16(&parameter.name.to_utf16()));
+
+ // If the function parameter has a type, and that type is not the universal syntax definition:
+ if !parameter.syntax.is_universal() {
+ // - A single SPACE (U+0020), followed by the result of performing serialize a CSS type on that type.
+ sink.push_ascii(" ");
+ for unit in serialize_a_css_type(&parameter.syntax) {
+ sink.push_code_unit(unit);
+ }
+ }
+
+ // If the function parameter has a default value:
+ if let Some(default_value) = &parameter.default_value {
+ // - A single COLON (U+003A), followed by a single SPACE (U+0020), followed by the result of performing
+ // serialize a CSS value on that value.
+ sink.push_ascii(": ");
+ serialize_style_value(&mut sink, default_value, SerializationMode::Normal);
+ }
+ }
+
+ // 4. A single RIGHT PARENTHESIS (U+0029).
+ sink.push_ascii(")");
+
+ // 5. If the custom function has return type, and that return type is not the universal syntax definition ("*"):
+ if !signature.return_type.is_universal() {
+ // - A single SPACE (U+0020), followed by the string "returns", followed by a single SPACE (U+0020).
+ sink.push_ascii(" returns ");
+
+ // - The result of performing serialize a CSS type on that type.
+ for unit in serialize_a_css_type(&signature.return_type) {
+ sink.push_code_unit(unit);
+ }
+ }
+ sink_to_string(sink)
+ }
+
+ fn supports_handle(&self) -> &FfiQueryHandle {
+ let RulePayload::Supports(handle) = &self.payload else {
+ unreachable!("expected a @supports rule")
+ };
+ handle
+ }
+
+ pub fn supports_condition_text(&self) -> Utf16String {
+ utf16(&serialized_query_condition(self.supports_handle()))
+ }
+
+ pub fn supports_condition_matches(&self) -> bool {
+ supports_query_matches(self.supports_handle())
+ }
+
+ pub fn import_supports_text(&self) -> Option<Utf16String> {
+ let RulePayload::Import { data, .. } = &self.payload else {
+ unreachable!("expected an @import rule")
+ };
+ data.supports
+ .as_ref()
+ .map(|supports| utf16(&serialized_query_condition(supports)))
+ }
+
+ pub fn import_layer(&self) -> Option<Utf16String> {
+ let RulePayload::Import { data, .. } = &self.payload else {
+ unreachable!("expected an @import rule")
+ };
+ data.layer.as_ref().map(css_utf16)
+ }
+
+ /// The conditions of a @container rule, in the order of the rule.
+ pub fn container_conditions(&self) -> Vec<ContainerCondition> {
+ let RulePayload::Container(data) = &self.payload else {
+ unreachable!("expected a @container rule")
+ };
+ data.conditions
+ .iter()
+ .map(|condition| ContainerCondition {
+ name: condition
+ .name
+ .as_ref()
+ .map_or_else(|| utf16(&[]), |name| serialize_identifier(name.units())),
+ query: condition
+ .query
+ .as_ref()
+ .map_or_else(|| utf16(&[]), |query| utf16(&serialized_query_condition(query))),
+ })
+ .collect()
+ }
+
+ /// The media queries of a rule with a list of them, which the MediaList of the rule shares.
+ pub fn media_list(&self) -> crate::NativeMediaList {
+ match &self.payload {
+ RulePayload::Media { list } | RulePayload::Import { media: list, .. } => list.clone(),
+ _ => unreachable!("expected a @media or @import rule"),
+ }
+ }
+
+ /// The selector list of a style rule, as a pointer that C++ turns into text.
+ pub fn style_selector_list(&self) -> *const core::ffi::c_void {
+ Arc::as_ptr(&self.style_rule().selectors()).cast()
+ }
+
+ /// The selector lists that a @scope or a scoped @import rule starts and ends with, as pointers that C++ turns into
+ /// text. A list that the rule omits is null.
+ pub fn scope_selector_lists(&self) -> Option<(*const core::ffi::c_void, *const core::ffi::c_void)> {
+ let scope = match &self.payload {
+ RulePayload::Scope(scope) => Arc::clone(&scope.borrow()),
+ RulePayload::Import { scope: Some(scope), .. } => Arc::clone(scope),
+ _ => return None,
+ };
+ let pointer = |list: &Option<Arc<crate::css::selector_parser::RustParsedSelectorList>>| {
+ list.as_ref().map_or(core::ptr::null(), |list| Arc::as_ptr(list).cast())
+ };
+ Some((pointer(&scope.start), pointer(&scope.end)))
+ }
+
+ fn counter_style(&self) -> &crate::css::counter_style::FfiCounterStyle {
+ let RulePayload::CounterStyle(rule) = &self.payload else {
+ unreachable!("expected a @counter-style rule")
+ };
+ rule
+ }
+
+ pub fn counter_style_name(&self) -> Utf16String {
+ self.counter_style().name_text()
+ }
+
+ /// Sets the name of a @counter-style rule, and returns whether the name is valid.
+ pub fn set_counter_style_name(&self, name: &[u16]) -> bool {
+ self.counter_style().set_name_text(name)
+ }
+
+ /// The descriptor of a @counter-style rule, serialized, or the empty string if the rule does not have it.
+ pub fn counter_style_descriptor(&self, name: &str) -> Utf16String {
+ self.descriptor_text(COUNTER_STYLE_AT_RULE, name)
+ .unwrap_or_else(|| utf16(&[]))
+ }
+
+ /// https://drafts.csswg.org/css-counter-styles-3/#the-csscounterstylerule-interface
+ /// Sets the descriptor to the value that the text parses to, and returns whether it did.
+ pub fn set_counter_style_descriptor(&self, name: &str, text: &[u16]) -> bool {
+ // 1. parse the given value as the descriptor associated with the attribute.
+ let name_units: Vec<u16> = name.encode_utf16().collect();
+ let Some(value) = parse_descriptor_text(COUNTER_STYLE_AT_RULE, &name_units, text) else {
+ // 2. If the result is invalid according to the given descriptor’s grammar, or would cause the
+ // @counter-style rule to not define a counter style, do nothing and abort these steps. (For example,
+ // some systems require the symbols descriptor to contain two values.)
+ return false;
+ };
+ let rule = self.counter_style();
+ match name {
+ "symbols" | "additive-symbols" => {
+ if !rule.system_accepts_symbols(name == "additive-symbols", &value) {
+ return false;
+ }
+ }
+ // 3. If the attribute being set is system, and the new value would change the algorithm used, do nothing
+ // and abort these steps.
+ // Note: It’s okay to change an aspect of the algorithm, like the first symbol value of a fixed system.
+ "system" if rule.system_change_alters_algorithm(&value) => return false,
+ _ => {}
+ }
+
+ // 4. Set the descriptor to the value.
+ rule.set_descriptor(&name_units, value);
+ true
+ }
+
+ pub fn font_feature_values_families(&self) -> Vec<Utf16String> {
+ self.font_feature_values().families_text()
+ }
+
+ pub fn set_font_feature_values_families(&self, families: Vec<Vec<u16>>) {
+ self.font_feature_values().set_families_text(families);
+ }
+
+ fn font_feature_values(&self) -> &crate::css::font_feature_values::FontFeatureValuesRule {
+ let RulePayload::FontFeatureValues(values) = &self.payload else {
+ unreachable!("expected a @font-feature-values rule")
+ };
+ values
+ }
+
+ /// The name and the values of each feature value of the kind, in the order of the map.
+ pub fn font_feature_values_entries(&self, kind: FontFeatureValuesRuleKind) -> Vec<(Vec<u16>, Vec<u32>)> {
+ self.font_feature_values().entries_of(kind)
+ }
+}
+
+impl NativeRuleList {
+ /// The list that the pointer points to, which keeps its reference.
+ ///
+ /// # Safety
+ ///
+ /// `list` must point to a live list that an `Rc` owns.
+ pub unsafe fn retained_from_raw(list: *const Self) -> Rc<Self> {
+ // SAFETY: The caller passes a pointer into a live Rc.
+ unsafe {
+ Rc::increment_strong_count(list);
+ Rc::from_raw(list)
+ }
+ }
+
+ pub fn cssom_length(&self) -> usize {
+ self.len()
+ }
+
+ pub fn cssom_rule_at(&self, index: usize) -> Rc<NativeRule> {
+ self.rule_at(index)
+ }
+
+ pub fn cssom_identity_at(&self, index: usize) -> u64 {
+ super::rust_rule_list_identity_at(self, index)
+ }
+
+ /// The path of indices from the list down to the rule with the identity.
+ pub fn cssom_path_to_rule(&self, identity: u64) -> Option<Vec<usize>> {
+ let mut path = Vec::new();
+ self.find_path(identity, &mut path).then_some(path)
+ }
+
+ pub fn cssom_insert_rule(&self, index: usize, rule: Rc<NativeRule>, nested: bool) -> RuleInsertionResult {
+ self.insert_css_rule(index, rule, nested)
+ }
+
+ pub fn cssom_append_rule(&self, rule: Rc<NativeRule>) {
+ self.insert(self.len(), rule);
+ }
+
+ pub fn cssom_validate_removal(&self, index: usize) -> RuleRemovalResult {
+ self.validate_removal(index)
+ }
+
+ pub fn cssom_remove(&self, index: usize) {
+ self.remove(index);
+ }
+
+ pub fn cssom_replace(&self, source: &Self) {
+ self.replace(source);
+ }
+
+ pub fn cssom_external_memory_size(&self) -> usize {
+ super::rust_rule_list_external_memory_size(self)
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/scope_selectors.rs b/Libraries/LibWeb/Rust/src/css/scope_selectors.rs
index 18d7961bb09..1ad2c9737b0 100644
--- a/Libraries/LibWeb/Rust/src/css/scope_selectors.rs
+++ b/Libraries/LibWeb/Rust/src/css/scope_selectors.rs
@@ -4,9 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use crate::css::ffi_support::OwnedArc;
use crate::css::selector_parser::RustParsedSelectorList;
-use std::ffi::c_void;
use std::sync::Arc;
pub struct ScopeSelectors {
@@ -18,25 +16,3 @@ const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<ScopeSelectors>();
};
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_scope_selectors_retain(
- selectors: crate::css::ffi_support::ArcRef<'_, ScopeSelectors>,
-) -> *const ScopeSelectors {
- Arc::into_raw(selectors.to_arc())
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_scope_selectors_release(selectors: OwnedArc<ScopeSelectors>) {
- drop(selectors);
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_scope_selectors_start(selectors: &ScopeSelectors) -> *const c_void {
- selectors.start.as_ref().map_or(std::ptr::null(), Arc::as_ptr).cast()
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_scope_selectors_end(selectors: &ScopeSelectors) -> *const c_void {
- selectors.end.as_ref().map_or(std::ptr::null(), Arc::as_ptr).cast()
-}
diff --git a/Libraries/LibWeb/Rust/src/lib.rs b/Libraries/LibWeb/Rust/src/lib.rs
index 91f7d45030a..c20e32f7110 100644
--- a/Libraries/LibWeb/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Rust/src/lib.rs
@@ -33,7 +33,10 @@ pub(crate) mod style_layout_pool;
pub(crate) mod svg;
// What libweb_bindings_rust, whose interfaces are implemented in Rust, uses of this crate.
+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::typed_om;
pub use svg::gfx_path_from_path_data;