Skip to content

Truly independent web browser

LibWeb: Implement StylePropertyMap and its read-only base in Rust

Andreas Kling736854f549c2
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_style_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_rule.rs
index a8405fe8fb8..daca1471fae 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_style_rule.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_rule.rs
@@ -8,9 +8,9 @@
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 super::css_rule::{CSSRule, RuleText, native_rules_of_sheet, selector_list_text};
+use super::style_property_map::StylePropertyMap;
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;
@@ -22,15 +22,14 @@ 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>>,
+ /// The StylePropertyMap of the rule, once it is asked for.
+ style_map: GcRefCell<Option<Ref<StylePropertyMap>>>,
}
impl_rule_wrappable!(CSSStyleRule);
@@ -100,19 +99,14 @@ impl CSSStyleRule {
}
// 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));
+ pub(crate) fn style_map(&self, cx: &mut CallContext) -> WebIdlResult<Ref<StylePropertyMap>> {
+ if let Some(style_map) = *self.style_map.borrow() {
+ return Ok(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);
+ let style_map = StylePropertyMap::create(vm, self.rule().declarations(vm));
*self.style_map.borrow_mut(vm) = Some(style_map);
- Ok(result)
+ Ok(style_map)
}
// https://drafts.csswg.org/cssom-1/#serialize-a-css-rule
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
index 4290b5ba493..394f2e71de3 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
@@ -60,6 +60,8 @@ use super::font_face_set_load_event::{FontFaceSetLoadEvent, FontFaceSetLoadEvent
use super::media_list::MediaList;
use super::media_query_list::MediaQueryList;
use super::screen::Screen;
+use super::style_property_map::StylePropertyMap;
+use super::style_property_map_read_only::StylePropertyMapReadOnly;
use super::style_sheet_list::StyleSheetList;
use super::transition_event::{TransitionEvent, TransitionEventInit};
use super::typed_om;
@@ -535,6 +537,30 @@ pub unsafe extern "C" fn web_font_face_set_load_event_create(
.as_ptr()
}
+/// A new StylePropertyMap of the declaration.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `declaration` a live CSSStyleDeclaration.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_style_property_map_create(vm: *mut c_void, declaration: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes the live VM and a live CSSStyleDeclaration.
+ let (vm, declaration) = unsafe { (vm_from_abi(vm), CppCell::from_raw(declaration)) };
+ cell_into_abi(StylePropertyMap::create(vm, declaration))
+}
+
+/// A new StylePropertyMapReadOnly of the computed style of the element.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `element` a live Element.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_style_property_map_read_only_create(vm: *mut c_void, element: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes the live VM and a live Element.
+ let (vm, element) = unsafe { (vm_from_abi(vm), CppCell::from_raw(element)) };
+ cell_into_abi(StylePropertyMapReadOnly::create_computed_style(vm, element))
+}
+
/// A new Screen of the window.
///
/// # Safety
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
index 1dd942fb212..e72fcfe75d4 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
@@ -70,6 +70,8 @@ pub(crate) mod media_query_list;
pub(crate) mod media_query_list_event;
pub(crate) mod screen;
pub(crate) mod screen_orientation;
+pub(crate) mod style_property_map;
+pub(crate) mod style_property_map_read_only;
pub(crate) mod style_sheet;
pub(crate) mod style_sheet_list;
pub(crate) mod transition_event;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/style_property_map.rs b/Libraries/LibWeb/Bindings/Rust/src/css/style_property_map.rs
new file mode 100644
index 00000000000..046b5881fe4
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/style_property_map.rs
@@ -0,0 +1,519 @@
+/*
+ * Copyright (c) 2025, Sam Atkins <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! StylePropertyMap, https://drafts.css-houdini.org/css-typed-om-1/#stylepropertymap
+
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libjs_rust::api::{MarkedVec, Trace, Vm};
+use libweb_rust::typed_om::{RetainedStyleValue, property_is_shorthand};
+
+use super::css_style_value::AnyCSSStyleValue;
+use super::style_property_map_read_only::{Property, SERIALIZATION_MODE_NORMAL, StylePropertyMapReadOnly};
+use super::typed_om::{comma_separated_style_value_list, parse_values, to_rust_string};
+use crate::bindings::conversions::UsvString;
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::css::css_style_value::PerformTypeCheck;
+
+unsafe extern "C" {
+ fn web_css_style_map_property_is_list_valued(property_id: u16) -> bool;
+ fn web_css_style_map_parse(declaration: *mut c_void, property_id: u16, css_text: usize) -> *const c_void;
+ fn web_css_style_map_declared_value(declaration: *mut c_void, name: usize) -> *const c_void;
+ fn web_css_style_map_set_value(
+ declaration: *mut c_void,
+ name: usize,
+ value: *const c_void,
+ message: *mut usize,
+ ) -> u8;
+ fn web_css_style_map_remove(declaration: *mut c_void, name: usize, message: *mut usize) -> u8;
+ fn web_css_style_map_clear(declaration: *mut c_void, message: *mut usize) -> u8;
+}
+
+fn type_error(message: String) -> Exception {
+ Exception::TypeError(Utf16String::from_utf8(&message))
+}
+
+/// What a change to a declaration reported, as the ChangeResult of C++.
+const CHANGE_RESULT_SUCCESS: u8 = 0;
+const CHANGE_RESULT_TYPE_ERROR: u8 = 1;
+
+/// Runs a change to a declaration, which writes a message if it fails.
+fn change_declaration(change: impl FnOnce(*mut usize) -> u8) -> WebIdlResult<()> {
+ let mut message = 0;
+ let result = change(&raw mut message);
+ if result == CHANGE_RESULT_SUCCESS {
+ return Ok(());
+ }
+ // SAFETY: C++ hands over a reference to a string when a change fails.
+ let message = unsafe { Utf16String::from_raw_owned(message) };
+ if result == CHANGE_RESULT_TYPE_ERROR {
+ return Err(Exception::TypeError(message));
+ }
+ Err(Exception::Dom("NoModificationAllowedError", message))
+}
+
+/// The union (CSSStyleValue or USVString) of CSS/StylePropertyMap.idl.
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) enum CSSStyleValueOrUSVString {
+ CSSStyleValue(AnyCSSStyleValue),
+ USVString(#[gc(untraced)] UsvString),
+}
+
+fn any_have_non_matching_associated_property(property: &Utf16String, values: &[CSSStyleValueOrUSVString]) -> bool {
+ values.iter().any(|value| {
+ let CSSStyleValueOrUSVString::CSSStyleValue(value) = value else {
+ return false;
+ };
+ value
+ .style_value()
+ .associated_property()
+ .is_some_and(|associated_property| associated_property != property)
+ })
+}
+
+/// The value of the text according to the grammar of the property, parsed for the declaration if one is given.
+fn parse(declaration: *mut c_void, property_id: u16, css_text: Utf16String) -> Option<RetainedStyleValue> {
+ // SAFETY: The declaration is live or null, and this hands over a reference to the string.
+ let value = unsafe { web_css_style_map_parse(declaration, property_id, css_text.into_raw()) };
+ // SAFETY: C++ hands over a strong reference, if it parsed the value.
+ (!value.is_null()).then(|| unsafe { RetainedStyleValue::from_raw(value) })
+}
+
+fn is_custom_property(property: &Property) -> bool {
+ libweb_rust::typed_om::is_a_custom_property_name_string(&property.name)
+}
+
+fn is_list_valued(property: &Property) -> bool {
+ // SAFETY: This only reads the tables of the properties.
+ unsafe { web_css_style_map_property_is_list_valued(property.id) }
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+fn create_an_internal_representation(
+ vm: &Vm,
+ property: &Property,
+ value: &CSSStyleValueOrUSVString,
+) -> WebIdlResult<RetainedStyleValue> {
+ let property_name = to_rust_string(&property.name);
+
+ // To create an internal representation, given a string property and a string or CSSStyleValue value:
+ let internal_representation = match value {
+ CSSStyleValueOrUSVString::CSSStyleValue(css_style_value) => {
+ let internal_representation = css_style_value.create_an_internal_representation(
+ vm,
+ property.id,
+ &property.name,
+ PerformTypeCheck::Yes,
+ )?;
+ // INTEROP: Custom properties, including registered ones, only accept CSSUnparsedValue objects and
+ // CSS-wide keywords.
+ if is_custom_property(property)
+ && !matches!(css_style_value, AnyCSSStyleValue::CSSUnparsedValue(_))
+ && !internal_representation.is_css_wide_keyword()
+ {
+ return Err(type_error(
+ "Custom properties only accept unparsed values and CSS-wide keywords".into(),
+ ));
+ }
+ internal_representation
+ }
+ CSSStyleValueOrUSVString::USVString(css_text) => {
+ // If value is a USVString,
+ // Parse a CSSStyleValue with property property, cssText value, and parseMultiple set to false, and
+ // return the result.
+ let values = parse_values(vm, property.name.clone(), css_text.clone().into_utf16_string())?;
+ let result = values.get(0).expect("a parsed value has an iteration");
+ // AD-HOC: Result is a CSSStyleValue but we want an internal representation, so... convert it again I guess?
+ result.create_an_internal_representation(vm, property.id, &property.name, PerformTypeCheck::Yes)?
+ }
+ };
+
+ if let CSSStyleValueOrUSVString::CSSStyleValue(css_style_value) = value
+ && let Some(numeric_value) = css_style_value.as_numeric()
+ && !is_custom_property(property)
+ {
+ // INTEROP: Shape image thresholds accept typed numbers but not typed percentages.
+ if property_name == "shape-image-threshold" && !numeric_value.numeric_type().matches_number(None) {
+ return Err(type_error("Shape image thresholds require a number".into()));
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+ // If value does not match the grammar of a list-valued property iteration of property, throw a TypeError.
+ // NB: A property's component types do not establish that a numeric value alone matches its whole grammar.
+ let serialized_value = internal_representation.serialize(SERIALIZATION_MODE_NORMAL);
+ if parse(core::ptr::null_mut(), property.id, serialized_value).is_none() {
+ return Err(type_error("Numeric value does not match the property's grammar".into()));
+ }
+ }
+
+ // NB: Step easing keywords are custom identifiers outside the property parser. Store the parsed iteration so
+ // multi-value set() and append() use the easing representation expected by style computation.
+ if internal_representation.is_custom_ident()
+ && matches!(
+ property_name.as_str(),
+ "animation-timing-function" | "transition-timing-function"
+ )
+ {
+ let serialized_value = internal_representation.serialize(SERIALIZATION_MODE_NORMAL);
+ if let Some(items) = parse(core::ptr::null_mut(), property.id, serialized_value)
+ .and_then(|parsed_value| parsed_value.value_list_items())
+ && let [item] = items.as_slice()
+ {
+ return Ok(item.clone());
+ }
+ }
+
+ // AD-HOC: Our parser represents a text-indent that is just a length-percentage as a text-indent value, and style
+ // computation expects that.
+ if property_name == "text-indent" && internal_representation.is_length_percentage() {
+ return Ok(internal_representation.into_text_indent());
+ }
+
+ Ok(internal_representation)
+}
+
+fn normalize_overflow_clip_margin_internal_representation(
+ declaration: *mut c_void,
+ property: &Property,
+ value: RetainedStyleValue,
+) -> WebIdlResult<RetainedStyleValue> {
+ let property_name = to_rust_string(&property.name);
+ if !matches!(
+ property_name.as_str(),
+ "overflow-clip-margin" | "overflow-clip-margin-block" | "overflow-clip-margin-inline"
+ ) {
+ return Ok(value);
+ }
+
+ if value.is_shorthand()
+ || value.is_unresolved()
+ || value.is_pending_substitution()
+ || value.is_guaranteed_invalid()
+ || value.is_css_wide_keyword()
+ {
+ return Ok(value);
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+ // If value is a CSSStyleValue subclass, if value does not match the grammar of a list-valued property
+ // iteration of property, throw a TypeError.
+ let serialized_value = value.serialize(SERIALIZATION_MODE_NORMAL);
+ parse(declaration, property.id, serialized_value.clone()).ok_or_else(|| {
+ type_error(format!(
+ "Property '{property_name}' does not accept the value '{}'",
+ to_rust_string(&serialized_value)
+ ))
+ })
+}
+
+/// AD-HOC: To match the behavior of our parser we should store values of list-valued longhands as lists even if there
+/// is only one value, except in some rare circumstances.
+fn should_wrap_value_in_list(property: &Property, value: &RetainedStyleValue) -> bool {
+ if property_is_shorthand(property.id) {
+ return false;
+ }
+
+ if !is_list_valued(property) {
+ return false;
+ }
+
+ // Values which are not yet fully resolved should not be wrapped in lists.
+ !(value.is_unresolved()
+ || value.is_pending_substitution()
+ || value.is_guaranteed_invalid()
+ || value.is_css_wide_keyword())
+}
+
+/// AD-HOC: A single keyword or identifier should be stored the way our parser stores it for the property. That is
+/// either the keyword on its own, as for `box-shadow: none`, or a list with the identifier as its only item, as
+/// for `container-name: foo`. So we parse it as a value of the property.
+fn parsed_identifier_value(
+ declaration: *mut c_void,
+ property: &Property,
+ value: &RetainedStyleValue,
+) -> Option<RetainedStyleValue> {
+ if is_custom_property(property) {
+ return None;
+ }
+ if !value.is_custom_ident() && !(value.is_keyword() && !value.is_css_wide_keyword()) {
+ return None;
+ }
+ parse(declaration, property.id, value.serialize(SERIALIZATION_MODE_NORMAL))
+}
+
+/// AD-HOC: Our parser represents the track sizes of grid-auto-columns and grid-auto-rows as a single track size list,
+/// and style computation expects that.
+fn grid_track_size_list(property: &Property, values: &[RetainedStyleValue]) -> Option<RetainedStyleValue> {
+ let property_name = to_rust_string(&property.name);
+ if !matches!(property_name.as_str(), "grid-auto-columns" | "grid-auto-rows") {
+ return None;
+ }
+ let is_not_a_track_size = |value: &RetainedStyleValue| {
+ value.is_grid_track_size_list()
+ || value.is_unresolved()
+ || value.is_pending_substitution()
+ || value.is_guaranteed_invalid()
+ || value.is_css_wide_keyword()
+ };
+ if values.iter().any(is_not_a_track_size) {
+ return None;
+ }
+ Some(RetainedStyleValue::grid_track_size_list(values.to_vec()))
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#stylepropertymap
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct StylePropertyMap {
+ read_only: StylePropertyMapReadOnly,
+}
+
+impl Wrappable for StylePropertyMap {}
+
+impl Inherits<StylePropertyMapReadOnly> for StylePropertyMap {
+ fn parent(&self) -> &StylePropertyMapReadOnly {
+ &self.read_only
+ }
+}
+
+impl StylePropertyMap {
+ pub(crate) fn create(vm: &Vm, declaration: CppCell) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ read_only: StylePropertyMapReadOnly::new_declared(declaration),
+ })
+ }
+
+ fn set_property_style_value(&self, property: &Property, value: RetainedStyleValue) -> WebIdlResult<()> {
+ change_declaration(|message| {
+ // SAFETY: The declaration is live, and this hands over references to the string and the value.
+ unsafe {
+ web_css_style_map_set_value(
+ self.read_only.declaration(),
+ property.name.clone().into_raw(),
+ value.into_raw(),
+ message,
+ )
+ }
+ })
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymap-set
+ pub(crate) fn set(
+ &self,
+ cx: &mut CallContext,
+ property: UsvString,
+ values: MarkedVec<'_, CSSStyleValueOrUSVString>,
+ ) -> WebIdlResult<()> {
+ // The set(property, ...values) method, when called on a StylePropertyMap this, must perform the following
+ // steps:
+
+ // 1. If property is not a custom property name string, set property to property ASCII lowercased.
+ // 2. If property is not a valid CSS property, throw a TypeError.
+ let property_name = property.into_utf16_string();
+ let property = Property::from_name(&property_name)?;
+ let name = to_rust_string(&property_name);
+ let values = values.values();
+
+ // 3. If property is a single-valued property and values has more than one item, throw a TypeError.
+ // NB: Custom properties should all be single-valued.
+ if (is_custom_property(&property) || !is_list_valued(&property)) && values.len() > 1 {
+ return Err(type_error(format!("Property '{name}' only accepts a single value")));
+ }
+
+ // FIXME: The spec doesn't say how to handle empty `values`, but other browsers throw a TypeError so let's do
+ // that too - see https://github.com/w3c/css-houdini-drafts/issues/1176
+ if values.is_empty() {
+ return Err(type_error(format!("Property '{name}' requires at least one value")));
+ }
+
+ // 4. If any of the items in values have a non-null [[associatedProperty]] internal slot, and that slot’s value
+ // is anything other than property, throw a TypeError.
+ if any_have_non_matching_associated_property(&property.name, &values) {
+ return Err(type_error(
+ "One of the passed CSSStyleValues has a different associated property".into(),
+ ));
+ }
+
+ // 5. If the size of values is two or more, and one or more of the items are a CSSUnparsedValue or
+ // CSSVariableReferenceValue object, throw a TypeError.
+ // NOTE: Having 2+ values implies that you’re setting multiple items of a list-valued property, but the presence
+ // of a var() function in the string-based OM disables all syntax parsing, including splitting into
+ // individual iterations (because there might be more commas inside of the var() value, so you can’t tell
+ // how many items are actually going to show up). This step’s restriction preserves the same semantics in
+ // the Typed OM.
+ // FIXME: This is done as part of step 9, because we need to detect if a string value would be an
+ // CSSUnparsedValue or CSSVariableReferenceValue. Spec issue:
+ // https://github.com/w3c/css-houdini-drafts/issues/1157
+
+ // 6. Let props be the value of this’s [[declarations]] internal slot.
+ let props = self.read_only.declaration();
+
+ // 8. Let values to set be an empty list.
+ let mut values_to_set = Vec::with_capacity(values.len());
+
+ // 9. For each value in values, create an internal representation for property and value, and append the result
+ // to values to set.
+ for value in values.iter() {
+ // AD-HOC: Step 5 is done here, see above.
+ let internal_representation = create_an_internal_representation(cx.vm(), &property, value)?;
+ let internal_representation =
+ normalize_overflow_clip_margin_internal_representation(props, &property, internal_representation)?;
+
+ if values.len() >= 2 && internal_representation.is_unresolved() {
+ return Err(type_error(
+ "Cannot provide multiple values if one is an CSSUnparsedValue or CSSVariableReferenceValue".into(),
+ ));
+ }
+
+ values_to_set.push(internal_representation);
+ }
+
+ // 7. If props[property] exists, remove it.
+ // NB: Removal and replacement happen together in set_property_style_value(), after validation, so observers
+ // receive a single style-attribute update.
+
+ // 10. Set props[property] to values to set.
+ // NOTE: The property is deleted then added back so that it gets put at the end of the ordered map, which gives
+ // the expected behavior in the face of shorthand properties.
+ if let [value] = values_to_set.as_slice()
+ && let Some(parsed_value) = parsed_identifier_value(props, &property, value)
+ {
+ return self.set_property_style_value(&property, parsed_value);
+ }
+ if let Some(track_size_list) = grid_track_size_list(&property, &values_to_set) {
+ return self.set_property_style_value(&property, track_size_list);
+ }
+ if let [value] = values_to_set.as_slice()
+ && !should_wrap_value_in_list(&property, value)
+ {
+ return self.set_property_style_value(&property, value.clone());
+ }
+ self.set_property_style_value(&property, comma_separated_style_value_list(values_to_set))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymap-append
+ pub(crate) fn append(
+ &self,
+ cx: &mut CallContext,
+ property: UsvString,
+ values: MarkedVec<'_, CSSStyleValueOrUSVString>,
+ ) -> WebIdlResult<()> {
+ // The append(property, ...values) method, when called on a StylePropertyMap this, must perform the following
+ // steps:
+
+ // 1. If property is not a custom property name string, set property to property ASCII lowercased.
+ // 2. If property is not a valid CSS property, throw a TypeError.
+ let property_name = property.into_utf16_string();
+ let property = Property::from_name(&property_name)?;
+ let name = to_rust_string(&property_name);
+ let values = values.values();
+
+ // 3. If property is not a list-valued property, throw a TypeError.
+ if !is_list_valued(&property) {
+ return Err(type_error(format!("'{name}' is not a list-valued property")));
+ }
+
+ // 4. If any of the items in values have a non-null [[associatedProperty]] internal slot, and that slot’s value
+ // is anything other than property, throw a TypeError.
+ if any_have_non_matching_associated_property(&property.name, &values) {
+ return Err(type_error(
+ "One of the passed CSSStyleValues has a different associated property".into(),
+ ));
+ }
+
+ // 5. If any of the items in values are a CSSUnparsedValue or CSSVariableReferenceValue object, throw a
+ // TypeError.
+ // NOTE: When a property is set via string-based APIs, the presence of var() in a property prevents the entire
+ // thing from being interpreted. In other words, everything besides the var() is a plain component value,
+ // not a meaningful type. This step’s restriction preserves the same semantics in the Typed OM.
+ // FIXME: This is done as part of step 10, because we need to detect if a string value would be an
+ // CSSUnparsedValue or CSSVariableReferenceValue. Spec issue:
+ // https://github.com/w3c/css-houdini-drafts/issues/1157
+
+ // 6. Let props be the value of this’s [[declarations]] internal slot.
+ let props = self.read_only.declaration();
+
+ // 7. If props[property] does not exist, set props[property] to an empty list.
+ // SAFETY: The declaration is live, and this hands over a reference to the string.
+ let existing_value = unsafe { web_css_style_map_declared_value(props, property.name.clone().into_raw()) };
+ // SAFETY: C++ hands over a strong reference, if the property has a value.
+ let existing_value =
+ (!existing_value.is_null()).then(|| unsafe { RetainedStyleValue::from_raw(existing_value) });
+
+ // 8. If props[property] contains a var() reference, throw a TypeError.
+ if existing_value.as_ref().is_some_and(RetainedStyleValue::is_unresolved) {
+ return Err(type_error(format!(
+ "Existing value for '{name}' contains var() references."
+ )));
+ }
+
+ // NB: Appending no values must not replace the declaration or update the style attribute.
+ if values.is_empty() {
+ return Ok(());
+ }
+
+ // 9. Let temp values be an empty list.
+ // NB: StyleValues are immutable, so we always create a new one. We add directly to it instead of using "temp
+ // values".
+ let mut value_list = Vec::new();
+ if let Some(existing_value) = existing_value {
+ match existing_value.value_list_items() {
+ Some(items) => value_list = items,
+ None => value_list.push(existing_value),
+ }
+ }
+
+ // 10. For each value in values, create an internal representation with property and value, and append the
+ // returned value to temp values.
+ for value in values.iter() {
+ // AD-HOC: Step 5 is done here, see above.
+ let internal_representation = create_an_internal_representation(cx.vm(), &property, value)?;
+
+ if internal_representation.is_unresolved() {
+ return Err(type_error(
+ "Cannot append a CSSUnparsedValue or CSSVariableReferenceValue".into(),
+ ));
+ }
+
+ value_list.push(internal_representation);
+ }
+
+ // 11. Append the entries of temp values to props[property].
+ // NB: StyleValues are immutable, so we create a new one instead.
+ self.set_property_style_value(&property, comma_separated_style_value_list(value_list))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymap-delete
+ pub(crate) fn delete(&self, _: &mut CallContext, property: UsvString) -> WebIdlResult<()> {
+ // The delete(property) method, when called on a StylePropertyMap this, must perform the following steps:
+
+ // 1. If property is not a custom property name string, set property to property ASCII lowercased.
+ // 2. If property is not a valid CSS property, throw a TypeError.
+ let property = Property::from_name(&property.into_utf16_string())?;
+
+ // 3. If this’s [[declarations]] internal slot contains property, remove it.
+ change_declaration(|message| {
+ // SAFETY: The declaration is live, and this hands over a reference to the string.
+ unsafe { web_css_style_map_remove(self.read_only.declaration(), property.name.into_raw(), message) }
+ })
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymap-clear
+ pub(crate) fn clear(&self, _: &mut CallContext) -> WebIdlResult<()> {
+ // The clear() method, when called on a StylePropertyMap this, must perform the following steps:
+
+ // 1. Remove all of the declarations in this’s [[declarations]] internal slot.
+ change_declaration(|message| {
+ // SAFETY: The declaration is live.
+ unsafe { web_css_style_map_clear(self.read_only.declaration(), message) }
+ })
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/style_property_map_read_only.rs b/Libraries/LibWeb/Bindings/Rust/src/css/style_property_map_read_only.rs
new file mode 100644
index 00000000000..988b5a8f320
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/style_property_map_read_only.rs
@@ -0,0 +1,385 @@
+/*
+ * Copyright (c) 2025, Sam Atkins <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! StylePropertyMapReadOnly, https://drafts.css-houdini.org/css-typed-om-1/#stylepropertymapreadonly
+
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libjs_rust::api::{
+ Array, DeferGc, EmbedderCell, EmbedderClass, EmbedderValue, Gc, MarkedVec, Object, Trace, Value, Vm,
+};
+use libweb_rust::typed_om::RetainedStyleValue;
+
+use super::css_style_value::{AnyCSSStyleValue, CSSStyleValue};
+use super::typed_om::{append_style_value, reify, to_rust_string};
+use crate::bindings::conversions::{ToJs, UsvString};
+use crate::bindings::cpp_cell::CppCell;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, implementation_if, implementation_of};
+use crate::bindings::iterable::{IterationKind, PairIterable};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::css::style_property_map::StylePropertyMap;
+
+unsafe extern "C" {
+ fn web_css_style_map_property(name: usize, id: *mut u16, canonical_name: *mut usize) -> bool;
+ fn web_css_style_map_iterations(
+ is_computed: bool,
+ source: *mut c_void,
+ name: usize,
+ values: *mut c_void,
+ append: unsafe extern "C" fn(*mut c_void, *const c_void),
+ ) -> u8;
+ fn web_css_style_map_has(is_computed: bool, source: *mut c_void, name: usize) -> bool;
+ fn web_css_style_map_property_names(
+ is_computed: bool,
+ source: *mut c_void,
+ names: *mut c_void,
+ append: unsafe extern "C" fn(*mut c_void, usize),
+ );
+ fn web_css_style_map_property_count(is_computed: bool, source: *mut c_void) -> usize;
+}
+
+/// The numeric value of SerializationMode::Normal of C++.
+pub(super) const SERIALIZATION_MODE_NORMAL: u8 = 0;
+/// The numeric value of SerializationMode::ResolvedValue of C++.
+const SERIALIZATION_MODE_RESOLVED_VALUE: u8 = 1;
+
+/// What web_css_style_map_iterations() found.
+const ITERATIONS_ABSENT: u8 = 0;
+const ITERATIONS_SHORTHAND: u8 = 2;
+
+/// A valid CSS property, https://drafts.css-houdini.org/css-typed-om-1/#valid-css-property
+pub(crate) struct Property {
+ pub(crate) id: u16,
+ pub(crate) name: Utf16String,
+}
+
+impl Property {
+ /// The steps that every method of a style map starts with:
+ /// 1. If property is not a custom property name string, set property to property ASCII lowercased.
+ /// 2. If property is not a valid CSS property, throw a TypeError.
+ pub(crate) fn from_name(name: &Utf16String) -> WebIdlResult<Self> {
+ let (mut id, mut canonical_name) = (0, 0);
+ // SAFETY: This hands over a reference to the string, and the results are lent for the call.
+ let is_valid =
+ unsafe { web_css_style_map_property(name.clone().into_raw(), &raw mut id, &raw mut canonical_name) };
+ if !is_valid {
+ return Err(Exception::TypeError(Utf16String::from_utf8(&format!(
+ "'{}' is not a valid CSS property",
+ to_rust_string(name)
+ ))));
+ }
+ Ok(Self {
+ id,
+ // SAFETY: C++ hands over a reference to a string.
+ name: unsafe { Utf16String::from_raw_owned(canonical_name) },
+ })
+ }
+}
+
+/// https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-declarations-slot
+/// NB: We just directly refer to our source, at least for now.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+enum Declarations {
+ /// The Element whose computed style this reflects.
+ ComputedStyle(CppCell),
+ /// The CSSStyleDeclaration that this reflects.
+ Declared(CppCell),
+}
+
+/// The value pairs of a style map when an iteration started.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct ValuePairs {
+ pairs: Vec<(Value, Value)>,
+}
+
+static VALUE_PAIRS_CLASS: EmbedderClass<ValuePairs> = EmbedderClass::new("StylePropertyMapReadOnly value pairs");
+
+impl EmbedderValue for ValuePairs {
+ const CLASS: &'static EmbedderClass<Self> = &VALUE_PAIRS_CLASS;
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#stylepropertymapreadonly
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct StylePropertyMapReadOnly {
+ declarations: Declarations,
+}
+
+impl Wrappable for StylePropertyMapReadOnly {}
+
+impl Inherits<StylePropertyMapReadOnly> for StylePropertyMapReadOnly {
+ fn parent(&self) -> &StylePropertyMapReadOnly {
+ self
+ }
+}
+
+impl PairIterable for StylePropertyMapReadOnly {
+ type Key = Value;
+ type Value = Value;
+ type Target = Gc<EmbedderCell<ValuePairs>>;
+
+ /// INTEROP: Snapshot the entry list when iteration starts, matching Chrome and Safari.
+ fn iteration_target(cx: &CallContext, wrapper: Gc<Object>, kind: IterationKind) -> Self::Target {
+ let pairs = if let Some(map) = implementation_if::<StylePropertyMap>(wrapper) {
+ map.parent().value_pairs(cx, kind)
+ } else {
+ implementation_of::<Self>(wrapper).value_pairs(cx, kind)
+ };
+ VALUE_PAIRS_CLASS.allocate(cx.vm(), |defer_gc| ValuePairs {
+ pairs: pairs.to_pairs(defer_gc),
+ })
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#stylepropertymapreadonly
+ fn value_pairs_to_iterate_over(target: &Self::Target) -> impl core::ops::Deref<Target = [(Value, Value)]> + '_ {
+ target.pairs.as_slice()
+ }
+}
+
+/// The keys and values of value pairs, one after the other, which stay alive while more of them are created.
+struct MarkedValuePairs<'vm>(MarkedVec<'vm, Value>);
+
+impl MarkedValuePairs<'_> {
+ fn to_pairs(&self, _: &DeferGc<'_>) -> Vec<(Value, Value)> {
+ let values = self.0.to_vec();
+ let (pairs, _) = values.as_chunks::<2>();
+ pairs.iter().map(|&[key, value]| (key, value)).collect()
+ }
+}
+
+impl StylePropertyMapReadOnly {
+ pub(crate) fn new_declared(declaration: CppCell) -> Self {
+ Self {
+ declarations: Declarations::Declared(declaration),
+ }
+ }
+
+ pub(crate) fn create_computed_style(vm: &Vm, element: CppCell) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ declarations: Declarations::ComputedStyle(element),
+ })
+ }
+
+ /// The CSSStyleDeclaration of a map that reflects one.
+ pub(crate) fn declaration(&self) -> *mut c_void {
+ match &self.declarations {
+ Declarations::Declared(declaration) => declaration.as_ptr(),
+ Declarations::ComputedStyle(_) => {
+ unreachable!("writable StylePropertyMaps are backed by a CSSStyleDeclaration")
+ }
+ }
+ }
+
+ fn source(&self) -> (bool, *mut c_void) {
+ match &self.declarations {
+ Declarations::ComputedStyle(element) => (true, element.as_ptr()),
+ Declarations::Declared(declaration) => (false, declaration.as_ptr()),
+ }
+ }
+
+ /// INTEROP: Computed border-image values represent all four sides or both axes, even when their serialization
+ /// collapses to a single numeric value or keyword.
+ fn reify_property_value(
+ vm: &Vm,
+ value: &RetainedStyleValue,
+ property: &Property,
+ is_computed: bool,
+ ) -> AnyCSSStyleValue {
+ let name = to_rust_string(&property.name);
+ let is_border_image_value = matches!(
+ name.as_str(),
+ "border-image-width" | "border-image-outset" | "border-image-slice" | "border-image-repeat"
+ );
+ if is_computed && is_border_image_value {
+ return AnyCSSStyleValue::CSSStyleValue(CSSStyleValue::create(
+ vm,
+ property.name.clone(),
+ value.clone(),
+ SERIALIZATION_MODE_NORMAL,
+ ));
+ }
+ reify(vm, value, &property.name)
+ }
+
+ /// The reified iterations of props[property], up to the limit. There are none if props[property] does not exist.
+ fn reified_iterations<'vm>(
+ &self,
+ vm: &'vm Vm,
+ property: &Property,
+ limit: usize,
+ ) -> MarkedVec<'vm, AnyCSSStyleValue> {
+ let (is_computed, source) = self.source();
+ let mut iterations: Vec<RetainedStyleValue> = Vec::new();
+ // SAFETY: The source is live, this hands over a reference to the string, and the values are lent for the call.
+ let kind = unsafe {
+ web_css_style_map_iterations(
+ is_computed,
+ source,
+ property.name.clone().into_raw(),
+ (&raw mut iterations).cast(),
+ append_style_value,
+ )
+ };
+
+ let results = MarkedVec::new(vm);
+ if kind == ITERATIONS_ABSENT {
+ return results;
+ }
+ if kind == ITERATIONS_SHORTHAND {
+ results.push(AnyCSSStyleValue::CSSStyleValue(CSSStyleValue::create(
+ vm,
+ property.name.clone(),
+ iterations.remove(0),
+ SERIALIZATION_MODE_RESOLVED_VALUE,
+ )));
+ return results;
+ }
+ for value in iterations.iter().take(limit) {
+ results.push(Self::reify_property_value(vm, value, property, is_computed));
+ }
+ results
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-get
+ pub(crate) fn get(&self, cx: &mut CallContext, property: UsvString) -> WebIdlResult<Option<AnyCSSStyleValue>> {
+ // The get(property) method, when called on a StylePropertyMapReadOnly this, must perform the following steps:
+
+ // 1. If property is not a custom property name string, set property to property ASCII lowercased.
+ // 2. If property is not a valid CSS property, throw a TypeError.
+ let property = Property::from_name(&property.into_utf16_string())?;
+
+ // 3. Let props be the value of this’s [[declarations]] internal slot.
+ // 4. If props[property] exists, subdivide into iterations props[property], then reify the first item of the
+ // result and return it.
+ // 5. Otherwise, return undefined.
+ Ok(self.reified_iterations(cx.vm(), &property, 1).get(0))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-getall
+ pub(crate) fn get_all<'vm>(
+ &self,
+ cx: &mut CallContext<'vm>,
+ property: UsvString,
+ ) -> WebIdlResult<MarkedVec<'vm, AnyCSSStyleValue>> {
+ // The getAll(property) method, when called on a StylePropertyMap this, must perform the following steps:
+
+ // 1. If property is not a custom property name string, set property to property ASCII lowercased.
+ // 2. If property is not a valid CSS property, throw a TypeError.
+ let property = Property::from_name(&property.into_utf16_string())?;
+
+ // 3. Let props be the value of this’s [[declarations]] internal slot.
+ // 4. If props[property] exists, subdivide into iterations props[property], then reify each item of the result,
+ // and return the list.
+ // 5. Otherwise, return an empty list.
+ Ok(self.reified_iterations(cx.vm(), &property, usize::MAX))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-has
+ pub(crate) fn has(&self, _: &mut CallContext, property: UsvString) -> WebIdlResult<bool> {
+ // The has(property) method, when called on a StylePropertyMapReadOnly this, must perform the following steps:
+
+ // 1. If property is not a custom property name string, set property to property ASCII lowercased.
+ // 2. If property is not a valid CSS property, throw a TypeError.
+ let property = Property::from_name(&property.into_utf16_string())?;
+
+ // 3. Let props be the value of this’s [[declarations]] internal slot.
+ // 4. If props[property] exists, return true. Otherwise, return false.
+ let (is_computed, source) = self.source();
+ // SAFETY: The source is live, and this hands over a reference to the string.
+ Ok(unsafe { web_css_style_map_has(is_computed, source, property.name.into_raw()) })
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-size
+ pub(crate) fn size(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ // The size attribute, on getting from a StylePropertyMapReadOnly this, must perform the following steps:
+
+ // 1. Return the size of the value of this’s [[declarations]] internal slot.
+ let (is_computed, source) = self.source();
+ // SAFETY: The source is live.
+ let size = unsafe { web_css_style_map_property_count(is_computed, source) };
+ Ok(u32::try_from(size).expect("a map has fewer than 2^32 properties"))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-declarations-slot
+ fn property_names(&self) -> Vec<Utf16String> {
+ unsafe extern "C" fn append_name(names: *mut c_void, name: usize) {
+ // SAFETY: The context is the vector below, and C++ hands over a reference to a string.
+ unsafe { (*names.cast::<Vec<Utf16String>>()).push(Utf16String::from_raw_owned(name)) };
+ }
+
+ let (is_computed, source) = self.source();
+ let mut names: Vec<Utf16String> = Vec::new();
+ // SAFETY: The source is live, and the names are lent for the call.
+ unsafe { web_css_style_map_property_names(is_computed, source, (&raw mut names).cast(), append_name) };
+
+ // INTEROP: Inline and declared maps preserve declaration order.
+ if is_computed {
+ // Unless otherwise stated, the initial ordering of the [[declarations]] internal slot is based on the key
+ // of each entry:
+ // 1. Standardized properties (not custom properties or vendor-prefixed properties), ASCII lowercased and
+ // then sorted in increasing code-point order.
+ // 2. Vendor-prefixed/experimental properties (those whose name starts with a single dash), ASCII lowercased
+ // and then sorted in increasing code-point order.
+ // 3. Custom properties, sorted in increasing code-point order. (These are never lower-cased; they are
+ // preserved exactly as written.)
+ names.sort_by_cached_key(|name| {
+ let name = name.to_utf16();
+ let category = match name.as_ref() {
+ [0x2d, 0x2d, ..] => 2,
+ [0x2d, ..] => 1,
+ _ => 0,
+ };
+ let code_points: Vec<u32> = char::decode_utf16(name.iter().copied())
+ .map(|unit| unit.map_or_else(|error| u32::from(error.unpaired_surrogate()), u32::from))
+ .collect();
+ (category, code_points)
+ });
+ }
+ names
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#stylepropertymapreadonly
+ fn value_pairs<'vm>(&self, cx: &CallContext<'vm>, kind: IterationKind) -> MarkedValuePairs<'vm> {
+ // The value pairs to iterate over for a StylePropertyMapReadOnly object this are obtained as follows:
+ // 1. Let declarations be this’s [[declarations]] slot.
+ // 2. Let value pairs be an empty list.
+ let value_pairs = MarkedVec::new(cx.vm());
+
+ // 3. For each prop → value in declarations:
+ for name in self.property_names() {
+ let key = name.clone().to_js(cx).expect("a string converts to a JS value");
+ value_pairs.push(key);
+
+ // NB: An iteration over the keys does not read the values.
+ if matches!(kind, IterationKind::Key) {
+ value_pairs.push(Value::UNDEFINED);
+ continue;
+ }
+
+ // 1. Let iterations be the result of dividing into iterations value.
+ // 2. Reify each item of iterations, and let objects be the result.
+ let Ok(property) = Property::from_name(&name) else {
+ unreachable!("the name of a declaration is a valid CSS property");
+ };
+ let objects = self.reified_iterations(cx.vm(), &property, usize::MAX);
+
+ // 3. Append prop/objects to value pairs.
+ let wrappers = MarkedVec::with_capacity(cx.vm(), objects.len());
+ for object in objects.values().iter() {
+ wrappers.push(object.to_js(cx).expect("an object converts to a JS value"));
+ }
+ let array = Array::create_from(cx.vm(), cx.realm(), &wrappers.to_vec());
+ value_pairs.push(Value::from_object(array.upcast::<Object>()));
+ }
+
+ // 4. Return value pairs.
+ MarkedValuePairs(value_pairs)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/typed_om.rs b/Libraries/LibWeb/Bindings/Rust/src/css/typed_om.rs
index 676301e2adf..55ccf3bcfbd 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/typed_om.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/typed_om.rs
@@ -63,7 +63,7 @@ unsafe extern "C" {
perform_type_check: bool,
) -> *const c_void;
fn web_css_typed_om_keyword_style_value(property_id: u16, value: usize, perform_type_check: bool) -> *const c_void;
- fn web_css_typed_om_style_value_list(values: *const *const c_void, count: usize) -> *const c_void;
+ fn web_css_typed_om_style_value_list(values: *const *const c_void, count: usize, comma: bool) -> *const c_void;
fn web_css_typed_om_parse_numeric_value(css_text: usize) -> *const c_void;
fn web_css_typed_om_parse_value(
property: usize,
@@ -156,20 +156,28 @@ pub(crate) fn keyword_style_value_for_property(
}
/// A list of the values, separated by spaces.
-pub(crate) fn style_value_list(values: Vec<RetainedStyleValue>) -> RetainedStyleValue {
+fn create_style_value_list(values: Vec<RetainedStyleValue>, comma: bool) -> RetainedStyleValue {
let values: Vec<_> = values.into_iter().map(RetainedStyleValue::into_raw).collect();
// SAFETY: This hands over one strong reference to each of the values.
- optional_style_value(unsafe { web_css_typed_om_style_value_list(values.as_ptr(), values.len()) })
+ optional_style_value(unsafe { web_css_typed_om_style_value_list(values.as_ptr(), values.len(), comma) })
.expect("a list is a style value")
}
+pub(crate) fn style_value_list(values: Vec<RetainedStyleValue>) -> RetainedStyleValue {
+ create_style_value_list(values, false)
+}
+
+pub(crate) fn comma_separated_style_value_list(values: Vec<RetainedStyleValue>) -> RetainedStyleValue {
+ create_style_value_list(values, true)
+}
+
/// The first of the numeric types that the text parses as, https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-parse
pub(crate) fn parse_a_numeric_value(css_text: &Utf16String) -> Option<RetainedStyleValue> {
// SAFETY: This hands over a reference to the string.
optional_style_value(unsafe { web_css_typed_om_parse_numeric_value(css_text.clone().into_raw()) })
}
-unsafe extern "C" fn append_style_value(values: *mut c_void, value: *const c_void) {
+pub(crate) unsafe extern "C" fn append_style_value(values: *mut c_void, value: *const c_void) {
// SAFETY: The context is the Vec of parse_a_css_style_value(), and C++ hands over a strong reference.
unsafe { (*values.cast::<Vec<RetainedStyleValue>>()).push(RetainedStyleValue::from_raw(value)) };
}
diff --git a/Libraries/LibWeb/Bindings/StylePropertyMapReadOnlyIterator.cpp b/Libraries/LibWeb/Bindings/StylePropertyMapReadOnlyIterator.cpp
deleted file mode 100644
index 92ea034aad9..00000000000
--- a/Libraries/LibWeb/Bindings/StylePropertyMapReadOnlyIterator.cpp
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/RootVector.h>
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/Array.h>
-#include <LibJS/Runtime/Iterator.h>
-#include <LibJS/Runtime/PrimitiveString.h>
-#include <LibWeb/Bindings/CSSStyleValue.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/Bindings/StylePropertyMapReadOnly.h>
-#include <LibWeb/Bindings/StylePropertyMapReadOnlyIterator.h>
-#include <LibWeb/Bindings/WrapperWorld.h>
-#include <LibWeb/CSS/CSSStyleValue.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(StylePropertyMapReadOnlyIterator);
-
-static constexpr JSHostClass style_property_map_iterator_host_class = JS::make_host_class(JS_HOST_CLASS_OBJECT, "StylePropertyMapReadOnlyIterator"sv, nullptr, nullptr, nullptr, 0);
-
-StylePropertyMapReadOnlyIterator::StylePropertyMapReadOnlyIterator(JS::Object::PropertyKind kind, Vector<StylePropertyMapReadOnly::IterationEntry> entries, ReadonlySpan<GC::Ref<CSSStyleValue>> values)
- : m_kind(kind)
- , m_entries(move(entries))
-{
- m_values.ensure_capacity(values.size());
- for (auto value : values)
- m_values.unchecked_append(value);
-}
-
-GC::Ref<JS::HostObject> StylePropertyMapReadOnlyIterator::create(JS::Realm& realm, StylePropertyMapReadOnly& map, JS::Object::PropertyKind kind)
-{
- // INTEROP: Snapshot the entry list when iteration starts, matching Chrome and Safari.
- Vector<StylePropertyMapReadOnly::IterationEntry> entries;
- GC::RootVector<GC::Ref<CSSStyleValue>> values;
- if (kind == JS::Object::PropertyKind::Key) {
- for (auto const& name : map.property_names())
- entries.append({ name, 0, 0 });
- } else {
- map.collect_iteration_entries(entries, values);
- }
- auto iterator = realm.create<StylePropertyMapReadOnlyIterator>(kind, move(entries), values.span());
- auto& prototype = Bindings::ensure_web_prototype<Bindings::StylePropertyMapReadOnlyIteratorPrototype>(realm, "StylePropertyMapReadOnlyIterator"_utf16_fly_string);
- return JS::HostObject::create(realm, style_property_map_iterator_host_class, prototype, {}, iterator);
-}
-
-void StylePropertyMapReadOnlyIterator::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- for (auto value : m_values)
- visitor.visit(value);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#stylepropertymapreadonly
-GC::Ref<JS::Object> StylePropertyMapReadOnlyIterator::next(JS::Realm& realm)
-{
- if (m_index >= m_entries.size())
- return JS::create_iterator_result_object(realm, JS::js_undefined(), true);
-
- auto const& entry = m_entries[m_index++];
- auto name = JS::PrimitiveString::create(vm(), entry.name.to_utf16_string());
- if (m_kind == JS::Object::PropertyKind::Key)
- return JS::create_iterator_result_object(realm, name, false);
-
- GC::RootVector<JS::Value> wrapped_values;
- wrapped_values.ensure_capacity(entry.value_count);
- for (auto value : m_values.span().slice(entry.value_offset, entry.value_count))
- wrapped_values.unchecked_append(Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, value));
- auto array = JS::Array::create_from(realm, wrapped_values.span());
- if (m_kind == JS::Object::PropertyKind::Value)
- return JS::create_iterator_result_object(realm, array, false);
-
- return JS::create_iterator_result_object(realm, JS::Array::create_from(realm, { name, array }), false);
-}
-
-}
diff --git a/Libraries/LibWeb/Bindings/StylePropertyMapReadOnlyIterator.h b/Libraries/LibWeb/Bindings/StylePropertyMapReadOnlyIterator.h
deleted file mode 100644
index 55b7f59c72e..00000000000
--- a/Libraries/LibWeb/Bindings/StylePropertyMapReadOnlyIterator.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibJS/Heap/Cell.h>
-#include <LibJS/Runtime/HostObject.h>
-#include <LibJS/Runtime/Object.h>
-#include <LibWeb/CSS/StylePropertyMapReadOnly.h>
-
-namespace Web::CSS {
-
-class StylePropertyMapReadOnlyIterator final : public JS::Cell {
- GC_CELL(StylePropertyMapReadOnlyIterator, JS::Cell);
- GC_DECLARE_ALLOCATOR(StylePropertyMapReadOnlyIterator);
-
-public:
- using JSValueConversionIsForbidden = void;
-
- static GC::Ref<JS::HostObject> create(JS::Realm&, StylePropertyMapReadOnly&, JS::Object::PropertyKind);
- GC::Ref<JS::Object> next(JS::Realm&);
-
-private:
- StylePropertyMapReadOnlyIterator(JS::Object::PropertyKind, Vector<StylePropertyMapReadOnly::IterationEntry>, ReadonlySpan<GC::Ref<CSSStyleValue>>);
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- JS::Object::PropertyKind m_kind;
- Vector<StylePropertyMapReadOnly::IterationEntry> m_entries;
- Vector<GC::Ref<CSSStyleValue>> m_values;
- size_t m_index { 0 };
-};
-
-}
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index bfba0d35bb5..e4af3cbafbe 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -31,7 +31,6 @@ set(SOURCES
Bindings/RustBindingsServices.cpp
Bindings/RustCSSDescriptors.cpp
Bindings/RustEventTarget.cpp
- Bindings/StylePropertyMapReadOnlyIterator.cpp
Bindings/PrincipalHostDefined.cpp
Bindings/Wrappable.cpp
Bindings/WrapperWorld.cpp
@@ -156,7 +155,6 @@ set(SOURCES
CSS/StyleProperty.cpp
CSS/StylePropertyMapReadOnly.cpp
CSS/Zoom.cpp
- CSS/StylePropertyMap.cpp
CSS/StyleScope.cpp
CSS/StyleSheetIdentifier.cpp
CSS/StyleSheetImport.cpp
diff --git a/Libraries/LibWeb/CSS/CSSRule.cpp b/Libraries/LibWeb/CSS/CSSRule.cpp
index b8664ec53a4..c8133e2d967 100644
--- a/Libraries/LibWeb/CSS/CSSRule.cpp
+++ b/Libraries/LibWeb/CSS/CSSRule.cpp
@@ -21,7 +21,6 @@
#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>
@@ -53,7 +52,6 @@ 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);
}
@@ -191,12 +189,6 @@ void web_css_counter_style_rule_changed(void* cell)
record_style_rule_declarations_changed(rule);
}
-void* web_css_style_property_map_create(void* declarations)
-{
- auto& style_properties = *static_cast<CSSStyleProperties*>(static_cast<GC::Cell*>(declarations));
- return static_cast<GC::Cell*>(StylePropertyMap::create(style_properties).ptr());
-}
-
void* web_css_font_feature_values_map_create(void* rule, u8 kind)
{
auto& parent_rule = *static_cast<CSSFontFeatureValuesRule*>(rule);
diff --git a/Libraries/LibWeb/CSS/StylePropertyMap.cpp b/Libraries/LibWeb/CSS/StylePropertyMap.cpp
deleted file mode 100644
index e9c55465ccd..00000000000
--- a/Libraries/LibWeb/CSS/StylePropertyMap.cpp
+++ /dev/null
@@ -1,378 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "StylePropertyMap.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSNumericValue.h>
-#include <LibWeb/CSS/CSSStyleDeclaration.h>
-#include <LibWeb/CSS/CSSStyleValue.h>
-#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/PropertyName.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/StyleValues/KeywordStyleValue.h>
-#include <LibWeb/CSS/StyleValues/StyleValueList.h>
-#include <LibWeb/DOM/Element.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(StylePropertyMap);
-
-GC::Ref<StylePropertyMap> StylePropertyMap::create(GC::Ref<CSSStyleDeclaration> declaration)
-{
- return GC::Heap::the().allocate<StylePropertyMap>(declaration);
-}
-
-StylePropertyMap::StylePropertyMap(GC::Ref<CSSStyleDeclaration> declaration)
- : StylePropertyMapReadOnly(declaration)
-{
-}
-
-StylePropertyMap::~StylePropertyMap() = default;
-
-CSSStyleDeclaration& StylePropertyMap::declarations()
-{
- // Writable StylePropertyMaps must be backed by a CSSStyleDeclaration, not an AbstractElement.
- return m_declarations.get<GC::Ref<CSSStyleDeclaration>>();
-}
-
-static bool any_have_non_matching_associated_property(Utf16FlyString const& property, ReadonlySpan<Variant<GC::Ref<CSSStyleValue>, Utf16String>> values)
-{
- return any_of(values, [&property](Variant<GC::Ref<CSSStyleValue>, Utf16String> const& value) {
- if (auto* style_value = value.get_pointer<GC::Ref<CSSStyleValue>>()) {
- if (auto associated_property = (*style_value)->associated_property();
- associated_property.has_value() && associated_property != property)
- return true;
- }
- return false;
- });
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
-static WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> create_an_internal_representation(PropertyNameAndID const& property, Variant<GC::Ref<CSSStyleValue>, Utf16String> const& value)
-{
- // To create an internal representation, given a string property and a string or CSSStyleValue value:
- auto internal_representation = TRY(value.visit(
- [&property](GC::Ref<CSSStyleValue> const& css_style_value) -> WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> {
- auto internal_representation = TRY(css_style_value->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::Yes));
- // INTEROP: Custom properties, including registered ones, only accept CSSUnparsedValue objects and
- // CSS-wide keywords.
- if (property.is_custom_property() && !css_style_value->is_unparsed_value() && !internal_representation->is_css_wide_keyword())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Custom properties only accept unparsed values and CSS-wide keywords"_utf16 };
- return internal_representation;
- },
- [&](Utf16String const& css_text) -> WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> {
- // If value is a USVString,
- // Parse a CSSStyleValue with property property, cssText value, and parseMultiple set to false, and
- // return the result.
- // FIXME: Avoid passing name as a string, as it gets immediately converted back to PropertyNameAndID.
- auto result = TRY(CSSStyleValue::parse_a_css_style_value(property.name(), css_text));
- // AD-HOC: Result is a CSSStyleValue but we want an internal representation, so... convert it again I guess?
- return result->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::Yes);
- }));
-
- if (auto const* css_style_value = value.get_pointer<GC::Ref<CSSStyleValue>>();
- css_style_value && is<CSSNumericValue>(**css_style_value) && !property.is_custom_property()) {
- // INTEROP: Shape image thresholds accept typed numbers but not typed percentages.
- if (property.id() == PropertyID::ShapeImageThreshold && !as<CSSNumericValue>(**css_style_value).type().matches_number({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Shape image thresholds require a number"_utf16 };
-
- // https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
- // If value does not match the grammar of a list-valued property iteration of property, throw a TypeError.
- // NB: A property's component types do not establish that a numeric value alone matches its whole grammar.
- auto parsed_value = parse_css_value(Parser::ParsingParams {}, internal_representation->to_utf16_string(SerializationMode::Normal), property.id());
- if (!parsed_value)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Numeric value does not match the property's grammar"_utf16 };
- }
-
- // NB: Step easing keywords are custom identifiers outside the property parser. Store the parsed iteration so
- // multi-value set() and append() use the easing representation expected by style computation.
- if (internal_representation->is_custom_ident()
- && first_is_one_of(property.id(), PropertyID::AnimationTimingFunction, PropertyID::TransitionTimingFunction)) {
- if (auto parsed_value = parse_css_value(Parser::ParsingParams {}, internal_representation->to_utf16_string(SerializationMode::Normal), property.id());
- parsed_value && parsed_value->is_value_list() && parsed_value->as_value_list().size() == 1)
- return parsed_value->as_value_list().value_at(0, false);
- }
-
- // AD-HOC: Our parser represents a text-indent that is just a length-percentage as a text-indent value, and style
- // computation expects that.
- if (property.id() == PropertyID::TextIndent
- && (internal_representation->is_length() || internal_representation->is_percentage() || internal_representation->is_calculated())) {
- return StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_create_text_indent(
- StyleValueFFI::rust_style_value_retain(internal_representation->rust_style_value_data()), false, false));
- }
-
- return internal_representation;
-}
-
-static WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> normalize_overflow_clip_margin_internal_representation(
- CSSStyleDeclaration const& declarations, PropertyNameAndID const& property, NonnullRefPtr<StyleValue const> value)
-{
- if (!first_is_one_of(
- property.id(),
- PropertyID::OverflowClipMargin,
- PropertyID::OverflowClipMarginBlock,
- PropertyID::OverflowClipMarginInline)) {
- return value;
- }
-
- if (value->is_shorthand()
- || value->is_unresolved()
- || value->is_pending_substitution()
- || value->is_guaranteed_invalid()
- || value->is_css_wide_keyword()) {
- return value;
- }
-
- // https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
- // If value is a CSSStyleValue subclass, if value does not match the grammar of a list-valued property
- // iteration of property, throw a TypeError.
- auto const parsing_params = declarations.owner_node().has_value()
- ? Parser::ParsingParams { declarations.owner_node()->element().document() }
- : Parser::ParsingParams {};
- auto serialized_value = value->to_string(SerializationMode::Normal);
- auto parsed_value = parse_css_value(parsing_params, serialized_value, property.id());
- if (!parsed_value) {
- return WebIDL::SimpleException {
- WebIDL::SimpleExceptionType::TypeError,
- Utf16String::formatted("Property '{}' does not accept the value '{}'", property.name(), serialized_value)
- };
- }
-
- return parsed_value.release_nonnull();
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymap-set
-WebIDL::ExceptionOr<void> StylePropertyMap::set(Utf16FlyString property_name, ReadonlySpan<Variant<GC::Ref<CSSStyleValue>, Utf16String>> values)
-{
- // The set(property, ...values) method, when called on a StylePropertyMap this, must perform the following steps:
-
- // 1. If property is not a custom property name string, set property to property ASCII lowercased.
- // 2. If property is not a valid CSS property, throw a TypeError.
- auto property = PropertyNameAndID::from_name(property_name);
- if (!property.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("'{}' is not a valid CSS property", property_name) };
-
- // 3. If property is a single-valued property and values has more than one item, throw a TypeError.
- // NB: Custom properties should all be single-valued.
- if ((property->is_custom_property() || property_is_single_valued(property->id())) && values.size() > 1)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Property '{}' only accepts a single value", property_name) };
-
- // FIXME: The spec doesn't say how to handle empty `values`, but other browsers throw a TypeError so let's do that
- // too - see https://github.com/w3c/css-houdini-drafts/issues/1176
- if (values.is_empty())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Property '{}' requires at least one value", property_name) };
-
- // FIXME: The spec doesn't say how to handle empty `values`, but other browsers throw a TypeError so let's do that
- // too - see https://github.com/w3c/css-houdini-drafts/issues/1176
- if (values.is_empty())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Property '{}' requires at least one value", property_name) };
-
- // 4. If any of the items in values have a non-null [[associatedProperty]] internal slot, and that slot’s value is
- // anything other than property, throw a TypeError.
- if (any_have_non_matching_associated_property(property->name(), values))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "One of the passed CSSStyleValues has a different associated property"_utf16 };
-
- // 5. If the size of values is two or more, and one or more of the items are a CSSUnparsedValue or
- // CSSVariableReferenceValue object, throw a TypeError.
- // NOTE: Having 2+ values implies that you’re setting multiple items of a list-valued property, but the presence of
- // a var() function in the string-based OM disables all syntax parsing, including splitting into individual
- // iterations (because there might be more commas inside of the var() value, so you can’t tell how many items
- // are actually going to show up). This step’s restriction preserves the same semantics in the Typed OM.
- // FIXME: This is done as part of step 9, because we need to detect if a string value would be an CSSUnparsedValue
- // or CSSVariableReferenceValue. Spec issue: https://github.com/w3c/css-houdini-drafts/issues/1157
-
- // 6. Let props be the value of this’s [[declarations]] internal slot.
- auto& props = declarations();
-
- // 8. Let values to set be an empty list.
- StyleValueVector values_to_set;
-
- // 9. For each value in values, create an internal representation for property and value, and append the result to values to set.
- for (auto const& value : values) {
- // AD-HOC: Step 5 is done here, see above.
- auto internal_representation = TRY(create_an_internal_representation(property.value(), value));
- internal_representation = TRY(normalize_overflow_clip_margin_internal_representation(
- props, property.value(), move(internal_representation)));
-
- if (values.size() >= 2 && internal_representation->is_unresolved())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot provide multiple values if one is an CSSUnparsedValue or CSSVariableReferenceValue"_utf16 };
-
- values_to_set.append(move(internal_representation));
- }
-
- // 7. If props[property] exists, remove it.
- // NB: Removal and replacement happen together in set_property_style_value(), after validation, so observers
- // receive a single style-attribute update.
-
- // AD-HOC: To match the behavior of our parser we should store values of list-valued longhands as lists even if
- // there is only one value, except in some rare circumstances.
- auto const should_wrap_value_in_list = [](PropertyNameAndID const& property, NonnullRefPtr<StyleValue const> const& value) {
- if (property_is_shorthand(property.id()))
- return false;
-
- if (!property_is_list_valued(property.id()))
- return false;
-
- // Values which are not yet fully resolved should not be wrapped in lists.
- if (value->is_unresolved() || value->is_pending_substitution() || value->is_guaranteed_invalid() || value->is_css_wide_keyword())
- return false;
-
- return true;
- };
-
- // AD-HOC: A single keyword or identifier should be stored the way our parser stores it for the property. That is
- // either the keyword on its own, as for `box-shadow: none`, or a list with the identifier as its only
- // item, as for `container-name: foo`. So we parse it as a value of the property.
- auto const parsed_identifier_value = [&](PropertyNameAndID const& property, NonnullRefPtr<StyleValue const> const& value) -> RefPtr<StyleValue const> {
- if (property.is_custom_property())
- return nullptr;
- if (!value->is_custom_ident() && !(value->is_keyword() && !value->is_css_wide_keyword()))
- return nullptr;
- auto const parsing_params = props.owner_node().has_value()
- ? Parser::ParsingParams { props.owner_node()->element().document() }
- : Parser::ParsingParams {};
- return parse_css_value(parsing_params, value->to_string(SerializationMode::Normal), property.id());
- };
-
- // AD-HOC: Our parser represents the track sizes of grid-auto-columns and grid-auto-rows as a single track size
- // list, and style computation expects that.
- auto const grid_track_size_list = [](PropertyNameAndID const& property, StyleValueVector const& values) -> RefPtr<StyleValue const> {
- if (!first_is_one_of(property.id(), PropertyID::GridAutoColumns, PropertyID::GridAutoRows))
- return nullptr;
- for (auto const& value : values) {
- if (value->is_grid_track_size_list() || value->is_unresolved() || value->is_pending_substitution() || value->is_guaranteed_invalid() || value->is_css_wide_keyword())
- return nullptr;
- }
- Vector<StyleValueFFI::StyleValueData const*> track_sizes;
- track_sizes.ensure_capacity(values.size());
- for (auto const& value : values)
- track_sizes.unchecked_append(StyleValueFFI::rust_style_value_retain(value->rust_style_value_data()));
- return StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_create_grid_track_size_list(track_sizes.data(), track_sizes.size()));
- };
-
- // 10. Set props[property] to values to set.
- // NOTE: The property is deleted then added back so that it gets put at the end of the ordered map, which gives the
- // expected behavior in the face of shorthand properties.
- if (values_to_set.size() == 1) {
- if (auto parsed_value = parsed_identifier_value(property.value(), values_to_set.first())) {
- TRY(props.set_property_style_value(property.value(), parsed_value.release_nonnull()));
- return {};
- }
- }
- if (auto track_size_list = grid_track_size_list(property.value(), values_to_set)) {
- TRY(props.set_property_style_value(property.value(), track_size_list.release_nonnull()));
- return {};
- }
- if (values_to_set.size() == 1 && !should_wrap_value_in_list(property.value(), values_to_set.first())) {
- TRY(props.set_property_style_value(property.value(), values_to_set.take_first()));
- } else {
- TRY(props.set_property_style_value(property.value(), StyleValueList::create(move(values_to_set), StyleValueList::Separator::Comma)));
- }
-
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymap-append
-WebIDL::ExceptionOr<void> StylePropertyMap::append(Utf16FlyString property_name, ReadonlySpan<Variant<GC::Ref<CSSStyleValue>, Utf16String>> values)
-{
- // The append(property, ...values) method, when called on a StylePropertyMap this, must perform the following steps:
-
- // 1. If property is not a custom property name string, set property to property ASCII lowercased.
- // 2. If property is not a valid CSS property, throw a TypeError.
- auto property = PropertyNameAndID::from_name(property_name);
- if (!property.has_value()) {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("'{}' is not a valid CSS property", property_name) };
- }
-
- // 3. If property is not a list-valued property, throw a TypeError.
- if (!property_is_list_valued(property->id())) {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("'{}' is not a list-valued property", property_name) };
- }
-
- // 4. If any of the items in values have a non-null [[associatedProperty]] internal slot, and that slot’s value is
- // anything other than property, throw a TypeError.
- if (any_have_non_matching_associated_property(property->name(), values)) {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "One of the passed CSSStyleValues has a different associated property"_utf16 };
- }
-
- // 5. If any of the items in values are a CSSUnparsedValue or CSSVariableReferenceValue object, throw a TypeError.
- // NOTE: When a property is set via string-based APIs, the presence of var() in a property prevents the entire
- // thing from being interpreted. In other words, everything besides the var() is a plain component value, not
- // a meaningful type. This step’s restriction preserves the same semantics in the Typed OM.
- // FIXME: This is done as part of step 10, because we need to detect if a string value would be an CSSUnparsedValue
- // or CSSVariableReferenceValue. Spec issue: https://github.com/w3c/css-houdini-drafts/issues/1157
-
- // 6. Let props be the value of this’s [[declarations]] internal slot.
- auto& props = declarations();
-
- // 7. If props[property] does not exist, set props[property] to an empty list.
- auto existing_value = props.get_property_style_value(property.value());
-
- // 8. If props[property] contains a var() reference, throw a TypeError.
- if (existing_value && existing_value->is_unresolved()) {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Existing value for '{}' contains var() references.", property_name) };
- }
-
- // NB: Appending no values must not replace the declaration or update the style attribute.
- if (values.is_empty())
- return {};
-
- // 9. Let temp values be an empty list.
- // NB: StyleValues are immutable, so we always create a new one. We add directly to it instead of using "temp values".
- StyleValueVector value_list;
- if (existing_value) {
- if (existing_value->is_value_list())
- value_list.extend(StyleValueVector { existing_value->as_value_list().values() });
- else
- value_list.append(existing_value.release_nonnull());
- }
-
- // 10. For each value in values, create an internal representation with property and value, and append the returned value to temp values.
- for (auto const& value : values) {
- // AD-HOC: Step 5 is done here, see above.
- auto internal_representation = TRY(create_an_internal_representation(property.value(), value));
-
- if (internal_representation->is_unresolved())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot append a CSSUnparsedValue or CSSVariableReferenceValue"_utf16 };
-
- value_list.append(move(internal_representation));
- }
-
- // 11. Append the entries of temp values to props[property].
- // NB: StyleValues are immutable, so we create a new one instead.
- return props.set_property_style_value(property.value(), StyleValueList::create(move(value_list), StyleValueList::Separator::Comma));
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymap-delete
-WebIDL::ExceptionOr<void> StylePropertyMap::delete_(Utf16FlyString property)
-{
- // The delete(property) method, when called on a StylePropertyMap this, must perform the following steps:
-
- // 1. If property is not a custom property name string, set property to property ASCII lowercased.
- if (!is_a_custom_property_name_string(property))
- property = property.to_ascii_lowercase();
-
- // 2. If property is not a valid CSS property, throw a TypeError.
- if (!is_a_valid_css_property(property))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("'{}' is not a valid CSS property", property) };
-
- // 3. If this’s [[declarations]] internal slot contains property, remove it.
- auto removed_value = TRY(declarations().remove_property(property));
- (void)removed_value;
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymap-clear
-WebIDL::ExceptionOr<void> StylePropertyMap::clear()
-{
- // The clear() method, when called on a StylePropertyMap this, must perform the following steps:
-
- // 1. Remove all of the declarations in this’s [[declarations]] internal slot.
- return declarations().set_css_text(""sv);
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/StylePropertyMap.h b/Libraries/LibWeb/CSS/StylePropertyMap.h
index e68b8f08dbb..35ffb348d82 100644
--- a/Libraries/LibWeb/CSS/StylePropertyMap.h
+++ b/Libraries/LibWeb/CSS/StylePropertyMap.h
@@ -6,30 +6,19 @@
#pragma once
-#include <AK/Utf16String.h>
-#include <LibWeb/CSS/StylePropertyMapReadOnly.h>
+#include <LibGC/Ptr.h>
+#include <LibWeb/Bindings/RustInterface.h>
+#include <LibWeb/Bindings/StylePropertyMap.h>
+#include <LibWeb/Forward.h>
namespace Web::CSS {
// https://drafts.css-houdini.org/css-typed-om-1/#stylepropertymap
-class StylePropertyMap : public StylePropertyMapReadOnly {
- WEB_WRAPPABLE(StylePropertyMap, StylePropertyMapReadOnly);
- GC_DECLARE_ALLOCATOR(StylePropertyMap);
+class StylePropertyMap final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(StylePropertyMap, style_property_map)
public:
[[nodiscard]] static GC::Ref<StylePropertyMap> create(GC::Ref<CSSStyleDeclaration>);
-
- virtual ~StylePropertyMap() override;
-
- WebIDL::ExceptionOr<void> set(Utf16FlyString property, ReadonlySpan<Variant<GC::Ref<CSSStyleValue>, Utf16String>> values);
- WebIDL::ExceptionOr<void> append(Utf16FlyString property, ReadonlySpan<Variant<GC::Ref<CSSStyleValue>, Utf16String>> values);
- WebIDL::ExceptionOr<void> delete_(Utf16FlyString property);
- WebIDL::ExceptionOr<void> clear();
-
-private:
- explicit StylePropertyMap(GC::Ref<CSSStyleDeclaration>);
-
- CSSStyleDeclaration& declarations();
};
}
diff --git a/Libraries/LibWeb/CSS/StylePropertyMap.idl b/Libraries/LibWeb/CSS/StylePropertyMap.idl
index 878f38658f3..6b9bc036c3f 100644
--- a/Libraries/LibWeb/CSS/StylePropertyMap.idl
+++ b/Libraries/LibWeb/CSS/StylePropertyMap.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#stylepropertymap
-[Exposed=Window]
+[Exposed=Window, ImplementedIn=Rust]
interface StylePropertyMap : StylePropertyMapReadOnly {
undefined set(USVString property, (CSSStyleValue or USVString)... values);
undefined append(USVString property, (CSSStyleValue or USVString)... values);
diff --git a/Libraries/LibWeb/CSS/StylePropertyMapReadOnly.cpp b/Libraries/LibWeb/CSS/StylePropertyMapReadOnly.cpp
index 2a53ad613ff..e6e0b142886 100644
--- a/Libraries/LibWeb/CSS/StylePropertyMapReadOnly.cpp
+++ b/Libraries/LibWeb/CSS/StylePropertyMapReadOnly.cpp
@@ -4,17 +4,18 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include "StylePropertyMapReadOnly.h"
-#include <AK/QuickSort.h>
-#include <LibGC/Heap.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
#include <LibWeb/CSS/CSSStyleDeclaration.h>
#include <LibWeb/CSS/CSSStyleProperties.h>
-#include <LibWeb/CSS/CSSStyleValue.h>
#include <LibWeb/CSS/ComputedValues.h>
#include <LibWeb/CSS/CustomPropertyData.h>
#include <LibWeb/CSS/CustomPropertyRegistration.h>
+#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/PropertyID.h>
#include <LibWeb/CSS/PropertyNameAndID.h>
+#include <LibWeb/CSS/StylePropertyMap.h>
+#include <LibWeb/CSS/StylePropertyMapReadOnly.h>
#include <LibWeb/CSS/StyleSheetState.h>
#include <LibWeb/CSS/StyleValues/KeywordStyleValue.h>
#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
@@ -22,32 +23,92 @@
#include <LibWeb/CSS/StyleValues/StyleValueList.h>
#include <LibWeb/CSS/Zoom.h>
#include <LibWeb/DOM/Document.h>
+#include <LibWeb/DOM/Element.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::CSS {
-GC_DEFINE_ALLOCATOR(StylePropertyMapReadOnly);
+using StyleValueData = StyleValueFFI::StyleValueData;
-GC::Ref<StylePropertyMapReadOnly> StylePropertyMapReadOnly::create_computed_style(DOM::AbstractElement element)
+extern "C" {
+
+// Defined in Bindings/Rust/src/css/exports.rs.
+void* web_style_property_map_create(JSVM*, void* declaration);
+void* web_style_property_map_read_only_create(JSVM*, void* element);
+
+// Declared in Bindings/Rust/src/css/style_property_map_read_only.rs.
+bool web_css_style_map_property(FlatPtr name, u16* id, FlatPtr* canonical_name);
+u8 web_css_style_map_iterations(bool is_computed, void* source, FlatPtr name, void* values, void (*append)(void*, StyleValueData const*));
+bool web_css_style_map_has(bool is_computed, void* source, FlatPtr name);
+void web_css_style_map_property_names(bool is_computed, void* source, void* names, void (*append)(void*, FlatPtr));
+size_t web_css_style_map_property_count(bool is_computed, void* source);
+
+// Declared in Bindings/Rust/src/css/style_property_map.rs.
+bool web_css_style_map_property_is_list_valued(u16 property_id);
+StyleValueData const* web_css_style_map_parse(void* declaration, u16 property_id, FlatPtr css_text);
+StyleValueData const* web_css_style_map_declared_value(void* declaration, FlatPtr name);
+u8 web_css_style_map_set_value(void* declaration, FlatPtr name, StyleValueData const* value, FlatPtr* message);
+u8 web_css_style_map_remove(void* declaration, FlatPtr name, FlatPtr* message);
+u8 web_css_style_map_clear(void* declaration, FlatPtr* message);
+}
+
+// What web_css_style_map_iterations() found, which Bindings/Rust/src/css/style_property_map_read_only.rs reads.
+enum class Iterations : u8 {
+ Absent,
+ Values,
+ Shorthand,
+};
+
+// How a change to a declaration ended, which Bindings/Rust/src/css/style_property_map.rs reads.
+enum class ChangeResult : u8 {
+ Success,
+ TypeError,
+ NoModificationAllowedError,
+};
+
+template<typename T>
+static u8 change_result(WebIDL::ExceptionOr<T> result, FlatPtr* message)
{
- return GC::Heap::the().allocate<StylePropertyMapReadOnly>(element);
+ if (!result.is_exception())
+ return to_underlying(ChangeResult::Success);
+ return to_underlying(result.exception().visit(
+ [&](WebIDL::SimpleException const& exception) {
+ VERIFY(exception.type == WebIDL::SimpleExceptionType::TypeError);
+ *message = Utf16String { exception.message }.into_raw();
+ return ChangeResult::TypeError;
+ },
+ [&](GC::Ref<WebIDL::DOMException> const& exception) {
+ VERIFY(exception->name() == "NoModificationAllowedError"sv);
+ *message = exception->message().to_utf16_string().into_raw();
+ return ChangeResult::NoModificationAllowedError;
+ },
+ [](JS::Completion const&) -> ChangeResult {
+ VERIFY_NOT_REACHED();
+ }));
}
-StylePropertyMapReadOnly::StylePropertyMapReadOnly(Source source)
- : m_declarations(move(source))
+using Source = Variant<DOM::AbstractElement, GC::Ref<CSSStyleDeclaration>>;
+
+static CSSStyleDeclaration& declaration_from_abi(void* declaration)
{
+ return *static_cast<CSSStyleDeclaration*>(static_cast<GC::Cell*>(declaration));
}
-StylePropertyMapReadOnly::~StylePropertyMapReadOnly() = default;
+static Source source_from_abi(bool is_computed, void* source)
+{
+ if (is_computed)
+ return DOM::AbstractElement { *static_cast<DOM::Element*>(static_cast<GC::Cell*>(source)) };
+ return GC::Ref { declaration_from_abi(source) };
+}
-void StylePropertyMapReadOnly::visit_edges(GC::Cell::Visitor& visitor)
+static StyleValueData const* into_rust(StyleValue const& value)
{
- Base::visit_edges(visitor);
- visitor.visit(m_cached_document);
+ return StyleValueFFI::rust_style_value_retain(value.rust_style_value_data());
+}
- m_declarations.visit(
- [&visitor](DOM::AbstractElement& element) { element.visit(visitor); },
- [&visitor](GC::Ref<CSSStyleDeclaration>& declaration) { visitor.visit(declaration); });
+static PropertyNameAndID property_from_abi(FlatPtr name)
+{
+ return PropertyNameAndID::from_name(Utf16FlyString { Utf16String::from_raw(name) }).release_value();
}
// A computed style map describes an element's computed style, and a disconnected element has none.
@@ -71,238 +132,7 @@ static StyleValueVector subdivide_property_value(StyleValue const& value, Proper
return value.subdivide_into_iterations(property);
}
-static GC::Ref<CSSStyleValue> reify_property_value(StyleValue const& value, PropertyNameAndID const& property, bool is_computed)
-{
- // INTEROP: Computed border-image values represent all four sides or both axes, even when their serialization
- // collapses to a single numeric value or keyword.
- if (is_computed && first_is_one_of(property.id(), PropertyID::BorderImageWidth, PropertyID::BorderImageOutset, PropertyID::BorderImageSlice, PropertyID::BorderImageRepeat))
- return CSSStyleValue::create(property.name(), value);
- return CSSStyleValue::reify(value, property.name());
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-get
-WebIDL::ExceptionOr<Variant<GC::Ref<CSSStyleValue>, Empty>> StylePropertyMapReadOnly::get(Utf16String property_name)
-{
- // The get(property) method, when called on a StylePropertyMapReadOnly this, must perform the following steps:
-
- // 1. If property is not a custom property name string, set property to property ASCII lowercased.
- // 2. If property is not a valid CSS property, throw a TypeError.
- auto property_name_utf16 = Utf16FlyString::from_utf16(property_name.utf16_view());
- auto property = PropertyNameAndID::from_name(property_name_utf16);
- if (!property.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("'{}' is not a valid CSS property", property_name) };
-
- // 3. Let props be the value of this’s [[declarations]] internal slot.
- auto& props = m_declarations;
-
- // 4. If props[property] exists, subdivide into iterations props[property], then reify the first item of the result and return it.
- if (auto property_value = get_style_value(props, property.value())) {
- if (props.has<DOM::AbstractElement>() && property_is_shorthand(property->id()))
- return CSSStyleValue::create(property->name(), *property_value, SerializationMode::ResolvedValue);
- auto iterations = subdivide_property_value(*property_value, property.value(), props.get_pointer<DOM::AbstractElement>());
- return reify_property_value(*iterations.first(), property.value(), props.has<DOM::AbstractElement>());
- }
-
- // 5. Otherwise, return undefined.
- return Empty {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-getall
-WebIDL::ExceptionOr<GC::RootVector<GC::Ref<CSSStyleValue>>> StylePropertyMapReadOnly::get_all(Utf16String property_name)
-{
- // The getAll(property) method, when called on a StylePropertyMap this, must perform the following steps:
-
- // 1. If property is not a custom property name string, set property to property ASCII lowercased.
- // 2. If property is not a valid CSS property, throw a TypeError.
- auto property_name_utf16 = Utf16FlyString::from_utf16(property_name.utf16_view());
- auto property = PropertyNameAndID::from_name(property_name_utf16);
- if (!property.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("'{}' is not a valid CSS property", property_name) };
-
- // 3. Let props be the value of this’s [[declarations]] internal slot.
- auto& props = m_declarations;
-
- GC::RootVector<GC::Ref<CSSStyleValue>> results;
-
- // 4. If props[property] exists, subdivide into iterations props[property], then reify each item of the result, and return the list.
- if (auto property_value = get_style_value(props, property.value())) {
- if (props.has<DOM::AbstractElement>() && property_is_shorthand(property->id())) {
- results.append(CSSStyleValue::create(property->name(), *property_value, SerializationMode::ResolvedValue));
- return results;
- }
- auto iterations = subdivide_property_value(*property_value, property.value(), props.get_pointer<DOM::AbstractElement>());
- for (auto const& style_value : iterations)
- results.append(reify_property_value(*style_value, property.value(), props.has<DOM::AbstractElement>()));
- return results;
- }
-
- // 5. Otherwise, return an empty list.
- return results;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-has
-WebIDL::ExceptionOr<bool> StylePropertyMapReadOnly::has(Utf16String property_name)
-{
- // The has(property) method, when called on a StylePropertyMapReadOnly this, must perform the following steps:
-
- // 1. If property is not a custom property name string, set property to property ASCII lowercased.
- // 2. If property is not a valid CSS property, throw a TypeError.
- auto property_name_utf16 = Utf16FlyString::from_utf16(property_name.utf16_view());
- auto property = PropertyNameAndID::from_name(property_name_utf16);
- if (!property.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("'{}' is not a valid CSS property", property_name) };
-
- // 3. Let props be the value of this’s [[declarations]] internal slot.
- auto& props = m_declarations;
-
- // 4. If props[property] exists, return true. Otherwise, return false.
- return props.visit(
- [&property](DOM::AbstractElement& element) {
- if (!has_computed_style(element))
- return false;
- // From https://drafts.css-houdini.org/css-typed-om-1/#dom-element-computedstylemap we need to include:
- // "the name and computed value of every longhand CSS property supported by the User Agent, every
- // registered custom property, and every non-registered custom property which is not set to its initial
- // value on this"
- // Ensure style is computed on the element before we try to read it, so we can check custom properties.
- element.document().update_style_for_element(element);
- if (property->is_custom_property()) {
- if (element.get_custom_property(property->name()))
- return true;
- return element.document().get_registered_custom_property(property->name()).has_value();
- }
- return true;
- },
- [&property](GC::Ref<CSSStyleDeclaration> const& declaration) {
- return declaration->has_property(property.value());
- });
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-size
-WebIDL::UnsignedLong StylePropertyMapReadOnly::size() const
-{
- // The size attribute, on getting from a StylePropertyMapReadOnly this, must perform the following steps:
-
- // 1. Return the size of the value of this’s [[declarations]] internal slot.
- return property_names().size();
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-declarations-slot
-ReadonlySpan<Utf16FlyString> StylePropertyMapReadOnly::property_names() const
-{
- if (auto* element = m_declarations.get_pointer<DOM::AbstractElement>(); element && !has_computed_style(*element))
- return {};
-
- auto needs_update = m_declarations.visit(
- [&](DOM::AbstractElement const& element) {
- element.document().update_style_for_element(element);
- auto custom_property_data = element.custom_property_data();
- auto& document = element.document();
- if (m_cached_document.ptr() == &document
- && m_cached_custom_property_data == custom_property_data
- && m_cached_registration_generation == document.custom_property_registration_generation()) {
- return false;
- }
-
- m_cached_document = document;
- m_cached_custom_property_data = move(custom_property_data);
- m_cached_registration_generation = document.custom_property_registration_generation();
- m_cached_property_names.clear_with_capacity();
- for (auto id = to_underlying(first_longhand_property_id); id <= to_underlying(last_longhand_property_id); ++id)
- m_cached_property_names.append(string_from_property_id(static_cast<PropertyID>(id)));
-
- HashTable<Utf16FlyString> custom_properties;
- if (m_cached_custom_property_data) {
- m_cached_custom_property_data->for_each_property([&](auto const& name, auto const& property) {
- if (!property.value->is_guaranteed_invalid())
- custom_properties.set(name);
- });
- }
- document.for_each_registered_custom_property([&](CustomPropertyRegistration const& registration) {
- custom_properties.set(registration.property_name);
- });
- for (auto const& name : custom_properties)
- m_cached_property_names.append(name);
- return true;
- },
- [&](GC::Ref<CSSStyleDeclaration> const& declaration) {
- // NB: Inline and declared maps are both backed by CSSStyleProperties.
- auto const& properties = as<CSSStyleProperties>(*declaration);
- if (m_cached_declaration_revision == properties.revision())
- return false;
- m_cached_declaration_revision = properties.revision();
- m_cached_property_names.clear_with_capacity();
- for (size_t i = 0; i < declaration->length(); ++i)
- m_cached_property_names.append(Utf16FlyString { declaration->item(i) });
- return true;
- });
-
- // INTEROP: Inline and declared maps preserve declaration order.
- if (needs_update && m_declarations.has<DOM::AbstractElement>()) {
- // Unless otherwise stated, the initial ordering of the [[declarations]] internal slot is based on the key of each entry:
- // 1. Standardized properties (not custom properties or vendor-prefixed properties), ASCII lowercased
- // and then sorted in increasing code-point order.
- // 2. Vendor-prefixed/experimental properties (those whose name starts with a single dash), ASCII lowercased
- // and then sorted in increasing code-point order.
- // 3. Custom properties, sorted in increasing code-point order. (These are never lower-cased; they are
- // preserved exactly as written.)
- quick_sort(m_cached_property_names, [](auto const& left, auto const& right) {
- auto category = [](auto const& name) {
- if (name.starts_with("--"sv))
- return 2;
- return name.starts_with("-"sv) ? 1 : 0;
- };
- if (category(left) != category(right))
- return category(left) < category(right);
- auto left_view = left.view();
- auto right_view = right.view();
- auto left_iterator = left_view.begin();
- auto right_iterator = right_view.begin();
- for (; left_iterator != left_view.end() && right_iterator != right_view.end(); ++left_iterator, ++right_iterator) {
- if (*left_iterator != *right_iterator)
- return *left_iterator < *right_iterator;
- }
- return left_iterator == left_view.end() && right_iterator != right_view.end();
- });
- }
- return m_cached_property_names;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#stylepropertymapreadonly
-void StylePropertyMapReadOnly::collect_iteration_entries(Vector<IterationEntry>& entries, GC::RootVector<GC::Ref<CSSStyleValue>>& values)
-{
- // The value pairs to iterate over for a StylePropertyMapReadOnly object this are obtained as follows:
- // 1. Let declarations be this’s [[declarations]] slot.
- // 2. Let value pairs be an empty list.
- // 3. For each prop → value in declarations:
- // NB: Copy the names, since reifying values may refresh the cached names.
- Vector<Utf16FlyString> names { property_names() };
- for (auto const& name : names) {
- // 1. Let iterations be the result of dividing into iterations value.
- // 2. Reify each item of iterations, and let objects be the result.
- auto objects = MUST(get_all(name.to_utf16_string()));
- // 3. Append prop/objects to value pairs.
- entries.append({ name, values.size(), objects.size() });
- for (auto object : objects)
- values.append(object);
- }
- // 4. Return value pairs.
-}
-
-// https://webidl.spec.whatwg.org/#es-iterable
-void StylePropertyMapReadOnly::for_each(ForEachCallback callback)
-{
- // INTEROP: Snapshot style-map entries before invoking callbacks, matching Chrome and Safari.
- Vector<IterationEntry> entries;
- GC::RootVector<GC::Ref<CSSStyleValue>> values;
- collect_iteration_entries(entries, values);
- for (auto const& entry : entries) {
- if (callback(entry.name.to_utf16_string(), values.span().slice(entry.value_offset, entry.value_count)) == IterationDecision::Break)
- break;
- }
-}
-
-RefPtr<StyleValue const> StylePropertyMapReadOnly::get_style_value(Source& source, PropertyNameAndID const& property)
+static RefPtr<StyleValue const> get_style_value(Source& source, PropertyNameAndID const& property)
{
return source.visit(
[&property](DOM::AbstractElement& element) -> RefPtr<StyleValue const> {
@@ -370,4 +200,162 @@ RefPtr<StyleValue const> StylePropertyMapReadOnly::get_style_value(Source& sourc
});
}
+GC::Ref<StylePropertyMapReadOnly> StylePropertyMapReadOnly::create_computed_style(DOM::Element& element)
+{
+ auto* map = web_style_property_map_read_only_create(JS::HostABI::vm_to_abi(JS::VM::the()), static_cast<GC::Cell*>(&element));
+ return GC::Ref { *static_cast<StylePropertyMapReadOnly*>(map) };
+}
+
+GC::Ref<StylePropertyMap> StylePropertyMap::create(GC::Ref<CSSStyleDeclaration> declaration)
+{
+ auto* map = web_style_property_map_create(JS::HostABI::vm_to_abi(JS::VM::the()), static_cast<GC::Cell*>(declaration.ptr()));
+ return GC::Ref { *static_cast<StylePropertyMap*>(map) };
+}
+
+bool web_css_style_map_property(FlatPtr raw_name, u16* id, FlatPtr* canonical_name)
+{
+ auto property = PropertyNameAndID::from_name(Utf16FlyString { Utf16String::from_raw(raw_name) });
+ if (!property.has_value())
+ return false;
+ *id = to_underlying(property->id());
+ *canonical_name = property->name().to_utf16_string().into_raw();
+ return true;
+}
+
+u8 web_css_style_map_iterations(bool is_computed, void* raw_source, FlatPtr name, void* values, void (*append)(void*, StyleValueData const*))
+{
+ auto source = source_from_abi(is_computed, raw_source);
+ auto property = property_from_abi(name);
+
+ auto property_value = get_style_value(source, property);
+ if (!property_value)
+ return to_underlying(Iterations::Absent);
+
+ if (is_computed && property_is_shorthand(property.id())) {
+ append(values, into_rust(*property_value));
+ return to_underlying(Iterations::Shorthand);
+ }
+
+ for (auto const& value : subdivide_property_value(*property_value, property, source.get_pointer<DOM::AbstractElement>()))
+ append(values, into_rust(*value));
+ return to_underlying(Iterations::Values);
+}
+
+bool web_css_style_map_has(bool is_computed, void* raw_source, FlatPtr name)
+{
+ auto source = source_from_abi(is_computed, raw_source);
+ auto property = property_from_abi(name);
+ return source.visit(
+ [&property](DOM::AbstractElement& element) {
+ if (!has_computed_style(element))
+ return false;
+ // From https://drafts.css-houdini.org/css-typed-om-1/#dom-element-computedstylemap we need to include:
+ // "the name and computed value of every longhand CSS property supported by the User Agent, every
+ // registered custom property, and every non-registered custom property which is not set to its initial
+ // value on this"
+ // Ensure style is computed on the element before we try to read it, so we can check custom properties.
+ element.document().update_style_for_element(element);
+ if (property.is_custom_property()) {
+ if (element.get_custom_property(property.name()))
+ return true;
+ return element.document().get_registered_custom_property(property.name()).has_value();
+ }
+ return true;
+ },
+ [&property](GC::Ref<CSSStyleDeclaration> const& declaration) {
+ return declaration->has_property(property);
+ });
+}
+
+static HashTable<Utf16FlyString> computed_custom_property_names(DOM::AbstractElement const& element)
+{
+ HashTable<Utf16FlyString> custom_properties;
+ if (auto custom_property_data = element.custom_property_data()) {
+ custom_property_data->for_each_property([&](auto const& name, auto const& property) {
+ if (!property.value->is_guaranteed_invalid())
+ custom_properties.set(name);
+ });
+ }
+ element.document().for_each_registered_custom_property([&](CustomPropertyRegistration const& registration) {
+ custom_properties.set(registration.property_name);
+ });
+ return custom_properties;
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-declarations-slot
+void web_css_style_map_property_names(bool is_computed, void* raw_source, void* names, void (*append)(void*, FlatPtr))
+{
+ source_from_abi(is_computed, raw_source)
+ .visit(
+ [&](DOM::AbstractElement const& element) {
+ if (!has_computed_style(element))
+ return;
+
+ element.document().update_style_for_element(element);
+ for (auto id = to_underlying(first_longhand_property_id); id <= to_underlying(last_longhand_property_id); ++id)
+ append(names, string_from_property_id(static_cast<PropertyID>(id)).to_utf16_string().into_raw());
+ for (auto const& name : computed_custom_property_names(element))
+ append(names, name.to_utf16_string().into_raw());
+ },
+ [&](GC::Ref<CSSStyleDeclaration> const& declaration) {
+ for (size_t i = 0; i < declaration->length(); ++i)
+ append(names, declaration->item(i).into_raw());
+ });
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-size
+size_t web_css_style_map_property_count(bool is_computed, void* raw_source)
+{
+ return source_from_abi(is_computed, raw_source)
+ .visit(
+ [](DOM::AbstractElement const& element) -> size_t {
+ if (!has_computed_style(element))
+ return 0;
+
+ element.document().update_style_for_element(element);
+ return number_of_longhand_properties + computed_custom_property_names(element).size();
+ },
+ [](GC::Ref<CSSStyleDeclaration> const& declaration) -> size_t {
+ return declaration->length();
+ });
+}
+
+bool web_css_style_map_property_is_list_valued(u16 property_id)
+{
+ return property_is_list_valued(static_cast<PropertyID>(property_id));
+}
+
+StyleValueData const* web_css_style_map_parse(void* raw_declaration, u16 property_id, FlatPtr css_text)
+{
+ auto text = Utf16String::from_raw(css_text);
+ auto parsing_params = Parser::ParsingParams {};
+ if (raw_declaration) {
+ if (auto owner_node = declaration_from_abi(raw_declaration).owner_node(); owner_node.has_value())
+ parsing_params = Parser::ParsingParams { owner_node->element().document() };
+ }
+ auto value = parse_css_value(parsing_params, text, static_cast<PropertyID>(property_id));
+ return value ? into_rust(*value) : nullptr;
+}
+
+StyleValueData const* web_css_style_map_declared_value(void* declaration, FlatPtr name)
+{
+ auto value = declaration_from_abi(declaration).get_property_style_value(property_from_abi(name));
+ return value ? into_rust(*value) : nullptr;
+}
+
+u8 web_css_style_map_set_value(void* declaration, FlatPtr name, StyleValueData const* value, FlatPtr* message)
+{
+ return change_result(declaration_from_abi(declaration).set_property_style_value(property_from_abi(name), StyleValue::adopt_rust_style_value_data(value)), message);
+}
+
+u8 web_css_style_map_remove(void* declaration, FlatPtr name, FlatPtr* message)
+{
+ return change_result(declaration_from_abi(declaration).remove_property(Utf16FlyString { Utf16String::from_raw(name) }), message);
+}
+
+u8 web_css_style_map_clear(void* declaration, FlatPtr* message)
+{
+ return change_result(declaration_from_abi(declaration).set_css_text(""sv), message);
+}
+
}
diff --git a/Libraries/LibWeb/CSS/StylePropertyMapReadOnly.h b/Libraries/LibWeb/CSS/StylePropertyMapReadOnly.h
index e7aff57b89d..7e9aff7a8a7 100644
--- a/Libraries/LibWeb/CSS/StylePropertyMapReadOnly.h
+++ b/Libraries/LibWeb/CSS/StylePropertyMapReadOnly.h
@@ -6,60 +6,19 @@
#pragma once
-#include <AK/Function.h>
-#include <AK/IterationDecision.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/CSS/StyleValues/StyleValue.h>
-#include <LibWeb/DOM/AbstractElement.h>
-#include <LibWebCommon/WebIDL/Types.h>
+#include <LibGC/Ptr.h>
+#include <LibWeb/Bindings/RustInterface.h>
+#include <LibWeb/Bindings/StylePropertyMapReadOnly.h>
+#include <LibWeb/Forward.h>
namespace Web::CSS {
// https://drafts.css-houdini.org/css-typed-om-1/#stylepropertymapreadonly
-class StylePropertyMapReadOnly : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(StylePropertyMapReadOnly, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(StylePropertyMapReadOnly);
+class StylePropertyMapReadOnly final : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(StylePropertyMapReadOnly, style_property_map_read_only)
public:
- [[nodiscard]] static GC::Ref<StylePropertyMapReadOnly> create_computed_style(DOM::AbstractElement);
-
- virtual ~StylePropertyMapReadOnly() override;
-
- WebIDL::ExceptionOr<Variant<GC::Ref<CSSStyleValue>, Empty>> get(Utf16String property);
- WebIDL::ExceptionOr<GC::RootVector<GC::Ref<CSSStyleValue>>> get_all(Utf16String property);
- WebIDL::ExceptionOr<bool> has(Utf16String property);
- WebIDL::UnsignedLong size() const;
-
- ReadonlySpan<Utf16FlyString> property_names() const;
- struct IterationEntry {
- Utf16FlyString name;
- size_t value_offset;
- size_t value_count;
- };
- void collect_iteration_entries(Vector<IterationEntry>&, GC::RootVector<GC::Ref<CSSStyleValue>>&);
- using ForEachCallback = Function<IterationDecision(Utf16String const&, ReadonlySpan<GC::Ref<CSSStyleValue>>)>;
- void for_each(ForEachCallback);
-
-protected:
- using Source = Variant<DOM::AbstractElement, GC::Ref<CSSStyleDeclaration>>;
- explicit StylePropertyMapReadOnly(Source);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- static RefPtr<StyleValue const> get_style_value(Source&, PropertyNameAndID const& property);
-
- // https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-declarations-slot
- // A StylePropertyMapReadOnly object has a [[declarations]] internal slot, which is a map reflecting the CSS
- // declaration block’s declarations.
- // NB: We just directly refer to our source, at least for now.
- Source m_declarations;
-
-private:
- mutable Vector<Utf16FlyString> m_cached_property_names;
- mutable Optional<u64> m_cached_declaration_revision;
- mutable GC::Ptr<DOM::Document> m_cached_document;
- mutable RefPtr<CustomPropertyData const> m_cached_custom_property_data;
- mutable size_t m_cached_registration_generation { 0 };
+ [[nodiscard]] static GC::Ref<StylePropertyMapReadOnly> create_computed_style(DOM::Element&);
};
}
diff --git a/Libraries/LibWeb/CSS/StylePropertyMapReadOnly.idl b/Libraries/LibWeb/CSS/StylePropertyMapReadOnly.idl
index 847b2daa73f..3b18a934305 100644
--- a/Libraries/LibWeb/CSS/StylePropertyMapReadOnly.idl
+++ b/Libraries/LibWeb/CSS/StylePropertyMapReadOnly.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#stylepropertymapreadonly
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface StylePropertyMapReadOnly {
iterable<USVString, sequence<CSSStyleValue>>;
(undefined or CSSStyleValue) get(USVString property);
diff --git a/Libraries/LibWeb/CSS/StylePropertyMapReadOnlyIterator.h b/Libraries/LibWeb/CSS/StylePropertyMapReadOnlyIterator.h
deleted file mode 100644
index 39c34cf0594..00000000000
--- a/Libraries/LibWeb/CSS/StylePropertyMapReadOnlyIterator.h
+++ /dev/null
@@ -1,10 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-// The iterable generator finds this header beside the interface. The JS iterator belongs to the bindings layer.
-#include <LibWeb/Bindings/StylePropertyMapReadOnlyIterator.h>
diff --git a/Libraries/LibWeb/CSS/TypedOM.cpp b/Libraries/LibWeb/CSS/TypedOM.cpp
index 6d573c58ab4..73a714e0048 100644
--- a/Libraries/LibWeb/CSS/TypedOM.cpp
+++ b/Libraries/LibWeb/CSS/TypedOM.cpp
@@ -196,7 +196,7 @@ bool web_css_typed_om_property_accepts_type(u16 property_id, TypedOmValueType va
StyleValueData const* web_css_typed_om_numeric_style_value(u16 property_id_abi, StyleValueData const* value_data, FfiCalcNode const* calculation_data, FfiNumericType numeric_type);
StyleValueData const* web_css_typed_om_calculated_style_value(u16 property_id_abi, FfiCalcNode const* calculation_data, FfiNumericType numeric_type, bool perform_type_check);
StyleValueData const* web_css_typed_om_keyword_style_value(u16 property_id_abi, FlatPtr raw_value, bool perform_type_check);
-StyleValueData const* web_css_typed_om_style_value_list(StyleValueData const* const* values, size_t count);
+StyleValueData const* web_css_typed_om_style_value_list(StyleValueData const* const* values, size_t count, bool comma);
StyleValueData const* web_css_typed_om_parse_numeric_value(FlatPtr raw_css_text);
bool web_css_typed_om_parse_value(FlatPtr raw_property, FlatPtr raw_css_text, void* values, void (*append)(void*, StyleValueData const*), FlatPtr* name_or_error);
bool web_css_typed_om_zero_is_a_length(FlatPtr raw_property, bool is_integer);
@@ -366,13 +366,13 @@ StyleValueData const* web_css_typed_om_keyword_style_value(u16 property_id_abi,
return into_rust(*CustomIdentStyleValue::create(value));
}
-StyleValueData const* web_css_typed_om_style_value_list(StyleValueData const* const* values, size_t count)
+StyleValueData const* web_css_typed_om_style_value_list(StyleValueData const* const* values, size_t count, bool comma)
{
StyleValueVector list;
list.ensure_capacity(count);
for (size_t i = 0; i < count; ++i)
list.unchecked_append(StyleValue::adopt_rust_style_value_data(values[i]));
- return into_rust(*StyleValueList::create(move(list), StyleValueList::Separator::Space));
+ return into_rust(*StyleValueList::create(move(list), comma ? StyleValueList::Separator::Comma : StyleValueList::Separator::Space));
}
// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-parse
diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp
index dad29df7d76..0eae8a5f685 100644
--- a/Libraries/LibWeb/DOM/Element.cpp
+++ b/Libraries/LibWeb/DOM/Element.cpp
@@ -54,6 +54,7 @@
#include <LibWeb/CSS/StyleEngineInput.h>
#include <LibWeb/CSS/StyleInvalidation.h>
#include <LibWeb/CSS/StylePropertyMap.h>
+#include <LibWeb/CSS/StylePropertyMapReadOnly.h>
#include <LibWeb/CSS/StyleSheetInvalidation.h>
#include <LibWeb/CSS/StyleValues/AbstractImageStyleValue.h>
#include <LibWeb/CSS/StyleValues/ContentStyleValue.h>
@@ -7135,7 +7136,7 @@ GC::Ref<CSS::StylePropertyMapReadOnly> Element::computed_style_map()
// until a given property is actually requested.
auto& computed_style_map_cache = ensure_element_rare_data().computed_style_map_cache;
if (computed_style_map_cache == nullptr) {
- computed_style_map_cache = CSS::StylePropertyMapReadOnly::create_computed_style(AbstractElement { *this });
+ computed_style_map_cache = CSS::StylePropertyMapReadOnly::create_computed_style(*this);
}
// 2. Return this’s [[computedStyleMapCache]] internal slot.
diff --git a/Libraries/LibWeb/Rust/src/css/typed_om.rs b/Libraries/LibWeb/Rust/src/css/typed_om.rs
index 51204897257..ce9c59f1ede 100644
--- a/Libraries/LibWeb/Rust/src/css/typed_om.rs
+++ b/Libraries/LibWeb/Rust/src/css/typed_om.rs
@@ -21,11 +21,13 @@ use crate::css::dimension_units::{
};
use crate::css::parser::arbitrary_substitution::SubstitutionFunctionsPresence;
use crate::css::parser::arbitrary_substitution::collect_arbitrary_substitution_function_presence;
-use crate::css::parser::value_parser::component_values_from_source;
+use crate::css::parser::value_parser::{component_values_from_source, is_css_wide_keyword};
use crate::css::property_metadata::is_custom_property_name;
+pub use crate::css::property_metadata::property_is_shorthand;
use crate::css::serialize::{SerializationMode, TextSink, serialize_style_value};
use crate::css::style_compute::{LENGTH_UNIT_CANONICAL_PX_RATIOS, LENGTH_UNIT_NAMES};
use crate::css::style_value::StyleValueData;
+use crate::css::style_value::rust_style_value_create_grid_track_size_list;
pub use crate::css::style_value::{ReifiedUnresolvedSegment, RetainedStyleValueData as RetainedStyleValue};
/// The base types of a numeric type, as indices of [`NumericType::exponents`].
@@ -355,6 +357,80 @@ impl RetainedStyleValue {
matches!(self.data(), StyleValueData::Transformation(_))
}
+ pub fn is_unresolved(&self) -> bool {
+ matches!(self.data(), StyleValueData::Unresolved(_))
+ }
+
+ pub fn is_custom_ident(&self) -> bool {
+ matches!(self.data(), StyleValueData::CustomIdent { .. })
+ }
+
+ pub fn is_keyword(&self) -> bool {
+ matches!(self.data(), StyleValueData::Keyword { .. })
+ }
+
+ pub fn is_css_wide_keyword(&self) -> bool {
+ matches!(self.data(), StyleValueData::Keyword { keyword } if is_css_wide_keyword(*keyword))
+ }
+
+ pub fn is_shorthand(&self) -> bool {
+ matches!(self.data(), StyleValueData::Shorthand(_))
+ }
+
+ pub fn is_pending_substitution(&self) -> bool {
+ matches!(self.data(), StyleValueData::PendingSubstitution { .. })
+ }
+
+ pub fn is_guaranteed_invalid(&self) -> bool {
+ matches!(self.data(), StyleValueData::GuaranteedInvalid)
+ }
+
+ pub fn is_grid_track_size_list(&self) -> bool {
+ matches!(self.data(), StyleValueData::GridTrackSizeList(_))
+ }
+
+ pub fn is_length_percentage(&self) -> bool {
+ matches!(
+ self.data(),
+ StyleValueData::Length { .. } | StyleValueData::Percentage { .. } | StyleValueData::Calculated(_)
+ )
+ }
+
+ /// The items of a value list.
+ pub fn value_list_items(&self) -> Option<Vec<RetainedStyleValue>> {
+ let StyleValueData::ValueList { values, .. } = self.data() else {
+ return None;
+ };
+ Some(
+ values
+ .as_slice()
+ .iter()
+ .map(RetainedStyleValue::clone_retained)
+ .collect(),
+ )
+ }
+
+ /// A text-indent value of the length-percentage, which neither hangs nor applies to each line.
+ pub fn into_text_indent(self) -> RetainedStyleValue {
+ RetainedStyleValue::from_owned(StyleValueData::TextIndent {
+ length_percentage: self,
+ hanging: false,
+ each_line: false,
+ })
+ }
+
+ /// A grid track size list of the track sizes.
+ pub fn grid_track_size_list(track_sizes: Vec<RetainedStyleValue>) -> RetainedStyleValue {
+ let pointers: Vec<_> = track_sizes.into_iter().map(|size| size.into_raw().cast()).collect();
+ // SAFETY: This hands over strong references to the track sizes, and takes over the one that the call returns.
+ unsafe {
+ RetainedStyleValue::from_retained_pointer(rust_style_value_create_grid_track_size_list(
+ pointers.as_ptr(),
+ pointers.len(),
+ ))
+ }
+ }
+
/// Takes over one strong reference, which C++ hands over.
///
/// # Safety