Skip to content

Truly independent web browser

LibWeb: Implement the CSS Typed OM in Rust

Andreas Kling47a9f060cd45
diff --git a/Libraries/LibWeb/Animations/Animation.cpp b/Libraries/LibWeb/Animations/Animation.cpp
index ea76721152a..e0529673cea 100644
--- a/Libraries/LibWeb/Animations/Animation.cpp
+++ b/Libraries/LibWeb/Animations/Animation.cpp
@@ -19,7 +19,6 @@
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/CSS/CSSAnimation.h>
#include <LibWeb/CSS/CSSKeywordValue.h>
-#include <LibWeb/CSS/CSSMathSum.h>
#include <LibWeb/CSS/CSSNumericValue.h>
#include <LibWeb/CSS/CSSTransition.h>
#include <LibWeb/CSS/CSSUnitValue.h>
@@ -439,14 +438,14 @@ WebIDL::ExceptionOr<TimelineRangeEdge> parse_timeline_range_edge(DOM::Document&
builder.append(**offset.range_name);
if (offset.offset) {
builder.append_ascii(' ');
- builder.append(offset.offset->to_string({}));
+ builder.append(offset.offset->to_string());
}
// NB: A TimelineRangeOffset that gives neither a range name nor an offset is the default edge.
if (builder.is_empty())
return parse("normal"_utf16);
return parse(builder.to_string());
},
- [&](GC::Ref<CSS::CSSNumericValue> const& offset) { return parse(offset->to_string({})); },
+ [&](GC::Ref<CSS::CSSNumericValue> const& offset) { return parse(offset->to_string()); },
// Passing a CSSKeywordValue with a value other than "normal" as the rangeStart or rangeEnd value to any API
// defined to accept KeyframeAnimationOptions throws a TypeError.
[&](GC::Ref<CSS::CSSKeywordValue> const& keyword) -> WebIDL::ExceptionOr<TimelineRangeEdge> {
@@ -467,10 +466,10 @@ static TimelineRangeBindingValue timeline_range_edge_to_bindings(TimelineRangeEd
auto percentage = CSS::CSSUnitValue::create(edge.offset_percentage, "percent"_utf16_fly_string);
GC::Ref<CSS::CSSNumericValue> offset = edge.offset_px == 0 ? GC::Ref<CSS::CSSNumericValue> { percentage } : GC::Ref<CSS::CSSNumericValue> { px };
if (edge.offset_px != 0 && edge.offset_percentage != 0)
- offset = MUST(CSS::CSSMathSum::create_for_constructor(Vector<CSS::CSSNumberish> { GC::Ref<CSS::CSSNumericValue> { px }, GC::Ref<CSS::CSSNumericValue> { percentage } }));
+ offset = CSS::CSSNumericValue::create_sum(px, percentage);
if (edge.calculated_offset) {
auto calculated = CSS::StyleValue::adopt_rust_style_value_data(CSS::StyleValueFFI::rust_style_value_retain(edge.calculated_offset.data()));
- offset = as<CSS::CSSNumericValue>(*calculated->as_calculated().reify({}));
+ offset = as<CSS::CSSNumericValue>(*CSS::CSSStyleValue::reify(*calculated, {}));
}
Bindings::TimelineRangeOffset range_offset {};
diff --git a/Libraries/LibWeb/Animations/TimeValue.cpp b/Libraries/LibWeb/Animations/TimeValue.cpp
index 5adeede8556..0b13cc6e128 100644
--- a/Libraries/LibWeb/Animations/TimeValue.cpp
+++ b/Libraries/LibWeb/Animations/TimeValue.cpp
@@ -25,7 +25,7 @@ TimeValue TimeValue::from_css_numberish(CSS::CSSNumberish const& time, CSS::Comp
return { Type::Milliseconds, unit_value->value() };
if (unit_value->type().matches_time({}))
- return { Type::Milliseconds, MUST(unit_value->to("ms"_utf16_fly_string))->value() };
+ return { Type::Milliseconds, CSS::Time { unit_value->value(), CSS::string_to_time_unit(unit_value->unit()).release_value() }.to_milliseconds() };
if (unit_value->type().matches_percentage())
return { Type::Percentage, unit_value->value() };
@@ -33,7 +33,7 @@ TimeValue TimeValue::from_css_numberish(CSS::CSSNumberish const& time, CSS::Comp
VERIFY_NOT_REACHED();
}
- auto calculation_node = MUST(numeric_value->create_calculation_node({}));
+ auto calculation_node = numeric_value->create_calculation_node().release_value();
auto numeric_type = calculation_node.determine_type({});
VERIFY(numeric_type.has_value());
diff --git a/Libraries/LibWeb/Animations/ViewTimeline.cpp b/Libraries/LibWeb/Animations/ViewTimeline.cpp
index 2deb9ee879e..90f583bd771 100644
--- a/Libraries/LibWeb/Animations/ViewTimeline.cpp
+++ b/Libraries/LibWeb/Animations/ViewTimeline.cpp
@@ -83,7 +83,7 @@ WebIDL::ExceptionOr<GC::Ref<ViewTimeline>> ViewTimeline::create_for_constructor(
for (auto const& value : values) {
auto edge = TRY(value.visit(
[&](GC::Ref<CSS::CSSNumericValue> const& numeric) -> WebIDL::ExceptionOr<InsetEdge> {
- return TRY(parse_inset(numeric->to_string({}))).start;
+ return TRY(parse_inset(numeric->to_string())).start;
},
[&](GC::Ref<CSS::CSSKeywordValue> const& keyword) { return parse_auto(keyword->value()); },
// INTEROP: Blink takes "auto" as a string in the sequence too.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
index ebeaa33e56a..a173e60915b 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs
@@ -112,6 +112,10 @@ impl UsvString {
Self(to_well_formed(string))
}
+ pub(crate) fn to_utf16(&self) -> std::borrow::Cow<'_, [u16]> {
+ self.0.to_utf16()
+ }
+
pub(crate) fn from_utf8(string: &str) -> Self {
Self(Utf16String::from_utf8(string))
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_image_value.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_image_value.rs
new file mode 100644
index 00000000000..52e8c49d00d
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_image_value.rs
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSImageValue, https://drafts.css-houdini.org/css-typed-om-1/#cssimagevalue
+
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::typed_om::RetainedStyleValue;
+
+use super::css_style_value::{AnyCSSStyleValue, CSSStyleValue, PerformTypeCheck};
+use super::typed_om::{self, TypedOmValueType};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{Exception, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSImageValue {
+ style_value: CSSStyleValue,
+}
+
+impl Wrappable for CSSImageValue {}
+
+impl Inherits<CSSStyleValue> for CSSImageValue {
+ fn parent(&self) -> &CSSStyleValue {
+ &self.style_value
+ }
+}
+
+impl CSSImageValue {
+ pub(crate) fn create(vm: &Vm, source_value: RetainedStyleValue) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ style_value: CSSStyleValue::with_source(source_value),
+ });
+ object
+ .style_value
+ .set_object(vm, AnyCSSStyleValue::CSSImageValue(object));
+ object
+ }
+
+ pub(crate) fn style_value(&self) -> &CSSStyleValue {
+ &self.style_value
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+ pub(crate) fn create_an_internal_representation(
+ &self,
+ property_id: u16,
+ property_name: &Utf16String,
+ perform_type_check: PerformTypeCheck,
+ ) -> WebIdlResult<RetainedStyleValue> {
+ // If value is a CSSStyleValue subclass,
+ // If value does not match the grammar of a list-valued property iteration of property, throw a TypeError.
+ // NB: https://drafts.css-houdini.org/css-typed-om-1/#cssstylevalue-match-a-grammar doesn't list CSSImageValue,
+ // but we should match <image>.
+ if perform_type_check == PerformTypeCheck::Yes
+ && !typed_om::property_accepts_type(property_id, TypedOmValueType::Image)
+ {
+ return Err(Exception::TypeError(Utf16String::from_utf8(&format!(
+ "Property '{}' does not accept <image>",
+ typed_om::to_rust_string(property_name)
+ ))));
+ }
+
+ // FIXME: If any component of property’s CSS grammar has a limited numeric range, and the corresponding part
+ // of value is a CSSUnitValue that is outside of that range, replace that value with the result of
+ // wrapping it in a fresh CSSMathSum whose values internal slot contains only that part of value.
+
+ // Return the value.
+ Ok(self
+ .style_value
+ .source_value()
+ .expect("a CSSImageValue has a source value")
+ .clone())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_keyword_value.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_keyword_value.rs
new file mode 100644
index 00000000000..f36b350b1fc
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_keyword_value.rs
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSKeywordValue, https://drafts.css-houdini.org/css-typed-om-1/#csskeywordvalue
+
+use core::cell::RefCell;
+
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::typed_om::{RetainedStyleValue, serialize_an_identifier};
+
+use super::css_style_value::{AnyCSSStyleValue, CSSStyleValue, PerformTypeCheck};
+use super::typed_om;
+use crate::bindings::conversions::UsvString;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+/// The union (DOMString or CSSKeywordValue) of CSS/CSSKeywordValue.idl.
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) enum CSSKeywordish {
+ DOMString(#[gc(untraced)] Utf16String),
+ CSSKeywordValue(Ref<CSSKeywordValue>),
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSKeywordValue {
+ style_value: CSSStyleValue,
+ #[gc(untraced)]
+ value: RefCell<Utf16String>,
+}
+
+impl Wrappable for CSSKeywordValue {}
+
+impl Inherits<CSSStyleValue> for CSSKeywordValue {
+ fn parent(&self) -> &CSSStyleValue {
+ &self.style_value
+ }
+}
+
+impl CSSKeywordValue {
+ pub(crate) fn create(vm: &Vm, value: Utf16String) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ style_value: CSSStyleValue::empty(),
+ value: RefCell::new(value),
+ });
+ object
+ .style_value
+ .set_object(vm, AnyCSSStyleValue::CSSKeywordValue(object));
+ object
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-csskeywordvalue-csskeywordvalue
+ pub(crate) fn construct(cx: &mut CallContext, value: UsvString) -> WebIdlResult<Ref<Self>> {
+ // 1. If value is an empty string, throw a TypeError.
+ let value = value.into_utf16_string();
+ if value.is_empty() {
+ return Err(Exception::type_error(
+ "Cannot create a CSSKeywordValue with an empty string as the value",
+ ));
+ }
+
+ // 2. Otherwise, return a new CSSKeywordValue with its value internal slot set to value.
+ Ok(Self::create(cx.vm(), value))
+ }
+
+ pub(crate) fn style_value(&self) -> &CSSStyleValue {
+ &self.style_value
+ }
+
+ pub(crate) fn raw_value(&self) -> Utf16String {
+ self.value.borrow().clone()
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-csskeywordvalue-value
+ pub(crate) fn value(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(self.raw_value())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-csskeywordvalue-value
+ pub(crate) fn set_value(&self, _: &mut CallContext, value: UsvString) -> WebIdlResult<()> {
+ // 1. If value is an empty string, throw a TypeError.
+ let value = value.into_utf16_string();
+ if value.is_empty() {
+ return Err(Exception::type_error(
+ "Cannot set CSSKeywordValue.value to an empty string",
+ ));
+ }
+
+ // 2. Otherwise, set this’s value internal slot, to value.
+ *self.value.borrow_mut() = value;
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#keywordvalue-serialization
+ pub(crate) fn serialize(&self) -> Utf16String {
+ // To serialize a CSSKeywordValue this:
+ // 1. Return this’s value internal slot.
+ // AD-HOC: Serialize it as an identifier. Spec issue: https://github.com/w3c/csswg-drafts/issues/12545
+ serialize_an_identifier(&self.value.borrow())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+ pub(crate) fn create_an_internal_representation(
+ &self,
+ property_id: u16,
+ property_name: &Utf16String,
+ perform_type_check: PerformTypeCheck,
+ ) -> WebIdlResult<RetainedStyleValue> {
+ // If value is a CSSStyleValue subclass,
+ // If value does not match the grammar of a list-valued property iteration of property, throw a TypeError.
+ // https://drafts.css-houdini.org/css-typed-om-1/#cssstylevalue-match-a-grammar
+ // A CSSKeywordValue matches an <ident> specified in a grammar if its value internal slot matches the
+ // identifier.
+ // If case-folding rules are in effect normally for that <ident> (such as Auto matching the keyword auto
+ // specified in the grammar for width), they apply to this comparison as well.
+ //
+ // If any component of property’s CSS grammar has a limited numeric range, and the corresponding part of
+ // value is a CSSUnitValue that is outside of that range, replace that value with the result of wrapping it
+ // in a fresh CSSMathSum whose values internal slot contains only that part of value.
+ // NB: Non-applicable.
+ //
+ // Return the value.
+ let value = self.value.borrow();
+ typed_om::keyword_style_value_for_property(property_id, &value, perform_type_check).ok_or_else(|| {
+ Exception::TypeError(Utf16String::from_utf8(&format!(
+ "Property '{}' does not accept the keyword '{}'",
+ typed_om::to_rust_string(property_name),
+ typed_om::to_rust_string(&value)
+ )))
+ })
+ }
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#rectify-a-keywordish-value
+pub(crate) fn rectify_a_keywordish_value(vm: &Vm, keywordish: &CSSKeywordish) -> Ref<CSSKeywordValue> {
+ // To rectify a keywordish value val, perform the following steps:
+ match keywordish {
+ // 1. If val is a CSSKeywordValue, return val.
+ CSSKeywordish::CSSKeywordValue(value) => *value,
+ // 2. If val is a DOMString, return a new CSSKeywordValue with its value internal slot set to val.
+ CSSKeywordish::DOMString(value) => CSSKeywordValue::create(vm, value.clone()),
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_math_clamp.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_math_clamp.rs
new file mode 100644
index 00000000000..7bedfd3ea02
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_math_clamp.rs
@@ -0,0 +1,168 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSMathClamp, https://drafts.css-houdini.org/css-typed-om-1/#cssmathclamp
+
+use std::sync::Arc;
+
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::typed_om::{CalcNode, NumericType, SumValue, SumValueItem};
+
+use super::css_math_value::*;
+use super::css_numeric_value::{AnyCSSNumericValue, CSSNumberish, rectify_a_numberish_value};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSMathClamp {
+ math_value: CSSMathValue,
+ lower: AnyCSSNumericValue,
+ value: AnyCSSNumericValue,
+ upper: AnyCSSNumericValue,
+}
+
+impl Wrappable for CSSMathClamp {}
+
+impl Inherits<CSSMathValue> for CSSMathClamp {
+ fn parent(&self) -> &CSSMathValue {
+ &self.math_value
+ }
+}
+
+impl CSSMathClamp {
+ pub(crate) fn create(
+ vm: &Vm,
+ numeric_type: NumericType,
+ lower: AnyCSSNumericValue,
+ value: AnyCSSNumericValue,
+ upper: AnyCSSNumericValue,
+ ) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ math_value: CSSMathValue::new(CSSMathOperator::Clamp, numeric_type),
+ lower,
+ value,
+ upper,
+ });
+ AnyCSSNumericValue::CSSMathClamp(object).finish(vm);
+ object
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathclamp-cssmathclamp
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ lower: CSSNumberish,
+ value: CSSNumberish,
+ upper: CSSNumberish,
+ ) -> WebIdlResult<Ref<Self>> {
+ // The CSSMathClamp(lower, value, upper) constructor must, when called, perform the following steps:
+ // 1. Replace lower, value, and upper with the result of rectifying a numberish value for each.
+ let vm = cx.vm();
+ let lower = rectify_a_numberish_value(vm, &lower, None);
+ let value = rectify_a_numberish_value(vm, &value, None);
+ let upper = rectify_a_numberish_value(vm, &upper, None);
+
+ // 2. Let type be the result of adding the types of lower, value, and upper. If type is failure, throw a
+ // TypeError.
+ let Some(numeric_type) = add_all_types(&[lower, value, upper]) else {
+ return Err(Exception::type_error(
+ "Cannot create a CSSMathClamp with values of incompatible types",
+ ));
+ };
+
+ // 3. Return a new CSSMathClamp whose lower, value, and upper internal slots are set to lower, value, and upper,
+ // respectively.
+ Ok(Self::create(vm, numeric_type, lower, value, upper))
+ }
+
+ pub(crate) fn math_value(&self) -> &CSSMathValue {
+ &self.math_value
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathclamp-lower
+ pub(crate) fn lower(&self, _: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {
+ // AD-HOC: No spec definition.
+ Ok(self.lower)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathclamp-value
+ pub(crate) fn value(&self, _: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {
+ // AD-HOC: No spec definition.
+ Ok(self.value)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathclamp-upper
+ pub(crate) fn upper(&self, _: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {
+ // AD-HOC: No spec definition.
+ Ok(self.upper)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmathvalue
+ pub(crate) fn serialize_math_value(&self, s: &mut String) {
+ // AD-HOC: The spec is missing serialization rules for CSSMathClamp:
+ // https://github.com/w3c/css-houdini-drafts/issues/1152
+ s.push_str("clamp(");
+ self.lower.serialize(s, NESTED_AND_PARENLESS);
+ s.push_str(", ");
+ self.value.serialize(s, NESTED_AND_PARENLESS);
+ s.push_str(", ");
+ self.upper.serialize(s, NESTED_AND_PARENLESS);
+ s.push(')');
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#equal-numeric-value
+ pub(crate) fn is_equal_clamp(&self, other: &Self) -> bool {
+ // AD-HOC: Spec doesn't handle clamp(). https://github.com/w3c/css-houdini-drafts/issues/1152
+ self.lower.is_equal_numeric_value(&other.lower)
+ && self.value.is_equal_numeric_value(&other.value)
+ && self.upper.is_equal_numeric_value(&other.upper)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
+ pub(crate) fn create_a_sum_value(&self) -> Option<SumValue> {
+ // AD-HOC: There is no spec for this. https://github.com/w3c/css-houdini-drafts/issues/1152
+ // So, basing it on the spec for CSSMathMin.
+ // Create sum values from lower, value, and upper.
+ let lower = self.lower.create_a_sum_value()?;
+ let value = self.value.create_a_sum_value()?;
+ let upper = self.upper.create_a_sum_value()?;
+
+ // If any of those are failure, or has a length greater than one, return failure.
+ if lower.len() > 1 || value.len() > 1 || upper.len() > 1 {
+ return None;
+ }
+
+ // If not all their unit maps are identical, return failure.
+ if lower[0].unit_map != value[0].unit_map || value[0].unit_map != upper[0].unit_map {
+ return None;
+ }
+
+ // Return value clamped between lower and upper.
+ // NB: Like the CSS clamp() function, this lets a lower bound above the upper bound win, and keeps a NaN value.
+ let at_most_upper = if upper[0].value < value[0].value {
+ upper[0].value
+ } else {
+ value[0].value
+ };
+ let clamped = if at_most_upper < lower[0].value {
+ lower[0].value
+ } else {
+ at_most_upper
+ };
+ Some(vec![SumValueItem {
+ value: clamped,
+ unit_map: value[0].unit_map.clone(),
+ }])
+ }
+
+ pub(crate) fn create_calculation_node(&self) -> WebIdlResult<Arc<CalcNode>> {
+ Ok(Arc::new(CalcNode::Clamp {
+ min: Some(self.lower.create_calculation_node()?),
+ center: self.value.create_calculation_node()?,
+ max: Some(self.upper.create_calculation_node()?),
+ }))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_math_invert.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_math_invert.rs
new file mode 100644
index 00000000000..8007357f736
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_math_invert.rs
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSMathInvert, https://drafts.css-houdini.org/css-typed-om-1/#cssmathinvert
+
+use std::sync::Arc;
+
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::typed_om::{CalcNode, SumValue};
+
+use super::css_math_value::*;
+use super::css_numeric_value::{AnyCSSNumericValue, CSSNumberish, rectify_a_numberish_value};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSMathInvert {
+ math_value: CSSMathValue,
+ value: AnyCSSNumericValue,
+}
+
+impl Wrappable for CSSMathInvert {}
+
+impl Inherits<CSSMathValue> for CSSMathInvert {
+ fn parent(&self) -> &CSSMathValue {
+ &self.math_value
+ }
+}
+
+impl CSSMathInvert {
+ pub(crate) fn create(vm: &Vm, value: AnyCSSNumericValue) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ math_value: CSSMathValue::new(CSSMathOperator::Invert, value.numeric_type().inverted()),
+ value,
+ });
+ AnyCSSNumericValue::CSSMathInvert(object).finish(vm);
+ object
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathinvert-cssmathinvert
+ pub(crate) fn construct(cx: &mut CallContext, arg: CSSNumberish) -> WebIdlResult<Ref<Self>> {
+ // The CSSMathInvert(arg) constructor is defined identically to the above, except that in the last step it
+ // returns a new CSSMathInvert object.
+ // 1. Replace arg with the result of rectifying a numberish value for arg.
+ let vm = cx.vm();
+ let converted_value = rectify_a_numberish_value(vm, &arg, None);
+
+ // 2. Return a new CSSMathInvert whose value internal slot is set to arg.
+ Ok(Self::create(vm, converted_value))
+ }
+
+ pub(crate) fn math_value(&self) -> &CSSMathValue {
+ &self.math_value
+ }
+
+ pub(crate) fn inner_value(&self) -> AnyCSSNumericValue {
+ self.value
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathinvert-value
+ pub(crate) fn value(&self, _: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {
+ Ok(self.value)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmathvalue
+ pub(crate) fn serialize_math_value(&self, s: &mut String, nested: bool, parenless: bool) {
+ // NB: Only steps 1 and 6 apply here.
+ // 1. Let s initially be the empty string.
+
+ // 6. Otherwise, if this is a CSSMathInvert:
+ // 1. If paren-less is true, continue to the next step; otherwise, if nested is true, append "(" to s;
+ // otherwise, append "calc(" to s.
+ serialize_opening(s, nested, parenless);
+
+ // 2. Append "1 / " to s.
+ s.push_str("1 / ");
+
+ // 3. Serialize this’s value internal slot with nested set to true, and append the result to s.
+ self.value.serialize(s, NESTED);
+
+ // 4. If paren-less is false, append ")" to s,
+ if !parenless {
+ s.push(')');
+ }
+
+ // 5. Return s.
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
+ pub(crate) fn create_a_sum_value(&self) -> Option<SumValue> {
+ // 1. Let values be the result of creating a sum value from this’s value internal slot.
+ // 2. If values is failure, return failure.
+ let mut values = self.value.create_a_sum_value()?;
+
+ // 3. If the length of values is more than one, return failure.
+ if values.len() > 1 {
+ return None;
+ }
+
+ // 4. Invert (find the reciprocal of) the value of the item in values, and negate the value of each entry in its
+ // unit map.
+ for item in &mut values {
+ item.value = 1.0 / item.value;
+ for power in item.unit_map.values_mut() {
+ *power = -*power;
+ }
+ }
+
+ // 5. Return values.
+ Some(values)
+ }
+
+ pub(crate) fn create_calculation_node(&self) -> WebIdlResult<Arc<CalcNode>> {
+ Ok(Arc::new(CalcNode::Invert(self.value.create_calculation_node()?)))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_math_max.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_math_max.rs
new file mode 100644
index 00000000000..678666d61d0
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_math_max.rs
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSMathMax, https://drafts.css-houdini.org/css-typed-om-1/#cssmathmax
+
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::{MarkedVec, Trace, Vm};
+use libweb_rust::typed_om::{CalcNode, NumericType, SumValue};
+
+use super::css_math_value::*;
+use super::css_numeric_array::CSSNumericArray;
+use super::css_numeric_value::{AnyCSSNumericValue, CSSNumberish};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSMathMax {
+ math_value: CSSMathValue,
+ values: Ref<CSSNumericArray>,
+}
+
+impl Wrappable for CSSMathMax {}
+
+impl Inherits<CSSMathValue> for CSSMathMax {
+ fn parent(&self) -> &CSSMathValue {
+ &self.math_value
+ }
+}
+
+impl CSSMathMax {
+ pub(crate) fn create(vm: &Vm, numeric_type: NumericType, values: Ref<CSSNumericArray>) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ math_value: CSSMathValue::new(CSSMathOperator::Max, numeric_type),
+ values,
+ });
+ AnyCSSNumericValue::CSSMathMax(object).finish(vm);
+ object
+ }
+
+ pub(crate) fn add_all_types_into_math_max(
+ vm: &Vm,
+ values: &MarkedVec<'_, AnyCSSNumericValue>,
+ ) -> WebIdlResult<Ref<Self>> {
+ let Some(numeric_type) = add_all_types(&values.to_vec()) else {
+ return Err(Exception::type_error(
+ "Cannot create a CSSMathMax with values of incompatible types",
+ ));
+ };
+ let values = CSSNumericArray::create(vm, values);
+ Ok(Self::create(vm, numeric_type, values))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathmax-cssmathmax
+ pub(crate) fn construct(cx: &mut CallContext, args: MarkedVec<'_, CSSNumberish>) -> WebIdlResult<Ref<Self>> {
+ // The CSSMathMin(...args) and CSSMathMax(...args) constructors are defined identically to the above, except
+ // that in the last step they return a new CSSMathMin or CSSMathMax object, respectively.
+
+ // 1. Replace each item of args with the result of rectifying a numberish value for the item.
+ let vm = cx.vm();
+ let values = rectify_numberish_values(vm, &args);
+
+ // 2. If args is empty, throw a SyntaxError.
+ if values.is_empty() {
+ return Err(Exception::syntax_error(Utf16String::from_utf8(
+ "Cannot create an empty CSSMathMax",
+ )));
+ }
+
+ // 3. Let type be the result of adding the types of all the items of args. If type is failure, throw a TypeError.
+ // 4. Return a new CSSMathMax whose values internal slot is set to args.
+ Self::add_all_types_into_math_max(vm, &values)
+ }
+
+ pub(crate) fn math_value(&self) -> &CSSMathValue {
+ &self.math_value
+ }
+
+ pub(crate) fn numeric_array(&self) -> Ref<CSSNumericArray> {
+ self.values
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathmax-values
+ pub(crate) fn values(&self, _: &mut CallContext) -> WebIdlResult<Ref<CSSNumericArray>> {
+ Ok(self.values)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmathvalue
+ pub(crate) fn serialize_math_value(&self, s: &mut String) {
+ // NB: Only steps 1 and 2 apply here.
+ // 1. Let s initially be the empty string.
+ serialize_min_or_max(s, "max", self.values.values());
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
+ pub(crate) fn create_a_sum_value(&self) -> Option<SumValue> {
+ min_or_max_sum_value(self.values.values(), |first, second| first > second)
+ }
+
+ pub(crate) fn create_calculation_node(&self) -> WebIdlResult<Arc<CalcNode>> {
+ let child_nodes = self
+ .values
+ .values()
+ .iter()
+ .map(AnyCSSNumericValue::create_calculation_node)
+ .collect::<WebIdlResult<Vec<_>>>()?;
+ Ok(Arc::new(CalcNode::Max(child_nodes)))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_math_min.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_math_min.rs
new file mode 100644
index 00000000000..1df98654e38
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_math_min.rs
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSMathMin, https://drafts.css-houdini.org/css-typed-om-1/#cssmathmin
+
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::{MarkedVec, Trace, Vm};
+use libweb_rust::typed_om::{CalcNode, NumericType, SumValue};
+
+use super::css_math_value::*;
+use super::css_numeric_array::CSSNumericArray;
+use super::css_numeric_value::{AnyCSSNumericValue, CSSNumberish};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSMathMin {
+ math_value: CSSMathValue,
+ values: Ref<CSSNumericArray>,
+}
+
+impl Wrappable for CSSMathMin {}
+
+impl Inherits<CSSMathValue> for CSSMathMin {
+ fn parent(&self) -> &CSSMathValue {
+ &self.math_value
+ }
+}
+
+impl CSSMathMin {
+ pub(crate) fn create(vm: &Vm, numeric_type: NumericType, values: Ref<CSSNumericArray>) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ math_value: CSSMathValue::new(CSSMathOperator::Min, numeric_type),
+ values,
+ });
+ AnyCSSNumericValue::CSSMathMin(object).finish(vm);
+ object
+ }
+
+ pub(crate) fn add_all_types_into_math_min(
+ vm: &Vm,
+ values: &MarkedVec<'_, AnyCSSNumericValue>,
+ ) -> WebIdlResult<Ref<Self>> {
+ let Some(numeric_type) = add_all_types(&values.to_vec()) else {
+ return Err(Exception::type_error(
+ "Cannot create a CSSMathMin with values of incompatible types",
+ ));
+ };
+ let values = CSSNumericArray::create(vm, values);
+ Ok(Self::create(vm, numeric_type, values))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathmin-cssmathmin
+ pub(crate) fn construct(cx: &mut CallContext, args: MarkedVec<'_, CSSNumberish>) -> WebIdlResult<Ref<Self>> {
+ // The CSSMathMin(...args) and CSSMathMax(...args) constructors are defined identically to the above, except
+ // that in the last step they return a new CSSMathMin or CSSMathMax object, respectively.
+
+ // 1. Replace each item of args with the result of rectifying a numberish value for the item.
+ let vm = cx.vm();
+ let values = rectify_numberish_values(vm, &args);
+
+ // 2. If args is empty, throw a SyntaxError.
+ if values.is_empty() {
+ return Err(Exception::syntax_error(Utf16String::from_utf8(
+ "Cannot create an empty CSSMathMin",
+ )));
+ }
+
+ // 3. Let type be the result of adding the types of all the items of args. If type is failure, throw a TypeError.
+ // 4. Return a new CSSMathMin whose values internal slot is set to args.
+ Self::add_all_types_into_math_min(vm, &values)
+ }
+
+ pub(crate) fn math_value(&self) -> &CSSMathValue {
+ &self.math_value
+ }
+
+ pub(crate) fn numeric_array(&self) -> Ref<CSSNumericArray> {
+ self.values
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathmin-values
+ pub(crate) fn values(&self, _: &mut CallContext) -> WebIdlResult<Ref<CSSNumericArray>> {
+ Ok(self.values)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmathvalue
+ pub(crate) fn serialize_math_value(&self, s: &mut String) {
+ // NB: Only steps 1 and 2 apply here.
+ // 1. Let s initially be the empty string.
+ serialize_min_or_max(s, "min", self.values.values());
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
+ pub(crate) fn create_a_sum_value(&self) -> Option<SumValue> {
+ min_or_max_sum_value(self.values.values(), |first, second| first < second)
+ }
+
+ pub(crate) fn create_calculation_node(&self) -> WebIdlResult<Arc<CalcNode>> {
+ let child_nodes = self
+ .values
+ .values()
+ .iter()
+ .map(AnyCSSNumericValue::create_calculation_node)
+ .collect::<WebIdlResult<Vec<_>>>()?;
+ Ok(Arc::new(CalcNode::Min(child_nodes)))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_math_negate.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_math_negate.rs
new file mode 100644
index 00000000000..614fd0823da
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_math_negate.rs
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSMathNegate, https://drafts.css-houdini.org/css-typed-om-1/#cssmathnegate
+
+use std::sync::Arc;
+
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::typed_om::{CalcNode, SumValue};
+
+use super::css_math_value::*;
+use super::css_numeric_value::{AnyCSSNumericValue, CSSNumberish, rectify_a_numberish_value};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSMathNegate {
+ math_value: CSSMathValue,
+ value: AnyCSSNumericValue,
+}
+
+impl Wrappable for CSSMathNegate {}
+
+impl Inherits<CSSMathValue> for CSSMathNegate {
+ fn parent(&self) -> &CSSMathValue {
+ &self.math_value
+ }
+}
+
+impl CSSMathNegate {
+ pub(crate) fn create(vm: &Vm, value: AnyCSSNumericValue) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ math_value: CSSMathValue::new(CSSMathOperator::Negate, value.numeric_type()),
+ value,
+ });
+ AnyCSSNumericValue::CSSMathNegate(object).finish(vm);
+ object
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathnegate-cssmathnegate
+ pub(crate) fn construct(cx: &mut CallContext, arg: CSSNumberish) -> WebIdlResult<Ref<Self>> {
+ // The CSSMathNegate(arg) constructor must, when called, perform the following steps:
+ // 1. Replace arg with the result of rectifying a numberish value for arg.
+ let vm = cx.vm();
+ let converted_value = rectify_a_numberish_value(vm, &arg, None);
+
+ // 2. Return a new CSSMathNegate whose value internal slot is set to arg.
+ Ok(Self::create(vm, converted_value))
+ }
+
+ pub(crate) fn math_value(&self) -> &CSSMathValue {
+ &self.math_value
+ }
+
+ pub(crate) fn inner_value(&self) -> AnyCSSNumericValue {
+ self.value
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathnegate-value
+ pub(crate) fn value(&self, _: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {
+ Ok(self.value)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmathvalue
+ pub(crate) fn serialize_math_value(&self, s: &mut String, nested: bool, parenless: bool) {
+ // NB: Only steps 1 and 4 apply here.
+ // 1. Let s initially be the empty string.
+
+ // 4. Otherwise, if this is a CSSMathNegate:
+ // 1. If paren-less is true, continue to the next step; otherwise, if nested is true, append "(" to s;
+ // otherwise, append "calc(" to s.
+ serialize_opening(s, nested, parenless);
+
+ // 2. Append "-" to s.
+ s.push('-');
+
+ // 3. Serialize this’s value internal slot with nested set to true, and append the result to s.
+ self.value.serialize(s, NESTED);
+
+ // 4. If paren-less is false, append ")" to s,
+ if !parenless {
+ s.push(')');
+ }
+
+ // 5. Return s.
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
+ pub(crate) fn create_a_sum_value(&self) -> Option<SumValue> {
+ // 1. Let values be the result of creating a sum value from this’s value internal slot.
+ // 2. If values is failure, return failure.
+ let mut values = self.value.create_a_sum_value()?;
+
+ // 3. Negate the value of each item of values.
+ for value in &mut values {
+ value.value = -value.value;
+ }
+
+ // 4. Return values.
+ Some(values)
+ }
+
+ pub(crate) fn create_calculation_node(&self) -> WebIdlResult<Arc<CalcNode>> {
+ Ok(Arc::new(CalcNode::Negate(self.value.create_calculation_node()?)))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_math_product.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_math_product.rs
new file mode 100644
index 00000000000..412498568fe
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_math_product.rs
@@ -0,0 +1,182 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSMathProduct, https://drafts.css-houdini.org/css-typed-om-1/#cssmathproduct
+
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::{MarkedVec, Trace, Vm};
+use libweb_rust::typed_om::{CalcNode, NumericType, SumValue, SumValueItem, UnitMap, product_of_two_unit_maps};
+
+use super::css_math_value::*;
+use super::css_numeric_array::CSSNumericArray;
+use super::css_numeric_value::{AnyCSSNumericValue, CSSNumberish};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSMathProduct {
+ math_value: CSSMathValue,
+ values: Ref<CSSNumericArray>,
+}
+
+impl Wrappable for CSSMathProduct {}
+
+impl Inherits<CSSMathValue> for CSSMathProduct {
+ fn parent(&self) -> &CSSMathValue {
+ &self.math_value
+ }
+}
+
+impl CSSMathProduct {
+ pub(crate) fn create(vm: &Vm, numeric_type: NumericType, values: Ref<CSSNumericArray>) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ math_value: CSSMathValue::new(CSSMathOperator::Product, numeric_type),
+ values,
+ });
+ AnyCSSNumericValue::CSSMathProduct(object).finish(vm);
+ object
+ }
+
+ pub(crate) fn multiply_all_types_into_math_product(
+ vm: &Vm,
+ values: &MarkedVec<'_, AnyCSSNumericValue>,
+ ) -> WebIdlResult<Ref<Self>> {
+ let Some(numeric_type) = multiply_all_types(&values.to_vec()) else {
+ return Err(Exception::type_error(
+ "Cannot create a CSSMathProduct with values of incompatible types",
+ ));
+ };
+ let values = CSSNumericArray::create(vm, values);
+ Ok(Self::create(vm, numeric_type, values))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathproduct-cssmathproduct
+ pub(crate) fn construct(cx: &mut CallContext, args: MarkedVec<'_, CSSNumberish>) -> WebIdlResult<Ref<Self>> {
+ // The CSSMathProduct(...args) constructor is defined identically to the above, except that in step 3 it
+ // multiplies the types instead of adding, and in the last step it returns a CSSMathProduct.
+
+ // 1. Replace each item of args with the result of rectifying a numberish value for the item.
+ let vm = cx.vm();
+ let values = rectify_numberish_values(vm, &args);
+
+ // 2. If args is empty, throw a SyntaxError.
+ if values.is_empty() {
+ return Err(Exception::syntax_error(Utf16String::from_utf8(
+ "Cannot create an empty CSSMathProduct",
+ )));
+ }
+
+ // 3. Let type be the result of multiplying the types of all the items of args. If type is failure, throw a TypeError.
+ // 4. Return a new CSSMathProduct whose values internal slot is set to args.
+ Self::multiply_all_types_into_math_product(vm, &values)
+ }
+
+ pub(crate) fn math_value(&self) -> &CSSMathValue {
+ &self.math_value
+ }
+
+ pub(crate) fn numeric_array(&self) -> Ref<CSSNumericArray> {
+ self.values
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathproduct-values
+ pub(crate) fn values(&self, _: &mut CallContext) -> WebIdlResult<Ref<CSSNumericArray>> {
+ Ok(self.values)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmathvalue
+ pub(crate) fn serialize_math_value(&self, s: &mut String, nested: bool, parenless: bool) {
+ // NB: Only steps 1 and 5 apply here.
+ // 1. Let s initially be the empty string.
+
+ // 5. Otherwise, if this is a CSSMathProduct:
+ // 1. If paren-less is true, continue to the next step; otherwise, if nested is true, append "(" to s;
+ // otherwise, append "calc(" to s.
+ serialize_opening(s, nested, parenless);
+
+ // 2. Serialize the first item in this’s values internal slot with nested set to true, and append the result
+ // to s.
+ let values = self.values.values();
+ values[0].serialize(s, NESTED);
+
+ // 3. For each arg in this’s values internal slot beyond the first:
+ for arg in &values[1..] {
+ // 1. If arg is a CSSMathInvert, append " / " to s, then serialize arg’s value internal slot with nested
+ // set to true, and append the result to s.
+ if let AnyCSSNumericValue::CSSMathInvert(invert) = arg {
+ s.push_str(" / ");
+ invert.inner_value().serialize(s, NESTED);
+ }
+ // 2. Otherwise, append " * " to s, then serialize arg with nested set to true, and append the result to s.
+ else {
+ s.push_str(" * ");
+ arg.serialize(s, NESTED);
+ }
+ }
+
+ // 4. If paren-less is false, append ")" to s,
+ if !parenless {
+ s.push(')');
+ }
+
+ // 5. Return s.
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
+ pub(crate) fn create_a_sum_value(&self) -> Option<SumValue> {
+ // 1. Let values initially be the sum value «(1, «[ ]»)». (I.e. what you’d get from 1.)
+ let mut values = vec![SumValueItem {
+ value: 1.0,
+ unit_map: UnitMap::new(),
+ }];
+
+ // 2. For each item in this’s values internal slot:
+ for item in self.values.values() {
+ // 1. Let new values be the result of creating a sum value from item.
+ // Let temp initially be an empty list.
+ // 2. If new values is failure, return failure.
+ let new_values = item.create_a_sum_value()?;
+ let mut temp = SumValue::new();
+
+ // 3. For each item1 in values:
+ for item1 in &values {
+ // 1. For each item2 in new values:
+ for item2 in &new_values {
+ // 1. Let item be a tuple with its value set to the product of the values of item1 and item2, and
+ // its unit map set to the product of the unit maps of item1 and item2, with all entries with a
+ // zero value removed.
+ let mut unit_map = product_of_two_unit_maps(&item1.unit_map, &item2.unit_map);
+ unit_map.retain(|_, power| *power != 0);
+
+ // 2. Append item to temp.
+ temp.push(SumValueItem {
+ value: item1.value * item2.value,
+ unit_map,
+ });
+ }
+ }
+
+ // 4. Set values to temp.
+ values = temp;
+ }
+
+ // 3. Return values.
+ Some(values)
+ }
+
+ pub(crate) fn create_calculation_node(&self) -> WebIdlResult<Arc<CalcNode>> {
+ let child_nodes = self
+ .values
+ .values()
+ .iter()
+ .map(AnyCSSNumericValue::create_calculation_node)
+ .collect::<WebIdlResult<Vec<_>>>()?;
+ Ok(Arc::new(CalcNode::Product(child_nodes)))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_math_sum.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_math_sum.rs
new file mode 100644
index 00000000000..f42143c2a9f
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_math_sum.rs
@@ -0,0 +1,174 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSMathSum, https://drafts.css-houdini.org/css-typed-om-1/#cssmathsum
+
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::{MarkedVec, Trace, Vm};
+use libweb_rust::typed_om::{CalcNode, NumericType, SumValue, create_a_type_from_a_unit_map};
+
+use super::css_math_value::*;
+use super::css_numeric_array::CSSNumericArray;
+use super::css_numeric_value::{AnyCSSNumericValue, CSSNumberish};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSMathSum {
+ math_value: CSSMathValue,
+ values: Ref<CSSNumericArray>,
+}
+
+impl Wrappable for CSSMathSum {}
+
+impl Inherits<CSSMathValue> for CSSMathSum {
+ fn parent(&self) -> &CSSMathValue {
+ &self.math_value
+ }
+}
+
+impl CSSMathSum {
+ pub(crate) fn create(vm: &Vm, numeric_type: NumericType, values: Ref<CSSNumericArray>) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ math_value: CSSMathValue::new(CSSMathOperator::Sum, numeric_type),
+ values,
+ });
+ AnyCSSNumericValue::CSSMathSum(object).finish(vm);
+ object
+ }
+
+ pub(crate) fn add_all_types_into_math_sum(
+ vm: &Vm,
+ values: &MarkedVec<'_, AnyCSSNumericValue>,
+ ) -> WebIdlResult<Ref<Self>> {
+ let Some(numeric_type) = add_all_types(&values.to_vec()) else {
+ return Err(Exception::type_error(
+ "Cannot create a CSSMathSum with values of incompatible types",
+ ));
+ };
+ let values = CSSNumericArray::create(vm, values);
+ Ok(Self::create(vm, numeric_type, values))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathsum-cssmathsum
+ pub(crate) fn construct(cx: &mut CallContext, args: MarkedVec<'_, CSSNumberish>) -> WebIdlResult<Ref<Self>> {
+ // The CSSMathSum(...args) constructor must, when called, perform the following steps:
+
+ // 1. Replace each item of args with the result of rectifying a numberish value for the item.
+ let vm = cx.vm();
+ let values = rectify_numberish_values(vm, &args);
+
+ // 2. If args is empty, throw a SyntaxError.
+ if values.is_empty() {
+ return Err(Exception::syntax_error(Utf16String::from_utf8(
+ "Cannot create an empty CSSMathSum",
+ )));
+ }
+
+ // 3. Let type be the result of adding the types of all the items of args. If type is failure, throw a TypeError.
+ // 4. Return a new CSSMathSum whose values internal slot is set to args.
+ Self::add_all_types_into_math_sum(vm, &values)
+ }
+
+ pub(crate) fn math_value(&self) -> &CSSMathValue {
+ &self.math_value
+ }
+
+ pub(crate) fn numeric_array(&self) -> Ref<CSSNumericArray> {
+ self.values
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathsum-values
+ pub(crate) fn values(&self, _: &mut CallContext) -> WebIdlResult<Ref<CSSNumericArray>> {
+ Ok(self.values)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmathvalue
+ pub(crate) fn serialize_math_value(&self, s: &mut String, nested: bool, parenless: bool) {
+ // NB: Only steps 1 and 3 apply here.
+ // 1. Let s initially be the empty string.
+
+ // 3. Otherwise, if this is a CSSMathSum:
+ // 1. If paren-less is true, continue to the next step; otherwise, if nested is true, append "(" to s;
+ // otherwise, append "calc(" to s.
+ serialize_opening(s, nested, parenless);
+
+ // 2. Serialize the first item in this’s values internal slot with nested set to true, and append the result
+ // to s.
+ let values = self.values.values();
+ values[0].serialize(s, NESTED);
+
+ // 3. For each arg in this's values internal slot beyond the first:
+ for arg in &values[1..] {
+ // 1. If arg is a CSSMathNegate, append " - " to s, then serialize arg’s value internal slot with nested
+ // set to true, and append the result to s.
+ if let AnyCSSNumericValue::CSSMathNegate(negate) = arg {
+ s.push_str(" - ");
+ negate.inner_value().serialize(s, NESTED);
+ }
+ // 2. Otherwise, append " + " to s, then serialize arg with nested set to true, and append the result to s.
+ else {
+ s.push_str(" + ");
+ arg.serialize(s, NESTED);
+ }
+ }
+
+ // 4. If paren-less is false, append ")" to s,
+ if !parenless {
+ s.push(')');
+ }
+
+ // 5. Return s.
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
+ pub(crate) fn create_a_sum_value(&self) -> Option<SumValue> {
+ // 1. Let values initially be an empty list.
+ let mut values = SumValue::new();
+
+ // 2. For each item in this’s values internal slot:
+ for item in self.values.values() {
+ // 1. Let value be the result of creating a sum value from item. If value is failure, return failure.
+ let value = item.create_a_sum_value()?;
+
+ // 2. For each subvalue of value:
+ for subvalue in value {
+ // 1. If values already contains an item with the same unit map as subvalue, increment that item’s
+ // value by the value of subvalue.
+ if let Some(existing_item) = values.iter_mut().find(|other| other.unit_map == subvalue.unit_map) {
+ existing_item.value += subvalue.value;
+ }
+ // 2. Otherwise, append subvalue to values.
+ else {
+ values.push(subvalue);
+ }
+ }
+ }
+
+ // 3. Create a type from the unit map of each item of values, and add all the types together.
+ // If the result is failure, return failure.
+ let mut added_type = create_a_type_from_a_unit_map(&values.first()?.unit_map)?;
+ for item in &values[1..] {
+ added_type = added_type.added_to(&create_a_type_from_a_unit_map(&item.unit_map)?)?;
+ }
+
+ // 4. Return values.
+ Some(values)
+ }
+
+ pub(crate) fn create_calculation_node(&self) -> WebIdlResult<Arc<CalcNode>> {
+ let child_nodes = self
+ .values
+ .values()
+ .iter()
+ .map(AnyCSSNumericValue::create_calculation_node)
+ .collect::<WebIdlResult<Vec<_>>>()?;
+ Ok(Arc::new(CalcNode::Sum(child_nodes)))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_math_value.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_math_value.rs
new file mode 100644
index 00000000000..cdb541a170b
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_math_value.rs
@@ -0,0 +1,157 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSMathValue, https://drafts.css-houdini.org/css-typed-om-1/#cssmathvalue
+
+use libjs_rust::api::{MarkedVec, Trace, Vm};
+use libweb_rust::typed_om::{NumericType, SumValue};
+
+use super::css_numeric_value::{
+ AnyCSSNumericValue, CSSNumberish, CSSNumericValue, SerializationParams, rectify_a_numberish_value,
+};
+use crate::bindings::interface::{Inherits, Wrappable};
+use crate::bindings::{CallContext, WebIdlResult};
+
+/// The enumeration CSSMathOperator of CSS/CSSMathValue.idl.
+#[derive(Clone, Copy, Eq, PartialEq)]
+pub(crate) enum CSSMathOperator {
+ Sum,
+ Product,
+ Negate,
+ Invert,
+ Min,
+ Max,
+ Clamp,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSMathValue {
+ numeric_value: CSSNumericValue,
+ #[gc(untraced)]
+ operator: CSSMathOperator,
+}
+
+impl Wrappable for CSSMathValue {}
+
+impl Inherits<CSSNumericValue> for CSSMathValue {
+ fn parent(&self) -> &CSSNumericValue {
+ &self.numeric_value
+ }
+}
+
+impl CSSMathValue {
+ pub(crate) fn new(operator: CSSMathOperator, numeric_type: NumericType) -> Self {
+ Self {
+ numeric_value: CSSNumericValue::new(numeric_type),
+ operator,
+ }
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathvalue-operator
+ pub(crate) fn operator(&self, _: &mut CallContext) -> WebIdlResult<CSSMathOperator> {
+ Ok(self.operator)
+ }
+}
+
+/// The result of rectifying a numberish value for each item of the arguments of a constructor.
+pub(crate) fn rectify_numberish_values<'vm>(
+ vm: &'vm Vm,
+ args: &MarkedVec<'_, CSSNumberish>,
+) -> MarkedVec<'vm, AnyCSSNumericValue> {
+ let values = MarkedVec::new(vm);
+ for value in args.values().iter() {
+ values.push(rectify_a_numberish_value(vm, value, None));
+ }
+ values
+}
+
+/// The result of adding the types of all the values, if that is not failure.
+pub(crate) fn add_all_types(values: &[AnyCSSNumericValue]) -> Option<NumericType> {
+ let (first, rest) = values.split_first().expect("a math value has at least one value");
+ rest.iter().try_fold(first.numeric_type(), |numeric_type, value| {
+ numeric_type.added_to(&value.numeric_type())
+ })
+}
+
+/// The result of multiplying the types of all the values, if that is not failure.
+pub(crate) fn multiply_all_types(values: &[AnyCSSNumericValue]) -> Option<NumericType> {
+ let (first, rest) = values.split_first().expect("a math value has at least one value");
+ rest.iter().try_fold(first.numeric_type(), |numeric_type, value| {
+ numeric_type.multiplied_by(&value.numeric_type())
+ })
+}
+
+/// What a math value that is not min(), max() or clamp() starts with: if paren-less is true, continue to the next step;
+/// otherwise, if nested is true, append "(" to s; otherwise, append "calc(" to s.
+pub(crate) fn serialize_opening(s: &mut String, nested: bool, parenless: bool) {
+ if parenless {
+ return;
+ }
+ s.push_str(if nested { "(" } else { "calc(" });
+}
+
+pub(crate) const NESTED: SerializationParams = SerializationParams {
+ minimum: None,
+ maximum: None,
+ nested: true,
+ parenless: false,
+};
+
+pub(crate) const NESTED_AND_PARENLESS: SerializationParams = SerializationParams {
+ minimum: None,
+ maximum: None,
+ nested: true,
+ parenless: true,
+};
+
+/// The steps that serialize a CSSMathMin or a CSSMathMax, https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmathvalue
+pub(crate) fn serialize_min_or_max(s: &mut String, function: &str, values: &[AnyCSSNumericValue]) {
+ // 2. If this is a CSSMathMin or CSSMathMax:
+ // 1. Append "min(" or "max(" to s, as appropriate.
+ s.push_str(function);
+ s.push('(');
+
+ // 2. For each arg in this’s values internal slot, serialize arg with nested and paren-less both true, and append
+ // the result to s, appending a ", " between successive values.
+ for (index, arg) in values.iter().enumerate() {
+ if index != 0 {
+ s.push_str(", ");
+ }
+ arg.serialize(s, NESTED_AND_PARENLESS);
+ }
+
+ // 3. Append ")" to s and return s.
+ s.push(')');
+}
+
+/// The steps that create a sum value from a CSSMathMin or a CSSMathMax, which end in the item that `is_better_than`
+/// prefers, https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
+pub(crate) fn min_or_max_sum_value(
+ values: &[AnyCSSNumericValue],
+ is_better_than: impl Fn(f64, f64) -> bool,
+) -> Option<SumValue> {
+ // 1. Let args be the result of creating a sum value for each item in this’s values internal slot.
+ let args: Vec<Option<SumValue>> = values.iter().map(AnyCSSNumericValue::create_a_sum_value).collect();
+
+ let mut best: Option<SumValue> = args.first()?.clone();
+ for item in &args {
+ // 2. If any item of args is failure, or has a length greater than one, return failure.
+ let item = item.as_ref().filter(|item| item.len() <= 1)?;
+
+ // 3. If not all of the unit maps among the items of args are identical, return failure.
+ let best_item = best.as_ref()?;
+ if item[0].unit_map != best_item[0].unit_map {
+ return None;
+ }
+ if is_better_than(item[0].value, best_item[0].value) {
+ best = Some(item.clone());
+ }
+ }
+
+ // 4. Return the item of args whose sole item has the smallest value.
+ best
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_matrix_component.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_matrix_component.rs
new file mode 100644
index 00000000000..4ff2ec74d65
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_matrix_component.rs
@@ -0,0 +1,163 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSMatrixComponent, https://drafts.css-houdini.org/css-typed-om-1/#cssmatrixcomponent
+
+use ak::Utf16String;
+use libjs_rust::api::{GcRefCell, Trace, Vm};
+use libweb_rust::typed_om::{NumericValue, RetainedStyleValue, TransformFunction, transformation_style_value};
+
+use super::css_transform_component::{AnyCSSTransformComponent, CSSTransformComponent, Is2D, create_dom_matrix};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::geometry::dom_matrix::DOMMatrix;
+use crate::geometry::dom_matrix_read_only::{AnyDOMMatrixReadOnly, DOMMatrixReadOnly};
+use crate::geometry::matrix::{ColumnMajor, Matrix4};
+
+// https://drafts.css-houdini.org/css-typed-om-1/#dictdef-cssmatrixcomponentoptions
+#[derive(Clone, Copy, Debug, Default)]
+pub(crate) struct CSSMatrixComponentOptions {
+ pub(crate) is2d: Option<bool>,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSMatrixComponent {
+ transform_component: CSSTransformComponent,
+ matrix: GcRefCell<Ref<DOMMatrix>>,
+}
+
+impl Wrappable for CSSMatrixComponent {}
+
+impl Inherits<CSSTransformComponent> for CSSMatrixComponent {
+ fn parent(&self) -> &CSSTransformComponent {
+ &self.transform_component
+ }
+}
+
+impl CSSMatrixComponent {
+ pub(crate) fn create(vm: &Vm, is_2d: Is2D, matrix: Ref<DOMMatrix>) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ transform_component: CSSTransformComponent::new(is_2d),
+ matrix: GcRefCell::new(matrix),
+ });
+ AnyCSSTransformComponent::CSSMatrixComponent(object).finish(vm);
+ object
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmatrixcomponent-cssmatrixcomponent
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ matrix: AnyDOMMatrixReadOnly,
+ options: CSSMatrixComponentOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ // The CSSMatrixComponent(matrix, options) constructor must, when invoked, perform the following steps:
+
+ // 1. Let this be a new CSSMatrixComponent object with its matrix internal slot set to matrix.
+ // NB: Done below.
+
+ // 2. If options was passed and has a is2D field, set this’s is2D internal slot to the value of that field.
+ // 3. Otherwise, set this’s is2D internal slot to the value of matrix’s is2D internal slot.
+ let is_2d = if options.is2d.unwrap_or(matrix.is_2d()) {
+ Is2D::Yes
+ } else {
+ Is2D::No
+ };
+
+ let vm = cx.vm();
+ let this = Self::create(vm, is_2d, create_dom_matrix(vm, matrix.matrix(), matrix.is_2d()));
+
+ // 4. Return this.
+ Ok(this)
+ }
+
+ /// The elements m11, m12, m13, m14, m21, ..., m44 of the matrix internal slot.
+ fn elements(&self) -> [f64; 16] {
+ let matrix = *self.matrix.borrow();
+ <DOMMatrix as Inherits<DOMMatrixReadOnly>>::parent(&matrix)
+ .matrix()
+ .to_column_major()
+ }
+
+ pub(crate) fn matrix(&self, _: &mut CallContext) -> WebIdlResult<Ref<DOMMatrix>> {
+ Ok(*self.matrix.borrow())
+ }
+
+ pub(crate) fn set_matrix(&self, cx: &mut CallContext, matrix: Ref<DOMMatrix>) -> WebIdlResult<()> {
+ // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
+ // FIXME: Should this modify is_2d? Or should we modify the matrix's is_2d?
+ *self.matrix.borrow_mut(cx.vm()) = matrix;
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmatrixcomponent
+ pub(crate) fn serialize(&self) -> WebIdlResult<Utf16String> {
+ // 1. Return the serialization of this’s matrix internal slot.
+ // FIXME: This means we ignore our is_2d state. https://github.com/w3c/css-houdini-drafts/issues/1155
+ let matrix = *self.matrix.borrow();
+ <DOMMatrix as Inherits<DOMMatrixReadOnly>>::parent(&matrix)
+ .stringify()
+ .ok_or_else(|| {
+ Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_ascii(b"Cannot stringify non-finite matrix values"),
+ )
+ })
+ }
+
+ pub(crate) fn to_matrix(&self, vm: &Vm) -> Ref<DOMMatrix> {
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformcomponent-tomatrix
+ // 1. Let matrix be a new DOMMatrix object, initialized to this’s equivalent 4x4 transform matrix, as defined in
+ // CSS Transforms 1 § 12. Mathematical Description of Transform Functions, and with its is2D internal slot
+ // set to the same value as this’s is2D internal slot.
+ // NB: The elements are m11, m12, m13, m14, m21, ..., m44. A 2D component only uses m11, m12, m21, m22, m41 and
+ // m42.
+ let is_2d = self.transform_component.raw_is_2d();
+ let mut elements = self.elements();
+ if is_2d {
+ elements = [
+ elements[0],
+ elements[1],
+ 0.0,
+ 0.0,
+ elements[4],
+ elements[5],
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 1.0,
+ 0.0,
+ elements[12],
+ elements[13],
+ 0.0,
+ 1.0,
+ ];
+ }
+
+ // 2. Return matrix.
+ create_dom_matrix(vm, Matrix4::from_column_major(elements), is_2d)
+ }
+
+ pub(crate) fn create_style_value(&self, property_id: u16) -> RetainedStyleValue {
+ // NB: The elements are m11, m12, m13, m14, m21, ..., m44, and the elements a to f of a 2D matrix are m11, m12,
+ // m21, m22, m41 and m42.
+ let elements = self.elements();
+ if self.transform_component.raw_is_2d() {
+ let values = [0, 1, 4, 5, 12, 13]
+ .into_iter()
+ .map(|index| NumericValue::Number(elements[index]).style_value())
+ .collect();
+ return transformation_style_value(property_id, TransformFunction::Matrix, values);
+ }
+
+ let values = elements
+ .into_iter()
+ .map(|element| NumericValue::Number(element).style_value())
+ .collect();
+ transformation_style_value(property_id, TransformFunction::Matrix3d, values)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_numeric_array.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_numeric_array.rs
new file mode 100644
index 00000000000..faa9945b63b
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_numeric_array.rs
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSNumericArray, https://drafts.css-houdini.org/css-typed-om-1/#cssnumericarray
+
+use libjs_rust::api::{MarkedVec, Trace, Vm};
+
+use super::css_numeric_value::AnyCSSNumericValue;
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSNumericArray {
+ values: Vec<AnyCSSNumericValue>,
+}
+
+impl Wrappable for CSSNumericArray {}
+
+impl CSSNumericArray {
+ pub(crate) fn create(vm: &Vm, values: &MarkedVec<'_, AnyCSSNumericValue>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ values: values.to_vec(),
+ })
+ }
+
+ pub(crate) fn values(&self) -> &[AnyCSSNumericValue] {
+ &self.values
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericarray-length
+ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ // The length attribute of CSSNumericArray indicates how many CSSNumericValues are contained within the
+ // CSSNumericArray.
+ Ok(u32::try_from(self.values.len()).expect("the array has fewer items than an index can name"))
+ }
+
+ pub(crate) fn item(&self, _: &mut CallContext, index: u32) -> WebIdlResult<AnyCSSNumericValue> {
+ Ok(self.values[index as usize])
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#equal-numeric-value
+ pub(crate) fn is_equal_numeric_values(&self, other: &Self) -> bool {
+ // NB: This is just step 3, moved here to reduce repetition.
+ // 3. If value1 and value2 are both CSSMathSums, CSSMathProducts, CSSMathMins, or CSSMathMaxs:
+ // 1. If value1’s values and value2s values internal slots have different sizes, return false.
+ if self.values.len() != other.values.len() {
+ return false;
+ }
+
+ // 2. If any item in value1’s values internal slot is not an equal numeric value to the item in value2’s values
+ // internal slot at the same index, return false.
+ // 3. Return true.
+ self.values
+ .iter()
+ .zip(&other.values)
+ .all(|(first, second)| first.is_equal_numeric_value(second))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_numeric_value.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_numeric_value.rs
new file mode 100644
index 00000000000..5c196e0ab7b
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_numeric_value.rs
@@ -0,0 +1,730 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSNumericValue, https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue
+
+use core::ops::Deref;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::{MarkedVec, ThrowCompletionOr, Trace, Value, Vm};
+use libweb_rust::typed_om::{
+ BASE_TYPE_ANGLE, BASE_TYPE_FLEX, BASE_TYPE_FREQUENCY, BASE_TYPE_LENGTH, BASE_TYPE_PERCENT, BASE_TYPE_RESOLUTION,
+ BASE_TYPE_TIME, CalcNode, NumericType, RetainedStyleValue, SumValue, create_a_type_from_unit,
+};
+
+use super::css_math_clamp::CSSMathClamp;
+use super::css_math_invert::CSSMathInvert;
+use super::css_math_max::CSSMathMax;
+use super::css_math_min::CSSMathMin;
+use super::css_math_negate::CSSMathNegate;
+use super::css_math_product::CSSMathProduct;
+use super::css_math_sum::CSSMathSum;
+use super::css_math_value::CSSMathValue;
+use super::css_style_value::{AnyCSSStyleValue, CSSStyleValue, PerformTypeCheck};
+use super::css_unit_value::CSSUnitValue;
+use super::typed_om;
+use crate::bindings::conversions::{ToJs, UsvString};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, wrap};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+/// The enumeration CSSNumericBaseType of CSS/CSSNumericValue.idl.
+#[derive(Clone, Copy, Eq, PartialEq)]
+pub(crate) enum CSSNumericBaseType {
+ Length,
+ Angle,
+ Time,
+ Frequency,
+ Resolution,
+ Flex,
+ Percent,
+}
+
+/// The dictionary CSSNumericType of CSS/CSSNumericValue.idl.
+#[derive(Default)]
+pub(crate) struct CSSNumericType {
+ pub(crate) length: Option<i32>,
+ pub(crate) angle: Option<i32>,
+ pub(crate) time: Option<i32>,
+ pub(crate) frequency: Option<i32>,
+ pub(crate) resolution: Option<i32>,
+ pub(crate) flex: Option<i32>,
+ pub(crate) percent: Option<i32>,
+ pub(crate) percent_hint: Option<CSSNumericBaseType>,
+}
+
+/// The union (double or CSSNumericValue) of CSS/CSSNumericValue.idl.
+#[derive(Clone, Copy, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) enum CSSNumberish {
+ Double(#[gc(untraced)] f64),
+ CSSNumericValue(AnyCSSNumericValue),
+}
+
+/// An object of CSSNumericValue or of an interface that inherits from it.
+#[derive(Clone, Copy, Trace)]
+#[gc(crate = libjs_rust)]
+#[expect(clippy::enum_variant_names, reason = "the variants are named after the interfaces")]
+pub(crate) enum AnyCSSNumericValue {
+ CSSNumericValue(Ref<CSSNumericValue>),
+ CSSMathClamp(Ref<CSSMathClamp>),
+ CSSMathInvert(Ref<CSSMathInvert>),
+ CSSMathMax(Ref<CSSMathMax>),
+ CSSMathMin(Ref<CSSMathMin>),
+ CSSMathNegate(Ref<CSSMathNegate>),
+ CSSMathProduct(Ref<CSSMathProduct>),
+ CSSMathSum(Ref<CSSMathSum>),
+ CSSMathValue(Ref<CSSMathValue>),
+ CSSUnitValue(Ref<CSSUnitValue>),
+}
+
+impl From<AnyCSSNumericValue> for AnyCSSStyleValue {
+ fn from(value: AnyCSSNumericValue) -> Self {
+ match value {
+ AnyCSSNumericValue::CSSNumericValue(object) => Self::CSSNumericValue(object),
+ AnyCSSNumericValue::CSSMathClamp(object) => Self::CSSMathClamp(object),
+ AnyCSSNumericValue::CSSMathInvert(object) => Self::CSSMathInvert(object),
+ AnyCSSNumericValue::CSSMathMax(object) => Self::CSSMathMax(object),
+ AnyCSSNumericValue::CSSMathMin(object) => Self::CSSMathMin(object),
+ AnyCSSNumericValue::CSSMathNegate(object) => Self::CSSMathNegate(object),
+ AnyCSSNumericValue::CSSMathProduct(object) => Self::CSSMathProduct(object),
+ AnyCSSNumericValue::CSSMathSum(object) => Self::CSSMathSum(object),
+ AnyCSSNumericValue::CSSMathValue(object) => Self::CSSMathValue(object),
+ AnyCSSNumericValue::CSSUnitValue(object) => Self::CSSUnitValue(object),
+ }
+ }
+}
+
+impl Deref for AnyCSSNumericValue {
+ type Target = CSSNumericValue;
+
+ fn deref(&self) -> &CSSNumericValue {
+ match self {
+ Self::CSSNumericValue(object) => object,
+ Self::CSSMathClamp(object) => object.math_value().parent(),
+ Self::CSSMathInvert(object) => object.math_value().parent(),
+ Self::CSSMathMax(object) => object.math_value().parent(),
+ Self::CSSMathMin(object) => object.math_value().parent(),
+ Self::CSSMathNegate(object) => object.math_value().parent(),
+ Self::CSSMathProduct(object) => object.math_value().parent(),
+ Self::CSSMathSum(object) => object.math_value().parent(),
+ Self::CSSMathValue(object) => <CSSMathValue as Inherits<CSSNumericValue>>::parent(object),
+ Self::CSSUnitValue(object) => <CSSUnitValue as Inherits<CSSNumericValue>>::parent(object),
+ }
+ }
+}
+
+impl ToJs for AnyCSSNumericValue {
+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {
+ Ok(Value::from_object(match self {
+ Self::CSSNumericValue(object) => wrap(cx, object),
+ Self::CSSMathClamp(object) => wrap(cx, object),
+ Self::CSSMathInvert(object) => wrap(cx, object),
+ Self::CSSMathMax(object) => wrap(cx, object),
+ Self::CSSMathMin(object) => wrap(cx, object),
+ Self::CSSMathNegate(object) => wrap(cx, object),
+ Self::CSSMathProduct(object) => wrap(cx, object),
+ Self::CSSMathSum(object) => wrap(cx, object),
+ Self::CSSMathValue(object) => wrap(cx, object),
+ Self::CSSUnitValue(object) => wrap(cx, object),
+ }))
+ }
+}
+
+/// The arguments of the serialization of a CSSNumericValue,
+/// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssnumericvalue
+#[derive(Clone, Copy, Default)]
+pub(crate) struct SerializationParams {
+ pub(crate) minimum: Option<f64>,
+ pub(crate) maximum: Option<f64>,
+ pub(crate) nested: bool,
+ pub(crate) parenless: bool,
+}
+
+impl AnyCSSNumericValue {
+ /// The object as the unit value that it is, if it is one.
+ pub(crate) fn as_unit_value(&self) -> Option<Ref<CSSUnitValue>> {
+ match self {
+ Self::CSSUnitValue(object) => Some(*object),
+ _ => None,
+ }
+ }
+
+ pub(crate) fn numeric_value_style_value(&self) -> &CSSStyleValue {
+ self.deref().parent()
+ }
+
+ /// Tells the part of the object that all CSSStyleValues have which object it is the part of.
+ pub(crate) fn finish(self, vm: &Vm) -> Self {
+ self.numeric_value_style_value().set_object(vm, self.into());
+ self
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#equal-numeric-value
+ pub(crate) fn is_equal_numeric_value(&self, other: &Self) -> bool {
+ // 1. If value1 and value2 are not members of the same interface, return false.
+ // NB: The steps of each interface return false for an object of another.
+ match (self, other) {
+ (Self::CSSUnitValue(first), Self::CSSUnitValue(second)) => first.is_equal_unit_value(second),
+ (Self::CSSMathSum(first), Self::CSSMathSum(second)) => {
+ first.numeric_array().is_equal_numeric_values(&second.numeric_array())
+ }
+ (Self::CSSMathProduct(first), Self::CSSMathProduct(second)) => {
+ first.numeric_array().is_equal_numeric_values(&second.numeric_array())
+ }
+ (Self::CSSMathMin(first), Self::CSSMathMin(second)) => {
+ first.numeric_array().is_equal_numeric_values(&second.numeric_array())
+ }
+ (Self::CSSMathMax(first), Self::CSSMathMax(second)) => {
+ first.numeric_array().is_equal_numeric_values(&second.numeric_array())
+ }
+ // 4. Assert: value1 and value2 are both CSSMathNegates or CSSMathInverts.
+ // 5. Return whether value1’s value and value2’s value are equal numeric values.
+ (Self::CSSMathNegate(first), Self::CSSMathNegate(second)) => {
+ first.inner_value().is_equal_numeric_value(&second.inner_value())
+ }
+ (Self::CSSMathInvert(first), Self::CSSMathInvert(second)) => {
+ first.inner_value().is_equal_numeric_value(&second.inner_value())
+ }
+ (Self::CSSMathClamp(first), Self::CSSMathClamp(second)) => first.is_equal_clamp(second),
+ _ => false,
+ }
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
+ pub(crate) fn create_a_sum_value(&self) -> Option<SumValue> {
+ match self {
+ Self::CSSNumericValue(_) | Self::CSSMathValue(_) => {
+ unreachable!("no object is only of an abstract interface")
+ }
+ Self::CSSMathClamp(object) => object.create_a_sum_value(),
+ Self::CSSMathInvert(object) => object.create_a_sum_value(),
+ Self::CSSMathMax(object) => object.create_a_sum_value(),
+ Self::CSSMathMin(object) => object.create_a_sum_value(),
+ Self::CSSMathNegate(object) => object.create_a_sum_value(),
+ Self::CSSMathProduct(object) => object.create_a_sum_value(),
+ Self::CSSMathSum(object) => object.create_a_sum_value(),
+ Self::CSSUnitValue(object) => Some(object.create_a_sum_value()),
+ }
+ }
+
+ pub(crate) fn create_calculation_node(&self) -> WebIdlResult<Arc<CalcNode>> {
+ match self {
+ Self::CSSNumericValue(_) | Self::CSSMathValue(_) => {
+ unreachable!("no object is only of an abstract interface")
+ }
+ Self::CSSMathClamp(object) => object.create_calculation_node(),
+ Self::CSSMathInvert(object) => object.create_calculation_node(),
+ Self::CSSMathMax(object) => object.create_calculation_node(),
+ Self::CSSMathMin(object) => object.create_calculation_node(),
+ Self::CSSMathNegate(object) => object.create_calculation_node(),
+ Self::CSSMathProduct(object) => object.create_calculation_node(),
+ Self::CSSMathSum(object) => object.create_calculation_node(),
+ Self::CSSUnitValue(object) => object.create_calculation_node(),
+ }
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssnumericvalue
+ pub(crate) fn serialize(&self, s: &mut String, params: SerializationParams) {
+ // To serialize a CSSNumericValue this, given an optional minimum, a numeric value, and optional maximum, a
+ // numeric value:
+ // 1. If this is a CSSUnitValue, serialize a CSSUnitValue from this, passing minimum and maximum. Return the
+ // result.
+ // 2. Otherwise, serialize a CSSMathValue from this, and return the result.
+ let (nested, parenless) = (params.nested, params.parenless);
+ match self {
+ Self::CSSNumericValue(_) | Self::CSSMathValue(_) => {
+ unreachable!("no object is only of an abstract interface")
+ }
+ Self::CSSUnitValue(object) => object.serialize_unit_value(s, params.minimum, params.maximum),
+ Self::CSSMathClamp(object) => object.serialize_math_value(s),
+ Self::CSSMathInvert(object) => object.serialize_math_value(s, nested, parenless),
+ Self::CSSMathMax(object) => object.serialize_math_value(s),
+ Self::CSSMathMin(object) => object.serialize_math_value(s),
+ Self::CSSMathNegate(object) => object.serialize_math_value(s, nested, parenless),
+ Self::CSSMathProduct(object) => object.serialize_math_value(s, nested, parenless),
+ Self::CSSMathSum(object) => object.serialize_math_value(s, nested, parenless),
+ }
+ }
+
+ pub(crate) fn to_string_with(self, params: SerializationParams) -> String {
+ let mut s = String::new();
+ self.serialize(&mut s, params);
+ s
+ }
+
+ pub(crate) fn to_css_string(self) -> Utf16String {
+ Utf16String::from_utf8(&self.to_string_with(SerializationParams::default()))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+ pub(crate) fn math_value_internal_representation(
+ &self,
+ property_id: u16,
+ perform_type_check: PerformTypeCheck,
+ ) -> WebIdlResult<RetainedStyleValue> {
+ // If value is a CSSStyleValue subclass,
+ // If value does not match the grammar of a list-valued property iteration of property, throw a TypeError.
+ //
+ // If any component of property’s CSS grammar has a limited numeric range, and the corresponding part of
+ // value is a CSSUnitValue that is outside of that range, replace that value with the result of wrapping it
+ // in a fresh CSSMathSum whose values internal slot contains only that part of value.
+ //
+ // Return the value.
+ let node = self.create_calculation_node()?;
+ typed_om::calculated_style_value(property_id, node, self.numeric_type(), perform_type_check)
+ .ok_or_else(|| Exception::type_error("Property does not accept values of this type."))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#cssmath-negate-a-cssnumericvalue
+ pub(crate) fn negate(&self, vm: &Vm) -> Self {
+ // 1. If this is a CSSMathNegate object, return this’s value internal slot.
+ if let Self::CSSMathNegate(negate) = self {
+ return negate.inner_value();
+ }
+
+ // 2. If this is a CSSUnitValue object, return a new CSSUnitValue with the same unit internal slot as this, and
+ // a value internal slot set to the negation of this’s.
+ if let Self::CSSUnitValue(unit_value) = self {
+ return Self::CSSUnitValue(CSSUnitValue::create(vm, -unit_value.raw_value(), unit_value.raw_unit()));
+ }
+
+ // 3. Otherwise, return a new CSSMathNegate object whose value internal slot is set to this.
+ Self::CSSMathNegate(CSSMathNegate::create(vm, *self))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#cssmath-invert-a-cssnumericvalue
+ pub(crate) fn invert(&self, vm: &Vm) -> WebIdlResult<Self> {
+ // 1. If this is a CSSMathInvert object, return this’s value internal slot.
+ if let Self::CSSMathInvert(invert) = self {
+ return Ok(invert.inner_value());
+ }
+
+ // 2. If this is a CSSUnitValue object with unit internal slot set to "number":
+ if let Self::CSSUnitValue(unit_value) = self
+ && unit_value.raw_unit() == "number"
+ {
+ // 1. If this’s value internal slot is set to 0 or -0, throw a RangeError.
+ if unit_value.raw_value() == 0.0 {
+ return Err(Exception::range_error("Zero has no multiplicative inverse"));
+ }
+
+ // 2. Else return a new CSSUnitValue with the unit internal slot set to "number", and a value internal slot
+ // set to 1 divided by this’s {CSSUnitValue/value}} internal slot.
+ return Ok(Self::CSSUnitValue(CSSUnitValue::create(
+ vm,
+ 1.0 / unit_value.raw_value(),
+ "number",
+ )));
+ }
+
+ // 3. Otherwise, return a new CSSMathInvert object whose value internal slot is set to this.
+ Ok(Self::CSSMathInvert(CSSMathInvert::create(vm, *self)))
+ }
+
+ /// The values of this object if it is of the interface that an operation makes, or this object, as the first steps
+ /// of add(), mul(), min() and max() prepend them to values.
+ fn with_rectified_values<'vm>(
+ &self,
+ vm: &'vm Vm,
+ own_values: Option<&[Self]>,
+ initial_values: &MarkedVec<'_, CSSNumberish>,
+ ) -> MarkedVec<'vm, Self> {
+ // 1. Replace each item of values with the result of rectifying a numberish value for the item.
+ // 2. If this is a CSSMathSum object, prepend the items in this’s values internal slot to values.
+ // Otherwise, prepend this to values.
+ // NB: We reorder the steps a little to avoid the awkward prepending.
+ let values = MarkedVec::new(vm);
+ match own_values {
+ Some(own_values) => values.extend_from_slice(own_values),
+ None => values.push(*self),
+ }
+ for value in initial_values.values().iter() {
+ values.push(rectify_a_numberish_value(vm, value, None));
+ }
+ values
+ }
+
+ fn add(&self, vm: &Vm, initial_values: &MarkedVec<'_, CSSNumberish>) -> WebIdlResult<Self> {
+ let own_values = match self {
+ Self::CSSMathSum(math_sum) => Some(math_sum.numeric_array()),
+ _ => None,
+ };
+ let own_values = own_values.as_ref().map(|array| array.values());
+ let values = self.with_rectified_values(vm, own_values, initial_values);
+
+ // 3. If all of the items in values are CSSUnitValues and have the same unit, return a new CSSUnitValue whose
+ // unit internal slot is set to that unit, and value internal slot is set to the sum of the value internal
+ // slots of the items in values. This addition must be done "left to right" - if values is « 1, 2, 3, 4 »,
+ // the result must be (((1 + 2) + 3) + 4). (This detail is necessary to ensure interoperability in the
+ // presence of floating-point arithmetic.)
+ if let Some(result) = apply_math_operation_on_css_unit_values(vm, &values, |a, b| a + b) {
+ return Ok(result);
+ }
+
+ // 4. Let type be the result of adding the types of every item in values. If type is failure, throw a TypeError.
+ // 5. Return a new CSSMathSum object whose values internal slot is set to values.
+ Ok(Self::CSSMathSum(CSSMathSum::add_all_types_into_math_sum(vm, &values)?))
+ }
+
+ fn mul(&self, vm: &Vm, initial_values: &MarkedVec<'_, CSSNumberish>) -> WebIdlResult<Self> {
+ let own_values = match self {
+ Self::CSSMathProduct(math_product) => Some(math_product.numeric_array()),
+ _ => None,
+ };
+ let own_values = own_values.as_ref().map(|array| array.values());
+ let values = self.with_rectified_values(vm, own_values, initial_values);
+
+ // 3. If all of the items in values are CSSUnitValues with unit internal slot set to "number", return a new
+ // CSSUnitValue whose unit internal slot is set to "number", and value internal slot is set to the product of
+ // the value internal slots of the items in values.
+ //
+ // This multiplication must be done "left to right" - if values is « 1, 2, 3, 4 », the result must be
+ // (((1 × 2) × 3) × 4). (This detail is necessary to ensure interoperability in the presence of
+ // floating-point arithmetic.)
+ //
+ // 4. If all of the items in values are CSSUnitValues with unit internal slot set to "number" except one which
+ // is set to unit, return a new CSSUnitValue whose unit internal slot is set to unit, and value internal slot
+ // is set to the product of the value internal slots of the items in values.
+ //
+ // This multiplication must be done "left to right" - if values is « 1, 2, 3, 4 », the result must be
+ // (((1 × 2) × 3) × 4).
+ if let Some(unit_values) = css_unit_values_of(vm, &values) {
+ let unit_values = unit_values.values();
+ let mut other_units = unit_values.iter().filter(|value| value.raw_unit() != "number");
+ let first_other_unit = other_units.next();
+ if other_units.next().is_none() {
+ let product = unit_values
+ .iter()
+ .fold(1.0, |product, value| product * value.raw_value());
+ let unit = first_other_unit.map_or("number", |value| value.raw_unit());
+ return Ok(Self::CSSUnitValue(CSSUnitValue::create(vm, product, unit)));
+ }
+ }
+
+ // 5. Let type be the result of multiplying the types of every item in values. If type is failure, throw a
+ // TypeError.
+ // 6. Return a new CSSMathProduct object whose values internal slot is set to values.
+ Ok(Self::CSSMathProduct(
+ CSSMathProduct::multiply_all_types_into_math_product(vm, &values)?,
+ ))
+ }
+}
+
+/// The CSSUnitValues of the values, if that is all they are.
+fn css_unit_values_of<'vm>(
+ vm: &'vm Vm,
+ values: &MarkedVec<'_, AnyCSSNumericValue>,
+) -> Option<MarkedVec<'vm, Ref<CSSUnitValue>>> {
+ let unit_values = MarkedVec::with_capacity(vm, values.len());
+ for value in values.values().iter() {
+ unit_values.push(value.as_unit_value()?);
+ }
+ Some(unit_values)
+}
+
+/// Whether all of the values are CSSUnitValues with the same unit, in which case the operation runs over them from left
+/// to right, and the new CSSUnitValue that results.
+fn apply_math_operation_on_css_unit_values(
+ vm: &Vm,
+ values: &MarkedVec<'_, AnyCSSNumericValue>,
+ operation: impl Fn(f64, f64) -> f64,
+) -> Option<AnyCSSNumericValue> {
+ let unit_values = css_unit_values_of(vm, values)?;
+ let unit_values = unit_values.values();
+ let (first, rest) = unit_values.split_first().expect("an operation has at least one value");
+ if rest.iter().any(|value| value.raw_unit() != first.raw_unit()) {
+ return None;
+ }
+ let result = rest
+ .iter()
+ .fold(first.raw_value(), |result, value| operation(result, value.raw_value()));
+ Some(AnyCSSNumericValue::CSSUnitValue(CSSUnitValue::create(
+ vm,
+ result,
+ first.raw_unit(),
+ )))
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#rectify-a-numberish-value
+pub(crate) fn rectify_a_numberish_value(vm: &Vm, numberish: &CSSNumberish, unit: Option<&str>) -> AnyCSSNumericValue {
+ match numberish {
+ CSSNumberish::CSSNumericValue(value) => *value,
+ CSSNumberish::Double(value) => {
+ AnyCSSNumericValue::CSSUnitValue(CSSUnitValue::create(vm, *value, unit.unwrap_or("number")))
+ }
+ }
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSNumericValue {
+ style_value: CSSStyleValue,
+ // https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue-type
+ #[gc(untraced)]
+ numeric_type: NumericType,
+}
+
+impl Wrappable for CSSNumericValue {}
+
+impl Inherits<CSSStyleValue> for CSSNumericValue {
+ fn parent(&self) -> &CSSStyleValue {
+ &self.style_value
+ }
+}
+
+fn to_om_numeric_base_type(base_type: usize) -> CSSNumericBaseType {
+ match base_type {
+ BASE_TYPE_LENGTH => CSSNumericBaseType::Length,
+ BASE_TYPE_ANGLE => CSSNumericBaseType::Angle,
+ BASE_TYPE_TIME => CSSNumericBaseType::Time,
+ BASE_TYPE_FREQUENCY => CSSNumericBaseType::Frequency,
+ BASE_TYPE_RESOLUTION => CSSNumericBaseType::Resolution,
+ BASE_TYPE_FLEX => CSSNumericBaseType::Flex,
+ BASE_TYPE_PERCENT => CSSNumericBaseType::Percent,
+ _ => unreachable!("a numeric type has seven base types"),
+ }
+}
+
+impl CSSNumericValue {
+ pub(crate) fn new(numeric_type: NumericType) -> Self {
+ Self {
+ style_value: CSSStyleValue::empty(),
+ numeric_type,
+ }
+ }
+
+ pub(crate) fn numeric_type(&self) -> NumericType {
+ self.numeric_type
+ }
+
+ /// The object that this is the CSSNumericValue part of.
+ fn this(&self) -> AnyCSSNumericValue {
+ self.style_value.object().as_numeric().expect("the object is numeric")
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-add
+ pub(crate) fn add(
+ &self,
+ cx: &mut CallContext,
+ values: MarkedVec<'_, CSSNumberish>,
+ ) -> WebIdlResult<AnyCSSNumericValue> {
+ self.this().add(cx.vm(), &values)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-sub
+ pub(crate) fn sub(
+ &self,
+ cx: &mut CallContext,
+ initial_values: MarkedVec<'_, CSSNumberish>,
+ ) -> WebIdlResult<AnyCSSNumericValue> {
+ // 1. Replace each item of values with the result of rectifying a numberish value for the item, then negating
+ // the value.
+ let vm = cx.vm();
+ let values = MarkedVec::new(vm);
+ for value in initial_values.values().iter() {
+ values.push(CSSNumberish::CSSNumericValue(
+ rectify_a_numberish_value(vm, value, None).negate(vm),
+ ));
+ }
+
+ // 2. Return the result of calling the add() internal algorithm with this and values.
+ self.this().add(vm, &values)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-mul
+ pub(crate) fn mul(
+ &self,
+ cx: &mut CallContext,
+ values: MarkedVec<'_, CSSNumberish>,
+ ) -> WebIdlResult<AnyCSSNumericValue> {
+ self.this().mul(cx.vm(), &values)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-div
+ pub(crate) fn div(
+ &self,
+ cx: &mut CallContext,
+ initial_values: MarkedVec<'_, CSSNumberish>,
+ ) -> WebIdlResult<AnyCSSNumericValue> {
+ // 1. Replace each item of values with the result of rectifying a numberish value for the item, then inverting
+ // the value.
+ let vm = cx.vm();
+ let values = MarkedVec::new(vm);
+ for value in initial_values.values().iter() {
+ values.push(CSSNumberish::CSSNumericValue(
+ rectify_a_numberish_value(vm, value, None).invert(vm)?,
+ ));
+ }
+
+ // 2. Return the result of calling the mul() internal algorithm with this and values.
+ self.this().mul(vm, &values)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-min
+ pub(crate) fn min(
+ &self,
+ cx: &mut CallContext,
+ initial_values: MarkedVec<'_, CSSNumberish>,
+ ) -> WebIdlResult<AnyCSSNumericValue> {
+ let vm = cx.vm();
+ let this = self.this();
+ let own_values = match this {
+ AnyCSSNumericValue::CSSMathMin(math_min) => Some(math_min.numeric_array()),
+ _ => None,
+ };
+ let own_values = own_values.as_ref().map(|array| array.values());
+ let values = this.with_rectified_values(vm, own_values, &initial_values);
+
+ // 3. If all of the items in values are CSSUnitValues and have the same unit, return a new CSSUnitValue whose
+ // unit internal slot is set to that unit, and value internal slot is set to the minimum of the value
+ // internal slots of the items in values.
+ if let Some(result) = apply_math_operation_on_css_unit_values(vm, &values, |a, b| if b < a { b } else { a }) {
+ return Ok(result);
+ }
+
+ // 4. Let type be the result of adding the types of every item in values. If type is failure, throw a TypeError.
+ // 5. Return a new CSSMathMin object whose values internal slot is set to values.
+ Ok(AnyCSSNumericValue::CSSMathMin(CSSMathMin::add_all_types_into_math_min(
+ vm, &values,
+ )?))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-max
+ pub(crate) fn max(
+ &self,
+ cx: &mut CallContext,
+ initial_values: MarkedVec<'_, CSSNumberish>,
+ ) -> WebIdlResult<AnyCSSNumericValue> {
+ let vm = cx.vm();
+ let this = self.this();
+ let own_values = match this {
+ AnyCSSNumericValue::CSSMathMax(math_max) => Some(math_max.numeric_array()),
+ _ => None,
+ };
+ let own_values = own_values.as_ref().map(|array| array.values());
+ let values = this.with_rectified_values(vm, own_values, &initial_values);
+
+ // 3. If all of the items in values are CSSUnitValues and have the same unit, return a new CSSUnitValue whose
+ // unit internal slot is set to that unit, and value internal slot is set to the maximum of the value
+ // internal slots of the items in values.
+ if let Some(result) = apply_math_operation_on_css_unit_values(vm, &values, |a, b| if a < b { b } else { a }) {
+ return Ok(result);
+ }
+
+ // 4. Let type be the result of adding the types of every item in values. If type is failure, throw a TypeError.
+ // 5. Return a new CSSMathMax object whose values internal slot is set to values.
+ Ok(AnyCSSNumericValue::CSSMathMax(CSSMathMax::add_all_types_into_math_max(
+ vm, &values,
+ )?))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-equals
+ pub(crate) fn equals_for_bindings(
+ &self,
+ cx: &mut CallContext,
+ values: MarkedVec<'_, CSSNumberish>,
+ ) -> WebIdlResult<bool> {
+ // The equals(...values) method, when called on a CSSNumericValue this, must perform the following steps:
+
+ // 1. Replace each item of values with the result of rectifying a numberish value for the item.
+ // 2. For each item in values, if the item is not an equal numeric value to this, return false.
+ let this = self.this();
+ for value in values.values().iter() {
+ let rectified_value = rectify_a_numberish_value(cx.vm(), value, None);
+ if !this.is_equal_numeric_value(&rectified_value) {
+ return Ok(false);
+ }
+ }
+
+ // 3. Return true.
+ Ok(true)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-to
+ pub(crate) fn to(&self, cx: &mut CallContext, unit: UsvString) -> WebIdlResult<Ref<CSSUnitValue>> {
+ let unit = typed_om::to_rust_string(&unit.into_utf16_string());
+ self.this().to_unit(cx.vm(), &unit)
+ }
+
+ pub(crate) fn type_for_bindings(&self, _: &mut CallContext) -> WebIdlResult<CSSNumericType> {
+ let mut result = CSSNumericType::default();
+ for (base_type, power) in self.numeric_type.exponents.iter().enumerate() {
+ let Some(power) = power.filter(|power| *power != 0) else {
+ continue;
+ };
+ let entry = match base_type {
+ BASE_TYPE_LENGTH => &mut result.length,
+ BASE_TYPE_ANGLE => &mut result.angle,
+ BASE_TYPE_TIME => &mut result.time,
+ BASE_TYPE_FREQUENCY => &mut result.frequency,
+ BASE_TYPE_RESOLUTION => &mut result.resolution,
+ BASE_TYPE_FLEX => &mut result.flex,
+ BASE_TYPE_PERCENT => &mut result.percent,
+ _ => unreachable!("a numeric type has seven base types"),
+ };
+ *entry = Some(power);
+ }
+ result.percent_hint = self
+ .numeric_type
+ .percent_hint
+ .map(|percent_hint| to_om_numeric_base_type(usize::from(percent_hint)));
+ Ok(result)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-parse
+ pub(crate) fn parse(cx: &mut CallContext, css_text: UsvString) -> WebIdlResult<AnyCSSNumericValue> {
+ // The parse(cssText) method, when called, must perform the following steps:
+ let value = typed_om::parse_a_numeric_value(&css_text.into_utf16_string()).ok_or_else(|| {
+ Exception::syntax_error(Utf16String::from_utf8("Input is not a numeric component value."))
+ })?;
+ typed_om::reify_a_numeric_value(cx.vm(), &value)
+ .ok_or_else(|| Exception::syntax_error(Utf16String::from_utf8("Unable to reify this math function.")))
+ }
+}
+
+impl AnyCSSNumericValue {
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-to
+ pub(crate) fn to_unit(self, vm: &Vm, unit: &str) -> WebIdlResult<Ref<CSSUnitValue>> {
+ // The to(unit) method converts an existing CSSNumericValue this into another one with the specified unit, if
+ // possible. When called, it must perform the following steps:
+
+ // 1. Let type be the result of creating a type from unit. If type is failure, throw a SyntaxError.
+ if create_a_type_from_unit(unit).is_none() {
+ return Err(Exception::syntax_error(Utf16String::from_utf8(&format!(
+ "Unrecognized unit '{unit}'"
+ ))));
+ }
+
+ // 2. Let sum be the result of creating a sum value from this. If sum is failure, throw a TypeError.
+ let Some(sum) = self.create_a_sum_value() else {
+ return Err(Exception::type_error(&format!(
+ "Unable to create a sum from input '{}'",
+ self.to_string_with(SerializationParams::default())
+ )));
+ };
+
+ // 3. If sum has more than one item, throw a TypeError.
+ // Otherwise, let item be the result of creating a CSSUnitValue from the sole item in sum, then converting it
+ // to unit. If item is failure, throw a TypeError.
+ if sum.len() > 1 {
+ return Err(Exception::type_error("Sum contains more than one item"));
+ }
+ let Some(item) = CSSUnitValue::create_from_sum_value_item(vm, &sum[0]) else {
+ return Err(Exception::type_error(&format!(
+ "Unable to create CSSUnitValue from input '{}'",
+ self.to_string_with(SerializationParams::default())
+ )));
+ };
+ let Some(converted_item) = item.converted_to_unit(vm, unit) else {
+ return Err(Exception::type_error("Unable to convert input to requested unit"));
+ };
+
+ // 4. Return item.
+ Ok(converted_item)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_perspective.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_perspective.rs
new file mode 100644
index 00000000000..d4013f8e4d8
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_perspective.rs
@@ -0,0 +1,197 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSPerspective, https://drafts.css-houdini.org/css-typed-om-1/#cssperspective
+
+use ak::Utf16String;
+use libjs_rust::api::{GcRefCell, Trace, Vm};
+use libweb_rust::typed_om::{BASE_TYPE_LENGTH, RetainedStyleValue, TransformFunction, transformation_style_value};
+
+use super::css_keyword_value::{CSSKeywordValue, CSSKeywordish, rectify_a_keywordish_value};
+use super::css_numeric_value::{AnyCSSNumericValue, SerializationParams};
+use super::css_style_value::AnyCSSStyleValue;
+use super::css_transform_component::{
+ AnyCSSTransformComponent, CSSTransformComponent, Is2D, argument_style_value, create_dom_matrix,
+};
+use super::typed_om;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::geometry::dom_matrix::DOMMatrix;
+use crate::geometry::matrix::Matrix4;
+
+// https://drafts.css-houdini.org/css-typed-om-1/#typedefdef-cssperspectivevalue
+// NB: CSSKeywordish is flattened here, because our bindings generator flattens nested variants.
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) enum CSSPerspectiveValue {
+ CSSNumericValue(AnyCSSNumericValue),
+ DOMString(#[gc(untraced)] Utf16String),
+ CSSKeywordValue(Ref<CSSKeywordValue>),
+}
+
+#[derive(Clone, Copy, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) enum CSSPerspectiveValueInternal {
+ CSSNumericValue(AnyCSSNumericValue),
+ CSSKeywordValue(Ref<CSSKeywordValue>),
+}
+
+fn to_internal(vm: &Vm, value: CSSPerspectiveValue) -> WebIdlResult<CSSPerspectiveValueInternal> {
+ // Steps 1 and 2 of The CSSPerspective(length) constructor:
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssperspective-cssperspective
+ let keywordish = match value {
+ // 1. If length is a CSSNumericValue:
+ CSSPerspectiveValue::CSSNumericValue(numeric_value) => {
+ // 1. If length does not match <length>, throw a TypeError.
+ if !numeric_value.numeric_type().matches_dimension(BASE_TYPE_LENGTH, None) {
+ return Err(Exception::type_error(
+ "CSSPerspective length component doesn't match <length>",
+ ));
+ }
+ return Ok(CSSPerspectiveValueInternal::CSSNumericValue(numeric_value));
+ }
+ // 2. Otherwise (that is, if length is not a CSSNumericValue):
+ CSSPerspectiveValue::DOMString(value) => CSSKeywordish::DOMString(value),
+ CSSPerspectiveValue::CSSKeywordValue(value) => CSSKeywordish::CSSKeywordValue(value),
+ };
+
+ // 1. Rectify a keywordish value from length, then set length to the result’s value.
+ let rectified_length = rectify_a_keywordish_value(vm, &keywordish);
+
+ // 2. If length does not represent a value that is an ASCII case-insensitive match for the keyword none,
+ // throw a TypeError.
+ if !typed_om::to_rust_string(&rectified_length.raw_value()).eq_ignore_ascii_case("none") {
+ return Err(Exception::type_error(
+ "CSSPerspective length component is a keyword other than `none`",
+ ));
+ }
+
+ Ok(CSSPerspectiveValueInternal::CSSKeywordValue(rectified_length))
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSPerspective {
+ transform_component: CSSTransformComponent,
+ length: GcRefCell<CSSPerspectiveValueInternal>,
+}
+
+impl Wrappable for CSSPerspective {}
+
+impl Inherits<CSSTransformComponent> for CSSPerspective {
+ fn parent(&self) -> &CSSTransformComponent {
+ &self.transform_component
+ }
+}
+
+impl CSSPerspective {
+ pub(crate) fn create(vm: &Vm, length: CSSPerspectiveValueInternal) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ transform_component: CSSTransformComponent::new(Is2D::No),
+ length: GcRefCell::new(length),
+ });
+ AnyCSSTransformComponent::CSSPerspective(object).finish(vm);
+ object
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssperspective-cssperspective
+ pub(crate) fn construct(cx: &mut CallContext, length: CSSPerspectiveValue) -> WebIdlResult<Ref<Self>> {
+ // The CSSPerspective(length) constructor must, when invoked, perform the following steps:
+ // NB: Steps 1 and 2 are implemented in to_internal().
+ let vm = cx.vm();
+ let internal_length = to_internal(vm, length)?;
+
+ // 3. Return a new CSSPerspective object with its length internal slot set to length, and its is2D internal slot
+ // set to false.
+ Ok(Self::create(vm, internal_length))
+ }
+
+ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<CSSPerspectiveValue> {
+ Ok(match *self.length.borrow() {
+ CSSPerspectiveValueInternal::CSSNumericValue(value) => CSSPerspectiveValue::CSSNumericValue(value),
+ CSSPerspectiveValueInternal::CSSKeywordValue(value) => CSSPerspectiveValue::CSSKeywordValue(value),
+ })
+ }
+
+ pub(crate) fn set_length(&self, cx: &mut CallContext, value: CSSPerspectiveValue) -> WebIdlResult<()> {
+ // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
+ // WPT expects this to throw for invalid values, so just reuse the constructor code.
+ let vm = cx.vm();
+ let length = to_internal(vm, value)?;
+ *self.length.borrow_mut(vm) = length;
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssperspective
+ pub(crate) fn serialize(&self) -> Utf16String {
+ // 1. Let s initially be "perspective(".
+ let mut s = String::from("perspective(");
+
+ // 2. Serialize this’s length internal slot, with a minimum of 0px, and append it to s.
+ match *self.length.borrow() {
+ CSSPerspectiveValueInternal::CSSNumericValue(numeric_value) => numeric_value.serialize(
+ &mut s,
+ SerializationParams {
+ minimum: Some(0.0),
+ ..SerializationParams::default()
+ },
+ ),
+ CSSPerspectiveValueInternal::CSSKeywordValue(keyword_value) => {
+ s.push_str(&typed_om::to_rust_string(&keyword_value.serialize()));
+ }
+ }
+
+ // 3. Append ")" to s, and return s.
+ s.push(')');
+ Utf16String::from_utf8(&s)
+ }
+
+ pub(crate) fn to_matrix(&self, vm: &Vm) -> WebIdlResult<Ref<DOMMatrix>> {
+ // 1. Let matrix be a new DOMMatrix object, initialized to this’s equivalent 4x4 transform matrix, as defined in
+ // CSS Transforms 1 § 12. Mathematical Description of Transform Functions, and with its is2D internal slot
+ // set to the same value as this’s is2D internal slot.
+ // NOTE: Recall that the is2D flag affects what transform, and thus what equivalent matrix, a
+ // CSSTransformComponent represents.
+ // As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in
+ // generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a
+ // TypeError.
+ let mut matrix = Matrix4::identity();
+
+ match *self.length.borrow() {
+ CSSPerspectiveValueInternal::CSSNumericValue(numeric_value) => {
+ // NB: to_unit() throws a TypeError if the conversion can't be done.
+ let distance = numeric_value.to_unit(vm, "px")?.raw_value();
+ // NB: Matrix4 is row by row, so the element m34 is in the fourth row and the third column.
+ // Unlike f64::max(), this keeps a distance that is NaN.
+ matrix.elements[3][2] = -1.0 / if distance < 1.0 { 1.0 } else { distance };
+ }
+ CSSPerspectiveValueInternal::CSSKeywordValue(_) => {
+ // NB: This is `none`, so do nothing.
+ }
+ }
+
+ Ok(create_dom_matrix(vm, matrix, self.transform_component.raw_is_2d()))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssperspective-is2d
+ pub(crate) fn set_is_2d(&self) {
+ // The is2D attribute of a CSSPerspective object must, on setting, do nothing.
+ }
+
+ pub(crate) fn create_style_value(&self, vm: &Vm, property_id: u16) -> WebIdlResult<RetainedStyleValue> {
+ let length = match *self.length.borrow() {
+ CSSPerspectiveValueInternal::CSSNumericValue(value) => argument_style_value(vm, property_id, value)?,
+ CSSPerspectiveValueInternal::CSSKeywordValue(value) => {
+ argument_style_value(vm, property_id, AnyCSSStyleValue::CSSKeywordValue(value))?
+ }
+ };
+ Ok(transformation_style_value(
+ property_id,
+ TransformFunction::Perspective,
+ vec![length],
+ ))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_rotate.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_rotate.rs
new file mode 100644
index 00000000000..ca4bae06305
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_rotate.rs
@@ -0,0 +1,294 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSRotate, https://drafts.css-houdini.org/css-typed-om-1/#cssrotate
+
+use ak::Utf16String;
+use libjs_rust::api::{GcRefCell, Trace, Vm};
+use libweb_rust::typed_om::{RetainedStyleValue, TransformFunction, transformation_style_value};
+
+use super::css_numeric_value::{AnyCSSNumericValue, CSSNumberish, SerializationParams, rectify_a_numberish_value};
+use super::css_transform_component::{
+ AnyCSSTransformComponent, CSSTransformComponent, Is2D, argument_style_value, create_dom_matrix, matches_angle,
+ matches_number,
+};
+use super::css_unit_value::CSSUnitValue;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::geometry::dom_matrix::DOMMatrix;
+use crate::geometry::dom_matrix_read_only::DOMMatrixReadOnly;
+use crate::geometry::matrix::Matrix4;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSRotate {
+ transform_component: CSSTransformComponent,
+ x: GcRefCell<AnyCSSNumericValue>,
+ y: GcRefCell<AnyCSSNumericValue>,
+ z: GcRefCell<AnyCSSNumericValue>,
+ angle: GcRefCell<AnyCSSNumericValue>,
+}
+
+impl Wrappable for CSSRotate {}
+
+impl Inherits<CSSTransformComponent> for CSSRotate {
+ fn parent(&self) -> &CSSTransformComponent {
+ &self.transform_component
+ }
+}
+
+impl CSSRotate {
+ pub(crate) fn create(
+ vm: &Vm,
+ is_2d: Is2D,
+ x: AnyCSSNumericValue,
+ y: AnyCSSNumericValue,
+ z: AnyCSSNumericValue,
+ angle: AnyCSSNumericValue,
+ ) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ transform_component: CSSTransformComponent::new(is_2d),
+ x: GcRefCell::new(x),
+ y: GcRefCell::new(y),
+ z: GcRefCell::new(z),
+ angle: GcRefCell::new(angle),
+ });
+ AnyCSSTransformComponent::CSSRotate(object).finish(vm);
+ object
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssrotate-cssrotate
+ pub(crate) fn construct_from_angle(cx: &mut CallContext, angle: AnyCSSNumericValue) -> WebIdlResult<Ref<Self>> {
+ // The CSSRotate(angle) constructor must, when invoked, perform the following steps:
+
+ // 1. If angle doesn’t match <angle>, throw a TypeError.
+ if !matches_angle(&angle) {
+ return Err(Exception::type_error("CSSRotate angle component doesn't match <angle>"));
+ }
+
+ // 2. Return a new CSSRotate with its angle internal slot set to angle, its x and y internal slots set to new
+ // unit values of (0, "number"), its z internal slot set to a new unit value of (1, "number"), and its is2D
+ // internal slot set to true.
+ let vm = cx.vm();
+ let unit_value = |value| AnyCSSNumericValue::CSSUnitValue(CSSUnitValue::create(vm, value, "number"));
+ Ok(Self::create(
+ vm,
+ Is2D::Yes,
+ unit_value(0.0),
+ unit_value(0.0),
+ unit_value(1.0),
+ angle,
+ ))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssrotate-cssrotate-x-y-z-anglec
+ pub(crate) fn construct_from_axis(
+ cx: &mut CallContext,
+ x: CSSNumberish,
+ y: CSSNumberish,
+ z: CSSNumberish,
+ angle: AnyCSSNumericValue,
+ ) -> WebIdlResult<Ref<Self>> {
+ // The CSSRotate(x, y, z, angle) constructor must, when invoked, perform the following steps:
+
+ // 1. If angle doesn’t match <angle>, throw a TypeError.
+ if !matches_angle(&angle) {
+ return Err(Exception::type_error("CSSRotate angle component doesn't match <angle>"));
+ }
+
+ // 2. Let x, y, and z be replaced by the result of rectifying a numberish value.
+ let vm = cx.vm();
+ let rectified_x = rectify_a_numberish_value(vm, &x, None);
+ let rectified_y = rectify_a_numberish_value(vm, &y, None);
+ let rectified_z = rectify_a_numberish_value(vm, &z, None);
+
+ // 3. If x, y, or z don’t match <number>, throw a TypeError.
+ if !matches_number(&rectified_x) {
+ return Err(Exception::type_error("CSSRotate x component doesn't match <number>"));
+ }
+ if !matches_number(&rectified_y) {
+ return Err(Exception::type_error("CSSRotate y component doesn't match <number>"));
+ }
+ if !matches_number(&rectified_z) {
+ return Err(Exception::type_error("CSSRotate z component doesn't match <number>"));
+ }
+
+ // 4. Return a new CSSRotate with its angle internal slot set to angle, its x, y, z internal slots set to x, y,
+ // and z, and its is2D internal slot set to false.
+ Ok(Self::create(vm, Is2D::No, rectified_x, rectified_y, rectified_z, angle))
+ }
+
+ pub(crate) fn x(&self, _: &mut CallContext) -> WebIdlResult<CSSNumberish> {
+ Ok(CSSNumberish::CSSNumericValue(*self.x.borrow()))
+ }
+
+ pub(crate) fn y(&self, _: &mut CallContext) -> WebIdlResult<CSSNumberish> {
+ Ok(CSSNumberish::CSSNumericValue(*self.y.borrow()))
+ }
+
+ pub(crate) fn z(&self, _: &mut CallContext) -> WebIdlResult<CSSNumberish> {
+ Ok(CSSNumberish::CSSNumericValue(*self.z.borrow()))
+ }
+
+ pub(crate) fn angle(&self, _: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {
+ Ok(*self.angle.borrow())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssrotate-x
+ pub(crate) fn set_x(&self, cx: &mut CallContext, value: CSSNumberish) -> WebIdlResult<()> {
+ // The x, y, and z attributes must, on setting to a new value val, rectify a numberish value from val and set
+ // the corresponding internal slot to the result of that.
+ // AD-HOC: WPT expects this to throw for invalid values. https://github.com/w3c/css-houdini-drafts/issues/1153
+ let vm = cx.vm();
+ let rectified_x = rectify_a_numberish_value(vm, &value, None);
+ if !matches_number(&rectified_x) {
+ return Err(Exception::type_error("CSSRotate x component doesn't match <number>"));
+ }
+ *self.x.borrow_mut(vm) = rectified_x;
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssrotate-y
+ pub(crate) fn set_y(&self, cx: &mut CallContext, value: CSSNumberish) -> WebIdlResult<()> {
+ // The x, y, and z attributes must, on setting to a new value val, rectify a numberish value from val and set
+ // the corresponding internal slot to the result of that.
+ // AD-HOC: WPT expects this to throw for invalid values. https://github.com/w3c/css-houdini-drafts/issues/1153
+ let vm = cx.vm();
+ let rectified_y = rectify_a_numberish_value(vm, &value, None);
+ if !matches_number(&rectified_y) {
+ return Err(Exception::type_error("CSSRotate y component doesn't match <number>"));
+ }
+ *self.y.borrow_mut(vm) = rectified_y;
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssrotate-z
+ pub(crate) fn set_z(&self, cx: &mut CallContext, value: CSSNumberish) -> WebIdlResult<()> {
+ // The x, y, and z attributes must, on setting to a new value val, rectify a numberish value from val and set
+ // the corresponding internal slot to the result of that.
+ // AD-HOC: WPT expects this to throw for invalid values. https://github.com/w3c/css-houdini-drafts/issues/1153
+ let vm = cx.vm();
+ let rectified_z = rectify_a_numberish_value(vm, &value, None);
+ if !matches_number(&rectified_z) {
+ return Err(Exception::type_error("CSSRotate z component doesn't match <number>"));
+ }
+ *self.z.borrow_mut(vm) = rectified_z;
+ Ok(())
+ }
+
+ pub(crate) fn set_angle(&self, cx: &mut CallContext, value: AnyCSSNumericValue) -> WebIdlResult<()> {
+ // AD-HOC: Not specced. WPT expects this to throw for invalid values.
+ // https://github.com/w3c/css-houdini-drafts/issues/1153
+ if !matches_angle(&value) {
+ return Err(Exception::type_error("CSSRotate angle component doesn't match <angle>"));
+ }
+ *self.angle.borrow_mut(cx.vm()) = value;
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssrotate
+ pub(crate) fn serialize(&self) -> Utf16String {
+ let params = SerializationParams::default();
+
+ // 1. Let s initially be the empty string.
+ let mut s = String::new();
+
+ // 2. If this’s is2D internal slot is false:
+ if !self.transform_component.raw_is_2d() {
+ // 1. Append "rotate3d(" to s.
+ s.push_str("rotate3d(");
+
+ // 2. Serialize this’s x internal slot, and append it to s.
+ self.x.borrow().serialize(&mut s, params);
+
+ // 3. Append ", " to s.
+ s.push_str(", ");
+
+ // 4. Serialize this’s y internal slot, and append it to s.
+ self.y.borrow().serialize(&mut s, params);
+
+ // 5. Append ", " to s.
+ s.push_str(", ");
+
+ // 6. Serialize this’s z internal slot, and append it to s.
+ self.z.borrow().serialize(&mut s, params);
+
+ // 7. Append "," to s.
+ s.push_str(", ");
+
+ // 8. Serialize this’s angle internal slot, and append it to s.
+ self.angle.borrow().serialize(&mut s, params);
+
+ // 9. Append ")" to s, and return s.
+ s.push(')');
+ }
+ // 2. Otherwise:
+ else {
+ // 1. Append "rotate(" to s.
+ s.push_str("rotate(");
+
+ // 2. Serialize this’s angle internal slot, and append it to s.
+ self.angle.borrow().serialize(&mut s, params);
+
+ // 3. Append ")" to s, and return s.
+ s.push(')');
+ }
+ Utf16String::from_utf8(&s)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformcomponent-tomatrix
+ pub(crate) fn to_matrix(&self, vm: &Vm) -> WebIdlResult<Ref<DOMMatrix>> {
+ // 1. Let matrix be a new DOMMatrix object, initialized to this’s equivalent 4x4 transform matrix, as defined in
+ // CSS Transforms 1 § 12. Mathematical Description of Transform Functions, and with its is2D internal slot
+ // set to the same value as this’s is2D internal slot.
+ // NOTE: Recall that the is2D flag affects what transform, and thus what equivalent matrix, a
+ // CSSTransformComponent represents.
+ // As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in
+ // generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a
+ // TypeError.
+ // 2. Return matrix.
+
+ let is_2d = self.transform_component.raw_is_2d();
+ let matrix = create_dom_matrix(vm, Matrix4::identity(), is_2d);
+ let read_only_matrix = <DOMMatrix as Inherits<DOMMatrixReadOnly>>::parent(&matrix);
+
+ // NB: to_unit() throws a TypeError if the conversion can't be done.
+ let angle = self.angle.borrow().to_unit(vm, "deg")?.raw_value();
+
+ if is_2d {
+ read_only_matrix.rotate_axis_angle_self_steps(0.0, 0.0, 1.0, angle);
+ return Ok(matrix);
+ }
+
+ let x = self.x.borrow().to_unit(vm, "number")?.raw_value();
+ let y = self.y.borrow().to_unit(vm, "number")?.raw_value();
+ let z = self.z.borrow().to_unit(vm, "number")?.raw_value();
+
+ read_only_matrix.rotate_axis_angle_self_steps(x, y, z, angle);
+ Ok(matrix)
+ }
+
+ pub(crate) fn create_style_value(&self, vm: &Vm, property_id: u16) -> WebIdlResult<RetainedStyleValue> {
+ if self.transform_component.raw_is_2d() {
+ let angle = argument_style_value(vm, property_id, *self.angle.borrow())?;
+ return Ok(transformation_style_value(
+ property_id,
+ TransformFunction::Rotate,
+ vec![angle],
+ ));
+ }
+
+ let x = argument_style_value(vm, property_id, *self.x.borrow())?;
+ let y = argument_style_value(vm, property_id, *self.y.borrow())?;
+ let z = argument_style_value(vm, property_id, *self.z.borrow())?;
+ let angle = argument_style_value(vm, property_id, *self.angle.borrow())?;
+ Ok(transformation_style_value(
+ property_id,
+ TransformFunction::Rotate3d,
+ vec![x, y, z, angle],
+ ))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_scale.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_scale.rs
new file mode 100644
index 00000000000..f1b72ae5f0d
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_scale.rs
@@ -0,0 +1,251 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSScale, https://drafts.css-houdini.org/css-typed-om-1/#cssscale
+
+use ak::Utf16String;
+use libjs_rust::api::{GcRefCell, Trace, Vm};
+use libweb_rust::typed_om::{RetainedStyleValue, TransformFunction, transformation_style_value};
+
+use super::css_numeric_value::{AnyCSSNumericValue, CSSNumberish, SerializationParams, rectify_a_numberish_value};
+use super::css_transform_component::{
+ AnyCSSTransformComponent, CSSTransformComponent, Is2D, argument_style_value, create_dom_matrix, matches_number,
+};
+use super::css_unit_value::CSSUnitValue;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::geometry::dom_matrix::DOMMatrix;
+use crate::geometry::matrix::Matrix4;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSScale {
+ transform_component: CSSTransformComponent,
+ x: GcRefCell<AnyCSSNumericValue>,
+ y: GcRefCell<AnyCSSNumericValue>,
+ z: GcRefCell<AnyCSSNumericValue>,
+}
+
+impl Wrappable for CSSScale {}
+
+impl Inherits<CSSTransformComponent> for CSSScale {
+ fn parent(&self) -> &CSSTransformComponent {
+ &self.transform_component
+ }
+}
+
+impl CSSScale {
+ pub(crate) fn create(
+ vm: &Vm,
+ is_2d: Is2D,
+ x: AnyCSSNumericValue,
+ y: AnyCSSNumericValue,
+ z: AnyCSSNumericValue,
+ ) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ transform_component: CSSTransformComponent::new(is_2d),
+ x: GcRefCell::new(x),
+ y: GcRefCell::new(y),
+ z: GcRefCell::new(z),
+ });
+ AnyCSSTransformComponent::CSSScale(object).finish(vm);
+ object
+ }
+
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ x: CSSNumberish,
+ y: CSSNumberish,
+ z: Option<CSSNumberish>,
+ ) -> WebIdlResult<Ref<Self>> {
+ // The CSSScale(x, y, z) constructor must, when invoked, perform the following steps:
+
+ // 1. Let x, y, and z (if passed) be replaced by the result of rectifying a numberish value.
+ let vm = cx.vm();
+ let rectified_x = rectify_a_numberish_value(vm, &x, None);
+ let rectified_y = rectify_a_numberish_value(vm, &y, None);
+ let rectified_z = z.map(|z| rectify_a_numberish_value(vm, &z, None));
+
+ // 2. If x, y, or z (if passed) don’t match <number>, throw a TypeError.
+ if !matches_number(&rectified_x) {
+ return Err(Exception::type_error("CSSScale x component doesn't match <number>"));
+ }
+ if !matches_number(&rectified_y) {
+ return Err(Exception::type_error("CSSScale y component doesn't match <number>"));
+ }
+ if rectified_z.as_ref().is_some_and(|z| !matches_number(z)) {
+ return Err(Exception::type_error("CSSScale z component doesn't match <number>"));
+ }
+
+ // 3. Let this be a new CSSScale object, with its x and y internal slots set to x and y.
+ // 4. If z was passed, set this’s z internal slot to z, and set this’s is2D internal slot to false.
+ // 5. If z was not passed, set this’s z internal slot to a new unit value of (1, "number"), and set this’s is2D
+ // internal slot to true.
+ let (is_2d, rectified_z) = match rectified_z {
+ Some(z) => (Is2D::No, z),
+ None => (
+ Is2D::Yes,
+ AnyCSSNumericValue::CSSUnitValue(CSSUnitValue::create(vm, 1.0, "number")),
+ ),
+ };
+ let this = Self::create(vm, is_2d, rectified_x, rectified_y, rectified_z);
+
+ // 6. Return this.
+ Ok(this)
+ }
+
+ pub(crate) fn x(&self, _: &mut CallContext) -> WebIdlResult<CSSNumberish> {
+ Ok(CSSNumberish::CSSNumericValue(*self.x.borrow()))
+ }
+
+ pub(crate) fn y(&self, _: &mut CallContext) -> WebIdlResult<CSSNumberish> {
+ Ok(CSSNumberish::CSSNumericValue(*self.y.borrow()))
+ }
+
+ pub(crate) fn z(&self, _: &mut CallContext) -> WebIdlResult<CSSNumberish> {
+ Ok(CSSNumberish::CSSNumericValue(*self.z.borrow()))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssscale-x
+ pub(crate) fn set_x(&self, cx: &mut CallContext, value: CSSNumberish) -> WebIdlResult<()> {
+ // The x, y, and z attributes must, on setting to a new value val, rectify a numberish value from val and set
+ // the corresponding internal slot to the result of that.
+ // AD-HOC: WPT expects this to throw for invalid values. https://github.com/w3c/css-houdini-drafts/issues/1153
+ let vm = cx.vm();
+ let rectified_x = rectify_a_numberish_value(vm, &value, None);
+ if !matches_number(&rectified_x) {
+ return Err(Exception::type_error("CSSScale x component doesn't match <number>"));
+ }
+ *self.x.borrow_mut(vm) = rectified_x;
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssscale-y
+ pub(crate) fn set_y(&self, cx: &mut CallContext, value: CSSNumberish) -> WebIdlResult<()> {
+ // The x, y, and z attributes must, on setting to a new value val, rectify a numberish value from val and set
+ // the corresponding internal slot to the result of that.
+ // AD-HOC: WPT expects this to throw for invalid values. https://github.com/w3c/css-houdini-drafts/issues/1153
+ let vm = cx.vm();
+ let rectified_y = rectify_a_numberish_value(vm, &value, None);
+ if !matches_number(&rectified_y) {
+ return Err(Exception::type_error("CSSScale y component doesn't match <number>"));
+ }
+ *self.y.borrow_mut(vm) = rectified_y;
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssscale-z
+ pub(crate) fn set_z(&self, cx: &mut CallContext, value: CSSNumberish) -> WebIdlResult<()> {
+ // The x, y, and z attributes must, on setting to a new value val, rectify a numberish value from val and set
+ // the corresponding internal slot to the result of that.
+ // AD-HOC: WPT expects this to throw for invalid values. https://github.com/w3c/css-houdini-drafts/issues/1153
+ let vm = cx.vm();
+ let rectified_z = rectify_a_numberish_value(vm, &value, None);
+ if !matches_number(&rectified_z) {
+ return Err(Exception::type_error("CSSScale z component doesn't match <number>"));
+ }
+ *self.z.borrow_mut(vm) = rectified_z;
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssscale
+ pub(crate) fn serialize(&self) -> Utf16String {
+ let params = SerializationParams::default();
+
+ // 1. Let s initially be the empty string.
+ let mut s = String::new();
+
+ // 2. If this’s is2D internal slot is false:
+ if !self.transform_component.raw_is_2d() {
+ // 1. Append "scale3d(" to s.
+ s.push_str("scale3d(");
+
+ // 2. Serialize this’s x internal slot, and append it to s.
+ self.x.borrow().serialize(&mut s, params);
+
+ // 3. Append ", " to s.
+ s.push_str(", ");
+
+ // 4. Serialize this’s y internal slot, and append it to s.
+ self.y.borrow().serialize(&mut s, params);
+
+ // 5. Append ", " to s.
+ s.push_str(", ");
+
+ // 6. Serialize this’s z internal slot, and append it to s.
+ self.z.borrow().serialize(&mut s, params);
+
+ // 7. Append ")" to s, and return s.
+ s.push(')');
+ }
+ // 3. Otherwise:
+ else {
+ // 1. Append "scale(" to s.
+ s.push_str("scale(");
+
+ // 2. Serialize this’s x internal slot, and append it to s.
+ self.x.borrow().serialize(&mut s, params);
+
+ // 3. If this’s x and y internal slots are equal numeric values, append ")" to s and return s.
+ // AD-HOC: Don't do this - neither Chrome nor Safari show this behavior.
+ // Upstream issue: https://github.com/w3c/css-houdini-drafts/issues/1161
+
+ // 4. Otherwise, append ", " to s.
+ s.push_str(", ");
+
+ // 5. Serialize this’s y internal slot, and append it to s.
+ self.y.borrow().serialize(&mut s, params);
+
+ // 6. Append ")" to s, and return s.
+ s.push(')');
+ }
+ Utf16String::from_utf8(&s)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformcomponent-tomatrix
+ pub(crate) fn to_matrix(&self, vm: &Vm) -> WebIdlResult<Ref<DOMMatrix>> {
+ // 1. Let matrix be a new DOMMatrix object, initialized to this’s equivalent 4x4 transform matrix, as defined in
+ // CSS Transforms 1 § 12. Mathematical Description of Transform Functions, and with its is2D internal slot
+ // set to the same value as this’s is2D internal slot.
+ // NOTE: Recall that the is2D flag affects what transform, and thus what equivalent matrix, a
+ // CSSTransformComponent represents.
+ // As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in
+ // generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a
+ // TypeError.
+ // 2. Return matrix.
+
+ // NB: to_unit() throws a TypeError if the conversion can't be done.
+ let is_2d = self.transform_component.raw_is_2d();
+ let x = self.x.borrow().to_unit(vm, "number")?.raw_value();
+ let y = self.y.borrow().to_unit(vm, "number")?.raw_value();
+
+ let mut z = 1.0;
+ if !is_2d {
+ z = self.z.borrow().to_unit(vm, "number")?.raw_value();
+ }
+
+ Ok(create_dom_matrix(vm, Matrix4::scale(x, y, z), is_2d))
+ }
+
+ pub(crate) fn create_style_value(&self, vm: &Vm, property_id: u16) -> WebIdlResult<RetainedStyleValue> {
+ let x = argument_style_value(vm, property_id, *self.x.borrow())?;
+ let y = argument_style_value(vm, property_id, *self.y.borrow())?;
+ if self.transform_component.raw_is_2d() {
+ return Ok(transformation_style_value(
+ property_id,
+ TransformFunction::Scale,
+ vec![x, y],
+ ));
+ }
+
+ let z = argument_style_value(vm, property_id, *self.z.borrow())?;
+ Ok(transformation_style_value(
+ property_id,
+ TransformFunction::Scale3d,
+ vec![x, y, z],
+ ))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_skew.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_skew.rs
new file mode 100644
index 00000000000..a5f5f316c5f
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_skew.rs
@@ -0,0 +1,161 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSSkew, https://drafts.css-houdini.org/css-typed-om-1/#cssskew
+
+use ak::{Utf16String, math};
+use libjs_rust::api::{GcRefCell, Trace, Vm};
+use libweb_rust::typed_om::{RetainedStyleValue, TransformFunction, transformation_style_value};
+
+use super::css_numeric_value::{AnyCSSNumericValue, SerializationParams};
+use super::css_transform_component::{
+ AnyCSSTransformComponent, CSSTransformComponent, Is2D, argument_style_value, create_dom_matrix, matches_angle,
+};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::geometry::dom_matrix::DOMMatrix;
+use crate::geometry::matrix::Matrix4;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSSkew {
+ transform_component: CSSTransformComponent,
+ ax: GcRefCell<AnyCSSNumericValue>,
+ ay: GcRefCell<AnyCSSNumericValue>,
+}
+
+impl Wrappable for CSSSkew {}
+
+impl Inherits<CSSTransformComponent> for CSSSkew {
+ fn parent(&self) -> &CSSTransformComponent {
+ &self.transform_component
+ }
+}
+
+impl CSSSkew {
+ pub(crate) fn create(vm: &Vm, ax: AnyCSSNumericValue, ay: AnyCSSNumericValue) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ transform_component: CSSTransformComponent::new(Is2D::Yes),
+ ax: GcRefCell::new(ax),
+ ay: GcRefCell::new(ay),
+ });
+ AnyCSSTransformComponent::CSSSkew(object).finish(vm);
+ object
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssskew-cssskew
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ ax: AnyCSSNumericValue,
+ ay: AnyCSSNumericValue,
+ ) -> WebIdlResult<Ref<Self>> {
+ // The CSSSkew(ax, ay) constructor must, when invoked, perform the following steps:
+
+ // 1. If ax or ay do not match <angle>, throw a TypeError.
+ if !matches_angle(&ax) {
+ return Err(Exception::type_error("CSSSkew ax component doesn't match <angle>"));
+ }
+ if !matches_angle(&ay) {
+ return Err(Exception::type_error("CSSSkew ay component doesn't match <angle>"));
+ }
+
+ // 2. Return a new CSSSkew object with its ax and ay internal slots set to ax and ay, and its is2D internal slot
+ // set to true.
+ Ok(Self::create(cx.vm(), ax, ay))
+ }
+
+ pub(crate) fn ax(&self, _: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {
+ Ok(*self.ax.borrow())
+ }
+
+ pub(crate) fn ay(&self, _: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {
+ Ok(*self.ay.borrow())
+ }
+
+ pub(crate) fn set_ax(&self, cx: &mut CallContext, ax: AnyCSSNumericValue) -> WebIdlResult<()> {
+ // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
+ // WPT expects this to throw for invalid values.
+ if !matches_angle(&ax) {
+ return Err(Exception::type_error("CSSSkew ax component doesn't match <angle>"));
+ }
+ *self.ax.borrow_mut(cx.vm()) = ax;
+ Ok(())
+ }
+
+ pub(crate) fn set_ay(&self, cx: &mut CallContext, ay: AnyCSSNumericValue) -> WebIdlResult<()> {
+ // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
+ // WPT expects this to throw for invalid values.
+ if !matches_angle(&ay) {
+ return Err(Exception::type_error("CSSSkew ay component doesn't match <angle>"));
+ }
+ *self.ay.borrow_mut(cx.vm()) = ay;
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssskew
+ pub(crate) fn serialize(&self) -> Utf16String {
+ let params = SerializationParams::default();
+
+ // 1. Let s initially be "skew(".
+ let mut s = String::from("skew(");
+
+ // 2. Serialize this’s ax internal slot, and append it to s.
+ self.ax.borrow().serialize(&mut s, params);
+
+ // 3. If this’s ay internal slot is a CSSUnitValue with a value of 0, then append ")" to s and return s.
+ let ay = *self.ay.borrow();
+ if ay.as_unit_value().is_some_and(|ay| ay.raw_value() == 0.0) {
+ s.push(')');
+ return Utf16String::from_utf8(&s);
+ }
+
+ // 4. Otherwise, append ", " to s.
+ s.push_str(", ");
+
+ // 5. Serialize this’s ay internal slot, and append it to s.
+ ay.serialize(&mut s, params);
+
+ // 6. Append ")" to s, and return s.
+ s.push(')');
+ Utf16String::from_utf8(&s)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformcomponent-tomatrix
+ pub(crate) fn to_matrix(&self, vm: &Vm) -> WebIdlResult<Ref<DOMMatrix>> {
+ // 1. Let matrix be a new DOMMatrix object, initialized to this’s equivalent 4x4 transform matrix, as defined in
+ // CSS Transforms 1 § 12. Mathematical Description of Transform Functions, and with its is2D internal slot
+ // set to the same value as this’s is2D internal slot.
+ // NOTE: Recall that the is2D flag affects what transform, and thus what equivalent matrix, a
+ // CSSTransformComponent represents.
+ // As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in
+ // generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a
+ // TypeError.
+ let ax_rad = self.ax.borrow().to_unit(vm, "rad")?.raw_value();
+ let ay_rad = self.ay.borrow().to_unit(vm, "rad")?.raw_value();
+
+ // NB: Matrix4 is row by row, so the element m21 is in the first row and m12 in the second.
+ let mut matrix = Matrix4::identity();
+ matrix.elements[0][1] = f64::from(math::tan(ax_rad as f32));
+ matrix.elements[1][0] = f64::from(math::tan(ay_rad as f32));
+
+ Ok(create_dom_matrix(vm, matrix, self.transform_component.raw_is_2d()))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssskew-is2d
+ pub(crate) fn set_is_2d(&self) {
+ // The is2D attribute of a CSSSkew, CSSSkewX, or CSSSkewY object must, on setting, do nothing.
+ }
+
+ pub(crate) fn create_style_value(&self, vm: &Vm, property_id: u16) -> WebIdlResult<RetainedStyleValue> {
+ let ax = argument_style_value(vm, property_id, *self.ax.borrow())?;
+ let ay = argument_style_value(vm, property_id, *self.ay.borrow())?;
+ Ok(transformation_style_value(
+ property_id,
+ TransformFunction::Skew,
+ vec![ax, ay],
+ ))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_skew_x.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_skew_x.rs
new file mode 100644
index 00000000000..835f4fd45d8
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_skew_x.rs
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSSkewX, https://drafts.css-houdini.org/css-typed-om-1/#cssskewx
+
+use ak::{Utf16String, math};
+use libjs_rust::api::{GcRefCell, Trace, Vm};
+use libweb_rust::typed_om::{RetainedStyleValue, TransformFunction, transformation_style_value};
+
+use super::css_numeric_value::{AnyCSSNumericValue, SerializationParams};
+use super::css_transform_component::{
+ AnyCSSTransformComponent, CSSTransformComponent, Is2D, argument_style_value, create_dom_matrix, matches_angle,
+};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::geometry::dom_matrix::DOMMatrix;
+use crate::geometry::matrix::Matrix4;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSSkewX {
+ transform_component: CSSTransformComponent,
+ ax: GcRefCell<AnyCSSNumericValue>,
+}
+
+impl Wrappable for CSSSkewX {}
+
+impl Inherits<CSSTransformComponent> for CSSSkewX {
+ fn parent(&self) -> &CSSTransformComponent {
+ &self.transform_component
+ }
+}
+
+impl CSSSkewX {
+ pub(crate) fn create(vm: &Vm, ax: AnyCSSNumericValue) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ transform_component: CSSTransformComponent::new(Is2D::Yes),
+ ax: GcRefCell::new(ax),
+ });
+ AnyCSSTransformComponent::CSSSkewX(object).finish(vm);
+ object
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssskewx-cssskewx
+ pub(crate) fn construct(cx: &mut CallContext, ax: AnyCSSNumericValue) -> WebIdlResult<Ref<Self>> {
+ // The CSSSkewX(ax) constructor must, when invoked, perform the following steps:
+
+ // 1. If ax does not match <angle>, throw a TypeError.
+ if !matches_angle(&ax) {
+ return Err(Exception::type_error("CSSSkewX ax component doesn't match <angle>"));
+ }
+
+ // 2. Return a new CSSSkewX object with its ax internal slot set to ax, and its is2D internal slot set to true.
+ Ok(Self::create(cx.vm(), ax))
+ }
+
+ pub(crate) fn ax(&self, _: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {
+ Ok(*self.ax.borrow())
+ }
+
+ pub(crate) fn set_ax(&self, cx: &mut CallContext, ax: AnyCSSNumericValue) -> WebIdlResult<()> {
+ // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
+ // WPT expects this to throw for invalid values.
+ if !matches_angle(&ax) {
+ return Err(Exception::type_error("CSSSkewX ax component doesn't match <angle>"));
+ }
+ *self.ax.borrow_mut(cx.vm()) = ax;
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssskewx
+ pub(crate) fn serialize(&self) -> Utf16String {
+ // 1. Let s initially be "skewX(".
+ let mut s = String::from("skewX(");
+
+ // 2. Serialize this’s ax internal slot, and append it to s.
+ self.ax.borrow().serialize(&mut s, SerializationParams::default());
+
+ // 3. Append ")" to s, and return s.
+ s.push(')');
+ Utf16String::from_utf8(&s)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformcomponent-tomatrix
+ pub(crate) fn to_matrix(&self, vm: &Vm) -> WebIdlResult<Ref<DOMMatrix>> {
+ // 1. Let matrix be a new DOMMatrix object, initialized to this’s equivalent 4x4 transform matrix, as defined in
+ // CSS Transforms 1 § 12. Mathematical Description of Transform Functions, and with its is2D internal slot
+ // set to the same value as this’s is2D internal slot.
+ // NOTE: Recall that the is2D flag affects what transform, and thus what equivalent matrix, a
+ // CSSTransformComponent represents.
+ // As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in
+ // generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a
+ // TypeError.
+ let ax_rad = self.ax.borrow().to_unit(vm, "rad")?.raw_value();
+
+ // NB: Matrix4 is row by row, so the element m21 is in the first row.
+ let mut matrix = Matrix4::identity();
+ matrix.elements[0][1] = f64::from(math::tan(ax_rad as f32));
+
+ Ok(create_dom_matrix(vm, matrix, self.transform_component.raw_is_2d()))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssskew-is2d
+ pub(crate) fn set_is_2d(&self) {
+ // The is2D attribute of a CSSSkew, CSSSkewX, or CSSSkewY object must, on setting, do nothing.
+ }
+
+ pub(crate) fn create_style_value(&self, vm: &Vm, property_id: u16) -> WebIdlResult<RetainedStyleValue> {
+ let ax = argument_style_value(vm, property_id, *self.ax.borrow())?;
+ Ok(transformation_style_value(
+ property_id,
+ TransformFunction::SkewX,
+ vec![ax],
+ ))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_skew_y.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_skew_y.rs
new file mode 100644
index 00000000000..9d8ece57e76
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_skew_y.rs
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSSkewY, https://drafts.css-houdini.org/css-typed-om-1/#cssskewy
+
+use ak::{Utf16String, math};
+use libjs_rust::api::{GcRefCell, Trace, Vm};
+use libweb_rust::typed_om::{RetainedStyleValue, TransformFunction, transformation_style_value};
+
+use super::css_numeric_value::{AnyCSSNumericValue, SerializationParams};
+use super::css_transform_component::{
+ AnyCSSTransformComponent, CSSTransformComponent, Is2D, argument_style_value, create_dom_matrix, matches_angle,
+};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::geometry::dom_matrix::DOMMatrix;
+use crate::geometry::matrix::Matrix4;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSSkewY {
+ transform_component: CSSTransformComponent,
+ ay: GcRefCell<AnyCSSNumericValue>,
+}
+
+impl Wrappable for CSSSkewY {}
+
+impl Inherits<CSSTransformComponent> for CSSSkewY {
+ fn parent(&self) -> &CSSTransformComponent {
+ &self.transform_component
+ }
+}
+
+impl CSSSkewY {
+ pub(crate) fn create(vm: &Vm, ay: AnyCSSNumericValue) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ transform_component: CSSTransformComponent::new(Is2D::Yes),
+ ay: GcRefCell::new(ay),
+ });
+ AnyCSSTransformComponent::CSSSkewY(object).finish(vm);
+ object
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssskewy-cssskewy
+ pub(crate) fn construct(cx: &mut CallContext, ay: AnyCSSNumericValue) -> WebIdlResult<Ref<Self>> {
+ // The CSSSkewY(ay) constructor must, when invoked, perform the following steps:
+
+ // 1. If ay does not match <angle>, throw a TypeError.
+ if !matches_angle(&ay) {
+ return Err(Exception::type_error("CSSSkewY ay component doesn't match <angle>"));
+ }
+
+ // 2. Return a new CSSSkewY object with its ay internal slot set to ay, and its is2D internal slot set to true.
+ Ok(Self::create(cx.vm(), ay))
+ }
+
+ pub(crate) fn ay(&self, _: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {
+ Ok(*self.ay.borrow())
+ }
+
+ pub(crate) fn set_ay(&self, cx: &mut CallContext, ay: AnyCSSNumericValue) -> WebIdlResult<()> {
+ // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
+ // WPT expects this to throw for invalid values.
+ if !matches_angle(&ay) {
+ return Err(Exception::type_error("CSSSkewY ay component doesn't match <angle>"));
+ }
+ *self.ay.borrow_mut(cx.vm()) = ay;
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssskewy
+ pub(crate) fn serialize(&self) -> Utf16String {
+ // 1. Let s initially be "skewY(".
+ let mut s = String::from("skewY(");
+
+ // 2. Serialize this’s ay internal slot, and append it to s.
+ self.ay.borrow().serialize(&mut s, SerializationParams::default());
+
+ // 3. Append ")" to s, and return s.
+ s.push(')');
+ Utf16String::from_utf8(&s)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformcomponent-tomatrix
+ pub(crate) fn to_matrix(&self, vm: &Vm) -> WebIdlResult<Ref<DOMMatrix>> {
+ // 1. Let matrix be a new DOMMatrix object, initialized to this’s equivalent 4x4 transform matrix, as defined in
+ // CSS Transforms 1 § 12. Mathematical Description of Transform Functions, and with its is2D internal slot
+ // set to the same value as this’s is2D internal slot.
+ // NOTE: Recall that the is2D flag affects what transform, and thus what equivalent matrix, a
+ // CSSTransformComponent represents.
+ // As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in
+ // generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a
+ // TypeError.
+ let ay_rad = self.ay.borrow().to_unit(vm, "rad")?.raw_value();
+
+ // NB: Matrix4 is row by row, so the element m12 is in the second row.
+ let mut matrix = Matrix4::identity();
+ matrix.elements[1][0] = f64::from(math::tan(ay_rad as f32));
+
+ Ok(create_dom_matrix(vm, matrix, self.transform_component.raw_is_2d()))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssskew-is2d
+ pub(crate) fn set_is_2d(&self) {
+ // The is2D attribute of a CSSSkew, CSSSkewX, or CSSSkewY object must, on setting, do nothing.
+ }
+
+ pub(crate) fn create_style_value(&self, vm: &Vm, property_id: u16) -> WebIdlResult<RetainedStyleValue> {
+ let ay = argument_style_value(vm, property_id, *self.ay.borrow())?;
+ Ok(transformation_style_value(
+ property_id,
+ TransformFunction::SkewY,
+ vec![ay],
+ ))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_style_value.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_value.rs
new file mode 100644
index 00000000000..8f5a22885e9
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_value.rs
@@ -0,0 +1,308 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSStyleValue, https://drafts.css-houdini.org/css-typed-om-1/#cssstylevalue
+
+use ak::Utf16String;
+use libjs_rust::api::{GcRefCell, MarkedVec, Trace, Vm};
+use libweb_rust::typed_om::RetainedStyleValue;
+
+use super::css_image_value::CSSImageValue;
+use super::css_keyword_value::CSSKeywordValue;
+use super::css_math_clamp::CSSMathClamp;
+use super::css_math_invert::CSSMathInvert;
+use super::css_math_max::CSSMathMax;
+use super::css_math_min::CSSMathMin;
+use super::css_math_negate::CSSMathNegate;
+use super::css_math_product::CSSMathProduct;
+use super::css_math_sum::CSSMathSum;
+use super::css_math_value::CSSMathValue;
+use super::css_numeric_value::{AnyCSSNumericValue, CSSNumericValue};
+use super::css_transform_value::CSSTransformValue;
+use super::css_unit_value::CSSUnitValue;
+use super::css_unparsed_value::CSSUnparsedValue;
+use super::typed_om;
+use crate::bindings::conversions::{ToJs, UsvString};
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, cell_into_abi, wrap};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use libjs_rust::api::{ThrowCompletionOr, Value};
+
+/// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+#[derive(Clone, Copy, Eq, PartialEq)]
+pub(crate) enum PerformTypeCheck {
+ No,
+ Yes,
+}
+
+/// An object of CSSStyleValue or of an interface that inherits from it.
+#[derive(Clone, Copy, Trace)]
+#[gc(crate = libjs_rust)]
+#[expect(clippy::enum_variant_names, reason = "the variants are named after the interfaces")]
+pub(crate) enum AnyCSSStyleValue {
+ CSSStyleValue(Ref<CSSStyleValue>),
+ CSSImageValue(Ref<CSSImageValue>),
+ CSSKeywordValue(Ref<CSSKeywordValue>),
+ CSSMathClamp(Ref<CSSMathClamp>),
+ CSSMathInvert(Ref<CSSMathInvert>),
+ CSSMathMax(Ref<CSSMathMax>),
+ CSSMathMin(Ref<CSSMathMin>),
+ CSSMathNegate(Ref<CSSMathNegate>),
+ CSSMathProduct(Ref<CSSMathProduct>),
+ CSSMathSum(Ref<CSSMathSum>),
+ CSSMathValue(Ref<CSSMathValue>),
+ CSSNumericValue(Ref<CSSNumericValue>),
+ CSSTransformValue(Ref<CSSTransformValue>),
+ CSSUnitValue(Ref<CSSUnitValue>),
+ CSSUnparsedValue(Ref<CSSUnparsedValue>),
+}
+
+impl AnyCSSStyleValue {
+ /// The object as a CSSNumericValue, if it is one.
+ pub(crate) fn as_numeric(self) -> Option<AnyCSSNumericValue> {
+ Some(match self {
+ Self::CSSMathClamp(object) => AnyCSSNumericValue::CSSMathClamp(object),
+ Self::CSSMathInvert(object) => AnyCSSNumericValue::CSSMathInvert(object),
+ Self::CSSMathMax(object) => AnyCSSNumericValue::CSSMathMax(object),
+ Self::CSSMathMin(object) => AnyCSSNumericValue::CSSMathMin(object),
+ Self::CSSMathNegate(object) => AnyCSSNumericValue::CSSMathNegate(object),
+ Self::CSSMathProduct(object) => AnyCSSNumericValue::CSSMathProduct(object),
+ Self::CSSMathSum(object) => AnyCSSNumericValue::CSSMathSum(object),
+ Self::CSSMathValue(object) => AnyCSSNumericValue::CSSMathValue(object),
+ Self::CSSNumericValue(object) => AnyCSSNumericValue::CSSNumericValue(object),
+ Self::CSSUnitValue(object) => AnyCSSNumericValue::CSSUnitValue(object),
+ _ => return None,
+ })
+ }
+
+ /// The part of the object that all CSSStyleValues have.
+ pub(crate) fn style_value(&self) -> &CSSStyleValue {
+ fn part_of_math_value(value: &CSSMathValue) -> &CSSStyleValue {
+ <CSSMathValue as Inherits<CSSNumericValue>>::parent(value).parent()
+ }
+
+ match self {
+ Self::CSSStyleValue(object) => object,
+ Self::CSSImageValue(object) => object.style_value(),
+ Self::CSSKeywordValue(object) => object.style_value(),
+ Self::CSSMathClamp(object) => part_of_math_value(object.math_value()),
+ Self::CSSMathInvert(object) => part_of_math_value(object.math_value()),
+ Self::CSSMathMax(object) => part_of_math_value(object.math_value()),
+ Self::CSSMathMin(object) => part_of_math_value(object.math_value()),
+ Self::CSSMathNegate(object) => part_of_math_value(object.math_value()),
+ Self::CSSMathProduct(object) => part_of_math_value(object.math_value()),
+ Self::CSSMathSum(object) => part_of_math_value(object.math_value()),
+ Self::CSSMathValue(object) => part_of_math_value(object),
+ Self::CSSNumericValue(object) => object.parent(),
+ Self::CSSTransformValue(object) => object.style_value(),
+ Self::CSSUnitValue(object) => <CSSUnitValue as Inherits<CSSNumericValue>>::parent(object).parent(),
+ Self::CSSUnparsedValue(object) => object.style_value(),
+ }
+ }
+
+ /// The cell of the object, as LibWeb's C++ code holds it.
+ pub(crate) fn cell_into_abi(self) -> *mut core::ffi::c_void {
+ match self {
+ Self::CSSStyleValue(object) => cell_into_abi(object),
+ Self::CSSImageValue(object) => cell_into_abi(object),
+ Self::CSSKeywordValue(object) => cell_into_abi(object),
+ Self::CSSMathClamp(object) => cell_into_abi(object),
+ Self::CSSMathInvert(object) => cell_into_abi(object),
+ Self::CSSMathMax(object) => cell_into_abi(object),
+ Self::CSSMathMin(object) => cell_into_abi(object),
+ Self::CSSMathNegate(object) => cell_into_abi(object),
+ Self::CSSMathProduct(object) => cell_into_abi(object),
+ Self::CSSMathSum(object) => cell_into_abi(object),
+ Self::CSSMathValue(object) => cell_into_abi(object),
+ Self::CSSNumericValue(object) => cell_into_abi(object),
+ Self::CSSTransformValue(object) => cell_into_abi(object),
+ Self::CSSUnitValue(object) => cell_into_abi(object),
+ Self::CSSUnparsedValue(object) => cell_into_abi(object),
+ }
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#stylevalue-serialization
+ pub(crate) fn serialize(&self, vm: &Vm) -> WebIdlResult<Utf16String> {
+ match self {
+ Self::CSSStyleValue(object) => Ok(object.serialize_source_value()),
+ // AD-HOC: The spec doesn't say how to serialize this, as it's intentionally a black box.
+ // We just rely on CSSStyleValue serializing its held StyleValue.
+ Self::CSSImageValue(object) => Ok(object.style_value().serialize_source_value()),
+ Self::CSSKeywordValue(object) => Ok(object.serialize()),
+ Self::CSSTransformValue(object) => object.serialize(vm),
+ Self::CSSUnparsedValue(object) => Ok(object.serialize()),
+ _ => Ok(self.as_numeric().expect("the object is numeric").to_css_string()),
+ }
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+ pub(crate) fn create_an_internal_representation(
+ &self,
+ vm: &Vm,
+ property_id: u16,
+ property_name: &Utf16String,
+ perform_type_check: PerformTypeCheck,
+ ) -> WebIdlResult<RetainedStyleValue> {
+ match self {
+ Self::CSSStyleValue(object) => object.create_an_internal_representation(),
+ Self::CSSImageValue(object) => {
+ object.create_an_internal_representation(property_id, property_name, perform_type_check)
+ }
+ Self::CSSKeywordValue(object) => {
+ object.create_an_internal_representation(property_id, property_name, perform_type_check)
+ }
+ Self::CSSTransformValue(object) => {
+ object.create_an_internal_representation(vm, property_id, perform_type_check)
+ }
+ Self::CSSUnparsedValue(object) => object.create_an_internal_representation(),
+ Self::CSSUnitValue(object) => object.create_an_internal_representation(property_id, perform_type_check),
+ _ => self
+ .as_numeric()
+ .expect("the object is numeric")
+ .math_value_internal_representation(property_id, perform_type_check),
+ }
+ }
+}
+
+impl ToJs for AnyCSSStyleValue {
+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {
+ Ok(match self {
+ Self::CSSStyleValue(object) => Value::from_object(wrap(cx, object)),
+ Self::CSSImageValue(object) => Value::from_object(wrap(cx, object)),
+ Self::CSSKeywordValue(object) => Value::from_object(wrap(cx, object)),
+ Self::CSSTransformValue(object) => Value::from_object(wrap(cx, object)),
+ Self::CSSUnparsedValue(object) => Value::from_object(wrap(cx, object)),
+ _ => return self.as_numeric().expect("the object is numeric").to_js(cx),
+ })
+ }
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#cssstylevalue
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSStyleValue {
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssstylevalue-associatedproperty-slot
+ #[gc(untraced)]
+ associated_property: Option<Utf16String>,
+ /// The value this object was reified from.
+ #[gc(untraced)]
+ source_value: Option<RetainedStyleValue>,
+ #[gc(untraced)]
+ serialization_mode: u8,
+ /// The object that this is the CSSStyleValue part of, by which the steps of CSSStyleValue reach the steps of the
+ /// interface of the object.
+ object: GcRefCell<Option<AnyCSSStyleValue>>,
+}
+
+impl Wrappable for CSSStyleValue {}
+
+impl CSSStyleValue {
+ /// The part of an object of an interface that inherits from CSSStyleValue and has no source value.
+ pub(crate) fn empty() -> Self {
+ Self::with_source_value(None, None, 0)
+ }
+
+ /// The part of an object of an interface that inherits from CSSStyleValue and has a source value.
+ pub(crate) fn with_source(source_value: RetainedStyleValue) -> Self {
+ Self::with_source_value(None, Some(source_value), 0)
+ }
+
+ fn with_source_value(
+ associated_property: Option<Utf16String>,
+ source_value: Option<RetainedStyleValue>,
+ serialization_mode: u8,
+ ) -> Self {
+ Self {
+ associated_property,
+ source_value,
+ serialization_mode,
+ object: GcRefCell::new(None),
+ }
+ }
+
+ pub(crate) fn create(
+ vm: &Vm,
+ associated_property: Utf16String,
+ source_value: RetainedStyleValue,
+ serialization_mode: u8,
+ ) -> Ref<Self> {
+ let object = allocate(vm, |_| {
+ Self::with_source_value(Some(associated_property), Some(source_value), serialization_mode)
+ });
+ object.set_object(vm, AnyCSSStyleValue::CSSStyleValue(object));
+ object
+ }
+
+ /// Tells the part which object it belongs to, which an object does as soon as it exists.
+ pub(crate) fn set_object(&self, vm: &Vm, object: AnyCSSStyleValue) {
+ *self.object.borrow_mut(vm) = Some(object);
+ }
+
+ pub(crate) fn object(&self) -> AnyCSSStyleValue {
+ self.object.borrow().expect("an object exists from when it is created")
+ }
+
+ pub(crate) fn associated_property(&self) -> Option<&Utf16String> {
+ self.associated_property.as_ref()
+ }
+
+ pub(crate) fn source_value(&self) -> Option<&RetainedStyleValue> {
+ self.source_value.as_ref()
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#stylevalue-serialization
+ fn serialize_source_value(&self) -> Utf16String {
+ // FIXME: if the value was constructed from a USVString
+ // NB: Basically, if this was constructed with "parse a CSSStyleValue", regardless of what CSSStyleValue type it
+ // is now.
+ // the serialization is the USVString from which the value was constructed.
+ // otherwise, if the value was constructed using an IDL constructor
+ // the serialization is specified in the sections below.
+ // NB: This is handled by the interfaces that inherit from this one.
+ // FIXME: otherwise, if the value was extracted from the CSSOM
+ // NB: For CSSStyleValue itself, we use the source value we were created from.
+ self.source_value
+ .as_ref()
+ .map(|source_value| source_value.serialize(self.serialization_mode))
+ .unwrap_or_default()
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+ fn create_an_internal_representation(&self) -> WebIdlResult<RetainedStyleValue> {
+ // If value is a direct CSSStyleValue,
+ // Return value’s associated value.
+ self.source_value
+ .clone()
+ .ok_or_else(|| Exception::type_error("Missing create_an_internal_representation() overload"))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#stylevalue-serialization
+ pub(crate) fn to_string(&self, cx: &mut CallContext) -> WebIdlResult<Utf16String> {
+ self.object().serialize(cx.vm())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssstylevalue-parse
+ pub(crate) fn parse(
+ cx: &mut CallContext,
+ property: UsvString,
+ css_text: UsvString,
+ ) -> WebIdlResult<AnyCSSStyleValue> {
+ // The parse(property, cssText) method, when invoked, must parse a CSSStyleValue with property property, cssText
+ // cssText, and parseMultiple set to false, and return the result.
+ let values = typed_om::parse_a_css_style_value(cx, property, css_text)?;
+ Ok(values.get(0).expect("parsing results in at least one value"))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssstylevalue-parseall
+ pub(crate) fn parse_all<'vm>(
+ cx: &mut CallContext<'vm>,
+ property: UsvString,
+ css_text: UsvString,
+ ) -> WebIdlResult<MarkedVec<'vm, AnyCSSStyleValue>> {
+ // The parseAll(property, cssText) method, when invoked, must parse a CSSStyleValue with property property,
+ // cssText cssText, and parseMultiple set to true, and return the result.
+ typed_om::parse_a_css_style_value(cx, property, css_text)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_transform_component.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_transform_component.rs
new file mode 100644
index 00000000000..0bf6a19227d
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_transform_component.rs
@@ -0,0 +1,386 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSTransformComponent, https://drafts.css-houdini.org/css-typed-om-1/#csstransformcomponent
+
+use core::cell::Cell;
+use core::ops::Deref;
+
+use ak::Utf16String;
+use libjs_rust::api::{GcRefCell, ThrowCompletionOr, Trace, Value, Vm};
+use libweb_rust::typed_om::{
+ BASE_TYPE_ANGLE, Reification, RetainedStyleValue, TransformFunction, reification_of, transform_matrix,
+ transformation_parts,
+};
+
+use super::css_keyword_value::CSSKeywordValue;
+use super::css_matrix_component::CSSMatrixComponent;
+use super::css_numeric_value::AnyCSSNumericValue;
+use super::css_perspective::{CSSPerspective, CSSPerspectiveValueInternal};
+use super::css_rotate::CSSRotate;
+use super::css_scale::CSSScale;
+use super::css_skew::CSSSkew;
+use super::css_skew_x::CSSSkewX;
+use super::css_skew_y::CSSSkewY;
+use super::css_style_value::{AnyCSSStyleValue, PerformTypeCheck};
+use super::css_translate::CSSTranslate;
+use super::css_unit_value::CSSUnitValue;
+use super::typed_om;
+use crate::bindings::conversions::ToJs;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, wrap};
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::geometry::dom_matrix::DOMMatrix;
+use crate::geometry::dom_matrix_read_only::DOMMatrixReadOnly;
+use crate::geometry::matrix::Matrix4;
+
+#[derive(Clone, Copy, Eq, PartialEq)]
+pub(crate) enum Is2D {
+ No,
+ Yes,
+}
+
+/// An object of CSSTransformComponent or of an interface that inherits from it.
+#[derive(Clone, Copy, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) enum AnyCSSTransformComponent {
+ CSSTransformComponent(Ref<CSSTransformComponent>),
+ CSSMatrixComponent(Ref<CSSMatrixComponent>),
+ CSSPerspective(Ref<CSSPerspective>),
+ CSSRotate(Ref<CSSRotate>),
+ CSSScale(Ref<CSSScale>),
+ CSSSkew(Ref<CSSSkew>),
+ CSSSkewX(Ref<CSSSkewX>),
+ CSSSkewY(Ref<CSSSkewY>),
+ CSSTranslate(Ref<CSSTranslate>),
+}
+
+impl Deref for AnyCSSTransformComponent {
+ type Target = CSSTransformComponent;
+
+ fn deref(&self) -> &CSSTransformComponent {
+ match self {
+ Self::CSSTransformComponent(object) => object,
+ Self::CSSMatrixComponent(object) => <CSSMatrixComponent as Inherits<CSSTransformComponent>>::parent(object),
+ Self::CSSPerspective(object) => <CSSPerspective as Inherits<CSSTransformComponent>>::parent(object),
+ Self::CSSRotate(object) => <CSSRotate as Inherits<CSSTransformComponent>>::parent(object),
+ Self::CSSScale(object) => <CSSScale as Inherits<CSSTransformComponent>>::parent(object),
+ Self::CSSSkew(object) => <CSSSkew as Inherits<CSSTransformComponent>>::parent(object),
+ Self::CSSSkewX(object) => <CSSSkewX as Inherits<CSSTransformComponent>>::parent(object),
+ Self::CSSSkewY(object) => <CSSSkewY as Inherits<CSSTransformComponent>>::parent(object),
+ Self::CSSTranslate(object) => <CSSTranslate as Inherits<CSSTransformComponent>>::parent(object),
+ }
+ }
+}
+
+impl ToJs for AnyCSSTransformComponent {
+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {
+ Ok(Value::from_object(match self {
+ Self::CSSTransformComponent(object) => wrap(cx, object),
+ Self::CSSMatrixComponent(object) => wrap(cx, object),
+ Self::CSSPerspective(object) => wrap(cx, object),
+ Self::CSSRotate(object) => wrap(cx, object),
+ Self::CSSScale(object) => wrap(cx, object),
+ Self::CSSSkew(object) => wrap(cx, object),
+ Self::CSSSkewX(object) => wrap(cx, object),
+ Self::CSSSkewY(object) => wrap(cx, object),
+ Self::CSSTranslate(object) => wrap(cx, object),
+ }))
+ }
+}
+
+impl AnyCSSTransformComponent {
+ /// Tells the part of the object that all CSSTransformComponents have which object it is the part of.
+ pub(crate) fn finish(self, vm: &Vm) -> Self {
+ self.set_object(vm, self);
+ self
+ }
+
+ pub(crate) fn serialize(&self) -> WebIdlResult<Utf16String> {
+ match self {
+ Self::CSSTransformComponent(_) => unreachable!("no object is only of an abstract interface"),
+ Self::CSSMatrixComponent(object) => object.serialize(),
+ Self::CSSPerspective(object) => Ok(object.serialize()),
+ Self::CSSRotate(object) => Ok(object.serialize()),
+ Self::CSSScale(object) => Ok(object.serialize()),
+ Self::CSSSkew(object) => Ok(object.serialize()),
+ Self::CSSSkewX(object) => Ok(object.serialize()),
+ Self::CSSSkewY(object) => Ok(object.serialize()),
+ Self::CSSTranslate(object) => Ok(object.serialize()),
+ }
+ }
+
+ pub(crate) fn to_matrix(self, vm: &Vm) -> WebIdlResult<Ref<DOMMatrix>> {
+ match self {
+ Self::CSSTransformComponent(_) => unreachable!("no object is only of an abstract interface"),
+ Self::CSSMatrixComponent(object) => Ok(object.to_matrix(vm)),
+ Self::CSSPerspective(object) => object.to_matrix(vm),
+ Self::CSSRotate(object) => object.to_matrix(vm),
+ Self::CSSScale(object) => object.to_matrix(vm),
+ Self::CSSSkew(object) => object.to_matrix(vm),
+ Self::CSSSkewX(object) => object.to_matrix(vm),
+ Self::CSSSkewY(object) => object.to_matrix(vm),
+ Self::CSSTranslate(object) => object.to_matrix(vm),
+ }
+ }
+
+ pub(crate) fn create_style_value(&self, vm: &Vm, property_id: u16) -> WebIdlResult<RetainedStyleValue> {
+ match self {
+ Self::CSSTransformComponent(_) => unreachable!("no object is only of an abstract interface"),
+ Self::CSSMatrixComponent(object) => Ok(object.create_style_value(property_id)),
+ Self::CSSPerspective(object) => object.create_style_value(vm, property_id),
+ Self::CSSRotate(object) => object.create_style_value(vm, property_id),
+ Self::CSSScale(object) => object.create_style_value(vm, property_id),
+ Self::CSSSkew(object) => object.create_style_value(vm, property_id),
+ Self::CSSSkewX(object) => object.create_style_value(vm, property_id),
+ Self::CSSSkewY(object) => object.create_style_value(vm, property_id),
+ Self::CSSTranslate(object) => object.create_style_value(vm, property_id),
+ }
+ }
+
+ fn set_is_2d_steps(&self, value: bool) {
+ match self {
+ Self::CSSPerspective(object) => object.set_is_2d(),
+ Self::CSSSkew(object) => object.set_is_2d(),
+ Self::CSSSkewX(object) => object.set_is_2d(),
+ Self::CSSSkewY(object) => object.set_is_2d(),
+ _ => self.is_2d.set(value),
+ }
+ }
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#csstransformcomponent
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSTransformComponent {
+ #[gc(untraced)]
+ is_2d: Cell<bool>,
+ /// The object that this is the CSSTransformComponent part of, by which the steps of CSSTransformComponent reach the
+ /// steps of the interface of the object.
+ object: GcRefCell<Option<AnyCSSTransformComponent>>,
+}
+
+impl Wrappable for CSSTransformComponent {}
+
+impl CSSTransformComponent {
+ pub(crate) fn new(is_2d: Is2D) -> Self {
+ Self {
+ is_2d: Cell::new(is_2d == Is2D::Yes),
+ object: GcRefCell::new(None),
+ }
+ }
+
+ /// Tells the part which object it belongs to, which an object does as soon as it exists.
+ pub(crate) fn set_object(&self, vm: &Vm, object: AnyCSSTransformComponent) {
+ *self.object.borrow_mut(vm) = Some(object);
+ }
+
+ pub(crate) fn object(&self) -> AnyCSSTransformComponent {
+ self.object.borrow().expect("an object exists from when it is created")
+ }
+
+ pub(crate) fn raw_is_2d(&self) -> bool {
+ self.is_2d.get()
+ }
+
+ pub(crate) fn to_string(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ self.object().serialize()
+ }
+
+ pub(crate) fn is_2d(&self, _: &mut CallContext) -> WebIdlResult<bool> {
+ Ok(self.is_2d.get())
+ }
+
+ pub(crate) fn set_is_2d(&self, _: &mut CallContext, value: bool) -> WebIdlResult<()> {
+ self.object().set_is_2d_steps(value);
+ Ok(())
+ }
+
+ pub(crate) fn to_matrix(&self, cx: &mut CallContext) -> WebIdlResult<Ref<DOMMatrix>> {
+ self.object().to_matrix(cx.vm())
+ }
+}
+
+/// A new DOMMatrix with the elements of the matrix, whose is 2D is the value.
+pub(crate) fn create_dom_matrix(vm: &Vm, matrix: Matrix4, is_2d: bool) -> Ref<DOMMatrix> {
+ allocate(vm, |_| DOMMatrix::from_read_only(DOMMatrixReadOnly::new(matrix, is_2d)))
+}
+
+/// The internal representation of an argument of a transform function, for the property.
+pub(crate) fn argument_style_value(
+ vm: &Vm,
+ property_id: u16,
+ argument: impl Into<AnyCSSStyleValue>,
+) -> WebIdlResult<RetainedStyleValue> {
+ // NB: The name of the property is only for the errors of the type check, which does not happen here.
+ argument
+ .into()
+ .create_an_internal_representation(vm, property_id, &Utf16String::default(), PerformTypeCheck::No)
+}
+
+pub(crate) fn matches_angle(value: &AnyCSSNumericValue) -> bool {
+ value.numeric_type().matches_dimension(BASE_TYPE_ANGLE, None)
+}
+
+pub(crate) fn matches_number(value: &AnyCSSNumericValue) -> bool {
+ value.numeric_type().matches_number(None)
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#reify-a-transform-function
+pub(crate) fn reify_a_transform_function(vm: &Vm, value: &RetainedStyleValue) -> Option<AnyCSSTransformComponent> {
+ let (transform_function, values) = transformation_parts(value);
+
+ let reify_numeric_argument = |index: usize| typed_om::reify_numeric_argument(vm, &values[index]);
+ let reify_unit_value =
+ |value: f64, unit: &str| AnyCSSNumericValue::CSSUnitValue(CSSUnitValue::create(vm, value, unit));
+ let reify_0 = || reify_unit_value(0.0, "number");
+ let reify_1 = || reify_unit_value(1.0, "number");
+ let reify_0px = || reify_unit_value(0.0, "px");
+ let reify_0deg = || reify_unit_value(0.0, "deg");
+
+ let translate = |is_2d, x, y, z| AnyCSSTransformComponent::CSSTranslate(CSSTranslate::create(vm, is_2d, x, y, z));
+ let scale = |is_2d, x, y, z| AnyCSSTransformComponent::CSSScale(CSSScale::create(vm, is_2d, x, y, z));
+ let rotate =
+ |is_2d, x, y, z, angle| AnyCSSTransformComponent::CSSRotate(CSSRotate::create(vm, is_2d, x, y, z, angle));
+
+ // To reify a <transform-function> func, perform the appropriate set of steps below, based on func:
+ Some(match transform_function {
+ // -> matrix()
+ // -> matrix3d()
+ // 1. Return a new CSSMatrixComponent object, whose matrix internal slot is set to a 4x4 matrix representing
+ // the same information as func, and whose is2D internal slot is true if func is matrix(), and false
+ // otherwise.
+ TransformFunction::Matrix | TransformFunction::Matrix3d => {
+ let transform_as_matrix = transform_matrix(value)?;
+
+ // NB: The matrix is row by row, as Matrix4 stores it.
+ let mut matrix = Matrix4::identity();
+ for (index, element) in transform_as_matrix.into_iter().enumerate() {
+ matrix.elements[index / 4][index % 4] = f64::from(element);
+ }
+
+ let is_2d = if transform_function == TransformFunction::Matrix {
+ Is2D::Yes
+ } else {
+ Is2D::No
+ };
+ let dom_matrix = create_dom_matrix(vm, matrix, matrix.is_2d_affine());
+ AnyCSSTransformComponent::CSSMatrixComponent(CSSMatrixComponent::create(vm, is_2d, dom_matrix))
+ }
+
+ // -> translate()
+ // -> translateX()
+ // -> translateY()
+ // -> translate3d()
+ // -> translateZ()
+ // 1. Return a new CSSTranslate object, whose x, y, and z internal slots are set to the reification of the
+ // specified x/y/z offsets, or the reification of 0px if not specified in func, and whose is2D internal
+ // slot is true if func is translate(), translateX(), or translateY(), and false otherwise.
+ TransformFunction::Translate => {
+ // NB: Default y to 0px if it's not specified.
+ let y = if values.len() > 1 {
+ reify_numeric_argument(1)
+ } else {
+ reify_0px()
+ };
+ translate(Is2D::Yes, reify_numeric_argument(0), y, reify_0px())
+ }
+ TransformFunction::TranslateX => translate(Is2D::Yes, reify_numeric_argument(0), reify_0px(), reify_0px()),
+ TransformFunction::TranslateY => translate(Is2D::Yes, reify_0px(), reify_numeric_argument(0), reify_0px()),
+ TransformFunction::Translate3d => translate(
+ Is2D::No,
+ reify_numeric_argument(0),
+ reify_numeric_argument(1),
+ reify_numeric_argument(2),
+ ),
+ TransformFunction::TranslateZ => translate(Is2D::No, reify_0px(), reify_0px(), reify_numeric_argument(0)),
+
+ // -> scale()
+ // -> scaleX()
+ // -> scaleY()
+ // -> scale3d()
+ // -> scaleZ()
+ // 1. Return a new CSSScale object, whose x, y, and z internal slots are set to the specified x/y/z scales,
+ // or to 1 if not specified in func and whose is2D internal slot is true if func is scale(), scaleX(), or
+ // scaleY(), and false otherwise.
+ TransformFunction::Scale => {
+ // NB: Default y to a copy of x if it's not specified.
+ let y = if values.len() > 1 {
+ reify_numeric_argument(1)
+ } else {
+ reify_numeric_argument(0)
+ };
+ scale(Is2D::Yes, reify_numeric_argument(0), y, reify_1())
+ }
+ TransformFunction::ScaleX => scale(Is2D::Yes, reify_numeric_argument(0), reify_1(), reify_1()),
+ TransformFunction::ScaleY => scale(Is2D::Yes, reify_1(), reify_numeric_argument(0), reify_1()),
+ TransformFunction::Scale3d => scale(
+ Is2D::No,
+ reify_numeric_argument(0),
+ reify_numeric_argument(1),
+ reify_numeric_argument(2),
+ ),
+ TransformFunction::ScaleZ => scale(Is2D::No, reify_1(), reify_1(), reify_numeric_argument(0)),
+
+ // -> rotate()
+ // -> rotate3d()
+ // -> rotateX()
+ // -> rotateY()
+ // -> rotateZ()
+ // 1. Return a new CSSRotate object, whose angle internal slot is set to the reification of the specified
+ // angle, and whose x, y, and z internal slots are set to the specified rotation axis coordinates, or the
+ // implicit axis coordinates if not specified in func and whose is2D internal slot is true if func is
+ // rotate(), and false otherwise.
+ TransformFunction::Rotate => rotate(Is2D::Yes, reify_0(), reify_0(), reify_1(), reify_numeric_argument(0)),
+ TransformFunction::Rotate3d => rotate(
+ Is2D::No,
+ reify_numeric_argument(0),
+ reify_numeric_argument(1),
+ reify_numeric_argument(2),
+ reify_numeric_argument(3),
+ ),
+ TransformFunction::RotateX => rotate(Is2D::No, reify_1(), reify_0(), reify_0(), reify_numeric_argument(0)),
+ TransformFunction::RotateY => rotate(Is2D::No, reify_0(), reify_1(), reify_0(), reify_numeric_argument(0)),
+ TransformFunction::RotateZ => rotate(Is2D::No, reify_0(), reify_0(), reify_1(), reify_numeric_argument(0)),
+
+ // -> skew()
+ // 1. Return a new CSSSkew object, whose ax and ay internal slots are set to the reification of the specified
+ // x and y angles, or the reification of 0deg if not specified in func, and whose is2D internal slot is
+ // true.
+ TransformFunction::Skew => {
+ // NB: Default y to 0deg if it's not specified.
+ let y = if values.len() > 1 {
+ reify_numeric_argument(1)
+ } else {
+ reify_0deg()
+ };
+ AnyCSSTransformComponent::CSSSkew(CSSSkew::create(vm, reify_numeric_argument(0), y))
+ }
+
+ // -> skewX()
+ // 1. Return a new CSSSkewX object, whose ax internal slot is set to the reification of the specified x
+ // angle, or the reification of 0deg if not specified in func, and whose is2D internal slot is true.
+ TransformFunction::SkewX => AnyCSSTransformComponent::CSSSkewX(CSSSkewX::create(vm, reify_numeric_argument(0))),
+
+ // -> skewY()
+ // 1. Return a new CSSSkewY object, whose ay internal slot is set to the reification of the specified y
+ // angle, or the reification of 0deg if not specified in func, and whose is2D internal slot is true.
+ TransformFunction::SkewY => AnyCSSTransformComponent::CSSSkewY(CSSSkewY::create(vm, reify_numeric_argument(0))),
+
+ // -> perspective()
+ // 1. Return a new CSSPerspective object, whose length internal slot is set to the reification of the
+ // specified length (see reify a numeric value if it is a length, and reify an identifier if it is the
+ // keyword none) and whose is2D internal slot is false.
+ TransformFunction::Perspective => {
+ let length = match reification_of(&values[0]) {
+ Reification::Keyword(keyword) => {
+ CSSPerspectiveValueInternal::CSSKeywordValue(CSSKeywordValue::create(vm, keyword))
+ }
+ _ => CSSPerspectiveValueInternal::CSSNumericValue(reify_numeric_argument(0)),
+ };
+ AnyCSSTransformComponent::CSSPerspective(CSSPerspective::create(vm, length))
+ }
+ })
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_transform_value.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_transform_value.rs
new file mode 100644
index 00000000000..f72713d344a
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_transform_value.rs
@@ -0,0 +1,199 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSTransformValue, https://drafts.css-houdini.org/css-typed-om-1/#csstransformvalue
+
+use ak::Utf16String;
+use libjs_rust::api::{GcRefCell, MarkedVec, Trace, Vm};
+use libweb_rust::typed_om::RetainedStyleValue;
+
+use super::css_style_value::{AnyCSSStyleValue, CSSStyleValue, PerformTypeCheck};
+use super::css_transform_component::{AnyCSSTransformComponent, create_dom_matrix};
+use super::typed_om;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::geometry::dom_matrix::DOMMatrix;
+use crate::geometry::dom_matrix_read_only::DOMMatrixReadOnly;
+use crate::geometry::matrix::Matrix4;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSTransformValue {
+ style_value: CSSStyleValue,
+ transforms: GcRefCell<Vec<AnyCSSTransformComponent>>,
+}
+
+impl Wrappable for CSSTransformValue {}
+
+impl Inherits<CSSStyleValue> for CSSTransformValue {
+ fn parent(&self) -> &CSSStyleValue {
+ &self.style_value
+ }
+}
+
+impl CSSTransformValue {
+ pub(crate) fn create(vm: &Vm, transforms: &MarkedVec<'_, AnyCSSTransformComponent>) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ style_value: CSSStyleValue::empty(),
+ transforms: GcRefCell::new(transforms.to_vec()),
+ });
+ object
+ .style_value
+ .set_object(vm, AnyCSSStyleValue::CSSTransformValue(object));
+ object
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformvalue-csstransformvalue
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ transforms: MarkedVec<'_, AnyCSSTransformComponent>,
+ ) -> WebIdlResult<Ref<Self>> {
+ // The CSSTransformValue(transforms) constructor must, when called, perform the following steps:
+
+ // 1. If transforms is empty, throw a TypeError.
+ if transforms.is_empty() {
+ return Err(Exception::type_error(
+ "CSSTransformValue's transforms list cannot be empty.",
+ ));
+ }
+
+ // 2. Return a new CSSTransformValue whose values to iterate over is transforms.
+ Ok(Self::create(cx.vm(), &transforms))
+ }
+
+ pub(crate) fn style_value(&self) -> &CSSStyleValue {
+ &self.style_value
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformvalue-length
+ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ // The length attribute indicates how many transform components are contained within the CSSTransformValue.
+ Ok(u32::try_from(self.transforms.borrow().len()).expect("the list has fewer items than an index can name"))
+ }
+
+ pub(crate) fn item(&self, _: &mut CallContext, index: u32) -> WebIdlResult<AnyCSSTransformComponent> {
+ Ok(self.transforms.borrow()[index as usize])
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#ref-for-dfn-set-the-value-of-an-existing-indexed-property%E2%91%A0
+ pub(crate) fn set_value_of_existing_indexed_property(
+ &self,
+ cx: &mut CallContext,
+ index: u32,
+ value: AnyCSSTransformComponent,
+ ) -> WebIdlResult<()> {
+ // To set the value of an existing indexed property of a CSSTransformValue this, an index n, and a value new
+ // value, let values be this’s [[values]] internal slot, and set values[n] to new value.
+ self.transforms.borrow_mut(cx.vm())[index as usize] = value;
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#ref-for-dfn-set-the-value-of-a-new-indexed-property①
+ pub(crate) fn set_value_of_new_indexed_property(
+ &self,
+ cx: &mut CallContext,
+ index: u32,
+ value: AnyCSSTransformComponent,
+ ) -> WebIdlResult<()> {
+ // To set the value of a new indexed property of a CSSTransformValue this, an index n, and a value new value,
+ // let values be this’s [[values]] internal slot. If n is not equal to the size of values, throw a RangeError.
+ // Otherwise, append new value to values.
+ if index as usize != self.transforms.borrow().len() {
+ return Err(Exception::range_error("Index out of range"));
+ }
+
+ self.transforms.borrow_mut(cx.vm()).push(value);
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformvalue-is2d
+ pub(crate) fn is_2d(&self, _: &mut CallContext) -> WebIdlResult<bool> {
+ // The is2D attribute of a CSSTransformValue this must, on getting, return true if, for each func in this’s
+ // values to iterate over, the func’s is2D attribute would return true; otherwise, the attribute returns false.
+ Ok(self.transforms.borrow().iter().all(|transform| transform.raw_is_2d()))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformvalue-tomatrix
+ pub(crate) fn to_matrix(&self, cx: &mut CallContext) -> WebIdlResult<Ref<DOMMatrix>> {
+ // The toMatrix() method of a CSSTransformValue this must, when called, perform the following steps:
+ let vm = cx.vm();
+
+ // 1. Let matrix be a new DOMMatrix, initialized to the identity matrix, with its is2D internal slot set to
+ // true.
+ // NB: The elements and the slot stay in locals until the matrix is returned.
+ let mut matrix = Matrix4::identity();
+ let mut is_2d = true;
+
+ // 2. For each func in this’s values to iterate over:
+ for function in self.transforms.borrow().iter() {
+ // 1. Let funcMatrix be the DOMMatrix returned by calling toMatrix() on func.
+ // AD-HOC: This can throw exceptions.
+ let function_matrix = function.to_matrix(vm)?;
+ let function_matrix = <DOMMatrix as Inherits<DOMMatrixReadOnly>>::parent(&function_matrix);
+
+ // 2. Set matrix to the result of multiplying matrix and the matrix represented by funcMatrix.
+ matrix = matrix.multiplied(function_matrix.matrix());
+ if !function_matrix.is_2d() {
+ is_2d = false;
+ }
+ }
+
+ // 3. Return matrix.
+ Ok(create_dom_matrix(vm, matrix, is_2d))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-csstransformvalue
+ pub(crate) fn serialize(&self, _: &Vm) -> WebIdlResult<Utf16String> {
+ // 1. Return the result of serializing each item in this’s values to iterate over, then concatenating them
+ // separated by " ".
+ let mut s = String::new();
+ for (index, transform) in self.transforms.borrow().iter().enumerate() {
+ if index != 0 {
+ s.push(' ');
+ }
+ s.push_str(&typed_om::to_rust_string(&transform.serialize()?));
+ }
+ Ok(Utf16String::from_utf8(&s))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+ pub(crate) fn create_an_internal_representation(
+ &self,
+ vm: &Vm,
+ property_id: u16,
+ perform_type_check: PerformTypeCheck,
+ ) -> WebIdlResult<RetainedStyleValue> {
+ // NB: This can become <transform-function> or <transform-list>, and we don't know which is wanted without
+ // performing the type checking.
+ // We can worry about that if and when we ever do have a CSSTransformValue that isn't top-level.
+ assert!(perform_type_check == PerformTypeCheck::Yes);
+
+ // If value is a CSSStyleValue subclass,
+ // If value does not match the grammar of a list-valued property iteration of property, throw a TypeError.
+ //
+ // If any component of property’s CSS grammar has a limited numeric range, and the corresponding part of
+ // value is a CSSUnitValue that is outside of that range, replace that value with the result of wrapping it
+ // in a fresh CSSMathSum whose values internal slot contains only that part of value.
+ //
+ // Return the value.
+
+ // NB: We match <transform-function> if we have 1 transform. We match <transform-list> always.
+ let transforms = self.transforms.borrow();
+ if transforms.len() == 1 && typed_om::property_accepts_transform_function(property_id) {
+ return transforms[0].create_style_value(vm, property_id);
+ }
+
+ if typed_om::property_accepts_transform_list(property_id) {
+ let values = transforms
+ .iter()
+ .map(|transform| transform.create_style_value(vm, property_id))
+ .collect::<WebIdlResult<Vec<_>>>()?;
+ return Ok(typed_om::style_value_list(values));
+ }
+
+ Err(Exception::type_error("Property does not accept values of this type."))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_translate.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_translate.rs
new file mode 100644
index 00000000000..e34eec281df
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_translate.rs
@@ -0,0 +1,249 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSTranslate, https://drafts.css-houdini.org/css-typed-om-1/#csstranslate
+
+use ak::Utf16String;
+use libjs_rust::api::{GcRefCell, Trace, Vm};
+use libweb_rust::typed_om::{BASE_TYPE_LENGTH, RetainedStyleValue, TransformFunction, transformation_style_value};
+
+use super::css_numeric_value::{AnyCSSNumericValue, SerializationParams};
+use super::css_transform_component::{
+ AnyCSSTransformComponent, CSSTransformComponent, Is2D, argument_style_value, create_dom_matrix,
+};
+use super::css_unit_value::CSSUnitValue;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::geometry::dom_matrix::DOMMatrix;
+use crate::geometry::matrix::Matrix4;
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSTranslate {
+ transform_component: CSSTransformComponent,
+ x: GcRefCell<AnyCSSNumericValue>,
+ y: GcRefCell<AnyCSSNumericValue>,
+ z: GcRefCell<AnyCSSNumericValue>,
+}
+
+impl Wrappable for CSSTranslate {}
+
+impl Inherits<CSSTransformComponent> for CSSTranslate {
+ fn parent(&self) -> &CSSTransformComponent {
+ &self.transform_component
+ }
+}
+
+fn matches_length_percentage(value: &AnyCSSNumericValue) -> bool {
+ value
+ .numeric_type()
+ .matches_dimension_percentage(BASE_TYPE_LENGTH, None)
+}
+
+fn matches_length(value: &AnyCSSNumericValue) -> bool {
+ value.numeric_type().matches_dimension(BASE_TYPE_LENGTH, None)
+}
+
+impl CSSTranslate {
+ pub(crate) fn create(
+ vm: &Vm,
+ is_2d: Is2D,
+ x: AnyCSSNumericValue,
+ y: AnyCSSNumericValue,
+ z: AnyCSSNumericValue,
+ ) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ transform_component: CSSTransformComponent::new(is_2d),
+ x: GcRefCell::new(x),
+ y: GcRefCell::new(y),
+ z: GcRefCell::new(z),
+ });
+ AnyCSSTransformComponent::CSSTranslate(object).finish(vm);
+ object
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-csstranslate-csstranslate
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ x: AnyCSSNumericValue,
+ y: AnyCSSNumericValue,
+ z: Option<AnyCSSNumericValue>,
+ ) -> WebIdlResult<Ref<Self>> {
+ // The CSSTranslate(x, y, z) constructor must, when invoked, perform the following steps:
+
+ // 1. If x or y don’t match <length-percentage>, throw a TypeError.
+ if !matches_length_percentage(&x) {
+ return Err(Exception::type_error(
+ "CSSTranslate x component doesn't match <length-percentage>",
+ ));
+ }
+
+ if !matches_length_percentage(&y) {
+ return Err(Exception::type_error(
+ "CSSTranslate y component doesn't match <length-percentage>",
+ ));
+ }
+
+ // 2. If z was passed, but doesn’t match <length>, throw a TypeError.
+ if z.as_ref().is_some_and(|z| !matches_length(z)) {
+ return Err(Exception::type_error("CSSTranslate z component doesn't match <length>"));
+ }
+
+ // 3. Let this be a new CSSTranslate object, with its x and y internal slots set to x and y.
+ // 4. If z was passed, set this’s z internal slot to z, and set this’s is2D internal slot to false.
+ // 5. If z was not passed, set this’s z internal slot to a new unit value of (0, "px"), and set this’s is2D
+ // internal slot to true.
+ let vm = cx.vm();
+ let (is_2d, z) = match z {
+ Some(z) => (Is2D::No, z),
+ None => (
+ Is2D::Yes,
+ AnyCSSNumericValue::CSSUnitValue(CSSUnitValue::create(vm, 0.0, "px")),
+ ),
+ };
+ let this = Self::create(vm, is_2d, x, y, z);
+
+ // 6. Return this.
+ Ok(this)
+ }
+
+ pub(crate) fn x(&self, _: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {
+ Ok(*self.x.borrow())
+ }
+
+ pub(crate) fn y(&self, _: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {
+ Ok(*self.y.borrow())
+ }
+
+ pub(crate) fn z(&self, _: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {
+ Ok(*self.z.borrow())
+ }
+
+ pub(crate) fn set_x(&self, cx: &mut CallContext, x: AnyCSSNumericValue) -> WebIdlResult<()> {
+ // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
+ // WPT expects this to throw for invalid values.
+ if !matches_length_percentage(&x) {
+ return Err(Exception::type_error(
+ "CSSTranslate x component doesn't match <length-percentage>",
+ ));
+ }
+ *self.x.borrow_mut(cx.vm()) = x;
+ Ok(())
+ }
+
+ pub(crate) fn set_y(&self, cx: &mut CallContext, y: AnyCSSNumericValue) -> WebIdlResult<()> {
+ // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
+ // WPT expects this to throw for invalid values.
+ if !matches_length_percentage(&y) {
+ return Err(Exception::type_error(
+ "CSSTranslate y component doesn't match <length-percentage>",
+ ));
+ }
+ *self.y.borrow_mut(cx.vm()) = y;
+ Ok(())
+ }
+
+ pub(crate) fn set_z(&self, cx: &mut CallContext, z: AnyCSSNumericValue) -> WebIdlResult<()> {
+ // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
+ // WPT expects this to throw for invalid values.
+ if !matches_length(&z) {
+ return Err(Exception::type_error("CSSTranslate z component doesn't match <length>"));
+ }
+ *self.z.borrow_mut(cx.vm()) = z;
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-csstranslate
+ pub(crate) fn serialize(&self) -> Utf16String {
+ let params = SerializationParams::default();
+
+ // 1. Let s initially be the empty string.
+ let mut s = String::new();
+
+ // 2. If this’s is2D internal slot is false:
+ if !self.transform_component.raw_is_2d() {
+ // 1. Append "translate3d(" to s.
+ s.push_str("translate3d(");
+
+ // 2. Serialize this’s x internal slot, and append it to s.
+ self.x.borrow().serialize(&mut s, params);
+
+ // 3. Append ", " to s.
+ s.push_str(", ");
+
+ // 4. Serialize this’s y internal slot, and append it to s.
+ self.y.borrow().serialize(&mut s, params);
+
+ // 5. Append ", " to s.
+ s.push_str(", ");
+
+ // 6. Serialize this’s z internal slot, and append it to s.
+ self.z.borrow().serialize(&mut s, params);
+
+ // 7. Append ")" to s, and return s.
+ s.push(')');
+ }
+ // 3. Otherwise:
+ else {
+ // 1. Append "translate(" to s.
+ s.push_str("translate(");
+
+ // 2. Serialize this’s x internal slot, and append it to s.
+ self.x.borrow().serialize(&mut s, params);
+
+ // 3. Append ", " to s.
+ s.push_str(", ");
+
+ // 4. Serialize this’s y internal slot, and append it to s.
+ self.y.borrow().serialize(&mut s, params);
+
+ // 5. Append ")" to s, and return s.
+ s.push(')');
+ }
+ Utf16String::from_utf8(&s)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformcomponent-tomatrix
+ pub(crate) fn to_matrix(&self, vm: &Vm) -> WebIdlResult<Ref<DOMMatrix>> {
+ // 1. Let matrix be a new DOMMatrix object, initialized to this’s equivalent 4x4 transform matrix, as defined in
+ // CSS Transforms 1 § 12. Mathematical Description of Transform Functions, and with its is2D internal slot
+ // set to the same value as this’s is2D internal slot.
+ // NOTE: Recall that the is2D flag affects what transform, and thus what equivalent matrix, a
+ // CSSTransformComponent represents.
+ // As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in
+ // generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a
+ // TypeError.
+ let is_2d = self.transform_component.raw_is_2d();
+ let x = self.x.borrow().to_unit(vm, "px")?.raw_value();
+ let y = self.y.borrow().to_unit(vm, "px")?.raw_value();
+
+ let mut z = 0.0;
+ if !is_2d {
+ z = self.z.borrow().to_unit(vm, "px")?.raw_value();
+ }
+
+ Ok(create_dom_matrix(vm, Matrix4::translation(x, y, z), is_2d))
+ }
+
+ pub(crate) fn create_style_value(&self, vm: &Vm, property_id: u16) -> WebIdlResult<RetainedStyleValue> {
+ let x = argument_style_value(vm, property_id, *self.x.borrow())?;
+ let y = argument_style_value(vm, property_id, *self.y.borrow())?;
+ if self.transform_component.raw_is_2d() {
+ return Ok(transformation_style_value(
+ property_id,
+ TransformFunction::Translate,
+ vec![x, y],
+ ));
+ }
+
+ let z = argument_style_value(vm, property_id, *self.z.borrow())?;
+ Ok(transformation_style_value(
+ property_id,
+ TransformFunction::Translate3d,
+ vec![x, y, z],
+ ))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_unit_value.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_unit_value.rs
new file mode 100644
index 00000000000..a7748766677
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_unit_value.rs
@@ -0,0 +1,237 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSUnitValue, https://drafts.css-houdini.org/css-typed-om-1/#cssunitvalue
+
+use core::cell::Cell;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::{Trace, Vm};
+use libweb_rust::typed_om::{
+ CalcNode, NumericValue, RetainedStyleValue, SumValue, SumValueItem, UnitMap, conversion_ratio,
+ create_a_type_from_unit, in_canonical_unit, serialize_a_number,
+};
+
+use super::css_numeric_value::{AnyCSSNumericValue, CSSNumericValue};
+use super::css_style_value::PerformTypeCheck;
+use super::typed_om;
+use crate::bindings::conversions::UsvString;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSUnitValue {
+ numeric_value: CSSNumericValue,
+ #[gc(untraced)]
+ value: Cell<f64>,
+ #[gc(untraced)]
+ unit: String,
+}
+
+impl Wrappable for CSSUnitValue {}
+
+impl Inherits<CSSNumericValue> for CSSUnitValue {
+ fn parent(&self) -> &CSSNumericValue {
+ &self.numeric_value
+ }
+}
+
+impl CSSUnitValue {
+ /// A new CSSUnitValue with a unit that is known to be one.
+ pub(crate) fn create(vm: &Vm, value: f64, unit: &str) -> Ref<Self> {
+ // The type of a CSSUnitValue is the result of creating a type from its unit internal slot.
+ // https://drafts.css-houdini.org/css-typed-om-1/#type-of-a-cssunitvalue
+ let numeric_type = create_a_type_from_unit(unit).expect("the unit of a CSSUnitValue is a unit");
+ let object = allocate(vm, |_| Self {
+ numeric_value: CSSNumericValue::new(numeric_type),
+ value: Cell::new(value),
+ // AD-HOC: WPT expects the unit to be lowercase but this doesn't seem to be specified anywhere.
+ unit: unit.to_ascii_lowercase(),
+ });
+ AnyCSSNumericValue::CSSUnitValue(object).finish(vm);
+ object
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-a-cssunitvalue-from-a-sum-value-item
+ pub(crate) fn create_from_sum_value_item(vm: &Vm, item: &SumValueItem) -> Option<Ref<Self>> {
+ // 1. If item has more than one entry in its unit map, return failure.
+ if item.unit_map.len() > 1 {
+ return None;
+ }
+
+ // 2. If item has no entries in its unit map, return a new CSSUnitValue whose unit internal slot is set to
+ // "number", and whose value internal slot is set to item’s value.
+ let Some((unit, power)) = item.unit_map.iter().next() else {
+ return Some(Self::create(vm, item.value, "number"));
+ };
+
+ // 3. Otherwise, item has a single entry in its unit map. If that entry’s value is anything other than 1, return
+ // failure.
+ if *power != 1 {
+ return None;
+ }
+
+ // 4. Otherwise, return a new CSSUnitValue whose unit internal slot is set to that entry’s key, and whose value
+ // internal slot is set to item’s value.
+ Some(Self::create(vm, item.value, unit))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssunitvalue-cssunitvalue
+ pub(crate) fn construct(cx: &mut CallContext, value: f64, unit: UsvString) -> WebIdlResult<Ref<Self>> {
+ // 1. If creating a type from unit returns failure, throw a TypeError and abort this algorithm.
+ let unit = typed_om::to_rust_string(&unit.into_utf16_string());
+ if create_a_type_from_unit(&unit).is_none() {
+ return Err(Exception::type_error(
+ "Cannot create CSSUnitValue with unrecognized unit",
+ ));
+ }
+
+ // 2. Return a new CSSUnitValue with its value internal slot set to value and its unit set to unit.
+ Ok(Self::create(cx.vm(), value, &unit))
+ }
+
+ pub(crate) fn raw_value(&self) -> f64 {
+ self.value.get()
+ }
+
+ pub(crate) fn raw_unit(&self) -> &str {
+ &self.unit
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssunitvalue-value
+ pub(crate) fn value(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ Ok(self.value.get())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssunitvalue-value
+ pub(crate) fn set_value(&self, _: &mut CallContext, value: f64) -> WebIdlResult<()> {
+ // AD-HOC: No definition: https://github.com/w3c/css-houdini-drafts/issues/1146
+ self.value.set(value);
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssunitvalue-unit
+ pub(crate) fn unit(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(Utf16String::from_utf8(&self.unit))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssunitvalue
+ pub(crate) fn serialize_unit_value(&self, s: &mut String, minimum: Option<f64>, maximum: Option<f64>) {
+ // To serialize a CSSUnitValue this, with optional arguments minimum, a numeric value, and maximum, a numeric
+ // value:
+
+ // 1. Let value and unit be this‘s value and unit internal slots.
+ let value = self.value.get();
+
+ // 4. If minimum was passed and this is less than minimum, or if maximum was passed and this is greater than
+ // maximum, or either minimum and/or maximum were passed and the relative size of this and minimum/maximum
+ // can’t be determined with the available information at this time, prepend "calc(" to s, then append ")" to
+ // s.
+ // NB: This step is done first to avoid prepending to the string.
+ // FIXME: "or either minimum and/or maximum were passed and the relative size of this and minimum/maximum can't
+ // be determined with the available information at this time"
+ let needs_calc_wrapper =
+ minimum.is_some_and(|minimum| value < minimum) || maximum.is_some_and(|maximum| value > maximum);
+ if needs_calc_wrapper {
+ s.push_str("calc(");
+ }
+
+ // 2. Set s to the result of serializing a <number> from value, per CSSOM §6.7.2 Serializing CSS Values.
+ serialize_a_number(s, value);
+
+ // 3. If unit is:
+ match self.unit.as_str() {
+ // -> "number"
+ // Do nothing.
+ "number" => {}
+ // -> "percent"
+ // Append "%" to s.
+ "percent" => s.push('%'),
+ // -> anything else
+ // Append unit to s.
+ unit => s.push_str(unit),
+ }
+
+ if needs_calc_wrapper {
+ s.push(')');
+ }
+
+ // 5. Return s.
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#convert-a-cssunitvalue
+ pub(crate) fn converted_to_unit(&self, vm: &Vm, unit: &str) -> Option<Ref<Self>> {
+ // 1. Let old unit be the value of this’s unit internal slot, and old value be the value of this’s value
+ // internal slot.
+ // 2. If old unit and unit are not compatible units, return failure.
+ let ratio = conversion_ratio(&self.unit, unit)?;
+
+ // 3. Return a new CSSUnitValue whose unit internal slot is set to unit, and whose value internal slot is set to
+ // old value multiplied by the conversation ratio between old unit and unit.
+ Some(Self::create(vm, self.value.get() * ratio, unit))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#equal-numeric-value
+ pub(crate) fn is_equal_unit_value(&self, other: &Self) -> bool {
+ // 2. If value1 and value2 are both CSSUnitValues, return true if they have equal unit and value internal slots,
+ // or false otherwise.
+ self.unit == other.unit && self.value.get() == other.value.get()
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
+ pub(crate) fn create_a_sum_value(&self) -> SumValue {
+ // 1. Let unit be the value of this’s unit internal slot, and value be the value of this’s value internal slot.
+ // 2. If unit is a member of a set of compatible units, and is not the set’s canonical unit, multiply value by
+ // the conversion ratio between unit and the canonical unit, and change unit to the canonical unit.
+ let (value, unit) = in_canonical_unit(self.value.get(), &self.unit);
+
+ // 3. If unit is "number", return «(value, «[ ]»)».
+ if unit == "number" {
+ return vec![SumValueItem {
+ value,
+ unit_map: UnitMap::new(),
+ }];
+ }
+
+ // 4. Otherwise, return «(value, «[unit → 1]»)».
+ vec![SumValueItem {
+ value,
+ unit_map: UnitMap::from([(unit, 1)]),
+ }]
+ }
+
+ pub(crate) fn create_calculation_node(&self) -> WebIdlResult<Arc<CalcNode>> {
+ NumericValue::from_unit(self.value.get(), &self.unit)
+ .map(NumericValue::calculation_node)
+ .ok_or_else(|| Exception::type_error("Unable to create calculation node."))
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+ pub(crate) fn create_an_internal_representation(
+ &self,
+ property_id: u16,
+ perform_type_check: PerformTypeCheck,
+ ) -> WebIdlResult<RetainedStyleValue> {
+ // If value is a CSSStyleValue subclass,
+ // If value does not match the grammar of a list-valued property iteration of property, throw a TypeError.
+ //
+ // If any component of property’s CSS grammar has a limited numeric range, and the corresponding part of
+ // value is a CSSUnitValue that is outside of that range, replace that value with the result of wrapping it
+ // in a fresh CSSMathSum whose values internal slot contains only that part of value.
+ //
+ // Return the value.
+ let Some(value) = NumericValue::from_unit(self.value.get(), &self.unit) else {
+ return Err(Exception::type_error("Unrecognized unit."));
+ };
+ if perform_type_check == PerformTypeCheck::No {
+ return Ok(value.style_value());
+ }
+ typed_om::numeric_style_value_for_property(property_id, value, self.numeric_value.numeric_type())
+ .ok_or_else(|| Exception::type_error("Property does not accept values of this type."))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_unparsed_value.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_unparsed_value.rs
new file mode 100644
index 00000000000..16ab2321360
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_unparsed_value.rs
@@ -0,0 +1,170 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSUnparsedValue, https://drafts.css-houdini.org/css-typed-om-1/#cssunparsedvalue
+
+use ak::Utf16String;
+use libjs_rust::api::{GcRefCell, MarkedVec, Trace, Vm};
+use libweb_rust::typed_om::{RetainedStyleValue, unresolved_style_value};
+
+use super::css_style_value::{AnyCSSStyleValue, CSSStyleValue};
+use super::css_variable_reference_value::CSSVariableReferenceValue;
+use crate::bindings::conversions::UsvString;
+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+/// The union (USVString or CSSVariableReferenceValue) of CSS/CSSUnparsedValue.idl.
+#[derive(Clone, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) enum CSSUnparsedSegment {
+ USVString(#[gc(untraced)] UsvString),
+ CSSVariableReferenceValue(Ref<CSSVariableReferenceValue>),
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSUnparsedValue {
+ style_value: CSSStyleValue,
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssunparsedvalue-tokens-slot
+ tokens: GcRefCell<Vec<CSSUnparsedSegment>>,
+}
+
+impl Wrappable for CSSUnparsedValue {}
+
+impl Inherits<CSSStyleValue> for CSSUnparsedValue {
+ fn parent(&self) -> &CSSStyleValue {
+ &self.style_value
+ }
+}
+
+impl CSSUnparsedValue {
+ pub(crate) fn create(vm: &Vm, members: &MarkedVec<'_, CSSUnparsedSegment>) -> Ref<Self> {
+ let object = allocate(vm, |_| Self {
+ style_value: CSSStyleValue::empty(),
+ tokens: GcRefCell::new(members.to_vec()),
+ });
+ object
+ .style_value
+ .set_object(vm, AnyCSSStyleValue::CSSUnparsedValue(object));
+ object
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssunparsedvalue-cssunparsedvalue
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ members: MarkedVec<'_, CSSUnparsedSegment>,
+ ) -> WebIdlResult<Ref<Self>> {
+ // AD-HOC: There is no spec for this, see https://github.com/w3c/css-houdini-drafts/issues/1146
+ Ok(Self::create(cx.vm(), &members))
+ }
+
+ pub(crate) fn style_value(&self) -> &CSSStyleValue {
+ &self.style_value
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssunparsedvalue-length
+ pub(crate) fn length(&self, _: &mut CallContext) -> WebIdlResult<u32> {
+ // The length attribute returns the size of the [[tokens]] internal slot.
+ Ok(u32::try_from(self.tokens.borrow().len()).expect("the value has fewer tokens than an index can name"))
+ }
+
+ pub(crate) fn item(&self, _: &mut CallContext, index: u32) -> WebIdlResult<CSSUnparsedSegment> {
+ Ok(self.tokens.borrow()[index as usize].clone())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#ref-for-dfn-set-the-value-of-an-existing-indexed-property
+ pub(crate) fn set_value_of_existing_indexed_property(
+ &self,
+ cx: &mut CallContext,
+ n: u32,
+ new_value: CSSUnparsedSegment,
+ ) -> WebIdlResult<()> {
+ // To set the value of an existing indexed property of a CSSUnparsedValue this, an index n, and a value new
+ // value, let tokens be this’s [[tokens]] internal slot, and set tokens[n] to new value.
+ self.tokens.borrow_mut(cx.vm())[n as usize] = new_value;
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#ref-for-dfn-set-the-value-of-a-new-indexed-property
+ pub(crate) fn set_value_of_new_indexed_property(
+ &self,
+ cx: &mut CallContext,
+ n: u32,
+ new_value: CSSUnparsedSegment,
+ ) -> WebIdlResult<()> {
+ // To set the value of a new indexed property of a CSSUnparsedValue this, an index n, and a value new value, let
+ // tokens be this’s [[tokens]] internal slot. If n is not equal to the size of tokens, throw a RangeError.
+ // Otherwise, append new value to tokens.
+ let mut tokens = self.tokens.borrow_mut(cx.vm());
+ if n as usize != tokens.len() {
+ return Err(Exception::range_error("Index out of range"));
+ }
+ tokens.push(new_value);
+ Ok(())
+ }
+
+ fn contains_unparsed_value(&self, needle: &Self) -> bool {
+ self.tokens.borrow().iter().any(|segment| {
+ let CSSUnparsedSegment::CSSVariableReferenceValue(variable_reference) = segment else {
+ return false;
+ };
+ let Some(fallback) = variable_reference.raw_fallback() else {
+ return false;
+ };
+ let fallback: &Self = &fallback;
+ core::ptr::eq(fallback, needle) || fallback.contains_unparsed_value(needle)
+ })
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssunparsedvalue
+ pub(crate) fn serialize(&self) -> Utf16String {
+ // AD-HOC: It's possible for one of the tokens to contain this in its fallback slot, or a similar situation with
+ // more levels of nesting. To avoid crashing, do a scan for that first and return the empty string.
+ // Spec issue: https://github.com/w3c/css-houdini-drafts/issues/1158
+ if self.contains_unparsed_value(self) {
+ return Utf16String::default();
+ }
+
+ // To serialize a CSSUnparsedValue this:
+ // 1. Let s initially be the empty string.
+ let mut s = Vec::new();
+
+ // 2. For each item in this’s [[tokens]] internal slot:
+ for item in self.tokens.borrow().iter() {
+ // FIXME: In order to match the expected test behaviour, this should insert comments, with the same rules as
+ // serialize_a_series_of_component_values(). See https://github.com/w3c/css-houdini-drafts/issues/1148
+ match item {
+ // 1. If item is a USVString, append it to s.
+ CSSUnparsedSegment::USVString(string) => s.extend_from_slice(&string.to_utf16()),
+ // 2. Otherwise, item is a CSSVariableReferenceValue. Serialize it, then append the result to s.
+ CSSUnparsedSegment::CSSVariableReferenceValue(variable) => variable.serialize(&mut s),
+ }
+ }
+
+ // 3. Return s.
+ Utf16String::from_utf16(&s)
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+ pub(crate) fn create_an_internal_representation(&self) -> WebIdlResult<RetainedStyleValue> {
+ // If value is a CSSStyleValue subclass,
+ // If value does not match the grammar of a list-valued property iteration of property, throw a TypeError.
+ //
+ // If any component of property’s CSS grammar has a limited numeric range, and the corresponding part of
+ // value is a CSSUnitValue that is outside of that range, replace that value with the result of wrapping it
+ // in a fresh CSSMathSum whose values internal slot contains only that part of value.
+ //
+ // Return the value.
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#cssstylevalue-match-a-grammar
+ // A CSSUnparsedValue matches any grammar.
+
+ // NB: CSSUnparsedValue stores a list of strings, each of which may contain any number of tokens. So the
+ // simplest way to convert it to ComponentValues is to serialize and then parse it.
+ unresolved_style_value(&self.serialize())
+ .ok_or_else(|| Exception::type_error("Invalid arbitrary substitution function syntax"))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_variable_reference_value.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_variable_reference_value.rs
new file mode 100644
index 00000000000..bd4f6f53287
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_variable_reference_value.rs
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! CSSVariableReferenceValue, https://drafts.css-houdini.org/css-typed-om-1/#cssvariablereferencevalue
+
+use core::cell::RefCell;
+
+use ak::Utf16String;
+use libjs_rust::api::{GcRefCell, Trace, Vm};
+use libweb_rust::typed_om::is_a_custom_property_name_string;
+
+use super::css_unparsed_value::CSSUnparsedValue;
+use super::typed_om;
+use crate::bindings::conversions::UsvString;
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct CSSVariableReferenceValue {
+ #[gc(untraced)]
+ variable: RefCell<Utf16String>,
+ fallback: GcRefCell<Option<Ref<CSSUnparsedValue>>>,
+}
+
+impl Wrappable for CSSVariableReferenceValue {}
+
+fn not_a_custom_property_name(variable: &Utf16String) -> Exception {
+ Exception::TypeError(Utf16String::from_utf8(&format!(
+ "'{}' is not a valid CSS custom property name",
+ typed_om::to_rust_string(variable)
+ )))
+}
+
+impl CSSVariableReferenceValue {
+ pub(crate) fn create(vm: &Vm, variable: Utf16String, fallback: Option<Ref<CSSUnparsedValue>>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ variable: RefCell::new(variable),
+ fallback: GcRefCell::new(fallback),
+ })
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssvariablereferencevalue-cssvariablereferencevalue
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ variable: UsvString,
+ fallback: Option<Ref<CSSUnparsedValue>>,
+ ) -> WebIdlResult<Ref<Self>> {
+ // The CSSVariableReferenceValue(variable, fallback) constructor must, when called, perform the following steps:
+ // 1. If variable is not a custom property name string, throw a TypeError.
+ let variable = variable.into_utf16_string();
+ if !is_a_custom_property_name_string(&variable) {
+ return Err(not_a_custom_property_name(&variable));
+ }
+
+ // 2. Return a new CSSVariableReferenceValue with its variable internal slot set to variable and its fallback
+ // internal slot set to fallback.
+ Ok(Self::create(cx.vm(), variable, fallback))
+ }
+
+ pub(crate) fn raw_fallback(&self) -> Option<Ref<CSSUnparsedValue>> {
+ *self.fallback.borrow()
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssvariablereferencevalue-variable
+ pub(crate) fn variable(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ // The getter for the variable attribute of a CSSVariableReferenceValue this must return its variable internal
+ // slot.
+ Ok(self.variable.borrow().clone())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssvariablereferencevalue-variable
+ pub(crate) fn set_variable(&self, _: &mut CallContext, variable: UsvString) -> WebIdlResult<()> {
+ // The variable attribute of a CSSVariableReferenceValue this must, on setting a variable variable, perform the
+ // following steps:
+ // 1. If variable is not a custom property name string, throw a TypeError.
+ let variable = variable.into_utf16_string();
+ if !is_a_custom_property_name_string(&variable) {
+ return Err(not_a_custom_property_name(&variable));
+ }
+
+ // 2. Otherwise, set this’s variable internal slot to variable.
+ *self.variable.borrow_mut() = variable;
+ Ok(())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssvariablereferencevalue-fallback
+ pub(crate) fn fallback(&self, _: &mut CallContext) -> WebIdlResult<Option<Ref<CSSUnparsedValue>>> {
+ // AD-HOC: No spec algorithm, see https://github.com/w3c/css-houdini-drafts/issues/1146#issuecomment-3188550133
+ Ok(self.raw_fallback())
+ }
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssvariablereferencevalue
+ pub(crate) fn serialize(&self, s: &mut Vec<u16>) {
+ // To serialize a CSSVariableReferenceValue this:
+ // 1. Let s initially be "var(".
+ s.extend("var(".encode_utf16());
+
+ // 2. Append this’s variable internal slot to s.
+ s.extend_from_slice(&self.variable.borrow().to_utf16());
+
+ // 3. If this’s fallback internal slot is not null, append ", " to s, then serialize the fallback internal slot
+ // and append it to s.
+ if let Some(fallback) = self.raw_fallback() {
+ // AD-HOC: Tested behaviour requires we append "," without the space.
+ // https://github.com/w3c/css-houdini-drafts/issues/1148
+ s.push(u16::from(b','));
+ s.extend_from_slice(&fallback.serialize().to_utf16());
+ }
+
+ // 4. Append ")" to s and return s.
+ s.push(u16::from(b')'));
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
index 771482b465a..52e963ee3ea 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs
@@ -4,16 +4,36 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! What the C++ code of LibWeb asks of the interfaces of CSS, declared in Libraries/LibWeb/CSS/MediaList.cpp.
+//! What the C++ code of LibWeb asks of the interfaces of CSS, declared in Libraries/LibWeb/CSS/MediaList.cpp and
+//! Libraries/LibWeb/CSS/TypedOM.cpp.
use core::ffi::c_void;
+use std::sync::Arc;
-use libjs_rust::api::Vm;
+use ak::Utf16String;
+use libjs_rust::api::{MarkedVec, Vm};
use libweb_rust::NativeMediaList;
+use libweb_rust::typed_om::{FfiNumericType, RetainedStyleValue};
+use super::css_image_value::CSSImageValue;
+use super::css_keyword_value::CSSKeywordValue;
+use super::css_math_clamp::CSSMathClamp;
+use super::css_math_invert::CSSMathInvert;
+use super::css_math_max::CSSMathMax;
+use super::css_math_min::CSSMathMin;
+use super::css_math_negate::CSSMathNegate;
+use super::css_math_product::CSSMathProduct;
+use super::css_math_sum::CSSMathSum;
+use super::css_numeric_value::AnyCSSNumericValue;
+use super::css_style_value::{AnyCSSStyleValue, CSSStyleValue, PerformTypeCheck};
+use super::css_transform_value::CSSTransformValue;
+use super::css_unit_value::CSSUnitValue;
+use super::css_unparsed_value::CSSUnparsedValue;
use super::media_list::MediaList;
+use super::typed_om;
+use crate::bindings::Exception;
use crate::bindings::cpp_cell::CppCell;
-use crate::bindings::interface::{Ref, allocate, cell_from_abi, cell_into_abi};
+use crate::bindings::interface::{Ref, allocate, cell_from_abi, cell_if_abi, cell_into_abi};
/// # Safety
///
@@ -83,3 +103,324 @@ pub unsafe extern "C" fn web_media_list_share_native_list(list: *mut c_void) ->
let media = unsafe { media_list_from_abi(list) }.share_media();
Box::into_raw(Box::new(media))
}
+
+/// The object of the cell of a CSSStyleValue or of an interface that inherits from it.
+///
+/// # Safety
+///
+/// `cell` must be the live cell of such an object.
+unsafe fn style_value_from_abi(cell: *mut c_void) -> AnyCSSStyleValue {
+ macro_rules! decode {
+ ($($interface:ident),+ $(,)?) => {
+ $(
+ // SAFETY: The caller passes a live cell.
+ if let Some(object) = unsafe { cell_if_abi::<$interface>(cell) } {
+ return AnyCSSStyleValue::$interface(object);
+ }
+ )+
+ };
+ }
+ decode!(
+ CSSUnitValue,
+ CSSMathSum,
+ CSSMathProduct,
+ CSSMathNegate,
+ CSSMathInvert,
+ CSSMathMin,
+ CSSMathMax,
+ CSSMathClamp,
+ CSSKeywordValue,
+ CSSUnparsedValue,
+ CSSTransformValue,
+ CSSImageValue,
+ CSSStyleValue,
+ );
+ unreachable!("C++ passes the cell of a CSSStyleValue")
+}
+
+/// The object of the cell of a CSSNumericValue.
+///
+/// # Safety
+///
+/// `cell` must be the live cell of a CSSNumericValue.
+unsafe fn numeric_value_from_abi(cell: *mut c_void) -> AnyCSSNumericValue {
+ // SAFETY: The caller passes a live cell.
+ unsafe { style_value_from_abi(cell) }
+ .as_numeric()
+ .expect("C++ passes the cell of a CSSNumericValue")
+}
+
+/// Hands the message of a type error to C++, which throws it, as the steps that C++ calls throw nothing else.
+fn type_error_into_abi(exception: Exception, error: *mut usize) {
+ let Exception::TypeError(message) = exception else {
+ unreachable!("the steps of the CSS Typed OM that C++ calls only throw TypeErrors");
+ };
+ // SAFETY: The caller of the export passes a place for the string.
+ unsafe { *error = message.into_raw() };
+}
+
+/// A new CSSStyleValue, given a raw string and a style value that C++ hands over.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, `associated_property` a raw string and `source_value` a strong reference to a style value
+/// that C++ hands over.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_style_value_create(
+ vm: *mut c_void,
+ associated_property: usize,
+ source_value: *const c_void,
+ serialization_mode: u8,
+) -> *mut c_void {
+ // SAFETY: The caller passes the live VM.
+ let vm = unsafe { vm_from_abi(vm) };
+ // SAFETY: The caller hands over the string and the style value.
+ let (associated_property, source_value) = unsafe {
+ (
+ Utf16String::from_raw_owned(associated_property),
+ RetainedStyleValue::from_raw(source_value),
+ )
+ };
+ cell_into_abi(CSSStyleValue::create(
+ vm,
+ associated_property,
+ source_value,
+ serialization_mode,
+ ))
+}
+
+/// # Safety
+///
+/// `vm` must be the live VM, `value` a strong reference to a style value and `associated_property` a raw string that
+/// C++ hands over.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_style_value_reify(
+ vm: *mut c_void,
+ value: *const c_void,
+ associated_property: usize,
+) -> *mut c_void {
+ // SAFETY: The caller passes the live VM.
+ let vm = unsafe { vm_from_abi(vm) };
+ // SAFETY: The caller hands over the string and the style value.
+ let (value, associated_property) = unsafe {
+ (
+ RetainedStyleValue::from_raw(value),
+ Utf16String::from_raw_owned(associated_property),
+ )
+ };
+ typed_om::reify(vm, &value, &associated_property).cell_into_abi()
+}
+
+/// The first value of parsing a CSSStyleValue, or null with the message of the TypeError in `error`.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, `property` and `css_text` raw strings that C++ hands over, and `error` a place for a raw
+/// string.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_style_value_parse(
+ vm: *mut c_void,
+ property: usize,
+ css_text: usize,
+ error: *mut usize,
+) -> *mut c_void {
+ // SAFETY: The caller passes the live VM.
+ let vm = unsafe { vm_from_abi(vm) };
+ // SAFETY: The caller hands over the strings.
+ let (property, css_text) = unsafe {
+ (
+ Utf16String::from_raw_owned(property),
+ Utf16String::from_raw_owned(css_text),
+ )
+ };
+ match typed_om::parse_values(vm, property, css_text) {
+ Ok(values) => values
+ .get(0)
+ .expect("parsing results in at least one value")
+ .cell_into_abi(),
+ Err(exception) => {
+ type_error_into_abi(exception, error);
+ core::ptr::null_mut()
+ }
+ }
+}
+
+/// Whether the value has an associated property, which goes to `associated_property` as a raw string.
+///
+/// # Safety
+///
+/// `value` must be the live cell of a CSSStyleValue, and `associated_property` a place for a raw string.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_style_value_associated_property(
+ value: *mut c_void,
+ associated_property: *mut usize,
+) -> bool {
+ // SAFETY: The caller passes a live cell.
+ let value = unsafe { style_value_from_abi(value) };
+ let Some(property) = value.style_value().associated_property() else {
+ return false;
+ };
+ // SAFETY: The caller passes a place for the string.
+ unsafe { *associated_property = property.clone().into_raw() };
+ true
+}
+
+/// The internal representation as a strong reference, or null with the message of the TypeError in `error`.
+///
+/// # Safety
+///
+/// `vm` must be the live VM, `value` the live cell of a CSSStyleValue, `property_name` a raw string that C++ hands over,
+/// and `error` a place for a raw string.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_style_value_create_an_internal_representation(
+ vm: *mut c_void,
+ value: *mut c_void,
+ property_id: u16,
+ property_name: usize,
+ perform_type_check: bool,
+ error: *mut usize,
+) -> *const c_void {
+ // SAFETY: The caller passes the live VM.
+ let vm = unsafe { vm_from_abi(vm) };
+ // SAFETY: The caller passes a live cell.
+ let value = unsafe { style_value_from_abi(value) };
+ // SAFETY: The caller hands over the string.
+ let property_name = unsafe { Utf16String::from_raw_owned(property_name) };
+ let perform_type_check = if perform_type_check {
+ PerformTypeCheck::Yes
+ } else {
+ PerformTypeCheck::No
+ };
+ match value.create_an_internal_representation(vm, property_id, &property_name, perform_type_check) {
+ Ok(representation) => representation.into_raw(),
+ Err(exception) => {
+ type_error_into_abi(exception, error);
+ core::ptr::null()
+ }
+ }
+}
+
+/// What C++ distinguishes CSSStyleValues by, whose order is that of `enum class StyleValueKind` in
+/// Libraries/LibWeb/CSS/TypedOM.cpp.
+#[repr(u8)]
+enum StyleValueKind {
+ Other,
+ Numeric,
+ Unit,
+ Unparsed,
+}
+
+/// # Safety
+///
+/// `value` must be the live cell of a CSSStyleValue.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_style_value_kind(value: *mut c_void) -> u8 {
+ // SAFETY: The caller passes a live cell.
+ let value = unsafe { style_value_from_abi(value) };
+ let kind = match value {
+ AnyCSSStyleValue::CSSUnitValue(_) => StyleValueKind::Unit,
+ AnyCSSStyleValue::CSSUnparsedValue(_) => StyleValueKind::Unparsed,
+ value if value.as_numeric().is_some() => StyleValueKind::Numeric,
+ _ => StyleValueKind::Other,
+ };
+ kind as u8
+}
+
+/// # Safety
+///
+/// `vm` must be the live VM, and `first` and `second` live cells of CSSNumericValues whose types can be added.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_numeric_value_create_sum(
+ vm: *mut c_void,
+ first: *mut c_void,
+ second: *mut c_void,
+) -> *mut c_void {
+ // SAFETY: The caller passes the live VM.
+ let vm = unsafe { vm_from_abi(vm) };
+ let values = MarkedVec::new(vm);
+ // SAFETY: The caller passes live cells.
+ unsafe {
+ values.push(numeric_value_from_abi(first));
+ values.push(numeric_value_from_abi(second));
+ }
+ let Ok(sum) = CSSMathSum::add_all_types_into_math_sum(vm, &values) else {
+ unreachable!("C++ passes values whose types can be added");
+ };
+ cell_into_abi(sum)
+}
+
+/// # Safety
+///
+/// `value` must be the live cell of a CSSNumericValue.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_numeric_value_type(value: *mut c_void) -> FfiNumericType {
+ // SAFETY: The caller passes a live cell.
+ FfiNumericType::from_calc(Some(unsafe { numeric_value_from_abi(value) }.numeric_type()))
+}
+
+/// The serialization of the value, as a raw string for C++.
+///
+/// # Safety
+///
+/// `value` must be the live cell of a CSSNumericValue.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_numeric_value_to_string(value: *mut c_void) -> usize {
+ // SAFETY: The caller passes a live cell.
+ unsafe { numeric_value_from_abi(value) }.to_css_string().into_raw()
+}
+
+/// A strong reference to the calculation of the value, or null if it has none.
+///
+/// # Safety
+///
+/// `value` must be the live cell of a CSSNumericValue.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_numeric_value_create_calculation_node(value: *mut c_void) -> *const c_void {
+ // SAFETY: The caller passes a live cell.
+ match unsafe { numeric_value_from_abi(value) }.create_calculation_node() {
+ Ok(node) => Arc::into_raw(node).cast(),
+ Err(_) => core::ptr::null(),
+ }
+}
+
+/// # Safety
+///
+/// `vm` must be the live VM, and `unit` a raw string that C++ hands over.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_unit_value_create(vm: *mut c_void, value: f64, unit: usize) -> *mut c_void {
+ // SAFETY: The caller passes the live VM.
+ let vm = unsafe { vm_from_abi(vm) };
+ // SAFETY: The caller hands over the string.
+ let unit = unsafe { Utf16String::from_raw_owned(unit) };
+ cell_into_abi(CSSUnitValue::create(vm, value, &typed_om::to_rust_string(&unit)))
+}
+
+/// # Safety
+///
+/// `value` must be the live cell of a CSSUnitValue.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_unit_value_value(value: *mut c_void) -> f64 {
+ // SAFETY: The caller passes a live cell of a CSSUnitValue.
+ let value: Ref<CSSUnitValue> = unsafe { cell_from_abi(value) };
+ value.raw_value()
+}
+
+/// # Safety
+///
+/// `value` must be the live cell of a CSSUnitValue.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_unit_value_unit(value: *mut c_void) -> usize {
+ // SAFETY: The caller passes a live cell of a CSSUnitValue.
+ let value: Ref<CSSUnitValue> = unsafe { cell_from_abi(value) };
+ Utf16String::from_utf8(value.raw_unit()).into_raw()
+}
+
+/// # Safety
+///
+/// `value` must be the live cell of a CSSKeywordValue.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_css_keyword_value_value(value: *mut c_void) -> usize {
+ // SAFETY: The caller passes a live cell of a CSSKeywordValue.
+ let value: Ref<CSSKeywordValue> = unsafe { cell_from_abi(value) };
+ value.raw_value().into_raw()
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
index 28367d97f57..6c17c424846 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs
@@ -6,5 +6,32 @@
//! The CSS Object Model, https://drafts.csswg.org/cssom/
+pub(crate) mod css_image_value;
+pub(crate) mod css_keyword_value;
+pub(crate) mod css_math_clamp;
+pub(crate) mod css_math_invert;
+pub(crate) mod css_math_max;
+pub(crate) mod css_math_min;
+pub(crate) mod css_math_negate;
+pub(crate) mod css_math_product;
+pub(crate) mod css_math_sum;
+pub(crate) mod css_math_value;
+pub(crate) mod css_matrix_component;
+pub(crate) mod css_numeric_array;
+pub(crate) mod css_numeric_value;
+pub(crate) mod css_perspective;
+pub(crate) mod css_rotate;
+pub(crate) mod css_scale;
+pub(crate) mod css_skew;
+pub(crate) mod css_skew_x;
+pub(crate) mod css_skew_y;
+pub(crate) mod css_style_value;
+pub(crate) mod css_transform_component;
+pub(crate) mod css_transform_value;
+pub(crate) mod css_translate;
+pub(crate) mod css_unit_value;
+pub(crate) mod css_unparsed_value;
+pub(crate) mod css_variable_reference_value;
pub(crate) mod exports;
pub(crate) mod media_list;
+pub(crate) mod typed_om;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/typed_om.rs b/Libraries/LibWeb/Bindings/Rust/src/css/typed_om.rs
new file mode 100644
index 00000000000..676301e2adf
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/typed_om.rs
@@ -0,0 +1,413 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! What the interfaces of the CSS Typed OM share: reification, and what they ask of LibWeb's C++ code, where the tables
+//! of the properties and the parser's entry points are.
+//! https://drafts.css-houdini.org/css-typed-om-1/
+
+use core::ffi::c_void;
+use std::sync::Arc;
+
+use ak::Utf16String;
+use libjs_rust::api::{MarkedVec, Vm};
+use libweb_rust::typed_om::{
+ CalcNode, CalcReificationNode, DimensionType, FfiNumericType, NumericType, NumericValue, Reification,
+ ReifiedUnresolvedSegment, RetainedStyleValue, calculation_nodes, reification_of,
+};
+
+use super::css_image_value::CSSImageValue;
+use super::css_keyword_value::CSSKeywordValue;
+use super::css_math_clamp::CSSMathClamp;
+use super::css_math_invert::CSSMathInvert;
+use super::css_math_max::CSSMathMax;
+use super::css_math_min::CSSMathMin;
+use super::css_math_negate::CSSMathNegate;
+use super::css_math_product::CSSMathProduct;
+use super::css_math_sum::CSSMathSum;
+use super::css_numeric_array::CSSNumericArray;
+use super::css_numeric_value::AnyCSSNumericValue;
+use super::css_style_value::{AnyCSSStyleValue, CSSStyleValue, PerformTypeCheck};
+use super::css_transform_component::{AnyCSSTransformComponent, reify_a_transform_function};
+use super::css_transform_value::CSSTransformValue;
+use super::css_unit_value::CSSUnitValue;
+use super::css_unparsed_value::{CSSUnparsedSegment, CSSUnparsedValue};
+use super::css_variable_reference_value::CSSVariableReferenceValue;
+use crate::bindings::conversions::UsvString;
+use crate::bindings::interface::Ref;
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+
+/// The value types that the Typed OM asks about, which C++ maps to its enum class ValueType.
+#[derive(Clone, Copy)]
+#[repr(u8)]
+pub(crate) enum TypedOmValueType {
+ Image,
+ TransformFunction,
+ TransformList,
+}
+
+unsafe extern "C" {
+ fn web_css_typed_om_property_accepts_type(property_id: u16, value_type: TypedOmValueType) -> bool;
+ fn web_css_typed_om_numeric_style_value(
+ property_id: u16,
+ value: *const c_void,
+ calculation: *const c_void,
+ numeric_type: FfiNumericType,
+ ) -> *const c_void;
+ fn web_css_typed_om_calculated_style_value(
+ property_id: u16,
+ calculation: *const c_void,
+ numeric_type: FfiNumericType,
+ 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_parse_numeric_value(css_text: usize) -> *const c_void;
+ fn web_css_typed_om_parse_value(
+ property: usize,
+ css_text: usize,
+ values: *mut c_void,
+ append: unsafe extern "C" fn(*mut c_void, *const c_void),
+ out_name_or_error: *mut usize,
+ ) -> bool;
+ fn web_css_typed_om_zero_is_a_length(property: usize, is_integer: bool) -> bool;
+}
+
+fn optional_style_value(pointer: *const c_void) -> Option<RetainedStyleValue> {
+ if pointer.is_null() {
+ return None;
+ }
+ // SAFETY: C++ hands over a strong reference to a style value.
+ Some(unsafe { RetainedStyleValue::from_raw(pointer) })
+}
+
+/// The string as a Rust string, for what is ASCII or only goes into a message.
+pub(crate) fn to_rust_string(string: &Utf16String) -> String {
+ String::from_utf16_lossy(&string.to_utf16())
+}
+
+pub(crate) fn property_accepts_type(property_id: u16, value_type: TypedOmValueType) -> bool {
+ // SAFETY: The call has no preconditions.
+ unsafe { web_css_typed_om_property_accepts_type(property_id, value_type) }
+}
+
+pub(crate) fn property_accepts_transform_function(property_id: u16) -> bool {
+ property_accepts_type(property_id, TypedOmValueType::TransformFunction)
+}
+
+pub(crate) fn property_accepts_transform_list(property_id: u16) -> bool {
+ property_accepts_type(property_id, TypedOmValueType::TransformList)
+}
+
+/// The value of the property for a CSSUnitValue, which is wrapped in a calculation if the property does not accept it
+/// on its own, if the property takes values of its type.
+pub(crate) fn numeric_style_value_for_property(
+ property_id: u16,
+ value: NumericValue,
+ numeric_type: NumericType,
+) -> Option<RetainedStyleValue> {
+ let style_value = value.style_value().into_raw();
+ let calculation = Arc::into_raw(Arc::new(CalcNode::Sum(vec![value.calculation_node()]))).cast();
+ // SAFETY: This hands over one strong reference to the style value and to the calculation.
+ optional_style_value(unsafe {
+ web_css_typed_om_numeric_style_value(
+ property_id,
+ style_value,
+ calculation,
+ FfiNumericType::from_calc(Some(numeric_type)),
+ )
+ })
+}
+
+/// The calculated value of the property for a CSSMathValue, if the property takes values of its type.
+pub(crate) fn calculated_style_value(
+ property_id: u16,
+ calculation: Arc<CalcNode>,
+ numeric_type: NumericType,
+ perform_type_check: PerformTypeCheck,
+) -> Option<RetainedStyleValue> {
+ // SAFETY: This hands over one strong reference to the calculation.
+ optional_style_value(unsafe {
+ web_css_typed_om_calculated_style_value(
+ property_id,
+ Arc::into_raw(calculation).cast(),
+ FfiNumericType::from_calc(Some(numeric_type)),
+ perform_type_check == PerformTypeCheck::Yes,
+ )
+ })
+}
+
+/// The value of the property for a CSSKeywordValue, if the keyword matches the grammar of the property.
+pub(crate) fn keyword_style_value_for_property(
+ property_id: u16,
+ value: &Utf16String,
+ perform_type_check: PerformTypeCheck,
+) -> Option<RetainedStyleValue> {
+ // SAFETY: This hands over a reference to the string.
+ optional_style_value(unsafe {
+ web_css_typed_om_keyword_style_value(
+ property_id,
+ value.clone().into_raw(),
+ perform_type_check == PerformTypeCheck::Yes,
+ )
+ })
+}
+
+/// A list of the values, separated by spaces.
+pub(crate) fn style_value_list(values: Vec<RetainedStyleValue>) -> 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()) })
+ .expect("a list is a style value")
+}
+
+/// 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) {
+ // 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)) };
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#parse-a-cssstylevalue
+pub(crate) fn parse_values(
+ vm: &Vm,
+ property: Utf16String,
+ css_text: Utf16String,
+) -> WebIdlResult<MarkedVec<'_, AnyCSSStyleValue>> {
+ // NB: Steps 1 to 4 parse with the tables of the properties, and result in the iterations of the value.
+ let mut values: Vec<RetainedStyleValue> = Vec::new();
+ let mut name_or_error = 0;
+ // SAFETY: This hands over references to the strings, and the context lives through the call.
+ let parsed = unsafe {
+ web_css_typed_om_parse_value(
+ property.into_raw(),
+ css_text.into_raw(),
+ (&raw mut values).cast(),
+ append_style_value,
+ &raw mut name_or_error,
+ )
+ };
+ // SAFETY: C++ hands over a reference to a string.
+ let name_or_error = unsafe { Utf16String::from_raw_owned(name_or_error) };
+ if !parsed {
+ return Err(Exception::TypeError(name_or_error));
+ }
+
+ // 5. For each value in values, replace it with the result of reifying value for property.
+ let reified_values = MarkedVec::new(vm);
+ for value in &values {
+ reified_values.push(reify(vm, value, &name_or_error));
+ }
+
+ // 6. If parseMultiple is false, return values[0]. Otherwise, return values.
+ // FIXME: We need to somehow store the source css_text on the returned CSSStyleValue.
+ // https://github.com/w3c/css-houdini-drafts/issues/1156
+ Ok(reified_values)
+}
+
+pub(crate) fn parse_a_css_style_value<'vm>(
+ cx: &mut CallContext<'vm>,
+ property: UsvString,
+ css_text: UsvString,
+) -> WebIdlResult<MarkedVec<'vm, AnyCSSStyleValue>> {
+ parse_values(cx.vm(), property.into_utf16_string(), css_text.into_utf16_string())
+}
+
+fn unit_value(vm: &Vm, value: f64, unit: &str) -> AnyCSSStyleValue {
+ AnyCSSNumericValue::CSSUnitValue(CSSUnitValue::create(vm, value, unit)).into()
+}
+
+fn default_reification(vm: &Vm, value: &RetainedStyleValue, property: &Utf16String) -> AnyCSSStyleValue {
+ // 1. Return a new CSSStyleValue object representing value whose [[associatedProperty]] internal slot is set to
+ // property.
+ AnyCSSStyleValue::CSSStyleValue(CSSStyleValue::create(vm, property.clone(), value.clone(), 0))
+}
+
+/// https://drafts.css-houdini.org/css-typed-om-1/#reify-stylevalue
+pub(crate) fn reify(vm: &Vm, value: &RetainedStyleValue, property: &Utf16String) -> AnyCSSStyleValue {
+ match reification_of(value) {
+ Reification::Default => default_reification(vm, value, property),
+ // AD-HOC: There's no spec description of how to reify as a CSSImageValue.
+ Reification::Image => AnyCSSStyleValue::CSSImageValue(CSSImageValue::create(vm, value.clone())),
+ // https://drafts.css-houdini.org/css-typed-om-1/#reify-ident
+ Reification::Keyword(keyword) => AnyCSSStyleValue::CSSKeywordValue(CSSKeywordValue::create(vm, keyword)),
+ // https://drafts.css-houdini.org/css-typed-om-1/#reify-a-numeric-value
+ // NB: Steps 1 and 2 don't apply here.
+ // 3. Return a new CSSUnitValue with its value internal slot set to the numeric value of num, and its unit
+ // internal slot set to "number" if num is a <number>, "percent" if num is a <percentage>, and num’s unit if
+ // num is a <dimension>.
+ // If the value being reified is a computed value, the unit used must be the appropriate canonical unit for
+ // the value’s type, with the numeric value scaled accordingly.
+ // FIXME: Reify computed value correctly. That sounds like it should work by computing the value properly before
+ // we reach this point.
+ Reification::Unit { value, unit } => unit_value(vm, value, &unit),
+ // NB: Step 1 doesn't apply here.
+ // 2. If num is the unitless value 0 and num is a <dimension>, return a new CSSUnitValue with its value internal
+ // slot set to 0, and its unit internal slot set to "px".
+ Reification::Number { value, is_integer } => {
+ // NB: Determine whether the associated property expects 0 to be a <length>.
+ // FIXME: Do this for registered custom properties.
+ // SAFETY: This hands over a reference to the string.
+ if value == 0.0 && unsafe { web_css_typed_om_zero_is_a_length(property.clone().into_raw(), is_integer) } {
+ return unit_value(vm, 0.0, "px");
+ }
+ unit_value(vm, value, "number")
+ }
+ Reification::Value(inner_value) => reify(vm, &inner_value, property),
+ // NB: This spec algorithm is incomplete and assumes we do not already have a calculation tree.
+ Reification::Calculated => reify_a_math_expression(vm, value)
+ .map(AnyCSSStyleValue::from)
+ // Some math functions are not reifiable yet. If we contain one, we have to fall back to CSSStyleValue.
+ // https://github.com/w3c/css-houdini-drafts/issues/1090
+ .unwrap_or_else(|| default_reification(vm, value, property)),
+ Reification::Unresolved(segments) => {
+ AnyCSSStyleValue::CSSUnparsedValue(reify_a_list_of_component_values(vm, &segments))
+ }
+ Reification::List(values) => {
+ // NB: <transform-list> is a StyleValueList that contains TransformStyleValues. If that's what we are,
+ // follow the steps for reifying that.
+ if values.iter().all(RetainedStyleValue::is_transformation)
+ && let Some(transform_list) = reify_a_transform_list(vm, &values)
+ {
+ return AnyCSSStyleValue::CSSTransformValue(transform_list);
+ }
+
+ // NB: A list with a single item, such as `text-decoration-line: underline`, is that item on its own. Reify
+ // the item, so that a single keyword reifies as a CSSKeywordValue.
+ if let [item] = values.as_slice() {
+ return reify(vm, item, property);
+ }
+
+ // NB: Otherwise, there isn't an equivalent CSSStyleValue for StyleValueList, so just use the default.
+ default_reification(vm, value, property)
+ }
+ }
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#reify-a-transform-list
+fn reify_a_transform_list(vm: &Vm, values: &[RetainedStyleValue]) -> Option<Ref<CSSTransformValue>> {
+ let transform_components: MarkedVec<'_, AnyCSSTransformComponent> = MarkedVec::new(vm);
+ for transform in values {
+ // NB: Not all transform functions are reifiable, in which case we give up reifying as a transform list.
+ transform_components.push(reify_a_transform_function(vm, transform)?);
+ }
+ Some(CSSTransformValue::create(vm, &transform_components))
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#reify-a-list-of-component-values
+fn reify_a_list_of_component_values(vm: &Vm, segments: &[ReifiedUnresolvedSegment]) -> Ref<CSSUnparsedValue> {
+ let members = MarkedVec::new(vm);
+ for segment in segments {
+ members.push(match segment {
+ ReifiedUnresolvedSegment::Text(text) => {
+ CSSUnparsedSegment::USVString(UsvString::from_utf16_replacing_lone_surrogates(text))
+ }
+ ReifiedUnresolvedSegment::Variable { name, fallback } => {
+ let fallback = fallback
+ .as_ref()
+ .map(|fallback| reify_a_list_of_component_values(vm, fallback));
+ CSSUnparsedSegment::CSSVariableReferenceValue(CSSVariableReferenceValue::create(
+ vm,
+ Utf16String::from_utf16(name),
+ fallback,
+ ))
+ }
+ });
+ }
+ CSSUnparsedValue::create(vm, &members)
+}
+
+fn unit_name_of(node: &CalcReificationNode) -> &'static str {
+ match node.numeric_kind {
+ 0 => "number",
+ 1 => DimensionType::Angle.unit_name(node.unit),
+ 2 => DimensionType::Flex.unit_name(node.unit),
+ 3 => DimensionType::Frequency.unit_name(node.unit),
+ 4 => DimensionType::Length.unit_name(node.unit),
+ 5 => "percent",
+ 6 => DimensionType::Resolution.unit_name(node.unit),
+ 7 => DimensionType::Time.unit_name(node.unit),
+ kind => unreachable!("invalid numeric kind {kind}"),
+ }
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#reify-a-math-expression
+pub(crate) fn reify_a_math_expression(vm: &Vm, calculated: &RetainedStyleValue) -> Option<AnyCSSNumericValue> {
+ let (nodes, child_indices) = calculation_nodes(calculated)?;
+ let reified_nodes: MarkedVec<'_, AnyCSSNumericValue> = MarkedVec::with_capacity(vm, nodes.len());
+ for node in &nodes {
+ let numeric_type = node.numeric_type.to_calc();
+ let children = &child_indices[node.child_start..node.child_start + node.child_count];
+ let child = |index: usize| {
+ reified_nodes
+ .get(children[index])
+ .expect("a child comes before its parent")
+ };
+
+ // NB: The reified objects get the types that their constructors would give them, computed from their reified
+ // children. The internal calculation's type may differ, for example by carrying a percent hint from the
+ // property that it belongs to.
+ let combined_type_of_children = |combine: fn(&NumericType, &NumericType) -> Option<NumericType>| {
+ let mut result: Option<NumericType> = None;
+ for index in 0..children.len() {
+ let child_type = child(index).numeric_type();
+ match result {
+ Some(numeric_type_so_far) => match combine(&numeric_type_so_far, &child_type) {
+ Some(combined) => result = Some(combined),
+ None => return numeric_type,
+ },
+ None => result = Some(child_type),
+ }
+ }
+ result.unwrap_or(numeric_type)
+ };
+ let added_types_of_children = || combined_type_of_children(NumericType::added_to);
+ let multiplied_types_of_children = || combined_type_of_children(NumericType::multiplied_by);
+ let reify_children = || {
+ let values = MarkedVec::with_capacity(vm, children.len());
+ for index in 0..children.len() {
+ values.push(child(index));
+ }
+ CSSNumericArray::create(vm, &values)
+ };
+
+ reified_nodes.push(match node.kind {
+ 0 => AnyCSSNumericValue::CSSUnitValue(CSSUnitValue::create(vm, node.value, unit_name_of(node))),
+ 2 => AnyCSSNumericValue::CSSMathSum(CSSMathSum::create(vm, added_types_of_children(), reify_children())),
+ 3 => AnyCSSNumericValue::CSSMathProduct(CSSMathProduct::create(
+ vm,
+ multiplied_types_of_children(),
+ reify_children(),
+ )),
+ 4 => AnyCSSNumericValue::CSSMathNegate(CSSMathNegate::create(vm, child(0))),
+ 5 => AnyCSSNumericValue::CSSMathInvert(CSSMathInvert::create(vm, child(0))),
+ 6 => AnyCSSNumericValue::CSSMathMin(CSSMathMin::create(vm, added_types_of_children(), reify_children())),
+ 7 => AnyCSSNumericValue::CSSMathMax(CSSMathMax::create(vm, added_types_of_children(), reify_children())),
+ 8 => AnyCSSNumericValue::CSSMathClamp(CSSMathClamp::create(
+ vm,
+ added_types_of_children(),
+ child(0),
+ child(1),
+ child(2),
+ )),
+ kind => unreachable!("invalid reification node kind {kind}"),
+ });
+ }
+ reified_nodes.pop()
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#reify-a-numeric-value
+pub(crate) fn reify_a_numeric_value(vm: &Vm, numeric_value: &RetainedStyleValue) -> Option<AnyCSSNumericValue> {
+ reify(vm, numeric_value, &Utf16String::default()).as_numeric()
+}
+
+/// The reification of an argument of a transform function, which is numeric.
+pub(crate) fn reify_numeric_argument(vm: &Vm, argument: &RetainedStyleValue) -> AnyCSSNumericValue {
+ reify_a_numeric_value(vm, argument).expect("an argument of a transform function is numeric")
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_matrix_read_only.rs b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_matrix_read_only.rs
index 083a25c7b2e..dc5bcd6fabc 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_matrix_read_only.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/geometry/dom_matrix_read_only.rs
@@ -7,6 +7,7 @@
//! https://drafts.fxtf.org/geometry/#dommatrixreadonly
use core::cell::Cell;
+use core::ops::Deref;
use ak::Utf16String;
use ak::math;
@@ -46,6 +47,25 @@ pub(crate) enum DOMStringOrUnrestrictedDoubleSequence {
Sequence(Vec<f64>),
}
+/// An object of DOMMatrixReadOnly or of DOMMatrix, which inherits from it.
+#[derive(Clone, Copy, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) enum AnyDOMMatrixReadOnly {
+ DOMMatrixReadOnly(Ref<DOMMatrixReadOnly>),
+ DOMMatrix(Ref<DOMMatrix>),
+}
+
+impl Deref for AnyDOMMatrixReadOnly {
+ type Target = DOMMatrixReadOnly;
+
+ fn deref(&self) -> &DOMMatrixReadOnly {
+ match self {
+ Self::DOMMatrixReadOnly(matrix) => matrix,
+ Self::DOMMatrix(matrix) => matrix.parent(),
+ }
+ }
+}
+
#[derive(Trace)]
#[gc(crate = libjs_rust)]
pub(crate) struct DOMMatrixReadOnly {
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index e1dc54a39bb..ccc36a557e2 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -93,55 +93,29 @@ set(SOURCES
CSS/CSSFunctionDescriptors.cpp
CSS/CSSFunctionRule.cpp
CSS/CSSGroupingRule.cpp
- CSS/CSSImageValue.cpp
CSS/CSSImportRule.cpp
CSS/CSSKeyframeRule.cpp
CSS/CSSKeyframesRule.cpp
- CSS/CSSKeywordValue.cpp
CSS/CSSLayerBlockRule.cpp
CSS/CSSLayerStatementRule.cpp
CSS/CSSMarginRule.cpp
- CSS/CSSMathClamp.cpp
- CSS/CSSMathInvert.cpp
- CSS/CSSMathMax.cpp
- CSS/CSSMathMin.cpp
- CSS/CSSMathNegate.cpp
- CSS/CSSMathProduct.cpp
- CSS/CSSMathSum.cpp
- CSS/CSSMathValue.cpp
- CSS/CSSMatrixComponent.cpp
CSS/CSSMediaRule.cpp
CSS/CSSNamespaceRule.cpp
CSS/CSSNestedDeclarations.cpp
- CSS/CSSNumericArray.cpp
- CSS/CSSNumericValue.cpp
CSS/CSSPageRule.cpp
CSS/CSSPageDescriptors.cpp
- CSS/CSSPerspective.cpp
CSS/CSSPositionTryDescriptors.cpp
CSS/CSSPositionTryRule.cpp
CSS/CSSPropertyRule.cpp
- CSS/CSSRotate.cpp
CSS/CSSRule.cpp
CSS/CSSRuleList.cpp
- CSS/CSSScale.cpp
CSS/CSSScopeRule.cpp
- CSS/CSSSkew.cpp
- CSS/CSSSkewX.cpp
- CSS/CSSSkewY.cpp
CSS/CSSStyleDeclaration.cpp
CSS/CSSStyleProperties.cpp
CSS/CSSStyleRule.cpp
CSS/CSSStyleSheet.cpp
- CSS/CSSStyleValue.cpp
CSS/CSSSupportsRule.cpp
- CSS/CSSTransformComponent.cpp
- CSS/CSSTransformValue.cpp
CSS/CSSTransition.cpp
- CSS/CSSTranslate.cpp
- CSS/CSSUnitValue.cpp
- CSS/CSSUnparsedValue.cpp
- CSS/CSSVariableReferenceValue.cpp
CSS/ColorFunctionDescriptor.cpp
CSS/CustomPropertyData.cpp
CSS/Descriptor.cpp
@@ -244,6 +218,7 @@ set(SOURCES
CSS/SyntaxHighlighter/SyntaxHighlighter.cpp
CSS/Time.cpp
CSS/TransitionEvent.cpp
+ CSS/TypedOM.cpp
CSS/URL.cpp
CSS/UpdateStyle.cpp
CSS/ValueType.cpp
diff --git a/Libraries/LibWeb/CSS/CSSImageValue.cpp b/Libraries/LibWeb/CSS/CSSImageValue.cpp
deleted file mode 100644
index 5abb2816e1d..00000000000
--- a/Libraries/LibWeb/CSS/CSSImageValue.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSImageValue.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/StyleValues/StyleValue.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSImageValue);
-
-GC::Ref<CSSImageValue> CSSImageValue::create(StyleValue const& source_value)
-{
- return GC::Heap::the().allocate<CSSImageValue>(source_value);
-}
-
-CSSImageValue::CSSImageValue(StyleValue const& source_value)
- : CSSStyleValue(source_value)
-{
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#stylevalue-serialization
-WebIDL::ExceptionOr<Utf16String> CSSImageValue::to_string() const
-{
- // AD-HOC: The spec doesn't say how to serialize this, as it's intentionally a black box.
- // We just rely on CSSStyleValue serializing its held StyleValue.
- return Base::to_string();
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
-WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> CSSImageValue::create_an_internal_representation(PropertyNameAndID const& property, PerformTypeCheck perform_type_check) const
-{
- // If value is a CSSStyleValue subclass,
- // If value does not match the grammar of a list-valued property iteration of property, throw a TypeError.
- // NB: https://drafts.css-houdini.org/css-typed-om-1/#cssstylevalue-match-a-grammar doesn't list CSSImageValue, but
- // we should match <image>.
- bool const matches_grammar = [&] {
- return property_accepts_type(property.id(), ValueType::Image);
- }();
- if (perform_type_check == PerformTypeCheck::Yes && !matches_grammar) {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Property '{}' does not accept <image>", property.name()) };
- }
-
- // FIXME: If any component of property’s CSS grammar has a limited numeric range, and the corresponding part of value
- // is a CSSUnitValue that is outside of that range, replace that value with the result of wrapping it in a
- // fresh CSSMathSum whose values internal slot contains only that part of value.
-
- // Return the value.
- return source_style_value().release_nonnull();
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSImageValue.h b/Libraries/LibWeb/CSS/CSSImageValue.h
deleted file mode 100644
index a50fc9df17d..00000000000
--- a/Libraries/LibWeb/CSS/CSSImageValue.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSStyleValue.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssimagevalue
-class CSSImageValue final : public CSSStyleValue {
- WEB_WRAPPABLE(CSSImageValue, CSSStyleValue);
- GC_DECLARE_ALLOCATOR(CSSImageValue);
-
-public:
- [[nodiscard]] static GC::Ref<CSSImageValue> create(StyleValue const& source_value);
-
- virtual ~CSSImageValue() override = default;
-
- virtual WebIDL::ExceptionOr<Utf16String> to_string() const override;
- virtual WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> create_an_internal_representation(PropertyNameAndID const&, PerformTypeCheck) const override;
-
-private:
- explicit CSSImageValue(StyleValue const& source_value);
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSImageValue.idl b/Libraries/LibWeb/CSS/CSSImageValue.idl
index 13805301994..0f80ff5e266 100644
--- a/Libraries/LibWeb/CSS/CSSImageValue.idl
+++ b/Libraries/LibWeb/CSS/CSSImageValue.idl
@@ -1,4 +1,4 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssimagevalue
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSImageValue : CSSStyleValue {
};
diff --git a/Libraries/LibWeb/CSS/CSSKeywordValue.cpp b/Libraries/LibWeb/CSS/CSSKeywordValue.cpp
deleted file mode 100644
index cb6d3751377..00000000000
--- a/Libraries/LibWeb/CSS/CSSKeywordValue.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSKeywordValue.h"
-#include <LibWeb/Bindings/CSSKeywordValue.h>
-#include <LibWeb/CSS/Keyword.h>
-#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/Serialize.h>
-#include <LibWeb/CSS/StyleValues/CustomIdentStyleValue.h>
-#include <LibWeb/CSS/StyleValues/KeywordStyleValue.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSKeywordValue);
-
-GC::Ref<CSSKeywordValue> CSSKeywordValue::create(Utf16FlyString value)
-{
- return GC::Heap::the().allocate<CSSKeywordValue>(move(value));
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-csskeywordvalue-csskeywordvalue
-WebIDL::ExceptionOr<GC::Ref<CSSKeywordValue>> CSSKeywordValue::construct_impl(Utf16String value)
-{
- // 1. If value is an empty string, throw a TypeError.
- if (value.is_empty())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create a CSSKeywordValue with an empty string as the value"_utf16 };
-
- // 2. Otherwise, return a new CSSKeywordValue with its value internal slot set to value.
- return CSSKeywordValue::create(Utf16FlyString { move(value) });
-}
-
-CSSKeywordValue::CSSKeywordValue(Utf16FlyString value)
- : CSSStyleValue()
- , m_value(move(value))
-{
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-csskeywordvalue-value
-WebIDL::ExceptionOr<void> CSSKeywordValue::set_value(Utf16String value)
-{
- // 1. If value is an empty string, throw a TypeError.
- if (value.is_empty())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot set CSSKeywordValue.value to an empty string"_utf16 };
-
- // 2. Otherwise, set this’s value internal slot, to value.
- m_value = Utf16FlyString { move(value) };
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#keywordvalue-serialization
-void CSSKeywordValue::serialize(Utf16StringBuilder& builder) const
-{
- // To serialize a CSSKeywordValue this:
- // 1. Return this’s value internal slot.
- // AD-HOC: Serialize it as an identifier. Spec issue: https://github.com/w3c/csswg-drafts/issues/12545
- builder.append(serialize_an_identifier_to_utf16(m_value));
-}
-
-WebIDL::ExceptionOr<Utf16String> CSSKeywordValue::to_string() const
-{
- Utf16StringBuilder builder;
- serialize(builder);
- return builder.to_string();
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
-WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> CSSKeywordValue::create_an_internal_representation(PropertyNameAndID const& property, PerformTypeCheck perform_type_check) const
-{
- // If value is a CSSStyleValue subclass,
- // If value does not match the grammar of a list-valued property iteration of property, throw a TypeError.
- bool const matches_grammar = [&] {
- // https://drafts.css-houdini.org/css-typed-om-1/#cssstylevalue-match-a-grammar
- // A CSSKeywordValue matches an <ident> specified in a grammar if its value internal slot matches the
- // identifier.
- // If case-folding rules are in effect normally for that <ident> (such as Auto matching the keyword auto
- // specified in the grammar for width), they apply to this comparison as well.
- if (auto keyword = keyword_from_string(m_value); keyword.has_value() && is_css_wide_keyword(*keyword))
- return true;
- // NB: The keywords listed for a property are not all valid on their own, like `hanging` for text-indent,
- // and a property may accept identifiers that are not listed, like a <custom-ident> or the axis keywords
- // of scroll-snap-type. So we check if the property accepts the value, as an identifier, when parsed.
- return parse_css_value(Parser::ParsingParams {}, serialize_an_identifier(m_value), property.id()) != nullptr;
- }();
- if (perform_type_check == PerformTypeCheck::Yes && !matches_grammar) {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Property '{}' does not accept the keyword '{}'", property.name(), m_value) };
- }
-
- // If any component of property’s CSS grammar has a limited numeric range, and the corresponding part of value
- // is a CSSUnitValue that is outside of that range, replace that value with the result of wrapping it in a
- // fresh CSSMathSum whose values internal slot contains only that part of value.
- // NB: Non-applicable.
-
- // Return the value.
- if (auto keyword = keyword_from_string(m_value); keyword.has_value()) {
- // NB: Style computation expects the same internal representation that the CSS parser produces for the
- // property. For example, `display` keywords become a DisplayStyleValue, and keyword combinations like
- // `text-decoration-line` or `white-space-trim` become a list even when only one keyword is given. So we
- // parse the keyword as a value of the property to get that representation. List-valued properties are
- // instead wrapped in a list by StylePropertyMap.
- if (!is_css_wide_keyword(*keyword) && !property.is_custom_property() && !property_is_list_valued(property.id())) {
- if (auto parsed_value = parse_css_value(Parser::ParsingParams {}, m_value.view(), property.id()))
- return parsed_value.release_nonnull();
- }
-
- return KeywordStyleValue::create(*keyword);
- }
- return CustomIdentStyleValue::create(m_value);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#rectify-a-keywordish-value
-GC::Ref<CSSKeywordValue> rectify_a_keywordish_value(CSSKeywordish const& keywordish)
-{
- // To rectify a keywordish value val, perform the following steps:
- return keywordish.visit(
- // 1. If val is a CSSKeywordValue, return val.
- [](GC::Ref<CSSKeywordValue> const& value) -> GC::Ref<CSSKeywordValue> {
- return value;
- },
-
- // 2. If val is a DOMString, return a new CSSKeywordValue with its value internal slot set to val.
- [](Utf16String const& value) -> GC::Ref<CSSKeywordValue> {
- return CSSKeywordValue::create(Utf16FlyString { value });
- });
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSKeywordValue.h b/Libraries/LibWeb/CSS/CSSKeywordValue.h
index 6c34d662c7d..3d2dd103732 100644
--- a/Libraries/LibWeb/CSS/CSSKeywordValue.h
+++ b/Libraries/LibWeb/CSS/CSSKeywordValue.h
@@ -6,40 +6,18 @@
#pragma once
-#include <AK/Utf16FlyString.h>
#include <AK/Utf16String.h>
-#include <AK/Utf16StringBuilder.h>
+#include <LibWeb/Bindings/CSSKeywordValue.h>
#include <LibWeb/CSS/CSSStyleValue.h>
namespace Web::CSS {
-// https://drafts.css-houdini.org/css-typed-om-1/#typedefdef-csskeywordish
-using CSSKeywordish = Variant<Utf16String, GC::Ref<CSSKeywordValue>>;
-
// https://drafts.css-houdini.org/css-typed-om-1/#csskeywordvalue
-class CSSKeywordValue final : public CSSStyleValue {
- WEB_WRAPPABLE(CSSKeywordValue, CSSStyleValue);
- GC_DECLARE_ALLOCATOR(CSSKeywordValue);
+class WEB_API CSSKeywordValue final : public CSSStyleValue {
+ WEB_RUST_INTERFACE(CSSKeywordValue, css_keyword_value)
public:
- [[nodiscard]] static GC::Ref<CSSKeywordValue> create(Utf16FlyString value);
- static WebIDL::ExceptionOr<GC::Ref<CSSKeywordValue>> construct_impl(Utf16String value);
-
- virtual ~CSSKeywordValue() override = default;
-
- Utf16FlyString const& value() const { return m_value; }
- WebIDL::ExceptionOr<void> set_value(Utf16String value);
-
- void serialize(Utf16StringBuilder&) const;
- virtual WebIDL::ExceptionOr<Utf16String> to_string() const override;
- virtual WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> create_an_internal_representation(PropertyNameAndID const&, PerformTypeCheck) const override;
-
-private:
- explicit CSSKeywordValue(Utf16FlyString value);
-
- Utf16FlyString m_value;
+ Utf16String value() const;
};
-GC::Ref<CSSKeywordValue> rectify_a_keywordish_value(CSSKeywordish const&);
-
}
diff --git a/Libraries/LibWeb/CSS/CSSKeywordValue.idl b/Libraries/LibWeb/CSS/CSSKeywordValue.idl
index 698ea326adb..3957686153a 100644
--- a/Libraries/LibWeb/CSS/CSSKeywordValue.idl
+++ b/Libraries/LibWeb/CSS/CSSKeywordValue.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#csskeywordvalue
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSKeywordValue : CSSStyleValue {
constructor(USVString value);
attribute USVString value;
diff --git a/Libraries/LibWeb/CSS/CSSMathClamp.cpp b/Libraries/LibWeb/CSS/CSSMathClamp.cpp
deleted file mode 100644
index 26547c225e6..00000000000
--- a/Libraries/LibWeb/CSS/CSSMathClamp.cpp
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSMathClamp.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSMathNegate.h>
-#include <LibWeb/CSS/CSSNumericArray.h>
-#include <LibWeb/CSS/StyleValues/CalculatedStyleValue.h>
-#include <LibWeb/WebIDL/DOMException.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSMathClamp);
-
-GC::Ref<CSSMathClamp> CSSMathClamp::create(NumericType type, GC::Ref<CSSNumericValue> lower, GC::Ref<CSSNumericValue> value, GC::Ref<CSSNumericValue> upper)
-{
- return GC::Heap::the().allocate<CSSMathClamp>(move(type), move(lower), move(value), move(upper));
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathclamp-cssmathclamp
-WebIDL::ExceptionOr<GC::Ref<CSSMathClamp>> CSSMathClamp::create_for_constructor(CSSNumberish lower, CSSNumberish value, CSSNumberish upper)
-{
- // The CSSMathClamp(lower, value, upper) constructor must, when called, perform the following steps:
- // 1. Replace lower, value, and upper with the result of rectifying a numberish value for each.
- auto lower_rectified = rectify_a_numberish_value(lower);
- auto value_rectified = rectify_a_numberish_value(value);
- auto upper_rectified = rectify_a_numberish_value(upper);
-
- // 2. Let type be the result of adding the types of lower, value, and upper. If type is failure, throw a TypeError.
- auto type = lower_rectified->type()
- .added_to(value_rectified->type())
- .map([&](auto&& type) { return type.added_to(upper_rectified->type()); });
- if (!type.has_value()) {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create a CSSMathClamp with values of incompatible types"_utf16 };
- }
-
- // 3. Return a new CSSMathClamp whose lower, value, and upper internal slots are set to lower, value, and upper, respectively.
- return CSSMathClamp::create(type->release_value(), move(lower_rectified), move(value_rectified), move(upper_rectified));
-}
-
-CSSMathClamp::CSSMathClamp(NumericType type, GC::Ref<CSSNumericValue> lower, GC::Ref<CSSNumericValue> value, GC::Ref<CSSNumericValue> upper)
- : CSSMathValue(CSSMathOperator::Clamp, move(type))
- , m_lower(move(lower))
- , m_value(move(value))
- , m_upper(move(upper))
-{
-}
-
-CSSMathClamp::~CSSMathClamp() = default;
-
-void CSSMathClamp::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_lower);
- visitor.visit(m_value);
- visitor.visit(m_upper);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmathvalue
-void CSSMathClamp::serialize_math_value(Utf16StringBuilder& s, Nested, Parens) const
-{
- // AD-HOC: The spec is missing serialization rules for CSSMathClamp: https://github.com/w3c/css-houdini-drafts/issues/1152
- s.append_ascii("clamp("sv);
- m_lower->serialize(s, { .nested = true, .parenless = true });
- s.append_ascii(", "sv);
- m_value->serialize(s, { .nested = true, .parenless = true });
- s.append_ascii(", "sv);
- m_upper->serialize(s, { .nested = true, .parenless = true });
- s.append_ascii(')');
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathclamp-lower
-GC::Ref<CSSNumericValue> CSSMathClamp::lower() const
-{
- // AD-HOC: No spec definition.
- return m_lower;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathclamp-value
-GC::Ref<CSSNumericValue> CSSMathClamp::value() const
-{
- // AD-HOC: No spec definition.
- return m_value;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathclamp-upper
-GC::Ref<CSSNumericValue> CSSMathClamp::upper() const
-{
- // AD-HOC: No spec definition.
- return m_upper;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#equal-numeric-value
-bool CSSMathClamp::is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const
-{
- // AD-HOC: Spec doesn't handle clamp(). https://github.com/w3c/css-houdini-drafts/issues/1152
- // 1. If value1 and value2 are not members of the same interface, return false.
- auto* other_clamp = as_if<CSSMathClamp>(*other);
- if (!other_clamp)
- return false;
-
- return m_lower->is_equal_numeric_value(other_clamp->m_lower)
- && m_value->is_equal_numeric_value(other_clamp->m_value)
- && m_upper->is_equal_numeric_value(other_clamp->m_upper);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
-Optional<SumValue> CSSMathClamp::create_a_sum_value() const
-{
- // AD-HOC: There is no spec for this. https://github.com/w3c/css-houdini-drafts/issues/1152
- // So, basing it on the spec for CSSMathMin.
-
- // Create sum values from lower, value, and upper.
- auto lower = m_lower->create_a_sum_value();
- auto value = m_value->create_a_sum_value();
- auto upper = m_upper->create_a_sum_value();
-
- // If any of those are failure, or has a length greater than one, return failure.
- if (!lower.has_value() || lower->size() > 1
- || !value.has_value() || value->size() > 1
- || !upper.has_value() || upper->size() > 1)
- return {};
-
- // If not all their unit maps are identical, return failure.
- if (lower->first().unit_map != value->first().unit_map || value->first().unit_map != upper->first().unit_map)
- return {};
-
- // Return value clamped between lower and upper.
- return SumValue {
- SumValueItem {
- clamp(value->first().value, lower->first().value, upper->first().value),
- value->first().unit_map,
- }
- };
-}
-
-WebIDL::ExceptionOr<CalcNodeRef> CSSMathClamp::create_calculation_node(CalculationContext const& context) const
-{
- auto lower = TRY(m_lower->create_calculation_node(context));
- auto value = TRY(m_value->create_calculation_node(context));
- auto upper = TRY(m_upper->create_calculation_node(context));
- return CalcNodeRef::clamp(move(lower), move(value), move(upper));
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMathClamp.h b/Libraries/LibWeb/CSS/CSSMathClamp.h
deleted file mode 100644
index 03fcaf3b53a..00000000000
--- a/Libraries/LibWeb/CSS/CSSMathClamp.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSMathValue.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssmathclamp
-class CSSMathClamp final : public CSSMathValue {
- WEB_WRAPPABLE(CSSMathClamp, CSSMathValue);
- GC_DECLARE_ALLOCATOR(CSSMathClamp);
-
-public:
- [[nodiscard]] static GC::Ref<CSSMathClamp> create(NumericType, GC::Ref<CSSNumericValue> lower, GC::Ref<CSSNumericValue> value, GC::Ref<CSSNumericValue> upper);
- static WebIDL::ExceptionOr<GC::Ref<CSSMathClamp>> create_for_constructor(CSSNumberish lower, CSSNumberish value, CSSNumberish upper);
-
- virtual ~CSSMathClamp() override;
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<CSSNumericValue> lower() const;
- GC::Ref<CSSNumericValue> value() const;
- GC::Ref<CSSNumericValue> upper() const;
-
- virtual void serialize_math_value(Utf16StringBuilder&, Nested, Parens) const override;
- virtual bool is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const override;
- virtual Optional<SumValue> create_a_sum_value() const override;
-
- virtual WebIDL::ExceptionOr<CalcNodeRef> create_calculation_node(CalculationContext const&) const override;
-
-private:
- CSSMathClamp(NumericType, GC::Ref<CSSNumericValue> lower, GC::Ref<CSSNumericValue> value, GC::Ref<CSSNumericValue> upper);
- GC::Ref<CSSNumericValue> m_lower;
- GC::Ref<CSSNumericValue> m_value;
- GC::Ref<CSSNumericValue> m_upper;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMathClamp.idl b/Libraries/LibWeb/CSS/CSSMathClamp.idl
index 0b3aa4bced8..7a1583b41a9 100644
--- a/Libraries/LibWeb/CSS/CSSMathClamp.idl
+++ b/Libraries/LibWeb/CSS/CSSMathClamp.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssmathclamp
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSMathClamp : CSSMathValue {
constructor(CSSNumberish lower, CSSNumberish value, CSSNumberish upper);
readonly attribute CSSNumericValue lower;
diff --git a/Libraries/LibWeb/CSS/CSSMathInvert.cpp b/Libraries/LibWeb/CSS/CSSMathInvert.cpp
deleted file mode 100644
index a73488b6552..00000000000
--- a/Libraries/LibWeb/CSS/CSSMathInvert.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSMathInvert.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/StyleValues/CalculatedStyleValue.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSMathInvert);
-
-GC::Ref<CSSMathInvert> CSSMathInvert::create(NumericType type, GC::Ref<CSSNumericValue> values)
-{
- return GC::Heap::the().allocate<CSSMathInvert>(move(type), move(values));
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathinvert-cssmathinvert
-GC::Ref<CSSMathInvert> CSSMathInvert::create_from_numberish(CSSNumberish value)
-{
- // The CSSMathInvert(arg) constructor is defined identically to the above, except that in the last step it returns
- // a new CSSMathInvert object.
- // NB: So, the steps below are a modification of the CSSMathNegate steps.
-
- // 1. Replace arg with the result of rectifying a numberish value for arg.
- auto converted_value = rectify_a_numberish_value(value);
-
- // 2. Return a new CSSMathInvert whose value internal slot is set to arg.
- return CSSMathInvert::create(converted_value->type().inverted(), converted_value);
-}
-
-CSSMathInvert::CSSMathInvert(NumericType type, GC::Ref<CSSNumericValue> values)
- : CSSMathValue(CSSMathOperator::Invert, move(type))
- , m_value(move(values))
-{
-}
-
-CSSMathInvert::~CSSMathInvert() = default;
-
-void CSSMathInvert::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_value);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmathvalue
-void CSSMathInvert::serialize_math_value(Utf16StringBuilder& s, Nested nested, Parens parens) const
-{
- // NB: Only steps 1 and 6 apply here.
- // 1. Let s initially be the empty string.
-
- // 6. Otherwise, if this is a CSSMathInvert:
- {
- // 1. If paren-less is true, continue to the next step; otherwise, if nested is true, append "(" to s;
- // otherwise, append "calc(" to s.
- if (parens == Parens::With) {
- if (nested == Nested::Yes) {
- s.append_ascii('(');
- } else {
- s.append_ascii("calc("sv);
- }
- }
-
- // 2. Append "1 / " to s.
- s.append_ascii("1 / "sv);
-
- // 3. Serialize this’s value internal slot with nested set to true, and append the result to s.
- m_value->serialize(s, { .nested = true });
-
- // 4. If paren-less is false, append ")" to s,
- if (parens == Parens::With)
- s.append_ascii(')');
-
- // 5. Return s.
- }
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathinvert-value
-GC::Ref<CSSNumericValue> CSSMathInvert::value() const
-{
- return m_value;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#equal-numeric-value
-bool CSSMathInvert::is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const
-{
- // NB: Only steps 1, 4 and 5 are relevant.
- // 1. If value1 and value2 are not members of the same interface, return false.
- auto* other_invert = as_if<CSSMathInvert>(*other);
- if (!other_invert)
- return false;
-
- // 4. Assert: value1 and value2 are both CSSMathNegates or CSSMathInverts.
- // 5. Return whether value1’s value and value2’s value are equal numeric values.
- return m_value->is_equal_numeric_value(other_invert->m_value);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
-Optional<SumValue> CSSMathInvert::create_a_sum_value() const
-{
- // 1. Let values be the result of creating a sum value from this’s value internal slot.
- auto values = m_value->create_a_sum_value();
-
- // 2. If values is failure, return failure.
- if (!values.has_value())
- return {};
-
- // 3. If the length of values is more than one, return failure.
- if (values->size() > 1)
- return {};
-
- // 4. Invert (find the reciprocal of) the value of the item in values, and negate the value of each entry in its unit map.
- for (auto& [value, unit_map] : *values) {
- value = 1.0 / value;
- for (auto& [_, power] : unit_map)
- power = -power;
- }
-
- // 5. Return values.
- return values;
-}
-
-WebIDL::ExceptionOr<CalcNodeRef> CSSMathInvert::create_calculation_node(CalculationContext const& context) const
-{
- return CalcNodeRef::invert(TRY(m_value->create_calculation_node(context)));
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMathInvert.h b/Libraries/LibWeb/CSS/CSSMathInvert.h
deleted file mode 100644
index 2dac8ebe555..00000000000
--- a/Libraries/LibWeb/CSS/CSSMathInvert.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSMathValue.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssmathinvert
-class CSSMathInvert final : public CSSMathValue {
- WEB_WRAPPABLE(CSSMathInvert, CSSMathValue);
- GC_DECLARE_ALLOCATOR(CSSMathInvert);
-
-public:
- [[nodiscard]] static GC::Ref<CSSMathInvert> create(NumericType, GC::Ref<CSSNumericValue>);
- static GC::Ref<CSSMathInvert> create_from_numberish(CSSNumberish);
-
- virtual ~CSSMathInvert() override;
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<CSSNumericValue> value() const;
-
- virtual void serialize_math_value(Utf16StringBuilder&, Nested, Parens) const override;
- virtual bool is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const override;
- virtual Optional<SumValue> create_a_sum_value() const override;
-
- virtual WebIDL::ExceptionOr<CalcNodeRef> create_calculation_node(CalculationContext const&) const override;
-
-private:
- CSSMathInvert(NumericType, GC::Ref<CSSNumericValue>);
- GC::Ref<CSSNumericValue> m_value;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMathInvert.idl b/Libraries/LibWeb/CSS/CSSMathInvert.idl
index 0568f880799..e0ca4825311 100644
--- a/Libraries/LibWeb/CSS/CSSMathInvert.idl
+++ b/Libraries/LibWeb/CSS/CSSMathInvert.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssmathinvert
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSMathInvert : CSSMathValue {
constructor(CSSNumberish arg);
readonly attribute CSSNumericValue value;
diff --git a/Libraries/LibWeb/CSS/CSSMathMax.cpp b/Libraries/LibWeb/CSS/CSSMathMax.cpp
deleted file mode 100644
index 66bebe29848..00000000000
--- a/Libraries/LibWeb/CSS/CSSMathMax.cpp
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSMathMax.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSMathNegate.h>
-#include <LibWeb/CSS/CSSNumericArray.h>
-#include <LibWeb/CSS/StyleValues/CalculatedStyleValue.h>
-#include <LibWeb/WebIDL/DOMException.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSMathMax);
-
-GC::Ref<CSSMathMax> CSSMathMax::create(NumericType type, GC::Ref<CSSNumericArray> values)
-{
- return GC::Heap::the().allocate<CSSMathMax>(move(type), move(values));
-}
-
-WebIDL::ExceptionOr<GC::Ref<CSSMathMax>> CSSMathMax::add_all_types_into_math_max(GC::RootVector<GC::Ref<CSSNumericValue>> const& values)
-{
- auto type = values.first()->type();
- bool first = true;
- for (auto const& value : values) {
- if (first) {
- first = false;
- continue;
- }
- if (auto added_types = type.added_to(value->type()); added_types.has_value()) {
- type = added_types.release_value();
- } else {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create a CSSMathMax with values of incompatible types"_utf16 };
- }
- }
-
- auto values_array = CSSNumericArray::create({ values });
- return CSSMathMax::create(type, values_array);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathmin-cssmathmin
-WebIDL::ExceptionOr<GC::Ref<CSSMathMax>> CSSMathMax::create_for_constructor(ReadonlySpan<CSSNumberish> values)
-{
- // The CSSMathMin(...args) and CSSMathMax(...args) constructors are defined identically to the above, except that
- // in the last step they return a new CSSMathMin or CSSMathMax object, respectively.
- // NB: So, the steps below are a modification of the CSSMathSum steps.
-
- // 1. Replace each item of args with the result of rectifying a numberish value for the item.
- GC::RootVector<GC::Ref<CSSNumericValue>> converted_values;
- converted_values.ensure_capacity(values.size());
- for (auto const& value : values) {
- converted_values.append(rectify_a_numberish_value(value));
- }
-
- // 2. If args is empty, throw a SyntaxError.
- if (converted_values.is_empty())
- return WebIDL::SyntaxError::create("Cannot create an empty CSSMathMax"_utf16);
-
- // 3. Let type be the result of adding the types of all the items of args. If type is failure, throw a TypeError.
- // 4. Return a new CSSMathMax whose values internal slot is set to args.
- return add_all_types_into_math_max(converted_values);
-}
-
-CSSMathMax::CSSMathMax(NumericType type, GC::Ref<CSSNumericArray> values)
- : CSSMathValue(CSSMathOperator::Max, move(type))
- , m_values(move(values))
-{
-}
-
-CSSMathMax::~CSSMathMax() = default;
-
-void CSSMathMax::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_values);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmathvalue
-void CSSMathMax::serialize_math_value(Utf16StringBuilder& s, Nested, Parens) const
-{
- // NB: Only steps 1 and 2 apply here.
- // 1. Let s initially be the empty string.
-
- // 2. If this is a CSSMathMin or CSSMathMax:
- {
- // 1. Append "min(" or "max(" to s, as appropriate.
- s.append_ascii("max("sv);
-
- // 2. For each arg in this’s values internal slot, serialize arg with nested and paren-less both true, and
- // append the result to s, appending a ", " between successive values.
- bool first = true;
- for (auto const& arg : m_values->values()) {
- if (first) {
- first = false;
- } else {
- s.append_ascii(", "sv);
- }
- arg->serialize(s, { .nested = true, .parenless = true });
- }
-
- // 3. Append ")" to s and return s.
- s.append_ascii(')');
- }
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathmin-values
-GC::Ref<CSSNumericArray> CSSMathMax::values() const
-{
- return m_values;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#equal-numeric-value
-bool CSSMathMax::is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const
-{
- // NB: Only steps 1 and 3 are relevant.
- // 1. If value1 and value2 are not members of the same interface, return false.
- auto* other_max = as_if<CSSMathMax>(*other);
- if (!other_max)
- return false;
-
- // 3. If value1 and value2 are both CSSMathSums, CSSMathProducts, CSSMathMins, or CSSMathMaxs:
- // NB: Substeps are implemented in CSSNumericArray.
- return m_values->is_equal_numeric_values(other_max->m_values);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
-Optional<SumValue> CSSMathMax::create_a_sum_value() const
-{
- // 1. Let args be the result of creating a sum value for each item in this’s values internal slot.
- Vector<Optional<SumValue>> args;
- args.ensure_capacity(m_values->length());
- for (auto const& value : m_values->values()) {
- args.unchecked_append(value->create_a_sum_value());
- }
-
- Optional<SumValue> item_with_largest_value = args.first();
- for (auto const& item : args) {
- // 2. If any item of args is failure, or has a length greater than one, return failure.
- if (!item.has_value() || item->size() > 1)
- return {};
-
- // 3. If not all of the unit maps among the items of args are identical, return failure.
- if (item->first().unit_map != item_with_largest_value->first().unit_map)
- return {};
-
- if (item->first().value > item_with_largest_value->first().value)
- item_with_largest_value = item;
- }
-
- // 4. Return the item of args whose sole item has the largest value.
- return item_with_largest_value;
-}
-
-WebIDL::ExceptionOr<CalcNodeRef> CSSMathMax::create_calculation_node(CalculationContext const& context) const
-{
- Vector<CalcNodeRef> child_nodes;
- for (auto const& child_value : m_values->values()) {
- child_nodes.append(TRY(child_value->create_calculation_node(context)));
- }
-
- return CalcNodeRef::max(move(child_nodes));
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMathMax.h b/Libraries/LibWeb/CSS/CSSMathMax.h
deleted file mode 100644
index ba42136aeb1..00000000000
--- a/Libraries/LibWeb/CSS/CSSMathMax.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibJS/Forward.h>
-#include <LibWeb/CSS/CSSMathValue.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssmathmax
-class CSSMathMax final : public CSSMathValue {
- WEB_WRAPPABLE(CSSMathMax, CSSMathValue);
- GC_DECLARE_ALLOCATOR(CSSMathMax);
-
-public:
- [[nodiscard]] static GC::Ref<CSSMathMax> create(NumericType, GC::Ref<CSSNumericArray>);
- static WebIDL::ExceptionOr<GC::Ref<CSSMathMax>> create_for_constructor(ReadonlySpan<CSSNumberish>);
- static WebIDL::ExceptionOr<GC::Ref<CSSMathMax>> add_all_types_into_math_max(GC::RootVector<GC::Ref<CSSNumericValue>> const&);
-
- virtual ~CSSMathMax() override;
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<CSSNumericArray> values() const;
-
- virtual void serialize_math_value(Utf16StringBuilder&, Nested, Parens) const override;
- virtual bool is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const override;
- virtual Optional<SumValue> create_a_sum_value() const override;
-
- virtual WebIDL::ExceptionOr<CalcNodeRef> create_calculation_node(CalculationContext const&) const override;
-
-private:
- CSSMathMax(NumericType, GC::Ref<CSSNumericArray>);
- GC::Ref<CSSNumericArray> m_values;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMathMax.idl b/Libraries/LibWeb/CSS/CSSMathMax.idl
index e4e44378f77..3db3a8d180b 100644
--- a/Libraries/LibWeb/CSS/CSSMathMax.idl
+++ b/Libraries/LibWeb/CSS/CSSMathMax.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssmathmax
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSMathMax : CSSMathValue {
constructor(CSSNumberish... args);
readonly attribute CSSNumericArray values;
diff --git a/Libraries/LibWeb/CSS/CSSMathMin.cpp b/Libraries/LibWeb/CSS/CSSMathMin.cpp
deleted file mode 100644
index e87a815f4d1..00000000000
--- a/Libraries/LibWeb/CSS/CSSMathMin.cpp
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSMathMin.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSMathNegate.h>
-#include <LibWeb/CSS/CSSNumericArray.h>
-#include <LibWeb/CSS/CSSNumericValue.h>
-#include <LibWeb/CSS/StyleValues/CalculatedStyleValue.h>
-#include <LibWeb/WebIDL/DOMException.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSMathMin);
-
-GC::Ref<CSSMathMin> CSSMathMin::create(NumericType type, GC::Ref<CSSNumericArray> values)
-{
- return GC::Heap::the().allocate<CSSMathMin>(move(type), move(values));
-}
-
-WebIDL::ExceptionOr<GC::Ref<CSSMathMin>> CSSMathMin::add_all_types_into_math_min(GC::RootVector<GC::Ref<CSSNumericValue>> const& values)
-{
- auto type = values.first()->type();
- bool first = true;
- for (auto const& value : values) {
- if (first) {
- first = false;
- continue;
- }
- if (auto added_types = type.added_to(value->type()); added_types.has_value()) {
- type = added_types.release_value();
- } else {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create a CSSMathMin with values of incompatible types"_utf16 };
- }
- }
-
- auto values_array = CSSNumericArray::create({ values });
- return CSSMathMin::create(type, values_array);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathmin-cssmathmin
-WebIDL::ExceptionOr<GC::Ref<CSSMathMin>> CSSMathMin::create_for_constructor(ReadonlySpan<CSSNumberish> values)
-{
- // The CSSMathMin(...args) and CSSMathMax(...args) constructors are defined identically to the above, except that
- // in the last step they return a new CSSMathMin or CSSMathMax object, respectively.
- // NB: So, the steps below are a modification of the CSSMathSum steps.
-
- // 1. Replace each item of args with the result of rectifying a numberish value for the item.
- GC::RootVector<GC::Ref<CSSNumericValue>> converted_values;
- converted_values.ensure_capacity(values.size());
- for (auto const& value : values) {
- converted_values.append(rectify_a_numberish_value(value));
- }
-
- // 2. If args is empty, throw a SyntaxError.
- if (converted_values.is_empty())
- return WebIDL::SyntaxError::create("Cannot create an empty CSSMathMin"_utf16);
-
- // 3. Let type be the result of adding the types of all the items of args. If type is failure, throw a TypeError.
- // 4. Return a new CSSMathMin whose values internal slot is set to args.
- return CSSMathMin::add_all_types_into_math_min(converted_values);
-}
-
-CSSMathMin::CSSMathMin(NumericType type, GC::Ref<CSSNumericArray> values)
- : CSSMathValue(CSSMathOperator::Min, move(type))
- , m_values(move(values))
-{
-}
-
-CSSMathMin::~CSSMathMin() = default;
-
-void CSSMathMin::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_values);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmathvalue
-void CSSMathMin::serialize_math_value(Utf16StringBuilder& s, Nested, Parens) const
-{
- // NB: Only steps 1 and 2 apply here.
- // 1. Let s initially be the empty string.
-
- // 2. If this is a CSSMathMin or CSSMathMax:
- {
- // 1. Append "min(" or "max(" to s, as appropriate.
- s.append_ascii("min("sv);
-
- // 2. For each arg in this’s values internal slot, serialize arg with nested and paren-less both true, and
- // append the result to s, appending a ", " between successive values.
- bool first = true;
- for (auto const& arg : m_values->values()) {
- if (first) {
- first = false;
- } else {
- s.append_ascii(", "sv);
- }
- arg->serialize(s, { .nested = true, .parenless = true });
- }
-
- // 3. Append ")" to s and return s.
- s.append_ascii(')');
- }
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathmin-values
-GC::Ref<CSSNumericArray> CSSMathMin::values() const
-{
- return m_values;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#equal-numeric-value
-bool CSSMathMin::is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const
-{
- // NB: Only steps 1 and 3 are relevant.
- // 1. If value1 and value2 are not members of the same interface, return false.
- auto* other_min = as_if<CSSMathMin>(*other);
- if (!other_min)
- return false;
-
- // 3. If value1 and value2 are both CSSMathSums, CSSMathProducts, CSSMathMins, or CSSMathMaxs:
- // NB: Substeps are implemented in CSSNumericArray.
- return m_values->is_equal_numeric_values(other_min->m_values);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
-Optional<SumValue> CSSMathMin::create_a_sum_value() const
-{
- // 1. Let args be the result of creating a sum value for each item in this’s values internal slot.
- Vector<Optional<SumValue>> args;
- args.ensure_capacity(m_values->length());
- for (auto const& value : m_values->values()) {
- args.unchecked_append(value->create_a_sum_value());
- }
-
- Optional<SumValue> item_with_smallest_value = args.first();
- for (auto const& item : args) {
- // 2. If any item of args is failure, or has a length greater than one, return failure.
- if (!item.has_value() || item->size() > 1)
- return {};
-
- // 3. If not all of the unit maps among the items of args are identical, return failure.
- if (item->first().unit_map != item_with_smallest_value->first().unit_map)
- return {};
-
- if (item->first().value < item_with_smallest_value->first().value)
- item_with_smallest_value = item;
- }
-
- // 4. Return the item of args whose sole item has the smallest value.
- return item_with_smallest_value;
-}
-
-WebIDL::ExceptionOr<CalcNodeRef> CSSMathMin::create_calculation_node(CalculationContext const& context) const
-{
- Vector<CalcNodeRef> child_nodes;
- for (auto const& child_value : m_values->values()) {
- child_nodes.append(TRY(child_value->create_calculation_node(context)));
- }
-
- return CalcNodeRef::min(move(child_nodes));
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMathMin.h b/Libraries/LibWeb/CSS/CSSMathMin.h
deleted file mode 100644
index 5fc6cec93b5..00000000000
--- a/Libraries/LibWeb/CSS/CSSMathMin.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibJS/Forward.h>
-#include <LibWeb/CSS/CSSMathValue.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssmathmin
-class CSSMathMin final : public CSSMathValue {
- WEB_WRAPPABLE(CSSMathMin, CSSMathValue);
- GC_DECLARE_ALLOCATOR(CSSMathMin);
-
-public:
- [[nodiscard]] static GC::Ref<CSSMathMin> create(NumericType, GC::Ref<CSSNumericArray>);
- static WebIDL::ExceptionOr<GC::Ref<CSSMathMin>> create_for_constructor(ReadonlySpan<CSSNumberish>);
- static WebIDL::ExceptionOr<GC::Ref<CSSMathMin>> add_all_types_into_math_min(GC::RootVector<GC::Ref<CSSNumericValue>> const&);
-
- virtual ~CSSMathMin() override;
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<CSSNumericArray> values() const;
-
- virtual void serialize_math_value(Utf16StringBuilder&, Nested, Parens) const override;
- virtual bool is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const override;
- virtual Optional<SumValue> create_a_sum_value() const override;
-
- virtual WebIDL::ExceptionOr<CalcNodeRef> create_calculation_node(CalculationContext const&) const override;
-
-private:
- CSSMathMin(NumericType, GC::Ref<CSSNumericArray>);
- GC::Ref<CSSNumericArray> m_values;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMathMin.idl b/Libraries/LibWeb/CSS/CSSMathMin.idl
index aa260d24c26..b93960056d3 100644
--- a/Libraries/LibWeb/CSS/CSSMathMin.idl
+++ b/Libraries/LibWeb/CSS/CSSMathMin.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssmathmin
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSMathMin : CSSMathValue {
constructor(CSSNumberish... args);
readonly attribute CSSNumericArray values;
diff --git a/Libraries/LibWeb/CSS/CSSMathNegate.cpp b/Libraries/LibWeb/CSS/CSSMathNegate.cpp
deleted file mode 100644
index 9535e9549c6..00000000000
--- a/Libraries/LibWeb/CSS/CSSMathNegate.cpp
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSMathNegate.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/StyleValues/CalculatedStyleValue.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSMathNegate);
-
-GC::Ref<CSSMathNegate> CSSMathNegate::create(NumericType type, GC::Ref<CSSNumericValue> values)
-{
- return GC::Heap::the().allocate<CSSMathNegate>(move(type), move(values));
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathnegate-cssmathnegate
-GC::Ref<CSSMathNegate> CSSMathNegate::create_from_numberish(CSSNumberish value)
-{
- // The CSSMathNegate(arg) constructor must, when called, perform the following steps:
- // 1. Replace arg with the result of rectifying a numberish value for arg.
- auto converted_value = rectify_a_numberish_value(value);
-
- // 2. Return a new CSSMathNegate whose value internal slot is set to arg.
- return CSSMathNegate::create(converted_value->type(), converted_value);
-}
-
-CSSMathNegate::CSSMathNegate(NumericType type, GC::Ref<CSSNumericValue> values)
- : CSSMathValue(CSSMathOperator::Negate, move(type))
- , m_value(move(values))
-{
-}
-
-CSSMathNegate::~CSSMathNegate() = default;
-
-void CSSMathNegate::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_value);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmathvalue
-void CSSMathNegate::serialize_math_value(Utf16StringBuilder& s, Nested nested, Parens parens) const
-{
- // NB: Only steps 1 and 4 apply here.
- // 1. Let s initially be the empty string.
-
- // 4. Otherwise, if this is a CSSMathNegate:
- {
- // 1. If paren-less is true, continue to the next step; otherwise, if nested is true, append "(" to s;
- // otherwise, append "calc(" to s.
- if (parens == Parens::With) {
- if (nested == Nested::Yes) {
- s.append_ascii('(');
- } else {
- s.append_ascii("calc("sv);
- }
- }
-
- // 2. Append "-" to s.
- s.append_ascii('-');
-
- // 3. Serialize this’s value internal slot with nested set to true, and append the result to s.
- m_value->serialize(s, { .nested = true });
-
- // 4. If paren-less is false, append ")" to s,
- if (parens == Parens::With)
- s.append_ascii(')');
-
- // 5. Return s.
- }
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathnegate-value
-GC::Ref<CSSNumericValue> CSSMathNegate::value() const
-{
- return m_value;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#equal-numeric-value
-bool CSSMathNegate::is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const
-{
- // NB: Only steps 1, 4 and 5 are relevant.
- // 1. If value1 and value2 are not members of the same interface, return false.
- auto* other_negate = as_if<CSSMathNegate>(*other);
- if (!other_negate)
- return false;
-
- // 4. Assert: value1 and value2 are both CSSMathNegates or CSSMathInverts.
- // 5. Return whether value1’s value and value2’s value are equal numeric values.
- return m_value->is_equal_numeric_value(other_negate->m_value);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
-Optional<SumValue> CSSMathNegate::create_a_sum_value() const
-{
- // 1. Let values be the result of creating a sum value from this’s value internal slot.
- auto values = m_value->create_a_sum_value();
-
- // 2. If values is failure, return failure.
- if (!values.has_value())
- return {};
-
- // 3. Negate the value of each item of values.
- for (auto& value : *values)
- value.value = -value.value;
-
- // 4. Return values.
- return values;
-}
-
-WebIDL::ExceptionOr<CalcNodeRef> CSSMathNegate::create_calculation_node(CalculationContext const& context) const
-{
- return CalcNodeRef::negate(TRY(m_value->create_calculation_node(context)));
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMathNegate.h b/Libraries/LibWeb/CSS/CSSMathNegate.h
deleted file mode 100644
index 6e277f680e5..00000000000
--- a/Libraries/LibWeb/CSS/CSSMathNegate.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSMathValue.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssmathnegate
-class CSSMathNegate final : public CSSMathValue {
- WEB_WRAPPABLE(CSSMathNegate, CSSMathValue);
- GC_DECLARE_ALLOCATOR(CSSMathNegate);
-
-public:
- [[nodiscard]] static GC::Ref<CSSMathNegate> create(NumericType, GC::Ref<CSSNumericValue>);
- static GC::Ref<CSSMathNegate> create_from_numberish(CSSNumberish);
-
- virtual ~CSSMathNegate() override;
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<CSSNumericValue> value() const;
-
- virtual void serialize_math_value(Utf16StringBuilder&, Nested, Parens) const override;
- virtual bool is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const override;
- virtual Optional<SumValue> create_a_sum_value() const override;
-
- virtual WebIDL::ExceptionOr<CalcNodeRef> create_calculation_node(CalculationContext const&) const override;
-
-private:
- CSSMathNegate(NumericType, GC::Ref<CSSNumericValue>);
- GC::Ref<CSSNumericValue> m_value;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMathNegate.idl b/Libraries/LibWeb/CSS/CSSMathNegate.idl
index ecbca514638..bdfb70f3215 100644
--- a/Libraries/LibWeb/CSS/CSSMathNegate.idl
+++ b/Libraries/LibWeb/CSS/CSSMathNegate.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssmathnegate
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSMathNegate : CSSMathValue {
constructor(CSSNumberish arg);
readonly attribute CSSNumericValue value;
diff --git a/Libraries/LibWeb/CSS/CSSMathProduct.cpp b/Libraries/LibWeb/CSS/CSSMathProduct.cpp
deleted file mode 100644
index 655d5cdbbe3..00000000000
--- a/Libraries/LibWeb/CSS/CSSMathProduct.cpp
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSMathProduct.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSMathInvert.h>
-#include <LibWeb/CSS/CSSNumericArray.h>
-#include <LibWeb/CSS/StyleValues/CalculatedStyleValue.h>
-#include <LibWeb/WebIDL/DOMException.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSMathProduct);
-
-GC::Ref<CSSMathProduct> CSSMathProduct::create(NumericType type, GC::Ref<CSSNumericArray> values)
-{
- return GC::Heap::the().allocate<CSSMathProduct>(move(type), move(values));
-}
-
-WebIDL::ExceptionOr<GC::Ref<CSSMathProduct>> CSSMathProduct::multiply_all_types_into_math_product(GC::RootVector<GC::Ref<CSSNumericValue>> const& values)
-{
- auto type = values.first()->type();
- bool first = true;
- for (auto const& value : values) {
- if (first) {
- first = false;
- continue;
- }
- if (auto multiplied_types = type.multiplied_by(value->type()); multiplied_types.has_value()) {
- type = multiplied_types.release_value();
- } else {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create a CSSMathProduct with values of incompatible types"_utf16 };
- }
- }
-
- auto values_array = CSSNumericArray::create({ values });
- return CSSMathProduct::create(type, values_array);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathproduct-cssmathproduct
-WebIDL::ExceptionOr<GC::Ref<CSSMathProduct>> CSSMathProduct::create_for_constructor(ReadonlySpan<CSSNumberish> values)
-{
- // The CSSMathProduct(...args) constructor is defined identically to the above, except that in step 3 it multiplies
- // the types instead of adding, and in the last step it returns a CSSMathProduct.
- // NB: So, the steps below are a modification of the CSSMathSum steps.
-
- // 1. Replace each item of args with the result of rectifying a numberish value for the item.
- GC::RootVector<GC::Ref<CSSNumericValue>> converted_values;
- converted_values.ensure_capacity(values.size());
- for (auto const& value : values) {
- converted_values.append(rectify_a_numberish_value(value));
- }
-
- // 2. If args is empty, throw a SyntaxError.
- if (converted_values.is_empty())
- return WebIDL::SyntaxError::create("Cannot create an empty CSSMathProduct"_utf16);
-
- // 3. Let type be the result of multiplying the types of all the items of args. If type is failure, throw a TypeError.
- // 4. Return a new CSSMathProduct whose values internal slot is set to args.
- return multiply_all_types_into_math_product(converted_values);
-}
-
-CSSMathProduct::CSSMathProduct(NumericType type, GC::Ref<CSSNumericArray> values)
- : CSSMathValue(CSSMathOperator::Product, move(type))
- , m_values(move(values))
-{
-}
-
-CSSMathProduct::~CSSMathProduct() = default;
-
-void CSSMathProduct::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_values);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmathvalue
-void CSSMathProduct::serialize_math_value(Utf16StringBuilder& s, Nested nested, Parens parens) const
-{
- // NB: Only steps 1 and 5 apply here.
- // 1. Let s initially be the empty string.
-
- // 5. Otherwise, if this is a CSSMathProduct:
- {
- // 1. If paren-less is true, continue to the next step; otherwise, if nested is true, append "(" to s;
- // otherwise, append "calc(" to s.
- if (parens == Parens::With) {
- if (nested == Nested::Yes) {
- s.append_ascii('(');
- } else {
- s.append_ascii("calc("sv);
- }
- }
-
- // 2. Serialize the first item in this’s values internal slot with nested set to true, and append the result to s.
- m_values->values().first()->serialize(s, { .nested = true });
-
- // 3. For each arg in this’s values internal slot beyond the first:
- bool first = true;
- for (auto const& arg : m_values->values()) {
- if (first) {
- first = false;
- continue;
- }
-
- // 1. If arg is a CSSMathInvert, append " / " to s, then serialize arg’s value internal slot with nested
- // set to true, and append the result to s.
- if (auto* invert = as_if<CSSMathInvert>(*arg)) {
- s.append_ascii(" / "sv);
- invert->value()->serialize(s, { .nested = true });
- }
-
- // 2. Otherwise, append " * " to s, then serialize arg with nested set to true, and append the result to s.
- else {
- s.append_ascii(" * "sv);
- arg->serialize(s, { .nested = true });
- }
- }
-
- // 4. If paren-less is false, append ")" to s,
- if (parens == Parens::With)
- s.append_ascii(')');
-
- // 5. Return s.
- }
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathproduct-values
-GC::Ref<CSSNumericArray> CSSMathProduct::values() const
-{
- return m_values;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#equal-numeric-value
-bool CSSMathProduct::is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const
-{
- // NB: Only steps 1 and 3 are relevant.
- // 1. If value1 and value2 are not members of the same interface, return false.
- auto* other_product = as_if<CSSMathProduct>(*other);
- if (!other_product)
- return false;
-
- // 3. If value1 and value2 are both CSSMathSums, CSSMathProducts, CSSMathMins, or CSSMathMaxs:
- // NB: Substeps are implemented in CSSNumericArray.
- return m_values->is_equal_numeric_values(other_product->m_values);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
-Optional<SumValue> CSSMathProduct::create_a_sum_value() const
-{
- // 1. Let values initially be the sum value «(1, «[ ]»)». (I.e. what you’d get from 1.)
- SumValue values {
- SumValueItem { 1, {} }
- };
-
- // 2. For each item in this’s values internal slot:
- for (auto const& item : m_values->values()) {
- // 1. Let new values be the result of creating a sum value from item.
- // Let temp initially be an empty list.
- auto new_values = item->create_a_sum_value();
- SumValue temp;
-
- // 2. If new values is failure, return failure.
- if (!new_values.has_value())
- return {};
-
- // 3. For each item1 in values:
- for (auto const& item1 : values) {
- // 1. For each item2 in new values:
- for (auto const& item2 : *new_values) {
- // 1. Let item be a tuple with its value set to the product of the values of item1 and item2, and its
- // unit map set to the product of the unit maps of item1 and item2, with all entries with a zero
- // value removed.
- auto unit_map = product_of_two_unit_maps(item1.unit_map, item2.unit_map);
- unit_map.remove_all_matching([](auto&, auto& value) { return value == 0; });
-
- // 2. Append item to temp.
- temp.empend(item1.value * item2.value, move(unit_map));
- }
- }
-
- // 4. Set values to temp.
- values = move(temp);
- }
-
- // 3. Return values.
- return values;
-}
-
-WebIDL::ExceptionOr<CalcNodeRef> CSSMathProduct::create_calculation_node(CalculationContext const& context) const
-{
- Vector<CalcNodeRef> child_nodes;
- for (auto const& child_value : m_values->values()) {
- child_nodes.append(TRY(child_value->create_calculation_node(context)));
- }
-
- return CalcNodeRef::product(move(child_nodes));
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMathProduct.h b/Libraries/LibWeb/CSS/CSSMathProduct.h
deleted file mode 100644
index 243e93800cf..00000000000
--- a/Libraries/LibWeb/CSS/CSSMathProduct.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibJS/Forward.h>
-#include <LibWeb/CSS/CSSMathValue.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssmathproduct
-class CSSMathProduct final : public CSSMathValue {
- WEB_WRAPPABLE(CSSMathProduct, CSSMathValue);
- GC_DECLARE_ALLOCATOR(CSSMathProduct);
-
-public:
- [[nodiscard]] static GC::Ref<CSSMathProduct> create(NumericType, GC::Ref<CSSNumericArray>);
- static WebIDL::ExceptionOr<GC::Ref<CSSMathProduct>> create_for_constructor(ReadonlySpan<CSSNumberish>);
- static WebIDL::ExceptionOr<GC::Ref<CSSMathProduct>> multiply_all_types_into_math_product(GC::RootVector<GC::Ref<CSSNumericValue>> const&);
-
- virtual ~CSSMathProduct() override;
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<CSSNumericArray> values() const;
-
- virtual void serialize_math_value(Utf16StringBuilder&, Nested, Parens) const override;
- virtual bool is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const override;
- virtual Optional<SumValue> create_a_sum_value() const override;
-
- virtual WebIDL::ExceptionOr<CalcNodeRef> create_calculation_node(CalculationContext const&) const override;
-
-private:
- CSSMathProduct(NumericType, GC::Ref<CSSNumericArray>);
- GC::Ref<CSSNumericArray> m_values;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMathProduct.idl b/Libraries/LibWeb/CSS/CSSMathProduct.idl
index a24ac7249b2..19437b79a02 100644
--- a/Libraries/LibWeb/CSS/CSSMathProduct.idl
+++ b/Libraries/LibWeb/CSS/CSSMathProduct.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssmathproduct
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSMathProduct : CSSMathValue {
constructor(CSSNumberish... args);
readonly attribute CSSNumericArray values;
diff --git a/Libraries/LibWeb/CSS/CSSMathSum.cpp b/Libraries/LibWeb/CSS/CSSMathSum.cpp
deleted file mode 100644
index 0f3d2df8e0e..00000000000
--- a/Libraries/LibWeb/CSS/CSSMathSum.cpp
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSMathSum.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSMathNegate.h>
-#include <LibWeb/CSS/CSSNumericArray.h>
-#include <LibWeb/CSS/StyleValues/CalculatedStyleValue.h>
-#include <LibWeb/WebIDL/DOMException.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSMathSum);
-
-GC::Ref<CSSMathSum> CSSMathSum::create(NumericType type, GC::Ref<CSSNumericArray> values)
-{
- return GC::Heap::the().allocate<CSSMathSum>(move(type), move(values));
-}
-
-WebIDL::ExceptionOr<GC::Ref<CSSMathSum>> CSSMathSum::add_all_types_into_math_sum(GC::RootVector<GC::Ref<CSSNumericValue>> const& values)
-{
- auto type = values.first()->type();
- bool first = true;
- for (auto const& value : values) {
- if (first) {
- first = false;
- continue;
- }
- if (auto added_types = type.added_to(value->type()); added_types.has_value()) {
- type = added_types.release_value();
- } else {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create a CSSMathSum with values of incompatible types"_utf16 };
- }
- }
-
- auto values_array = CSSNumericArray::create({ values });
- return CSSMathSum::create(type, values_array);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathsum-cssmathsum
-WebIDL::ExceptionOr<GC::Ref<CSSMathSum>> CSSMathSum::create_for_constructor(ReadonlySpan<CSSNumberish> values)
-{
- // The CSSMathSum(...args) constructor must, when called, perform the following steps:
-
- // 1. Replace each item of args with the result of rectifying a numberish value for the item.
- GC::RootVector<GC::Ref<CSSNumericValue>> converted_values;
- converted_values.ensure_capacity(values.size());
- for (auto const& value : values) {
- converted_values.append(rectify_a_numberish_value(value));
- }
-
- // 2. If args is empty, throw a SyntaxError.
- if (converted_values.is_empty())
- return WebIDL::SyntaxError::create("Cannot create an empty CSSMathSum"_utf16);
-
- // 3. Let type be the result of adding the types of all the items of args. If type is failure, throw a TypeError.
- // 4. Return a new CSSMathSum whose values internal slot is set to args.
- return add_all_types_into_math_sum(converted_values);
-}
-
-CSSMathSum::CSSMathSum(NumericType type, GC::Ref<CSSNumericArray> values)
- : CSSMathValue(CSSMathOperator::Sum, move(type))
- , m_values(move(values))
-{
-}
-
-CSSMathSum::~CSSMathSum() = default;
-
-void CSSMathSum::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_values);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmathvalue
-void CSSMathSum::serialize_math_value(Utf16StringBuilder& s, Nested nested, Parens parens) const
-{
- // NB: Only steps 1 and 3 apply here.
- // 1. Let s initially be the empty string.
-
- // 3. Otherwise, if this is a CSSMathSum:
- {
- // 1. If paren-less is true, continue to the next step; otherwise, if nested is true, append "(" to s;
- // otherwise, append "calc(" to s.
- if (parens == Parens::With) {
- if (nested == Nested::Yes) {
- s.append_ascii('(');
- } else {
- s.append_ascii("calc("sv);
- }
- }
-
- // 2. Serialize the first item in this’s values internal slot with nested set to true, and append the result
- // to s.
- m_values->values().first()->serialize(s, { .nested = true });
-
- // 3. For each arg in this's values internal slot beyond the first:
- bool first = true;
- for (auto const& arg : m_values->values()) {
- if (first) {
- first = false;
- continue;
- }
-
- // 1. If arg is a CSSMathNegate, append " - " to s, then serialize arg’s value internal slot with nested
- // set to true, and append the result to s.
- if (auto* negate = as_if<CSSMathNegate>(*arg)) {
- s.append_ascii(" - "sv);
- negate->value()->serialize(s, { .nested = true });
- }
-
- // 2. Otherwise, append " + " to s, then serialize arg with nested set to true, and append the result to s.
- else {
- s.append_ascii(" + "sv);
- arg->serialize(s, { .nested = true });
- }
- }
-
- // 4. If paren-less is false, append ")" to s,
- if (parens == Parens::With)
- s.append_ascii(')');
-
- // 5. Return s.
- }
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmathsum-values
-GC::Ref<CSSNumericArray> CSSMathSum::values() const
-{
- return m_values;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#equal-numeric-value
-bool CSSMathSum::is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const
-{
- // NB: Only steps 1 and 3 are relevant.
- // 1. If value1 and value2 are not members of the same interface, return false.
- auto* other_sum = as_if<CSSMathSum>(*other);
- if (!other_sum)
- return false;
-
- // 3. If value1 and value2 are both CSSMathSums, CSSMathProducts, CSSMathMins, or CSSMathMaxs:
- // NB: Substeps are implemented in CSSNumericArray.
- return m_values->is_equal_numeric_values(other_sum->m_values);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
-Optional<SumValue> CSSMathSum::create_a_sum_value() const
-{
- // 1. Let values initially be an empty list.
- SumValue values;
-
- // 2. For each item in this’s values internal slot:
- for (auto const item : m_values->values()) {
- // 1. Let value be the result of creating a sum value from item. If value is failure, return failure.
- auto maybe_value = item->create_a_sum_value();
- if (!maybe_value.has_value())
- return {};
- auto const& value = maybe_value.value();
-
- // 2. For each subvalue of value:
- for (auto const& subvalue : value) {
- // 1. If values already contains an item with the same unit map as subvalue, increment that item’s value by
- // the value of subvalue.
- auto existing_item = values.find_if([&subvalue](SumValueItem const& other) {
- return subvalue.unit_map == other.unit_map;
- });
- if (existing_item != values.end()) {
- existing_item->value += subvalue.value;
- }
- // 2. Otherwise, append subvalue to values.
- else {
- values.append(subvalue);
- }
- }
- }
-
- // 3. Create a type from the unit map of each item of values, and add all the types together.
- // If the result is failure, return failure.
- auto added_type = NumericType::create_from_unit_map(values.first().unit_map);
- if (!added_type.has_value())
- return {};
- bool first = true;
- for (auto const& [_, unit_map] : values) {
- if (first) {
- first = false;
- continue;
- }
- auto type = NumericType::create_from_unit_map(unit_map);
- if (!type.has_value())
- return {};
-
- added_type = added_type->added_to(type.value());
- if (!added_type.has_value())
- return {};
- }
-
- // 4. Return values.
- return values;
-}
-
-WebIDL::ExceptionOr<CalcNodeRef> CSSMathSum::create_calculation_node(CalculationContext const& context) const
-{
- Vector<CalcNodeRef> child_nodes;
- for (auto const& child_value : m_values->values()) {
- child_nodes.append(TRY(child_value->create_calculation_node(context)));
- }
-
- return CalcNodeRef::sum(move(child_nodes));
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMathSum.h b/Libraries/LibWeb/CSS/CSSMathSum.h
deleted file mode 100644
index 821b243f1a2..00000000000
--- a/Libraries/LibWeb/CSS/CSSMathSum.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibJS/Forward.h>
-#include <LibWeb/CSS/CSSMathValue.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssmathsum
-class CSSMathSum final : public CSSMathValue {
- WEB_WRAPPABLE(CSSMathSum, CSSMathValue);
- GC_DECLARE_ALLOCATOR(CSSMathSum);
-
-public:
- [[nodiscard]] static GC::Ref<CSSMathSum> create(NumericType, GC::Ref<CSSNumericArray>);
- static WebIDL::ExceptionOr<GC::Ref<CSSMathSum>> create_for_constructor(ReadonlySpan<CSSNumberish>);
- static WebIDL::ExceptionOr<GC::Ref<CSSMathSum>> add_all_types_into_math_sum(GC::RootVector<GC::Ref<CSSNumericValue>> const&);
-
- virtual ~CSSMathSum() override;
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<CSSNumericArray> values() const;
-
- virtual void serialize_math_value(Utf16StringBuilder&, Nested, Parens) const override;
- virtual bool is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const override;
- virtual Optional<SumValue> create_a_sum_value() const override;
-
- virtual WebIDL::ExceptionOr<CalcNodeRef> create_calculation_node(CalculationContext const&) const override;
-
-private:
- CSSMathSum(NumericType, GC::Ref<CSSNumericArray>);
- GC::Ref<CSSNumericArray> m_values;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMathSum.idl b/Libraries/LibWeb/CSS/CSSMathSum.idl
index e8114ac27d5..39c7350973d 100644
--- a/Libraries/LibWeb/CSS/CSSMathSum.idl
+++ b/Libraries/LibWeb/CSS/CSSMathSum.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssmathsum
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSMathSum : CSSMathValue {
constructor(CSSNumberish... args);
readonly attribute CSSNumericArray values;
diff --git a/Libraries/LibWeb/CSS/CSSMathValue.cpp b/Libraries/LibWeb/CSS/CSSMathValue.cpp
deleted file mode 100644
index 3fbfcc5e76b..00000000000
--- a/Libraries/LibWeb/CSS/CSSMathValue.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSMathValue.h"
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/StyleValues/CalculatedStyleValue.h>
-#include <LibWeb/CSS/StyleValues/OpacityValueStyleValue.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSMathValue);
-
-CSSMathValue::CSSMathValue(CSSMathOperator operator_, NumericType type)
- : CSSNumericValue(move(type))
- , m_operator(operator_)
-{
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
-WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> CSSMathValue::create_an_internal_representation(PropertyNameAndID const& property, PerformTypeCheck perform_type_check) const
-{
- // If value is a CSSStyleValue subclass,
- // If value does not match the grammar of a list-valued property iteration of property, throw a TypeError.
- //
- // If any component of property’s CSS grammar has a limited numeric range, and the corresponding part of value
- // is a CSSUnitValue that is outside of that range, replace that value with the result of wrapping it in a
- // fresh CSSMathSum whose values internal slot contains only that part of value.
- //
- // Return the value.
-
- auto context = CalculationContext::for_property(property);
- auto matches = [&] {
- if (type().matches_angle(context.percentages_resolve_as))
- return property_accepts_type(property.id(), ValueType::Angle);
- if (type().matches_flex(context.percentages_resolve_as)) {
- // https://drafts.csswg.org/css-grid-2/#fr-unit
- // NB: <flex> values "cannot be represented in or combined with other unit types in calc() expressions".
- return property.is_custom_property() && property_accepts_type(property.id(), ValueType::Flex);
- }
- if (type().matches_frequency(context.percentages_resolve_as))
- return property_accepts_type(property.id(), ValueType::Frequency);
- if (type().matches_length(context.percentages_resolve_as))
- return property_accepts_type(property.id(), ValueType::Length);
- if (type().matches_number(context.percentages_resolve_as))
- return property_accepts_type(property.id(), ValueType::Number) || property_accepts_type(property.id(), ValueType::Integer) || property_accepts_type(property.id(), ValueType::OpacityValue);
- if (type().matches_percentage())
- return property_accepts_type(property.id(), ValueType::Percentage) || property_accepts_type(property.id(), ValueType::OpacityValue);
- if (type().matches_resolution(context.percentages_resolve_as))
- return property_accepts_type(property.id(), ValueType::Resolution);
- if (type().matches_time(context.percentages_resolve_as))
- return property_accepts_type(property.id(), ValueType::Time);
- return false;
- }();
-
- if (perform_type_check == PerformTypeCheck::Yes && !matches)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Property does not accept values of this type."_utf16 };
-
- auto calculated_value = CalculatedStyleValue::create(TRY(create_calculation_node(context)), type(), move(context));
-
- // NB: Our parser represents an <opacity-value> as an opacity value that holds the calculation.
- if (property_accepts_type(property.id(), ValueType::OpacityValue) && (type().matches_number({}) || type().matches_percentage()))
- return OpacityValueStyleValue::create(move(calculated_value));
-
- return calculated_value;
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMathValue.h b/Libraries/LibWeb/CSS/CSSMathValue.h
deleted file mode 100644
index 459aab2a406..00000000000
--- a/Libraries/LibWeb/CSS/CSSMathValue.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/CSSMathValue.h>
-#include <LibWeb/CSS/CSSNumericValue.h>
-#include <LibWeb/Forward.h>
-
-namespace Web::CSS {
-
-using CSSMathOperator = Bindings::CSSMathOperator;
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssmathvalue
-class CSSMathValue : public CSSNumericValue {
- WEB_WRAPPABLE(CSSMathValue, CSSNumericValue);
- GC_DECLARE_ALLOCATOR(CSSMathValue);
-
-public:
- virtual ~CSSMathValue() override = default;
-
- CSSMathOperator operator_() const { return m_operator; }
-
- enum class Nested : u8 {
- No,
- Yes,
- };
- enum class Parens : u8 {
- With,
- Without,
- };
- virtual void serialize_math_value(Utf16StringBuilder&, Nested, Parens) const = 0;
-
- virtual WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> create_an_internal_representation(PropertyNameAndID const&, PerformTypeCheck) const final override;
-
-protected:
- explicit CSSMathValue(CSSMathOperator, NumericType);
-
- CSSMathOperator m_operator;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMathValue.idl b/Libraries/LibWeb/CSS/CSSMathValue.idl
index d05d3e6b93f..d65a6d667b9 100644
--- a/Libraries/LibWeb/CSS/CSSMathValue.idl
+++ b/Libraries/LibWeb/CSS/CSSMathValue.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssmathvalue
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSMathValue : CSSNumericValue {
readonly attribute CSSMathOperator operator;
};
diff --git a/Libraries/LibWeb/CSS/CSSMatrixComponent.cpp b/Libraries/LibWeb/CSS/CSSMatrixComponent.cpp
deleted file mode 100644
index 6bd652cdf28..00000000000
--- a/Libraries/LibWeb/CSS/CSSMatrixComponent.cpp
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSMatrixComponent.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/Bindings/CSSMatrixComponent.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
-#include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
-#include <LibWeb/Geometry/DOMMatrix.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSMatrixComponent);
-
-GC::Ref<CSSMatrixComponent> CSSMatrixComponent::create(Is2D is_2d, GC::Ref<Geometry::DOMMatrix> matrix)
-{
- return GC::Heap::the().allocate<CSSMatrixComponent>(is_2d, matrix);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssmatrixcomponent-cssmatrixcomponent
-WebIDL::ExceptionOr<GC::Ref<CSSMatrixComponent>> CSSMatrixComponent::create_from_dom_matrix_read_only(GC::Ref<Geometry::DOMMatrixReadOnly> matrix, Optional<bool> is_2d_option)
-{
- // The CSSMatrixComponent(matrix, options) constructor must, when invoked, perform the following steps:
-
- // 1. Let this be a new CSSMatrixComponent object with its matrix internal slot set to matrix.
- // NB: Done below.
-
- // 2. If options was passed and has a is2D field, set this’s is2D internal slot to the value of that field.
- // 3. Otherwise, set this’s is2D internal slot to the value of matrix’s is2D internal slot.
- auto is_2d = matrix->is2d() ? Is2D::Yes : Is2D::No;
- if (is_2d_option.has_value())
- is_2d = is_2d_option.value() ? Is2D::Yes : Is2D::No;
-
- auto this_ = CSSMatrixComponent::create(is_2d, Geometry::DOMMatrix::create_from_dom_matrix_read_only(matrix));
-
- // 4. Return this.
- return this_;
-}
-
-WebIDL::ExceptionOr<GC::Ref<CSSMatrixComponent>> CSSMatrixComponent::create_for_constructor(GC::Ref<Geometry::DOMMatrixReadOnly> matrix, Bindings::CSSMatrixComponentOptions const& options)
-{
- return create_from_dom_matrix_read_only(matrix, options.is2d);
-}
-
-CSSMatrixComponent::CSSMatrixComponent(Is2D is_2d, GC::Ref<Geometry::DOMMatrix> matrix)
- : CSSTransformComponent(is_2d)
- , m_matrix(matrix)
-{
-}
-
-CSSMatrixComponent::~CSSMatrixComponent() = default;
-
-void CSSMatrixComponent::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_matrix);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssmatrixcomponent
-WebIDL::ExceptionOr<Utf16String> CSSMatrixComponent::to_string() const
-{
- // 1. Return the serialization of this’s matrix internal slot.
- // FIXME: This means we ignore our is_2d state. https://github.com/w3c/css-houdini-drafts/issues/1155
- return m_matrix->to_string();
-}
-
-WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSMatrixComponent::to_matrix() const
-{
- // https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformcomponent-tomatrix
- // 1. Let matrix be a new DOMMatrix object, initialized to this’s equivalent 4x4 transform matrix, as defined in
- // CSS Transforms 1 § 12. Mathematical Description of Transform Functions, and with its is2D internal slot set to
- // the same value as this’s is2D internal slot.
- // NB: The elements are m11, m12, m13, m14, m21, ..., m44. A 2D component only uses m11, m12, m21, m22, m41 and m42.
- auto elements = m_matrix->elements();
- if (is_2d()) {
- elements = { elements[0], elements[1], 0, 0,
- elements[4], elements[5], 0, 0,
- 0, 0, 1, 0,
- elements[12], elements[13], 0, 1 };
- }
- auto matrix = Geometry::DOMMatrix::create();
- matrix->set_elements(elements, is_2d());
-
- // 2. Return matrix.
- return matrix;
-}
-
-WebIDL::ExceptionOr<void> CSSMatrixComponent::set_matrix(GC::Ref<Geometry::DOMMatrix> matrix)
-{
- // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
- // FIXME: Should this modify is_2d? Or should we modify the matrix's is_2d?
- m_matrix = matrix;
- return {};
-}
-
-WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> CSSMatrixComponent::create_style_value(PropertyNameAndID const& property) const
-{
- // NB: The elements are m11, m12, m13, m14, m21, ..., m44, and the elements a to f of a 2D matrix are m11, m12, m21,
- // m22, m41 and m42.
- auto elements = m_matrix->elements();
- StyleValueVector values;
- if (is_2d()) {
- for (auto index : { 0, 1, 4, 5, 12, 13 })
- values.append(NumberStyleValue::create(elements[index]));
- return TransformationStyleValue::create(property.id(), TransformFunction::Matrix, move(values));
- }
-
- for (auto element : elements)
- values.append(NumberStyleValue::create(element));
- return TransformationStyleValue::create(property.id(), TransformFunction::Matrix3d, move(values));
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMatrixComponent.h b/Libraries/LibWeb/CSS/CSSMatrixComponent.h
deleted file mode 100644
index 00f00a5530a..00000000000
--- a/Libraries/LibWeb/CSS/CSSMatrixComponent.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSTransformComponent.h>
-#include <LibWeb/Export.h>
-
-namespace Web::Bindings {
-
-struct CSSMatrixComponentOptions;
-
-}
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssmatrixcomponent
-class CSSMatrixComponent final : public CSSTransformComponent {
- WEB_WRAPPABLE(CSSMatrixComponent, CSSTransformComponent);
- GC_DECLARE_ALLOCATOR(CSSMatrixComponent);
-
-public:
- [[nodiscard]] static GC::Ref<CSSMatrixComponent> create(Is2D, GC::Ref<Geometry::DOMMatrix>);
- static WebIDL::ExceptionOr<GC::Ref<CSSMatrixComponent>> create_from_dom_matrix_read_only(GC::Ref<Geometry::DOMMatrixReadOnly>, Optional<bool> is_2d = {});
- static WebIDL::ExceptionOr<GC::Ref<CSSMatrixComponent>> create_for_constructor(GC::Ref<Geometry::DOMMatrixReadOnly>, Bindings::CSSMatrixComponentOptions const&);
-
- virtual ~CSSMatrixComponent() override;
-
- virtual WebIDL::ExceptionOr<Utf16String> to_string() const override;
-
- virtual WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> to_matrix() const override;
-
- GC::Ref<Geometry::DOMMatrix> matrix() const { return m_matrix; }
- WebIDL::ExceptionOr<void> set_matrix(GC::Ref<Geometry::DOMMatrix> matrix);
-
- virtual WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> create_style_value(PropertyNameAndID const&) const override;
-
-private:
- explicit CSSMatrixComponent(Is2D, GC::Ref<Geometry::DOMMatrix>);
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<Geometry::DOMMatrix> m_matrix;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSMatrixComponent.idl b/Libraries/LibWeb/CSS/CSSMatrixComponent.idl
index d9a797f5461..d24d90b2615 100644
--- a/Libraries/LibWeb/CSS/CSSMatrixComponent.idl
+++ b/Libraries/LibWeb/CSS/CSSMatrixComponent.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssmatrixcomponent
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSMatrixComponent : CSSTransformComponent {
constructor(DOMMatrixReadOnly matrix, optional CSSMatrixComponentOptions options = {});
attribute DOMMatrix matrix;
diff --git a/Libraries/LibWeb/CSS/CSSNumericArray.cpp b/Libraries/LibWeb/CSS/CSSNumericArray.cpp
deleted file mode 100644
index 790880516fc..00000000000
--- a/Libraries/LibWeb/CSS/CSSNumericArray.cpp
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSNumericArray.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSNumericValue.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSNumericArray);
-
-GC::Ref<CSSNumericArray> CSSNumericArray::create(GC::RootVector<GC::Ref<CSSNumericValue>> values)
-{
- return GC::Heap::the().allocate<CSSNumericArray>(move(values));
-}
-
-CSSNumericArray::CSSNumericArray(Vector<GC::Ref<CSSNumericValue>>&& values)
- : m_values(move(values))
-{
-}
-
-CSSNumericArray::~CSSNumericArray() = default;
-
-void CSSNumericArray::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_values);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericarray-length
-WebIDL::UnsignedLong CSSNumericArray::length() const
-{
- // The length attribute of CSSNumericArray indicates how many CSSNumericValues are contained within the CSSNumericArray.
- return m_values.size();
-}
-
-GC::Ptr<CSSNumericValue> CSSNumericArray::value_at(size_t index) const
-{
- if (auto item = m_values.get(index); item.has_value())
- return item.release_value().ptr();
- return nullptr;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#equal-numeric-value
-bool CSSNumericArray::is_equal_numeric_values(GC::Ref<CSSNumericArray> other) const
-{
- // NB: This is just step 3, moved here to reduce repetition.
- // 3. If value1 and value2 are both CSSMathSums, CSSMathProducts, CSSMathMins, or CSSMathMaxs:
- {
- // 1. If value1’s values and value2s values internal slots have different sizes, return false.
- if (m_values.size() != other->m_values.size())
- return false;
-
- // 2. If any item in value1’s values internal slot is not an equal numeric value to the item in value2’s values
- // internal slot at the same index, return false.
- for (auto index = 0u; index < m_values.size(); ++index) {
- if (!m_values[index]->is_equal_numeric_value(other->m_values[index]))
- return false;
- }
-
- // 3. Return true.
- return true;
- }
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSNumericArray.h b/Libraries/LibWeb/CSS/CSSNumericArray.h
deleted file mode 100644
index ddebc6ea292..00000000000
--- a/Libraries/LibWeb/CSS/CSSNumericArray.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Vector.h>
-#include <LibGC/RootVector.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericarray
-class CSSNumericArray : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(CSSNumericArray, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(CSSNumericArray);
-
-public:
- [[nodiscard]] static GC::Ref<CSSNumericArray> create(GC::RootVector<GC::Ref<CSSNumericValue>>);
-
- virtual ~CSSNumericArray() override;
-
- WebIDL::UnsignedLong length() const;
- GC::Ptr<CSSNumericValue> value_at(size_t index) const;
- ReadonlySpan<GC::Ref<CSSNumericValue>> values() const { return m_values; }
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
- bool is_equal_numeric_values(GC::Ref<CSSNumericArray> other) const;
-
-private:
- CSSNumericArray(Vector<GC::Ref<CSSNumericValue>>&&);
-
- Vector<GC::Ref<CSSNumericValue>> m_values;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSNumericArray.idl b/Libraries/LibWeb/CSS/CSSNumericArray.idl
index 5f20778829c..71cc8b67c19 100644
--- a/Libraries/LibWeb/CSS/CSSNumericArray.idl
+++ b/Libraries/LibWeb/CSS/CSSNumericArray.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericarray
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSNumericArray {
iterable<CSSNumericValue>;
readonly attribute unsigned long length;
diff --git a/Libraries/LibWeb/CSS/CSSNumericValue.cpp b/Libraries/LibWeb/CSS/CSSNumericValue.cpp
deleted file mode 100644
index e7766e40843..00000000000
--- a/Libraries/LibWeb/CSS/CSSNumericValue.cpp
+++ /dev/null
@@ -1,452 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- * Copyright (c) 2026, Shannon Booth <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/ConservativeVector.h>
-#include <LibWeb/Bindings/CSSNumericValue.h>
-#include <LibWeb/CSS/CSSMathInvert.h>
-#include <LibWeb/CSS/CSSMathMax.h>
-#include <LibWeb/CSS/CSSMathMin.h>
-#include <LibWeb/CSS/CSSMathNegate.h>
-#include <LibWeb/CSS/CSSMathProduct.h>
-#include <LibWeb/CSS/CSSMathSum.h>
-#include <LibWeb/CSS/CSSMathValue.h>
-#include <LibWeb/CSS/CSSNumericArray.h>
-#include <LibWeb/CSS/CSSNumericValue.h>
-#include <LibWeb/CSS/CSSUnitValue.h>
-#include <LibWeb/CSS/NumericType.h>
-#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/StyleValues/DimensionStyleValue.h>
-#include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
-#include <LibWeb/WebIDL/DOMException.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSNumericValue);
-
-CSSNumericValue::CSSNumericValue(NumericType type)
- : CSSStyleValue()
- , m_type(move(type))
-{
-}
-
-static Bindings::CSSNumericBaseType to_om_numeric_base_type(NumericType::BaseType source)
-{
- switch (source) {
- case NumericType::BaseType::Length:
- return Bindings::CSSNumericBaseType::Length;
- case NumericType::BaseType::Angle:
- return Bindings::CSSNumericBaseType::Angle;
- case NumericType::BaseType::Time:
- return Bindings::CSSNumericBaseType::Time;
- case NumericType::BaseType::Frequency:
- return Bindings::CSSNumericBaseType::Frequency;
- case NumericType::BaseType::Resolution:
- return Bindings::CSSNumericBaseType::Resolution;
- case NumericType::BaseType::Flex:
- return Bindings::CSSNumericBaseType::Flex;
- case NumericType::BaseType::Percent:
- return Bindings::CSSNumericBaseType::Percent;
- case NumericType::BaseType::__Count:
- VERIFY_NOT_REACHED();
- }
- VERIFY_NOT_REACHED();
-}
-
-Bindings::CSSNumericType CSSNumericValue::type_for_bindings() const
-{
- Bindings::CSSNumericType result {};
- m_type.for_each_type_and_exponent([&result](NumericType::BaseType base_type, auto power) {
- if (power == 0)
- return;
- switch (base_type) {
- case NumericType::BaseType::Length:
- result.length = power;
- break;
- case NumericType::BaseType::Angle:
- result.angle = power;
- break;
- case NumericType::BaseType::Time:
- result.time = power;
- break;
- case NumericType::BaseType::Frequency:
- result.frequency = power;
- break;
- case NumericType::BaseType::Resolution:
- result.resolution = power;
- break;
- case NumericType::BaseType::Flex:
- result.flex = power;
- break;
- case NumericType::BaseType::Percent:
- result.percent = power;
- break;
- case NumericType::BaseType::__Count:
- VERIFY_NOT_REACHED();
- }
- });
- if (auto percent_hint = m_type.percent_hint(); percent_hint.has_value())
- result.percent_hint = to_om_numeric_base_type(percent_hint.value());
- return result;
-}
-
-static bool all_values_are_css_unit_values_with_the_same_unit(ReadonlySpan<GC::Ref<CSSNumericValue>> const& values)
-{
- VERIFY(!values.is_empty());
- return all_of(values, [&](auto& value) {
- if (auto* unit_value = as_if<CSSUnitValue>(*value))
- return unit_value->unit() == as<CSSUnitValue>(*values[0]).unit();
- return false;
- });
-}
-
-template<typename Operation>
-static GC::Ref<CSSNumericValue> apply_math_operation_on_css_unit_values(ReadonlySpan<GC::Ref<CSSNumericValue>> values, Operation&& operation)
-{
- auto& first_unit_value = as<CSSUnitValue>(*values[0]);
- auto& unit = first_unit_value.unit();
-
- double result = first_unit_value.value();
- for (size_t i = 1; i < values.size(); ++i)
- result = operation(result, as<CSSUnitValue>(*values[i]).value());
- return CSSUnitValue::create(result, unit);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-add
-WebIDL::ExceptionOr<GC::Ref<CSSNumericValue>> CSSNumericValue::add(ReadonlySpan<CSSNumberish> initial_values)
-{
- // 1. Replace each item of values with the result of rectifying a numberish value for the item.
- // 2. If this is a CSSMathSum object, prepend the items in this’s values internal slot to values.
- // Otherwise, prepend this to values.
-
- // NB: We reorder the steps a little to avoid the awkward prepending.
- GC::RootVector<GC::Ref<CSSNumericValue>> values;
- if (auto const* math_sum = as_if<CSSMathSum>(*this)) {
- auto items = math_sum->values()->values();
- values.append(items.data(), items.size());
- } else {
- values.append(*this);
- }
-
- for (auto const& value : initial_values)
- values.append(rectify_a_numberish_value(value));
-
- // 3. If all of the items in values are CSSUnitValues and have the same unit, return a new CSSUnitValue whose unit
- // internal slot is set to that unit, and value internal slot is set to the sum of the value internal slots of
- // the items in values. This addition must be done "left to right" - if values is « 1, 2, 3, 4 », the result must
- // be (((1 + 2) + 3) + 4). (This detail is necessary to ensure interoperability in the presence of floating-point
- // arithmetic.)
- if (all_values_are_css_unit_values_with_the_same_unit(values))
- return apply_math_operation_on_css_unit_values(values, [](double a, double b) { return a + b; });
-
- // 4. Let type be the result of adding the types of every item in values. If type is failure, throw a TypeError.
- // 5. Return a new CSSMathSum object whose values internal slot is set to values.
- return TRY(CSSMathSum::add_all_types_into_math_sum(values));
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-sub
-WebIDL::ExceptionOr<GC::Ref<CSSNumericValue>> CSSNumericValue::sub(ReadonlySpan<CSSNumberish> initial_values)
-{
- // 1. Replace each item of values with the result of rectifying a numberish value for the item, then negating the value.
- GC::ConservativeVector<CSSNumberish> values;
- for (auto const& value : initial_values)
- values.append(rectify_a_numberish_value(value)->negate());
-
- // 2. Return the result of calling the add() internal algorithm with this and values.
- return add(values);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssmath-negate-a-cssnumericvalue
-CSSNumberish CSSNumericValue::negate()
-{
- // 1. If this is a CSSMathNegate object, return this’s value internal slot.
- if (auto* negate = as_if<CSSMathNegate>(*this))
- return GC::Ref<CSSNumericValue> { negate->value() };
-
- // 2. If this is a CSSUnitValue object, return a new CSSUnitValue with the same unit internal slot as this, and a
- // value internal slot set to the negation of this’s.
- if (auto* unit_value = as_if<CSSUnitValue>(*this))
- return GC::Ref<CSSNumericValue> { CSSUnitValue::create(-unit_value->value(), unit_value->unit()) };
-
- // 3. Otherwise, return a new CSSMathNegate object whose value internal slot is set to this.
- return GC::Ref<CSSNumericValue> { CSSMathNegate::create_from_numberish(GC::Ref<CSSNumericValue> { *this }) };
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-mul
-WebIDL::ExceptionOr<GC::Ref<CSSNumericValue>> CSSNumericValue::mul(ReadonlySpan<CSSNumberish> initial_values)
-{
- // 1. Replace each item of values with the result of rectifying a numberish value for the item.
- // 2. If this is a CSSMathProduct object, prepend the items in this’s values internal slot to values.
- // Otherwise, prepend this to values.
-
- // NB: We reorder the steps a little to avoid the awkward prepending.
- GC::RootVector<GC::Ref<CSSNumericValue>> values;
- if (auto const* math_product = as_if<CSSMathProduct>(*this)) {
- auto items = math_product->values()->values();
- values.append(items.data(), items.size());
- } else {
- values.append(*this);
- }
-
- for (auto const& value : initial_values)
- values.append(rectify_a_numberish_value(value));
-
- // 3. If all of the items in values are CSSUnitValues with unit internal slot set to "number", return a new
- // CSSUnitValue whose unit internal slot is set to "number", and value internal slot is set to the product of the
- // value internal slots of the items in values.
- //
- // This multiplication must be done "left to right" - if values is « 1, 2, 3, 4 », the result must be (((1 × 2) × 3) × 4).
- // (This detail is necessary to ensure interoperability in the presence of floating-point arithmetic.)
- //
- // 4. If all of the items in values are CSSUnitValues with unit internal slot set to "number" except one which is
- // set to unit, return a new CSSUnitValue whose unit internal slot is set to unit, and value internal slot is set
- // to the product of the value internal slots of the items in values.
- //
- // This multiplication must be done "left to right" - if values is « 1, 2, 3, 4 », the result must be (((1 × 2) × 3) × 4).
- bool all_values_are_units = all_of(values, [](auto& value) {
- return is<CSSUnitValue>(*value);
- });
-
- if (all_values_are_units) {
- bool multiple_units_found = false;
- Optional<size_t> non_number_unit_index;
- for (size_t i = 0; i < values.size(); ++i) {
- auto unit = as<CSSUnitValue>(*values[i]).unit();
- if (unit == "number"_utf16_fly_string)
- continue;
- if (non_number_unit_index.has_value()) {
- multiple_units_found = true;
- break;
- }
- non_number_unit_index = i;
- }
- if (!multiple_units_found) {
- double product = 1;
- for (auto& value : values)
- product *= as<CSSUnitValue>(*value).value();
- auto unit = non_number_unit_index.has_value() ? as<CSSUnitValue>(*values[*non_number_unit_index]).unit() : "number"_utf16_fly_string;
- return CSSUnitValue::create(product, unit);
- }
- }
-
- // 5. Let type be the result of multiplying the types of every item in values. If type is failure, throw a TypeError.
- // 6. Return a new CSSMathProduct object whose values internal slot is set to values.
- return TRY(CSSMathProduct::multiply_all_types_into_math_product(values));
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-div
-WebIDL::ExceptionOr<GC::Ref<CSSNumericValue>> CSSNumericValue::div(ReadonlySpan<CSSNumberish> initial_values)
-{
- // 1. Replace each item of values with the result of rectifying a numberish value for the item, then inverting the value.
- GC::ConservativeVector<CSSNumberish> values;
- for (auto const& value : initial_values)
- values.append(TRY(rectify_a_numberish_value(value)->invert()));
-
- // 2. Return the result of calling the mul() internal algorithm with this and values.
- return mul(values);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssmath-invert-a-cssnumericvalue
-WebIDL::ExceptionOr<CSSNumberish> CSSNumericValue::invert()
-{
- // 1. If this is a CSSMathInvert object, return this’s value internal slot.
- if (auto* invert = as_if<CSSMathInvert>(*this))
- return CSSNumberish { GC::Ref<CSSNumericValue> { invert->value() } };
-
- // 2. If this is a CSSUnitValue object with unit internal slot set to "number":
- if (auto* unit_value = as_if<CSSUnitValue>(*this); unit_value && unit_value->unit() == "number"_utf16_fly_string) {
- // 1. If this’s value internal slot is set to 0 or -0, throw a RangeError.
- if (unit_value->value() == 0 || unit_value->value() == -0)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Zero has no multiplicative inverse"_utf16 };
-
- // 2. Else return a new CSSUnitValue with the unit internal slot set to "number", and a value internal slot set
- // to 1 divided by this’s {CSSUnitValue/value}} internal slot.
- return CSSNumberish { GC::Ref<CSSNumericValue> { CSSUnitValue::create(1.0 / unit_value->value(), "number"_utf16_fly_string) } };
- }
-
- // 3. Otherwise, return a new CSSMathInvert object whose value internal slot is set to this.
- return CSSNumberish { GC::Ref<CSSNumericValue> { CSSMathInvert::create_from_numberish(GC::Ref<CSSNumericValue> { *this }) } };
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-min
-WebIDL::ExceptionOr<GC::Ref<CSSNumericValue>> CSSNumericValue::min(ReadonlySpan<CSSNumberish> initial_values)
-{
- // 1. Replace each item of values with the result of rectifying a numberish value for the item.
- // 2. If this is a CSSMathMin object, prepend the items in this’s values internal slot to values.
- // Otherwise, prepend this to values.
-
- // NB: We reorder the steps a little to avoid the awkward prepending.
- GC::RootVector<GC::Ref<CSSNumericValue>> values;
- if (auto const* math_product = as_if<CSSMathMin>(*this)) {
- auto items = math_product->values()->values();
- values.append(items.data(), items.size());
- } else {
- values.append(*this);
- }
-
- for (auto const& value : initial_values)
- values.append(rectify_a_numberish_value(value));
-
- // 3. If all of the items in values are CSSUnitValues and have the same unit, return a new CSSUnitValue whose unit
- // internal slot is set to that unit, and value internal slot is set to the minimum of the value internal slots
- // of the items in values.
- if (all_values_are_css_unit_values_with_the_same_unit(values))
- return apply_math_operation_on_css_unit_values(values, [](double a, double b) { return AK::min(a, b); });
-
- // 4. Let type be the result of adding the types of every item in values. If type is failure, throw a TypeError.
- // 5. Return a new CSSMathMin object whose values internal slot is set to values.
- return TRY(CSSMathMin::add_all_types_into_math_min(values));
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-max
-WebIDL::ExceptionOr<GC::Ref<CSSNumericValue>> CSSNumericValue::max(ReadonlySpan<CSSNumberish> initial_values)
-{
- // 1. Replace each item of values with the result of rectifying a numberish value for the item.
- // 2. If this is a CSSMathMax object, prepend the items in this’s values internal slot to values.
- // Otherwise, prepend this to values.
-
- // NB: We reorder the steps a little to avoid the awkward prepending.
- GC::RootVector<GC::Ref<CSSNumericValue>> values;
- if (auto const* math_product = as_if<CSSMathMax>(*this)) {
- auto items = math_product->values()->values();
- values.append(items.data(), items.size());
- } else {
- values.append(*this);
- }
-
- for (auto const& value : initial_values)
- values.append(rectify_a_numberish_value(value));
-
- // 3. If all of the items in values are CSSUnitValues and have the same unit, return a new CSSUnitValue whose unit
- // internal slot is set to that unit, and value internal slot is set to the maximum of the value internal slots
- // of the items in values.
- if (all_values_are_css_unit_values_with_the_same_unit(values))
- return apply_math_operation_on_css_unit_values(values, [](double a, double b) { return AK::max(a, b); });
-
- // 4. Let type be the result of adding the types of every item in values. If type is failure, throw a TypeError.
- // 5. Return a new CSSMathMax object whose values internal slot is set to values.
- return TRY(CSSMathMax::add_all_types_into_math_max(values));
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-equals
-bool CSSNumericValue::equals_for_bindings(ReadonlySpan<CSSNumberish> values) const
-{
- // The equals(...values) method, when called on a CSSNumericValue this, must perform the following steps:
-
- // 1. Replace each item of values with the result of rectifying a numberish value for the item.
- // 2. For each item in values, if the item is not an equal numeric value to this, return false.
- for (auto const& value : values) {
- auto rectified_value = rectify_a_numberish_value(value);
- if (!is_equal_numeric_value(rectified_value))
- return false;
- }
-
- // 3. Return true.
- return true;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-to
-WebIDL::ExceptionOr<GC::Ref<CSSUnitValue>> CSSNumericValue::to(Utf16String const& unit) const
-{
- return to(Utf16FlyString { unit });
-}
-
-WebIDL::ExceptionOr<GC::Ref<CSSUnitValue>> CSSNumericValue::to(Utf16FlyString const& unit) const
-{
- // The to(unit) method converts an existing CSSNumericValue this into another one with the specified unit, if
- // possible. When called, it must perform the following steps:
-
- // 1. Let type be the result of creating a type from unit. If type is failure, throw a SyntaxError.
- auto maybe_type = NumericType::create_from_unit(unit);
- if (!maybe_type.has_value())
- return WebIDL::SyntaxError::create(Utf16String::formatted("Unrecognized unit '{}'", unit));
-
- // 2. Let sum be the result of creating a sum value from this. If sum is failure, throw a TypeError.
- auto sum = create_a_sum_value();
- if (!sum.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Unable to create a sum from input '{}'", MUST(to_string())) };
-
- // 3. If sum has more than one item, throw a TypeError.
- // Otherwise, let item be the result of creating a CSSUnitValue from the sole item in sum, then converting it to
- // unit. If item is failure, throw a TypeError.
- if (sum->size() > 1)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Sum contains more than one item"_utf16 };
- auto item = CSSUnitValue::create_from_sum_value_item(sum->first());
- if (!item)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Unable to create CSSUnitValue from input '{}'", MUST(to_string())) };
-
- auto converted_item = item->converted_to_unit(unit);
- if (!converted_item)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Unable to convert input to requested unit"_utf16 };
-
- // 4. Return item.
- return converted_item.as_nonnull();
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssnumericvalue
-void CSSNumericValue::serialize(Utf16StringBuilder& builder, SerializationParams const& params) const
-{
- // To serialize a CSSNumericValue this, given an optional minimum, a numeric value, and optional maximum, a numeric value:
- // 1. If this is a CSSUnitValue, serialize a CSSUnitValue from this, passing minimum and maximum. Return the result.
- if (auto* unit_value = as_if<CSSUnitValue>(this)) {
- unit_value->serialize_unit_value(builder, params.minimum, params.maximum);
- return;
- }
- // 2. Otherwise, serialize a CSSMathValue from this, and return the result.
- auto& math_value = as<CSSMathValue>(*this);
- math_value.serialize_math_value(builder,
- params.nested ? CSSMathValue::Nested::Yes : CSSMathValue::Nested::No,
- params.parenless ? CSSMathValue::Parens::Without : CSSMathValue::Parens::With);
-}
-
-Utf16String CSSNumericValue::to_string(SerializationParams const& params) const
-{
- Utf16StringBuilder builder;
- serialize(builder, params);
- return builder.to_string();
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#rectify-a-numberish-value
-GC::Ref<CSSNumericValue> rectify_a_numberish_value(CSSNumberish const& numberish, Optional<Utf16FlyString> unit)
-{
- return numberish.visit(
- [](GC::Ref<CSSNumericValue> num) -> GC::Ref<CSSNumericValue> { return num; },
- [&unit](double num) -> GC::Ref<CSSNumericValue> {
- return CSSUnitValue::create(num, unit.value_or("number"_utf16_fly_string));
- });
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#reify-a-numeric-value
-static WebIDL::ExceptionOr<GC::Ref<CSSNumericValue>> reify_a_numeric_value(StyleValue const& numeric_value)
-{
- if (numeric_value.is_calculated()) {
- auto reified = numeric_value.as_calculated().reify({});
- if (auto* reified_numeric = as_if<CSSNumericValue>(*reified))
- return GC::Ref { *reified_numeric };
- return WebIDL::SyntaxError::create("Unable to reify this math function."_utf16);
- }
- if (numeric_value.is_number())
- return CSSUnitValue::create(numeric_value.as_number().number(), "number"_utf16_fly_string);
- VERIFY(numeric_value.is_dimension());
- return CSSUnitValue::create(numeric_value.as_dimension().raw_value(), numeric_value.as_dimension().unit_name());
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-parse
-WebIDL::ExceptionOr<GC::Ref<CSSNumericValue>> CSSNumericValue::parse(JS::VM& vm, Utf16View css_text)
-{
- (void)vm;
- // The parse(cssText) method, when called, must perform the following steps:
-
- for (auto value_type : { ValueType::Number, ValueType::Percentage, ValueType::Length, ValueType::LengthPercentage, ValueType::Angle, ValueType::Time, ValueType::Frequency, ValueType::Resolution, ValueType::Flex }) {
- auto value = parse_css_type(Parser::ParsingParams {}, css_text, value_type);
- if (value)
- return reify_a_numeric_value(*value);
- }
- return WebIDL::SyntaxError::create("Input is not a numeric component value."_utf16);
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSNumericValue.h b/Libraries/LibWeb/CSS/CSSNumericValue.h
index 16e89ed504c..47e094e0d0f 100644
--- a/Libraries/LibWeb/CSS/CSSNumericValue.h
+++ b/Libraries/LibWeb/CSS/CSSNumericValue.h
@@ -6,81 +6,29 @@
#pragma once
-#include <AK/Utf16FlyString.h>
#include <AK/Utf16String.h>
-#include <AK/Utf16StringBuilder.h>
-#include <AK/Utf16View.h>
#include <LibWeb/Bindings/CSSNumericValue.h>
#include <LibWeb/CSS/CSSStyleValue.h>
#include <LibWeb/CSS/NumericType.h>
#include <LibWeb/CSS/StyleValues/CalcNodeRef.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::Bindings {
-
-struct CSSNumericType;
-
-}
namespace Web::CSS {
-// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue-sum-value
-struct SumValueItem {
- double value;
- UnitMap unit_map;
-};
-using SumValue = Vector<SumValueItem>;
-
// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue
-class CSSNumericValue : public CSSStyleValue {
- WEB_WRAPPABLE(CSSNumericValue, CSSStyleValue);
- GC_DECLARE_ALLOCATOR(CSSNumericValue);
+class WEB_API CSSNumericValue : public CSSStyleValue {
+ WEB_RUST_INTERFACE(CSSNumericValue, css_numeric_value)
public:
- struct SerializationParams {
- Optional<double> minimum {};
- Optional<double> maximum {};
- bool nested { false };
- bool parenless { false };
- };
- virtual ~CSSNumericValue() override = default;
-
- WebIDL::ExceptionOr<GC::Ref<CSSNumericValue>> add(ReadonlySpan<CSSNumberish>);
- WebIDL::ExceptionOr<GC::Ref<CSSNumericValue>> sub(ReadonlySpan<CSSNumberish>);
- WebIDL::ExceptionOr<GC::Ref<CSSNumericValue>> mul(ReadonlySpan<CSSNumberish>);
- WebIDL::ExceptionOr<GC::Ref<CSSNumericValue>> div(ReadonlySpan<CSSNumberish>);
- WebIDL::ExceptionOr<GC::Ref<CSSNumericValue>> min(ReadonlySpan<CSSNumberish>);
- WebIDL::ExceptionOr<GC::Ref<CSSNumericValue>> max(ReadonlySpan<CSSNumberish>);
-
- bool equals_for_bindings(ReadonlySpan<CSSNumberish>) const;
- virtual bool is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const = 0;
+ // A new CSSMathSum of the values, whose types can be added.
+ static GC::Ref<CSSNumericValue> create_sum(GC::Ref<CSSNumericValue>, GC::Ref<CSSNumericValue>);
- WebIDL::ExceptionOr<GC::Ref<CSSUnitValue>> to(Utf16String const& unit) const;
- WebIDL::ExceptionOr<GC::Ref<CSSUnitValue>> to(Utf16FlyString const& unit) const;
+ // https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue-type
+ NumericType type() const;
- CSSNumberish negate();
- WebIDL::ExceptionOr<CSSNumberish> invert();
+ // https://drafts.css-houdini.org/css-typed-om-1/#numeric-value-serialization
+ Utf16String to_string() const;
- virtual Optional<SumValue> create_a_sum_value() const = 0;
-
- Bindings::CSSNumericType type_for_bindings() const;
- NumericType const& type() const { return m_type; }
-
- virtual WebIDL::ExceptionOr<Utf16String> to_string() const final override { return to_string({}); }
- void serialize(Utf16StringBuilder&, SerializationParams const&) const;
- Utf16String to_string(SerializationParams const&) const;
-
- static WebIDL::ExceptionOr<GC::Ref<CSSNumericValue>> parse(JS::VM&, Utf16View css_text);
-
- virtual WebIDL::ExceptionOr<CalcNodeRef> create_calculation_node(CalculationContext const&) const = 0;
-
-protected:
- explicit CSSNumericValue(NumericType);
-
- NumericType m_type;
+ Optional<CalcNodeRef> create_calculation_node() const;
};
-GC::Ref<CSSNumericValue> rectify_a_numberish_value(CSSNumberish const&, Optional<Utf16FlyString> unit = {});
-
}
diff --git a/Libraries/LibWeb/CSS/CSSNumericValue.idl b/Libraries/LibWeb/CSS/CSSNumericValue.idl
index 91376a5d406..2586f2c9f10 100644
--- a/Libraries/LibWeb/CSS/CSSNumericValue.idl
+++ b/Libraries/LibWeb/CSS/CSSNumericValue.idl
@@ -22,7 +22,7 @@ dictionary CSSNumericType {
};
// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSNumericValue : CSSStyleValue {
CSSNumericValue add(CSSNumberish... values);
CSSNumericValue sub(CSSNumberish... values);
diff --git a/Libraries/LibWeb/CSS/CSSPerspective.cpp b/Libraries/LibWeb/CSS/CSSPerspective.cpp
deleted file mode 100644
index 64bf470695b..00000000000
--- a/Libraries/LibWeb/CSS/CSSPerspective.cpp
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSPerspective.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSNumericValue.h>
-#include <LibWeb/CSS/CSSUnitValue.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
-#include <LibWeb/Geometry/DOMMatrix.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSPerspective);
-
-static WebIDL::ExceptionOr<CSSPerspectiveValueInternal> to_internal(CSSPerspectiveValue const& value)
-{
- // Steps 1 and 2 of The CSSPerspective(length) constructor:
- // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssperspective-cssperspective
- return value.visit(
- // 1. If length is a CSSNumericValue:
- [](GC::Ref<CSSNumericValue> const& numeric_value) -> WebIDL::ExceptionOr<CSSPerspectiveValueInternal> {
- // 1. If length does not match <length>, throw a TypeError.
- if (!numeric_value->type().matches_length({})) {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSPerspective length component doesn't match <length>"_utf16 };
- }
- return { GC::Ref { *numeric_value } };
- },
- // 2. Otherwise (that is, if length is not a CSSNumericValue):
- [](CSSKeywordish const& keywordish) -> WebIDL::ExceptionOr<CSSPerspectiveValueInternal> {
- // 1. Rectify a keywordish value from length, then set length to the result’s value.
- auto rectified_length = rectify_a_keywordish_value(keywordish);
-
- // 2. If length does not represent a value that is an ASCII case-insensitive match for the keyword none,
- // throw a TypeError.
- if (!rectified_length->value().equals_ignoring_ascii_case("none"_fly_string)) {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSPerspective length component is a keyword other than `none`"_utf16 };
- }
-
- return { rectified_length };
- });
-}
-
-GC::Ref<CSSPerspective> CSSPerspective::create(CSSPerspectiveValueInternal length)
-{
- return GC::Heap::the().allocate<CSSPerspective>(length);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssperspective-cssperspective
-WebIDL::ExceptionOr<GC::Ref<CSSPerspective>> CSSPerspective::create_for_constructor(CSSPerspectiveValue length)
-{
- // The CSSPerspective(length) constructor must, when invoked, perform the following steps:
- // NB: Steps 1 and 2 are implemented in to_internal().
- auto internal_length = TRY(to_internal(length));
-
- // 3. Return a new CSSPerspective object with its length internal slot set to length, and its is2D internal slot
- // set to false.
- return CSSPerspective::create(internal_length);
-}
-
-CSSPerspective::CSSPerspective(CSSPerspectiveValueInternal length)
- : CSSTransformComponent(Is2D::No)
- , m_length(length)
-{
-}
-
-CSSPerspective::~CSSPerspective() = default;
-
-void CSSPerspective::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_length);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssperspective
-WebIDL::ExceptionOr<Utf16String> CSSPerspective::to_string() const
-{
- // 1. Let s initially be "perspective(".
- Utf16StringBuilder builder;
- builder.append_ascii("perspective("sv);
-
- // 2. Serialize this’s length internal slot, with a minimum of 0px, and append it to s.
- TRY(m_length.visit(
- [&](GC::Ref<CSSNumericValue> const& numeric_value) -> WebIDL::ExceptionOr<void> {
- numeric_value->serialize(builder, { .minimum = 0 });
- return {};
- },
- [&](GC::Ref<CSSKeywordValue> const& keyword_value) -> WebIDL::ExceptionOr<void> {
- builder.append(TRY(keyword_value->to_string()));
- return {};
- }));
-
- // 3. Append ")" to s, and return s.
- builder.append_ascii(')');
- return builder.to_string();
-}
-
-WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSPerspective::to_matrix() const
-{
- // 1. Let matrix be a new DOMMatrix object, initialized to this’s equivalent 4x4 transform matrix, as defined in
- // CSS Transforms 1 § 12. Mathematical Description of Transform Functions, and with its is2D internal slot set
- // to the same value as this’s is2D internal slot.
- // NOTE: Recall that the is2D flag affects what transform, and thus what equivalent matrix, a
- // CSSTransformComponent represents.
- // As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in
- // generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a
- // TypeError.
- auto matrix = Gfx::DoubleMatrix4x4::identity();
-
- TRY(m_length.visit(
- [&matrix](GC::Ref<CSSNumericValue> const& numeric_value) -> WebIDL::ExceptionOr<void> {
- // NB: to() throws a TypeError if the conversion can't be done.
- auto distance = TRY(numeric_value->to("px"_utf16_fly_string))->value();
- // NB: Gfx::Matrix4x4 is row by row, so the element m34 is in the fourth row and the third column.
- matrix[3, 2] = -1 / max(distance, 1);
- return {};
- },
- [](GC::Ref<CSSKeywordValue> const&) -> WebIDL::ExceptionOr<void> {
- // NB: This is `none`, so do nothing.
- return {};
- }));
-
- return Geometry::DOMMatrix::create(matrix, is_2d());
-}
-
-CSSPerspectiveValue CSSPerspective::length() const
-{
- return m_length;
-}
-
-WebIDL::ExceptionOr<void> CSSPerspective::set_length(CSSPerspectiveValue value)
-{
- // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
- // WPT expects this to throw for invalid values, so just reuse the constructor code.
- auto length = TRY(to_internal(value));
- m_length = length;
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssperspective-is2d
-void CSSPerspective::set_is_2d(bool)
-{
- // The is2D attribute of a CSSPerspective object must, on setting, do nothing.
-}
-
-WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> CSSPerspective::create_style_value(PropertyNameAndID const& property) const
-{
- auto length = TRY(m_length.visit([&](auto const& value) {
- return value->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No);
- }));
- return TransformationStyleValue::create(property.id(), TransformFunction::Perspective, { move(length) });
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSPerspective.h b/Libraries/LibWeb/CSS/CSSPerspective.h
deleted file mode 100644
index adb241da44e..00000000000
--- a/Libraries/LibWeb/CSS/CSSPerspective.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSKeywordValue.h>
-#include <LibWeb/CSS/CSSNumericValue.h>
-#include <LibWeb/CSS/CSSTransformComponent.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#typedefdef-cssperspectivevalue
-// NB: CSSKeywordish is flattened here, because our bindings generator flattens nested variants.
-using CSSPerspectiveValue = Variant<GC::Ref<CSSNumericValue>, Utf16String, GC::Ref<CSSKeywordValue>>;
-using CSSPerspectiveValueInternal = Variant<GC::Ref<CSSNumericValue>, GC::Ref<CSSKeywordValue>>;
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssperspective
-class CSSPerspective final : public CSSTransformComponent {
- WEB_WRAPPABLE(CSSPerspective, CSSTransformComponent);
- GC_DECLARE_ALLOCATOR(CSSPerspective);
-
-public:
- [[nodiscard]] static GC::Ref<CSSPerspective> create(CSSPerspectiveValueInternal);
- static WebIDL::ExceptionOr<GC::Ref<CSSPerspective>> create_for_constructor(CSSPerspectiveValue);
-
- virtual ~CSSPerspective() override;
-
- virtual WebIDL::ExceptionOr<Utf16String> to_string() const override;
-
- virtual WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> to_matrix() const override;
-
- CSSPerspectiveValue length() const;
- WebIDL::ExceptionOr<void> set_length(CSSPerspectiveValue value);
-
- virtual void set_is_2d(bool value) override;
-
- virtual WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> create_style_value(PropertyNameAndID const&) const override;
-
-private:
- explicit CSSPerspective(CSSPerspectiveValueInternal);
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- CSSPerspectiveValueInternal m_length;
-};
-
-}
-
-class CSSPerspective {
-};
diff --git a/Libraries/LibWeb/CSS/CSSPerspective.idl b/Libraries/LibWeb/CSS/CSSPerspective.idl
index 0c162a540ff..f012b857771 100644
--- a/Libraries/LibWeb/CSS/CSSPerspective.idl
+++ b/Libraries/LibWeb/CSS/CSSPerspective.idl
@@ -1,7 +1,7 @@
typedef (CSSNumericValue or CSSKeywordish) CSSPerspectiveValue;
// https://drafts.css-houdini.org/css-typed-om-1/#cssperspective
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSPerspective : CSSTransformComponent {
constructor(CSSPerspectiveValue length);
attribute CSSPerspectiveValue length;
diff --git a/Libraries/LibWeb/CSS/CSSRotate.cpp b/Libraries/LibWeb/CSS/CSSRotate.cpp
deleted file mode 100644
index b3ed60a06aa..00000000000
--- a/Libraries/LibWeb/CSS/CSSRotate.cpp
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSRotate.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSUnitValue.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
-#include <LibWeb/Geometry/DOMMatrix.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSRotate);
-
-GC::Ref<CSSRotate> CSSRotate::create(Is2D is_2d, GC::Ref<CSSNumericValue> x, GC::Ref<CSSNumericValue> y, GC::Ref<CSSNumericValue> z, GC::Ref<CSSNumericValue> angle)
-{
- return GC::Heap::the().allocate<CSSRotate>(is_2d, x, y, z, angle);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssrotate-cssrotate
-WebIDL::ExceptionOr<GC::Ref<CSSRotate>> CSSRotate::create_for_constructor(GC::Ref<CSSNumericValue> angle)
-{
- // The CSSRotate(angle) constructor must, when invoked, perform the following steps:
-
- // 1. If angle doesn’t match <angle>, throw a TypeError.
- if (!angle->type().matches_angle({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSRotate angle component doesn't match <angle>"_utf16 };
-
- // 2. Return a new CSSRotate with its angle internal slot set to angle, its x and y internal slots set to new unit
- // values of (0, "number"), its z internal slot set to a new unit value of (1, "number"), and its is2D internal
- // slot set to true.
- return CSSRotate::create(Is2D::Yes,
- CSSUnitValue::create(0, "number"_utf16_fly_string),
- CSSUnitValue::create(0, "number"_utf16_fly_string),
- CSSUnitValue::create(1, "number"_utf16_fly_string),
- angle);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssrotate-cssrotate-x-y-z-anglec
-WebIDL::ExceptionOr<GC::Ref<CSSRotate>> CSSRotate::create_for_constructor(CSSNumberish x, CSSNumberish y, CSSNumberish z, GC::Ref<CSSNumericValue> angle)
-{
- // The CSSRotate(x, y, z, angle) constructor must, when invoked, perform the following steps:
-
- // 1. If angle doesn’t match <angle>, throw a TypeError.
- if (!angle->type().matches_angle({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSRotate angle component doesn't match <angle>"_utf16 };
-
- // 2. Let x, y, and z be replaced by the result of rectifying a numberish value.
- auto rectified_x = rectify_a_numberish_value(x);
- auto rectified_y = rectify_a_numberish_value(y);
- auto rectified_z = rectify_a_numberish_value(z);
-
- // 3. If x, y, or z don’t match <number>, throw a TypeError.
- if (!rectified_x->type().matches_number({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSRotate x component doesn't match <number>"_utf16 };
- if (!rectified_y->type().matches_number({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSRotate y component doesn't match <number>"_utf16 };
- if (!rectified_z->type().matches_number({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSRotate z component doesn't match <number>"_utf16 };
-
- // 4. Return a new CSSRotate with its angle internal slot set to angle, its x, y, z internal slots set to x, y, and
- // z, and its is2D internal slot set to false.
- return CSSRotate::create(Is2D::No, rectified_x, rectified_y, rectified_z, angle);
-}
-
-CSSRotate::CSSRotate(Is2D is_2d, GC::Ref<CSSNumericValue> x, GC::Ref<CSSNumericValue> y, GC::Ref<CSSNumericValue> z, GC::Ref<CSSNumericValue> angle)
- : CSSTransformComponent(is_2d)
- , m_x(x)
- , m_y(y)
- , m_z(z)
- , m_angle(angle)
-{
-}
-
-CSSRotate::~CSSRotate() = default;
-
-void CSSRotate::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_x);
- visitor.visit(m_y);
- visitor.visit(m_z);
- visitor.visit(m_angle);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssrotate
-WebIDL::ExceptionOr<Utf16String> CSSRotate::to_string() const
-{
- // 1. Let s initially be the empty string.
- Utf16StringBuilder builder;
-
- // 2. If this’s is2D internal slot is false:
- if (!is_2d()) {
- // 1. Append "rotate3d(" to s.
- builder.append_ascii("rotate3d("sv);
-
- // 2. Serialize this’s x internal slot, and append it to s.
- m_x->serialize(builder, {});
-
- // 3. Append ", " to s.
- builder.append_ascii(", "sv);
-
- // 4. Serialize this’s y internal slot, and append it to s.
- m_y->serialize(builder, {});
-
- // 5. Append ", " to s.
- builder.append_ascii(", "sv);
-
- // 6. Serialize this’s z internal slot, and append it to s.
- m_z->serialize(builder, {});
-
- // 7. Append "," to s.
- builder.append_ascii(", "sv);
-
- // 8. Serialize this’s angle internal slot, and append it to s.
- m_angle->serialize(builder, {});
-
- // 9. Append ")" to s, and return s.
- builder.append_ascii(')');
- return builder.to_string();
- }
- // 2. Otherwise:
- else {
- // 1. Append "rotate(" to s.
- builder.append_ascii("rotate("sv);
-
- // 2. Serialize this’s angle internal slot, and append it to s.
- m_angle->serialize(builder, {});
-
- // 3. Append ")" to s, and return s.
- builder.append_ascii(')');
- return builder.to_string();
- }
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformcomponent-tomatrix
-WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSRotate::to_matrix() const
-{
- // 1. Let matrix be a new DOMMatrix object, initialized to this’s equivalent 4x4 transform matrix, as defined in
- // CSS Transforms 1 § 12. Mathematical Description of Transform Functions, and with its is2D internal slot set
- // to the same value as this’s is2D internal slot.
- // NOTE: Recall that the is2D flag affects what transform, and thus what equivalent matrix, a
- // CSSTransformComponent represents.
- // As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in
- // generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a
- // TypeError.
- // 2. Return matrix.
-
- auto matrix = Geometry::DOMMatrix::create(Gfx::DoubleMatrix4x4::identity(), is_2d());
-
- // NB: to() throws a TypeError if the conversion can't be done.
- auto angle = TRY(m_angle->to("deg"_utf16_fly_string))->value();
-
- if (is_2d()) {
- matrix->rotate_axis_angle_self(0, 0, 1, angle);
- return matrix;
- }
-
- auto x = TRY(m_x->to("number"_utf16_fly_string))->value();
- auto y = TRY(m_y->to("number"_utf16_fly_string))->value();
- auto z = TRY(m_z->to("number"_utf16_fly_string))->value();
-
- matrix->rotate_axis_angle_self(x, y, z, angle);
- return matrix;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssrotate-x
-WebIDL::ExceptionOr<void> CSSRotate::set_x(CSSNumberish value)
-{
- // The x, y, and z attributes must, on setting to a new value val, rectify a numberish value from val and set the
- // corresponding internal slot to the result of that.
- // AD-HOC: WPT expects this to throw for invalid values. https://github.com/w3c/css-houdini-drafts/issues/1153
- auto rectified_x = rectify_a_numberish_value(value);
- if (!rectified_x->type().matches_number({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSRotate x component doesn't match <number>"_utf16 };
- m_x = rectified_x;
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssrotate-y
-WebIDL::ExceptionOr<void> CSSRotate::set_y(CSSNumberish value)
-{
- // The x, y, and z attributes must, on setting to a new value val, rectify a numberish value from val and set the
- // corresponding internal slot to the result of that.
- // AD-HOC: WPT expects this to throw for invalid values. https://github.com/w3c/css-houdini-drafts/issues/1153
- auto rectified_y = rectify_a_numberish_value(value);
- if (!rectified_y->type().matches_number({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSRotate y component doesn't match <number>"_utf16 };
- m_y = rectified_y;
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssrotate-z
-WebIDL::ExceptionOr<void> CSSRotate::set_z(CSSNumberish value)
-{
- // The x, y, and z attributes must, on setting to a new value val, rectify a numberish value from val and set the
- // corresponding internal slot to the result of that.
- // AD-HOC: WPT expects this to throw for invalid values. https://github.com/w3c/css-houdini-drafts/issues/1153
- auto rectified_z = rectify_a_numberish_value(value);
- if (!rectified_z->type().matches_number({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSRotate z component doesn't match <number>"_utf16 };
- m_z = rectified_z;
- return {};
-}
-
-WebIDL::ExceptionOr<void> CSSRotate::set_angle(GC::Ref<CSSNumericValue> value)
-{
- // AD-HOC: Not specced. WPT expects this to throw for invalid values. https://github.com/w3c/css-houdini-drafts/issues/1153
- if (!value->type().matches_angle({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSRotate angle component doesn't match <angle>"_utf16 };
- m_angle = value;
- return {};
-}
-
-WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> CSSRotate::create_style_value(PropertyNameAndID const& property) const
-{
- if (is_2d()) {
- return TransformationStyleValue::create(property.id(), TransformFunction::Rotate,
- {
- TRY(m_angle->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- });
- }
-
- return TransformationStyleValue::create(property.id(), TransformFunction::Rotate3d,
- {
- TRY(m_x->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- TRY(m_y->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- TRY(m_z->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- TRY(m_angle->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- });
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSRotate.h b/Libraries/LibWeb/CSS/CSSRotate.h
deleted file mode 100644
index fdc46a4b396..00000000000
--- a/Libraries/LibWeb/CSS/CSSRotate.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSNumericValue.h>
-#include <LibWeb/CSS/CSSTransformComponent.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssrotate
-class CSSRotate final : public CSSTransformComponent {
- WEB_WRAPPABLE(CSSRotate, CSSTransformComponent);
- GC_DECLARE_ALLOCATOR(CSSRotate);
-
-public:
- static constexpr size_t angle_offset() { return offsetof(CSSRotate, m_angle); }
- [[nodiscard]] static GC::Ref<CSSRotate> create(Is2D, GC::Ref<CSSNumericValue> x, GC::Ref<CSSNumericValue> y, GC::Ref<CSSNumericValue> z, GC::Ref<CSSNumericValue> angle);
- static WebIDL::ExceptionOr<GC::Ref<CSSRotate>> create_for_constructor(GC::Ref<CSSNumericValue> angle);
- static WebIDL::ExceptionOr<GC::Ref<CSSRotate>> create_for_constructor(CSSNumberish x, CSSNumberish y, CSSNumberish z, GC::Ref<CSSNumericValue> angle);
-
- virtual ~CSSRotate() override;
-
- virtual WebIDL::ExceptionOr<Utf16String> to_string() const override;
-
- virtual WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> to_matrix() const override;
-
- CSSNumberish x() const { return m_x; }
- CSSNumberish y() const { return m_y; }
- CSSNumberish z() const { return m_z; }
- GC::Ref<CSSNumericValue> angle() const { return m_angle; }
- WebIDL::ExceptionOr<void> set_x(CSSNumberish value);
- WebIDL::ExceptionOr<void> set_y(CSSNumberish value);
- WebIDL::ExceptionOr<void> set_z(CSSNumberish value);
- WebIDL::ExceptionOr<void> set_angle(GC::Ref<CSSNumericValue> value);
-
- virtual WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> create_style_value(PropertyNameAndID const&) const override;
-
-private:
- explicit CSSRotate(Is2D, GC::Ref<CSSNumericValue> x, GC::Ref<CSSNumericValue> y, GC::Ref<CSSNumericValue> z, GC::Ref<CSSNumericValue> angle);
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<CSSNumericValue> m_x;
- GC::Ref<CSSNumericValue> m_y;
- GC::Ref<CSSNumericValue> m_z;
- GC::Ref<CSSNumericValue> m_angle;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSRotate.idl b/Libraries/LibWeb/CSS/CSSRotate.idl
index 496ab2941ae..f2a257d0879 100644
--- a/Libraries/LibWeb/CSS/CSSRotate.idl
+++ b/Libraries/LibWeb/CSS/CSSRotate.idl
@@ -1,10 +1,10 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssrotate
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSRotate : CSSTransformComponent {
- constructor(CSSNumericValue angle);
- constructor(CSSNumberish x, CSSNumberish y, CSSNumberish z, CSSNumericValue angle);
+ [ImplementedAs=construct_from_angle] constructor(CSSNumericValue angle);
+ [ImplementedAs=construct_from_axis] constructor(CSSNumberish x, CSSNumberish y, CSSNumberish z, CSSNumericValue angle);
attribute CSSNumberish x;
attribute CSSNumberish y;
attribute CSSNumberish z;
- [DirectGetter] attribute CSSNumericValue angle;
+ attribute CSSNumericValue angle;
};
diff --git a/Libraries/LibWeb/CSS/CSSScale.cpp b/Libraries/LibWeb/CSS/CSSScale.cpp
deleted file mode 100644
index a8ea7765d59..00000000000
--- a/Libraries/LibWeb/CSS/CSSScale.cpp
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSScale.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSNumericValue.h>
-#include <LibWeb/CSS/CSSUnitValue.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
-#include <LibWeb/Geometry/DOMMatrix.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSScale);
-
-GC::Ref<CSSScale> CSSScale::create(Is2D is_2d, GC::Ref<CSSNumericValue> x, GC::Ref<CSSNumericValue> y, GC::Ref<CSSNumericValue> z)
-{
- return GC::Heap::the().allocate<CSSScale>(is_2d, x, y, z);
-}
-
-WebIDL::ExceptionOr<GC::Ref<CSSScale>> CSSScale::create_for_constructor(CSSNumberish x, CSSNumberish y, Optional<CSSNumberish> z)
-{
- // The CSSScale(x, y, z) constructor must, when invoked, perform the following steps:
-
- // 1. Let x, y, and z (if passed) be replaced by the result of rectifying a numberish value.
- auto rectified_x = rectify_a_numberish_value(x);
- auto rectified_y = rectify_a_numberish_value(y);
- auto rectified_z = z.map([](auto& it) { return rectify_a_numberish_value(it); });
-
- // 2. If x, y, or z (if passed) don’t match <number>, throw a TypeError.
- if (!rectified_x->type().matches_number({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSScale x component doesn't match <number>"_utf16 };
- if (!rectified_y->type().matches_number({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSScale y component doesn't match <number>"_utf16 };
- if (rectified_z.has_value() && !rectified_z.value()->type().matches_number({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSScale z component doesn't match <number>"_utf16 };
-
- // 3. Let this be a new CSSScale object, with its x and y internal slots set to x and y.
- // 4. If z was passed, set this’s z internal slot to z, and set this’s is2D internal slot to false.
- // 5. If z was not passed, set this’s z internal slot to a new unit value of (1, "number"), and set this’s is2D internal slot to true.
- Is2D is_2d = Is2D::No;
- if (!rectified_z.has_value()) {
- rectified_z = CSSUnitValue::create(1, "number"_utf16_fly_string);
- is_2d = Is2D::Yes;
- }
- auto this_ = CSSScale::create(is_2d, rectified_x, rectified_y, rectified_z.release_value());
-
- // 6. Return this.
- return this_;
-}
-
-CSSScale::CSSScale(Is2D is_2d, GC::Ref<CSSNumericValue> x, GC::Ref<CSSNumericValue> y, GC::Ref<CSSNumericValue> z)
- : CSSTransformComponent(is_2d)
- , m_x(x)
- , m_y(y)
- , m_z(z)
-{
-}
-
-CSSScale::~CSSScale() = default;
-
-void CSSScale::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_x);
- visitor.visit(m_y);
- visitor.visit(m_z);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssscale
-WebIDL::ExceptionOr<Utf16String> CSSScale::to_string() const
-{
- // 1. Let s initially be the empty string.
- Utf16StringBuilder builder;
-
- // 2. If this’s is2D internal slot is false:
- if (!is_2d()) {
-
- // 1. Append "scale3d(" to s.
- builder.append_ascii("scale3d("sv);
-
- // 2. Serialize this’s x internal slot, and append it to s.
- m_x->serialize(builder, {});
-
- // 3. Append ", " to s.
- builder.append_ascii(", "sv);
-
- // 4. Serialize this’s y internal slot, and append it to s.
- m_y->serialize(builder, {});
-
- // 5. Append ", " to s.
- builder.append_ascii(", "sv);
-
- // 6. Serialize this’s z internal slot, and append it to s.
- m_z->serialize(builder, {});
-
- // 7. Append ")" to s, and return s.
- builder.append_ascii(')');
- return builder.to_string();
- }
-
- // 3. Otherwise:
- else {
- // 1. Append "scale(" to s.
- builder.append_ascii("scale("sv);
-
- // 2. Serialize this’s x internal slot, and append it to s.
- m_x->serialize(builder, {});
-
- // 3. If this’s x and y internal slots are equal numeric values, append ")" to s and return s.
- // AD-HOC: Don't do this - neither Chrome nor Safari show this behavior.
- // Upstream issue: https://github.com/w3c/css-houdini-drafts/issues/1161
-
- // 4. Otherwise, append ", " to s.
- builder.append_ascii(", "sv);
-
- // 5. Serialize this’s y internal slot, and append it to s.
- m_y->serialize(builder, {});
-
- // 6. Append ")" to s, and return s.
- builder.append_ascii(')');
- return builder.to_string();
- }
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformcomponent-tomatrix
-WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSScale::to_matrix() const
-{
- // 1. Let matrix be a new DOMMatrix object, initialized to this’s equivalent 4x4 transform matrix, as defined in
- // CSS Transforms 1 § 12. Mathematical Description of Transform Functions, and with its is2D internal slot set
- // to the same value as this’s is2D internal slot.
- // NOTE: Recall that the is2D flag affects what transform, and thus what equivalent matrix, a
- // CSSTransformComponent represents.
- // As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in
- // generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a
- // TypeError.
- // 2. Return matrix.
-
- // NB: to() throws a TypeError if the conversion can't be done.
- auto x = TRY(m_x->to("number"_utf16_fly_string))->value();
- auto y = TRY(m_y->to("number"_utf16_fly_string))->value();
-
- double z = 1;
- if (!is_2d())
- z = TRY(m_z->to("number"_utf16_fly_string))->value();
-
- return Geometry::DOMMatrix::create(Gfx::scale_matrix(Vector3<double> { x, y, z }), is_2d());
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssscale-x
-WebIDL::ExceptionOr<void> CSSScale::set_x(CSSNumberish value)
-{
- // The x, y, and z attributes must, on setting to a new value val, rectify a numberish value from val and set the
- // corresponding internal slot to the result of that.
- // AD-HOC: WPT expects this to throw for invalid values. https://github.com/w3c/css-houdini-drafts/issues/1153
- auto rectified_x = rectify_a_numberish_value(value);
- if (!rectified_x->type().matches_number({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSScale x component doesn't match <number>"_utf16 };
- m_x = rectified_x;
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssscale-y
-WebIDL::ExceptionOr<void> CSSScale::set_y(CSSNumberish value)
-{
- // The x, y, and z attributes must, on setting to a new value val, rectify a numberish value from val and set the
- // corresponding internal slot to the result of that.
- // AD-HOC: WPT expects this to throw for invalid values. https://github.com/w3c/css-houdini-drafts/issues/1153
- auto rectified_y = rectify_a_numberish_value(value);
- if (!rectified_y->type().matches_number({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSScale y component doesn't match <number>"_utf16 };
- m_y = rectified_y;
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssscale-z
-WebIDL::ExceptionOr<void> CSSScale::set_z(CSSNumberish value)
-{
- // The x, y, and z attributes must, on setting to a new value val, rectify a numberish value from val and set the
- // corresponding internal slot to the result of that.
- // AD-HOC: WPT expects this to throw for invalid values. https://github.com/w3c/css-houdini-drafts/issues/1153
- auto rectified_z = rectify_a_numberish_value(value);
- if (!rectified_z->type().matches_number({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSScale z component doesn't match <number>"_utf16 };
- m_z = rectified_z;
- return {};
-}
-
-WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> CSSScale::create_style_value(PropertyNameAndID const& property) const
-{
- if (is_2d()) {
- return TransformationStyleValue::create(property.id(), TransformFunction::Scale,
- {
- TRY(m_x->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- TRY(m_y->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- });
- }
-
- return TransformationStyleValue::create(property.id(), TransformFunction::Scale3d,
- {
- TRY(m_x->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- TRY(m_y->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- TRY(m_z->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- });
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSScale.h b/Libraries/LibWeb/CSS/CSSScale.h
deleted file mode 100644
index b5721476254..00000000000
--- a/Libraries/LibWeb/CSS/CSSScale.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSNumericValue.h>
-#include <LibWeb/CSS/CSSTransformComponent.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssscale
-class CSSScale final : public CSSTransformComponent {
- WEB_WRAPPABLE(CSSScale, CSSTransformComponent);
- GC_DECLARE_ALLOCATOR(CSSScale);
-
-public:
- [[nodiscard]] static GC::Ref<CSSScale> create(Is2D, GC::Ref<CSSNumericValue> x, GC::Ref<CSSNumericValue> y, GC::Ref<CSSNumericValue> z);
- static WebIDL::ExceptionOr<GC::Ref<CSSScale>> create_for_constructor(CSSNumberish x, CSSNumberish y, Optional<CSSNumberish> z = {});
-
- virtual ~CSSScale() override;
-
- virtual WebIDL::ExceptionOr<Utf16String> to_string() const override;
-
- virtual WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> to_matrix() const override;
-
- CSSNumberish x() const { return m_x; }
- CSSNumberish y() const { return m_y; }
- CSSNumberish z() const { return m_z; }
- WebIDL::ExceptionOr<void> set_x(CSSNumberish value);
- WebIDL::ExceptionOr<void> set_y(CSSNumberish value);
- WebIDL::ExceptionOr<void> set_z(CSSNumberish value);
-
- virtual WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> create_style_value(PropertyNameAndID const&) const override;
-
-private:
- explicit CSSScale(Is2D, GC::Ref<CSSNumericValue> x, GC::Ref<CSSNumericValue> y, GC::Ref<CSSNumericValue> z);
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<CSSNumericValue> m_x;
- GC::Ref<CSSNumericValue> m_y;
- GC::Ref<CSSNumericValue> m_z;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSScale.idl b/Libraries/LibWeb/CSS/CSSScale.idl
index d80ec700d9a..1b0ada08d82 100644
--- a/Libraries/LibWeb/CSS/CSSScale.idl
+++ b/Libraries/LibWeb/CSS/CSSScale.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssscale
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSScale : CSSTransformComponent {
constructor(CSSNumberish x, CSSNumberish y, optional CSSNumberish z);
attribute CSSNumberish x;
diff --git a/Libraries/LibWeb/CSS/CSSSkew.cpp b/Libraries/LibWeb/CSS/CSSSkew.cpp
deleted file mode 100644
index 6312ba9916d..00000000000
--- a/Libraries/LibWeb/CSS/CSSSkew.cpp
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSSkew.h"
-#include <AK/Math.h>
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSNumericValue.h>
-#include <LibWeb/CSS/CSSUnitValue.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
-#include <LibWeb/Geometry/DOMMatrix.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSSkew);
-
-GC::Ref<CSSSkew> CSSSkew::create(GC::Ref<CSSNumericValue> ax, GC::Ref<CSSNumericValue> ay)
-{
- return GC::Heap::the().allocate<CSSSkew>(ax, ay);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssskew-cssskew
-WebIDL::ExceptionOr<GC::Ref<CSSSkew>> CSSSkew::create_for_constructor(GC::Ref<CSSNumericValue> ax, GC::Ref<CSSNumericValue> ay)
-{
- // The CSSSkew(ax, ay) constructor must, when invoked, perform the following steps:
-
- // 1. If ax or ay do not match <angle>, throw a TypeError.
- if (!ax->type().matches_angle({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSSkew ax component doesn't match <angle>"_utf16 };
- if (!ay->type().matches_angle({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSSkew ay component doesn't match <angle>"_utf16 };
-
- // 2. Return a new CSSSkew object with its ax and ay internal slots set to ax and ay, and its is2D internal slot
- // set to true.
- return CSSSkew::create(ax, ay);
-}
-
-CSSSkew::CSSSkew(GC::Ref<CSSNumericValue> ax, GC::Ref<CSSNumericValue> ay)
- : CSSTransformComponent(Is2D::Yes)
- , m_ax(ax)
- , m_ay(ay)
-{
-}
-
-CSSSkew::~CSSSkew() = default;
-
-void CSSSkew::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_ax);
- visitor.visit(m_ay);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssskew
-WebIDL::ExceptionOr<Utf16String> CSSSkew::to_string() const
-{
- // 1. Let s initially be "skew(".
- Utf16StringBuilder builder;
- builder.append_ascii("skew("sv);
-
- // 2. Serialize this’s ax internal slot, and append it to s.
- m_ax->serialize(builder, {});
-
- // 3. If this’s ay internal slot is a CSSUnitValue with a value of 0, then append ")" to s and return s.
- if (auto* ay_unit_value = as_if<CSSUnitValue>(*m_ay); ay_unit_value && ay_unit_value->value() == 0) {
- builder.append_ascii(')');
- return builder.to_string();
- }
-
- // 4. Otherwise, append ", " to s.
- builder.append_ascii(", "sv);
-
- // 5. Serialize this’s ay internal slot, and append it to s.
- m_ay->serialize(builder, {});
-
- // 6. Append ")" to s, and return s.
- builder.append_ascii(')');
- return builder.to_string();
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformcomponent-tomatrix
-WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSSkew::to_matrix() const
-{
- // 1. Let matrix be a new DOMMatrix object, initialized to this’s equivalent 4x4 transform matrix, as defined in
- // CSS Transforms 1 § 12. Mathematical Description of Transform Functions, and with its is2D internal slot set
- // to the same value as this’s is2D internal slot.
- // NOTE: Recall that the is2D flag affects what transform, and thus what equivalent matrix, a
- // CSSTransformComponent represents.
- // As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in
- // generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a
- // TypeError.
- auto ax_rad = TRY(m_ax->to("rad"_utf16_fly_string))->value();
- auto ay_rad = TRY(m_ay->to("rad"_utf16_fly_string))->value();
-
- // NB: Gfx::Matrix4x4 is row by row, so the element m21 is in the first row and m12 in the second.
- auto matrix = Gfx::DoubleMatrix4x4::identity();
- matrix[0, 1] = AK::tan<float>(ax_rad);
- matrix[1, 0] = AK::tan<float>(ay_rad);
-
- return Geometry::DOMMatrix::create(matrix, is_2d());
-}
-
-WebIDL::ExceptionOr<void> CSSSkew::set_ax(GC::Ref<CSSNumericValue> ax)
-{
- // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
- // WPT expects this to throw for invalid values.
- if (!ax->type().matches_angle({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSSkew ax component doesn't match <angle>"_utf16 };
- m_ax = ax;
- return {};
-}
-
-WebIDL::ExceptionOr<void> CSSSkew::set_ay(GC::Ref<CSSNumericValue> ay)
-{
- // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
- // WPT expects this to throw for invalid values.
- if (!ay->type().matches_angle({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSSkew ay component doesn't match <angle>"_utf16 };
- m_ay = ay;
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssskew-is2d
-void CSSSkew::set_is_2d(bool)
-{
- // The is2D attribute of a CSSSkew, CSSSkewX, or CSSSkewY object must, on setting, do nothing.
-}
-
-WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> CSSSkew::create_style_value(PropertyNameAndID const& property) const
-{
- return TransformationStyleValue::create(property.id(), TransformFunction::Skew,
- {
- TRY(m_ax->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- TRY(m_ay->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- });
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSSkew.h b/Libraries/LibWeb/CSS/CSSSkew.h
deleted file mode 100644
index b3e28f24db0..00000000000
--- a/Libraries/LibWeb/CSS/CSSSkew.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSTransformComponent.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssskew
-class CSSSkew final : public CSSTransformComponent {
- WEB_WRAPPABLE(CSSSkew, CSSTransformComponent);
- GC_DECLARE_ALLOCATOR(CSSSkew);
-
-public:
- static constexpr size_t ax_offset() { return offsetof(CSSSkew, m_ax); }
- static constexpr size_t ay_offset() { return offsetof(CSSSkew, m_ay); }
- [[nodiscard]] static GC::Ref<CSSSkew> create(GC::Ref<CSSNumericValue> ax, GC::Ref<CSSNumericValue> ay);
- static WebIDL::ExceptionOr<GC::Ref<CSSSkew>> create_for_constructor(GC::Ref<CSSNumericValue> ax, GC::Ref<CSSNumericValue> ay);
-
- virtual ~CSSSkew() override;
-
- virtual WebIDL::ExceptionOr<Utf16String> to_string() const override;
-
- virtual WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> to_matrix() const override;
-
- GC::Ref<CSSNumericValue> ax() const { return m_ax; }
- GC::Ref<CSSNumericValue> ay() const { return m_ay; }
- WebIDL::ExceptionOr<void> set_ax(GC::Ref<CSSNumericValue> value);
- WebIDL::ExceptionOr<void> set_ay(GC::Ref<CSSNumericValue> value);
-
- virtual void set_is_2d(bool value) override;
-
- virtual WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> create_style_value(PropertyNameAndID const&) const override;
-
-private:
- explicit CSSSkew(GC::Ref<CSSNumericValue> ax, GC::Ref<CSSNumericValue> ay);
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<CSSNumericValue> m_ax;
- GC::Ref<CSSNumericValue> m_ay;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSSkew.idl b/Libraries/LibWeb/CSS/CSSSkew.idl
index 620b6b14973..e8e22c84a36 100644
--- a/Libraries/LibWeb/CSS/CSSSkew.idl
+++ b/Libraries/LibWeb/CSS/CSSSkew.idl
@@ -1,7 +1,7 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssskew
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSSkew : CSSTransformComponent {
constructor(CSSNumericValue ax, CSSNumericValue ay);
- [DirectGetter] attribute CSSNumericValue ax;
- [DirectGetter] attribute CSSNumericValue ay;
+ attribute CSSNumericValue ax;
+ attribute CSSNumericValue ay;
};
diff --git a/Libraries/LibWeb/CSS/CSSSkewX.cpp b/Libraries/LibWeb/CSS/CSSSkewX.cpp
deleted file mode 100644
index 58de40f45ee..00000000000
--- a/Libraries/LibWeb/CSS/CSSSkewX.cpp
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSSkewX.h"
-#include <AK/Math.h>
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSNumericValue.h>
-#include <LibWeb/CSS/CSSUnitValue.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
-#include <LibWeb/Geometry/DOMMatrix.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSSkewX);
-
-GC::Ref<CSSSkewX> CSSSkewX::create(GC::Ref<CSSNumericValue> ax)
-{
- return GC::Heap::the().allocate<CSSSkewX>(ax);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssskewx-cssskewx
-WebIDL::ExceptionOr<GC::Ref<CSSSkewX>> CSSSkewX::create_for_constructor(GC::Ref<CSSNumericValue> ax)
-{
- // The CSSSkewX(ax) constructor must, when invoked, perform the following steps:
-
- // 1. If ax does not match <angle>, throw a TypeError.
- if (!ax->type().matches_angle({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSSkewX ax component doesn't match <angle>"_utf16 };
-
- // 2. Return a new CSSSkewX object with its ax internal slot set to ax, and its is2D internal slot set to true.
- return CSSSkewX::create(ax);
-}
-
-CSSSkewX::CSSSkewX(GC::Ref<CSSNumericValue> ax)
- : CSSTransformComponent(Is2D::Yes)
- , m_ax(ax)
-{
-}
-
-CSSSkewX::~CSSSkewX() = default;
-
-void CSSSkewX::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_ax);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssskewx
-WebIDL::ExceptionOr<Utf16String> CSSSkewX::to_string() const
-{
- // 1. Let s initially be "skewX(".
- Utf16StringBuilder builder;
- builder.append_ascii("skewX("sv);
-
- // 2. Serialize this’s ax internal slot, and append it to s.
- m_ax->serialize(builder, {});
-
- // 3. Append ")" to s, and return s.
- builder.append_ascii(')');
- return builder.to_string();
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformcomponent-tomatrix
-WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSSkewX::to_matrix() const
-{
- // 1. Let matrix be a new DOMMatrix object, initialized to this’s equivalent 4x4 transform matrix, as defined in
- // CSS Transforms 1 § 12. Mathematical Description of Transform Functions, and with its is2D internal slot set
- // to the same value as this’s is2D internal slot.
- // NOTE: Recall that the is2D flag affects what transform, and thus what equivalent matrix, a
- // CSSTransformComponent represents.
- // As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in
- // generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a
- // TypeError.
- auto ax_rad = TRY(m_ax->to("rad"_utf16_fly_string))->value();
-
- // NB: Gfx::Matrix4x4 is row by row, so the element m21 is in the first row.
- auto matrix = Gfx::DoubleMatrix4x4::identity();
- matrix[0, 1] = AK::tan<float>(ax_rad);
-
- return Geometry::DOMMatrix::create(matrix, is_2d());
-}
-
-WebIDL::ExceptionOr<void> CSSSkewX::set_ax(GC::Ref<CSSNumericValue> ax)
-{
- // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
- // WPT expects this to throw for invalid values.
- if (!ax->type().matches_angle({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSSkewX ax component doesn't match <angle>"_utf16 };
- m_ax = ax;
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssskew-is2d
-void CSSSkewX::set_is_2d(bool)
-{
- // The is2D attribute of a CSSSkewX, CSSSkewXX, or CSSSkewXY object must, on setting, do nothing.
-}
-
-WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> CSSSkewX::create_style_value(PropertyNameAndID const& property) const
-{
- return TransformationStyleValue::create(property.id(), TransformFunction::SkewX,
- {
- TRY(m_ax->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- });
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSSkewX.h b/Libraries/LibWeb/CSS/CSSSkewX.h
deleted file mode 100644
index 282f071a76e..00000000000
--- a/Libraries/LibWeb/CSS/CSSSkewX.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSTransformComponent.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssskewx
-class CSSSkewX final : public CSSTransformComponent {
- WEB_WRAPPABLE(CSSSkewX, CSSTransformComponent);
- GC_DECLARE_ALLOCATOR(CSSSkewX);
-
-public:
- static constexpr size_t ax_offset() { return offsetof(CSSSkewX, m_ax); }
- [[nodiscard]] static GC::Ref<CSSSkewX> create(GC::Ref<CSSNumericValue> ax);
- static WebIDL::ExceptionOr<GC::Ref<CSSSkewX>> create_for_constructor(GC::Ref<CSSNumericValue> ax);
-
- virtual ~CSSSkewX() override;
-
- virtual WebIDL::ExceptionOr<Utf16String> to_string() const override;
-
- virtual WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> to_matrix() const override;
-
- GC::Ref<CSSNumericValue> ax() const { return m_ax; }
- WebIDL::ExceptionOr<void> set_ax(GC::Ref<CSSNumericValue> value);
-
- virtual void set_is_2d(bool value) override;
-
- virtual WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> create_style_value(PropertyNameAndID const&) const override;
-
-private:
- explicit CSSSkewX(GC::Ref<CSSNumericValue> ax);
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<CSSNumericValue> m_ax;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSSkewX.idl b/Libraries/LibWeb/CSS/CSSSkewX.idl
index 174a0460552..c17d7406994 100644
--- a/Libraries/LibWeb/CSS/CSSSkewX.idl
+++ b/Libraries/LibWeb/CSS/CSSSkewX.idl
@@ -1,6 +1,6 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssskewx
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSSkewX : CSSTransformComponent {
constructor(CSSNumericValue ax);
- [DirectGetter] attribute CSSNumericValue ax;
+ attribute CSSNumericValue ax;
};
diff --git a/Libraries/LibWeb/CSS/CSSSkewY.cpp b/Libraries/LibWeb/CSS/CSSSkewY.cpp
deleted file mode 100644
index 537e928b0d0..00000000000
--- a/Libraries/LibWeb/CSS/CSSSkewY.cpp
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSSkewY.h"
-#include <AK/Math.h>
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSNumericValue.h>
-#include <LibWeb/CSS/CSSUnitValue.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
-#include <LibWeb/Geometry/DOMMatrix.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSSkewY);
-
-GC::Ref<CSSSkewY> CSSSkewY::create(GC::Ref<CSSNumericValue> ay)
-{
- return GC::Heap::the().allocate<CSSSkewY>(ay);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssskewy-cssskewy
-WebIDL::ExceptionOr<GC::Ref<CSSSkewY>> CSSSkewY::create_for_constructor(GC::Ref<CSSNumericValue> ay)
-{
- // The CSSSkewY(ay) constructor must, when invoked, perform the following steps:
-
- // 1. If ay does not match <angle>, throw a TypeError.
- if (!ay->type().matches_angle({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSSkewY ay component doesn't match <angle>"_utf16 };
-
- // 2. Return a new CSSSkewY object with its ay internal slot set to ay, and its is2D internal slot set to true.
- return CSSSkewY::create(ay);
-}
-
-CSSSkewY::CSSSkewY(GC::Ref<CSSNumericValue> ay)
- : CSSTransformComponent(Is2D::Yes)
- , m_ay(ay)
-{
-}
-
-CSSSkewY::~CSSSkewY() = default;
-
-void CSSSkewY::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_ay);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssskewy
-WebIDL::ExceptionOr<Utf16String> CSSSkewY::to_string() const
-{
- // 1. Let s initially be "skewY(".
- Utf16StringBuilder builder;
- builder.append_ascii("skewY("sv);
-
- // 2. Serialize this’s ay internal slot, and append it to s.
- m_ay->serialize(builder, {});
-
- // 3. Append ")" to s, and return s.
- builder.append_ascii(')');
- return builder.to_string();
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformcomponent-tomatrix
-WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSSkewY::to_matrix() const
-{
- // 1. Let matrix be a new DOMMatrix object, initialized to this’s equivalent 4x4 transform matrix, as defined in
- // CSS Transforms 1 § 12. Mathematical Description of Transform Functions, and with its is2D internal slot set
- // to the same value as this’s is2D internal slot.
- // NOTE: Recall that the is2D flag affects what transform, and thus what equivalent matrix, a
- // CSSTransformComponent represents.
- // As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in
- // generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a
- // TypeError.
- auto ay_rad = TRY(m_ay->to("rad"_utf16_fly_string))->value();
-
- // NB: Gfx::Matrix4x4 is row by row, so the element m12 is in the second row.
- auto matrix = Gfx::DoubleMatrix4x4::identity();
- matrix[1, 0] = AK::tan<float>(ay_rad);
-
- return Geometry::DOMMatrix::create(matrix, is_2d());
-}
-
-WebIDL::ExceptionOr<void> CSSSkewY::set_ay(GC::Ref<CSSNumericValue> ay)
-{
- // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
- // WPT expects this to throw for invalid values.
- if (!ay->type().matches_angle({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSSkewY ay component doesn't match <angle>"_utf16 };
- m_ay = ay;
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssskew-is2d
-void CSSSkewY::set_is_2d(bool)
-{
- // The is2D attribute of a CSSSkewY, CSSSkewYX, or CSSSkewYY object must, on setting, do nothing.
-}
-
-WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> CSSSkewY::create_style_value(PropertyNameAndID const& property) const
-{
- return TransformationStyleValue::create(property.id(), TransformFunction::SkewY,
- {
- TRY(m_ay->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- });
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSSkewY.h b/Libraries/LibWeb/CSS/CSSSkewY.h
deleted file mode 100644
index 58a76c44f07..00000000000
--- a/Libraries/LibWeb/CSS/CSSSkewY.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSTransformComponent.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssskewy
-class CSSSkewY final : public CSSTransformComponent {
- WEB_WRAPPABLE(CSSSkewY, CSSTransformComponent);
- GC_DECLARE_ALLOCATOR(CSSSkewY);
-
-public:
- static constexpr size_t ay_offset() { return offsetof(CSSSkewY, m_ay); }
- [[nodiscard]] static GC::Ref<CSSSkewY> create(GC::Ref<CSSNumericValue> ay);
- static WebIDL::ExceptionOr<GC::Ref<CSSSkewY>> create_for_constructor(GC::Ref<CSSNumericValue> ay);
-
- virtual ~CSSSkewY() override;
-
- virtual WebIDL::ExceptionOr<Utf16String> to_string() const override;
-
- virtual WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> to_matrix() const override;
-
- GC::Ref<CSSNumericValue> ay() const { return m_ay; }
- WebIDL::ExceptionOr<void> set_ay(GC::Ref<CSSNumericValue> value);
-
- virtual void set_is_2d(bool value) override;
-
- virtual WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> create_style_value(PropertyNameAndID const&) const override;
-
-private:
- explicit CSSSkewY(GC::Ref<CSSNumericValue> ay);
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<CSSNumericValue> m_ay;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSSkewY.idl b/Libraries/LibWeb/CSS/CSSSkewY.idl
index 4605df694e2..64d754a3652 100644
--- a/Libraries/LibWeb/CSS/CSSSkewY.idl
+++ b/Libraries/LibWeb/CSS/CSSSkewY.idl
@@ -1,6 +1,6 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssskewy
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSSkewY : CSSTransformComponent {
constructor(CSSNumericValue ay);
- [DirectGetter] attribute CSSNumericValue ay;
+ attribute CSSNumericValue ay;
};
diff --git a/Libraries/LibWeb/CSS/CSSStyleValue.cpp b/Libraries/LibWeb/CSS/CSSStyleValue.cpp
deleted file mode 100644
index cd7cad32bd8..00000000000
--- a/Libraries/LibWeb/CSS/CSSStyleValue.cpp
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSStyleValue.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/StyleValues/StyleValue.h>
-#include <LibWeb/CSS/StyleValues/StyleValueList.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSStyleValue);
-
-GC::Ref<CSSStyleValue> CSSStyleValue::create(Utf16FlyString associated_property, StyleValue const& source_value, SerializationMode serialization_mode)
-{
- return GC::Heap::the().allocate<CSSStyleValue>(move(associated_property), source_value, serialization_mode);
-}
-
-CSSStyleValue::CSSStyleValue()
-{
-}
-
-CSSStyleValue::CSSStyleValue(StyleValue const& source_value)
- : m_source_value(RustStyleValueHandle::retained(source_value.rust_style_value_data()))
-{
-}
-
-CSSStyleValue::CSSStyleValue(Utf16FlyString associated_property, StyleValue const& source_value, SerializationMode serialization_mode)
- : m_associated_property(move(associated_property))
- , m_source_value(RustStyleValueHandle::retained(source_value.rust_style_value_data()))
- , m_serialization_mode(serialization_mode)
-{
-}
-
-RefPtr<StyleValue const> CSSStyleValue::source_style_value() const
-{
- if (!m_source_value)
- return nullptr;
- return StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(m_source_value.data()));
-}
-
-CSSStyleValue::~CSSStyleValue() = default;
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssstylevalue-parse
-WebIDL::ExceptionOr<GC::Ref<CSSStyleValue>> CSSStyleValue::parse(JS::VM& vm, Utf16FlyString const& property, Utf16View css_text)
-{
- // The parse(property, cssText) method, when invoked, must parse a CSSStyleValue with property property, cssText
- // cssText, and parseMultiple set to false, and return the result.
- auto result = parse_a_css_style_value(vm, property, css_text, ParseMultiple::No);
- if (result.is_exception())
- return result.release_error();
- return result.value().get<GC::Ref<CSSStyleValue>>();
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssstylevalue-parseall
-WebIDL::ExceptionOr<GC::RootVector<GC::Ref<CSSStyleValue>>> CSSStyleValue::parse_all(JS::VM& vm, Utf16FlyString const& property, Utf16View css_text)
-{
- // The parseAll(property, cssText) method, when invoked, must parse a CSSStyleValue with property property, cssText
- // cssText, and parseMultiple set to true, and return the result.
- auto result = parse_a_css_style_value(vm, property, css_text, ParseMultiple::Yes);
- if (result.is_exception())
- return result.release_error();
- return result.value().get<GC::RootVector<GC::Ref<CSSStyleValue>>>();
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#parse-a-cssstylevalue
-WebIDL::ExceptionOr<Variant<GC::Ref<CSSStyleValue>, GC::RootVector<GC::Ref<CSSStyleValue>>>> CSSStyleValue::parse_a_css_style_value(JS::VM& vm, Utf16FlyString property_name, Utf16View css_text, ParseMultiple parse_multiple)
-{
- (void)vm;
- // 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. Attempt to parse cssText according to property’s grammar.
- // If this fails, throw a TypeError.
- // Otherwise, let whole value be the parsed result.
- auto whole_value = parse_css_value(Parser::ParsingParams {}, css_text, property->id());
- if (!whole_value)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Failed to parse '{}' as a value for '{}' property", css_text, property->name()) };
-
- // 4. Subdivide into iterations whole value, according to property, and let values be the result.
- auto values = whole_value->subdivide_into_iterations(property.value());
-
- // 5. For each value in values, replace it with the result of reifying value for property.
- GC::RootVector<GC::Ref<CSSStyleValue>> reified_values;
- for (auto const& value : values) {
- reified_values.append(value->reify(property->name()));
- }
-
- // 6. If parseMultiple is false, return values[0]. Otherwise, return values.
- // FIXME: We need to somehow store the source css_text on the returned CSSStyleValue.
- // https://github.com/w3c/css-houdini-drafts/issues/1156
- if (parse_multiple == ParseMultiple::No)
- return reified_values.take_first();
- return reified_values;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#stylevalue-serialization
-WebIDL::ExceptionOr<Utf16String> CSSStyleValue::to_string() const
-{
- // FIXME: if the value was constructed from a USVString
- // NB: Basically, if this was constructed with "parse a CSSStyleValue", regardless of what CSSStyleValue type it is now.
- {
- // the serialization is the USVString from which the value was constructed.
- }
- // otherwise, if the value was constructed using an IDL constructor
- {
- // the serialization is specified in the sections below.
- // NB: This is handled by subclasses overriding this to_string() method.
- }
- // FIXME: otherwise, if the value was extracted from the CSSOM
- // NB: For CSSStyleValue itself, we use the source value we were created from.
- if (auto source_value = source_style_value())
- return source_value->to_utf16_string(m_serialization_mode);
- {
- // the serialization is specified in §6.7 Serialization from CSSOM Values below.
- }
- return Utf16String {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
-WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> CSSStyleValue::create_an_internal_representation(PropertyNameAndID const&, PerformTypeCheck) const
-{
- // If value is a direct CSSStyleValue,
- // Return value’s associated value.
- auto source_value = source_style_value();
- if (!source_value)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Missing {}::create_an_internal_representation() overload", class_name()) };
- return source_value.release_nonnull();
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSStyleValue.h b/Libraries/LibWeb/CSS/CSSStyleValue.h
index d91c47ac574..abf58183aa9 100644
--- a/Libraries/LibWeb/CSS/CSSStyleValue.h
+++ b/Libraries/LibWeb/CSS/CSSStyleValue.h
@@ -6,62 +6,60 @@
#pragma once
+#include <AK/NonnullRefPtr.h>
+#include <AK/Optional.h>
#include <AK/Utf16FlyString.h>
-#include <AK/Utf16String.h>
#include <AK/Utf16View.h>
-#include <LibWeb/Bindings/Wrappable.h>
+#include <LibGC/Ptr.h>
+#include <LibWeb/Bindings/CSSStyleValue.h>
+#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/CSS/SerializationMode.h>
-#include <LibWeb/CSS/StyleValues/RustStyleValueHandle.h>
+#include <LibWeb/Export.h>
+#include <LibWeb/Forward.h>
+#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::CSS {
// https://drafts.css-houdini.org/css-typed-om-1/#cssstylevalue
-class CSSStyleValue : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(CSSStyleValue, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(CSSStyleValue);
+// The C++ side of the CSS Typed OM, which is implemented in Rust (Libraries/LibWeb/Bindings/Rust/src/css): what C++
+// creates and reads.
+class WEB_API CSSStyleValue : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(CSSStyleValue, css_style_value)
public:
- [[nodiscard]] static GC::Ref<CSSStyleValue> create(Utf16FlyString associated_property, StyleValue const&, SerializationMode = SerializationMode::Normal);
-
- virtual ~CSSStyleValue() override;
-
- Optional<Utf16FlyString> const& associated_property() const { return m_associated_property; }
- RustStyleValueHandle const& source_value() const { return m_source_value; }
-
- static WebIDL::ExceptionOr<GC::Ref<CSSStyleValue>> parse(JS::VM&, Utf16FlyString const& property, Utf16View css_text);
- static WebIDL::ExceptionOr<GC::RootVector<GC::Ref<CSSStyleValue>>> parse_all(JS::VM&, Utf16FlyString const& property, Utf16View css_text);
-
- enum class ParseMultiple : u8 {
+ enum class PerformTypeCheck : u8 {
No,
Yes,
};
- static WebIDL::ExceptionOr<Variant<GC::Ref<CSSStyleValue>, GC::RootVector<GC::Ref<CSSStyleValue>>>> parse_a_css_style_value(JS::VM&, Utf16FlyString property, Utf16View css_text, ParseMultiple);
- virtual WebIDL::ExceptionOr<Utf16String> to_string() const;
+ static GC::Ref<CSSStyleValue> create(Utf16FlyString associated_property, StyleValue const&, SerializationMode = SerializationMode::Normal);
- // FIXME: Temporary hack. Really we want to pass something like a CalculationContext with the valid types and ranges.
- enum class PerformTypeCheck : u8 {
- No,
- Yes,
- };
- virtual WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> create_an_internal_representation(PropertyNameAndID const&, PerformTypeCheck) const;
+ // https://drafts.css-houdini.org/css-typed-om-1/#reify-stylevalue
+ static GC::Ref<CSSStyleValue> reify(StyleValue const&, Utf16FlyString const& associated_property);
-protected:
- explicit CSSStyleValue();
- explicit CSSStyleValue(StyleValue const& source_value);
+ // https://drafts.css-houdini.org/css-typed-om-1/#parse-a-cssstylevalue, with parseMultiple set to false.
+ static WebIDL::ExceptionOr<GC::Ref<CSSStyleValue>> parse_a_css_style_value(Utf16FlyString const& property, Utf16View css_text);
- // Wraps the held Rust value in a C++ StyleValue facade on demand.
- RefPtr<StyleValue const> source_style_value() const;
+ Optional<Utf16FlyString> associated_property() const;
-private:
- explicit CSSStyleValue(Utf16FlyString associated_property, StyleValue const& source_value, SerializationMode);
+ // https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+ WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> create_an_internal_representation(PropertyNameAndID const&, PerformTypeCheck) const;
+
+ bool is_unparsed_value() const;
- // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssstylevalue-associatedproperty-slot
- Optional<Utf16FlyString> m_associated_property;
+ template<typename T>
+ bool fast_is() const
+ requires(IsSame<T, CSSNumericValue> || IsSame<T, CSSUnitValue>)
+ {
+ if constexpr (IsSame<T, CSSNumericValue>)
+ return is_numeric_value();
+ else
+ return is_unit_value();
+ }
- // Shared handle to the Rust-owned value data this object was reified from.
- RustStyleValueHandle m_source_value;
- SerializationMode m_serialization_mode { SerializationMode::Normal };
+private:
+ bool is_numeric_value() const;
+ bool is_unit_value() const;
};
}
diff --git a/Libraries/LibWeb/CSS/CSSStyleValue.idl b/Libraries/LibWeb/CSS/CSSStyleValue.idl
index 031f441c415..0b6e5778494 100644
--- a/Libraries/LibWeb/CSS/CSSStyleValue.idl
+++ b/Libraries/LibWeb/CSS/CSSStyleValue.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssstylevalue
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSStyleValue {
stringifier;
[Exposed=Window] static CSSStyleValue parse(USVString property, USVString cssText);
diff --git a/Libraries/LibWeb/CSS/CSSTransformComponent.cpp b/Libraries/LibWeb/CSS/CSSTransformComponent.cpp
deleted file mode 100644
index d9d0db8c717..00000000000
--- a/Libraries/LibWeb/CSS/CSSTransformComponent.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSTransformComponent.h"
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSTransformComponent);
-
-CSSTransformComponent::CSSTransformComponent(Is2D is_2d)
- : m_is_2d(is_2d == Is2D::Yes)
-{
-}
-
-CSSTransformComponent::~CSSTransformComponent() = default;
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSTransformComponent.h b/Libraries/LibWeb/CSS/CSSTransformComponent.h
deleted file mode 100644
index e82d943c362..00000000000
--- a/Libraries/LibWeb/CSS/CSSTransformComponent.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#csstransformcomponent
-class CSSTransformComponent : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(CSSTransformComponent, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(CSSTransformComponent);
-
-public:
- enum class Is2D : u8 {
- No,
- Yes,
- };
- virtual ~CSSTransformComponent() override;
-
- virtual WebIDL::ExceptionOr<Utf16String> to_string() const = 0;
-
- bool is_2d() const { return m_is_2d; }
- virtual void set_is_2d(bool value) { m_is_2d = value; }
-
- virtual WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> to_matrix() const = 0;
-
- virtual WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> create_style_value(PropertyNameAndID const&) const = 0;
-
-protected:
- explicit CSSTransformComponent(Is2D is_2d);
-
-private:
- bool m_is_2d;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSTransformComponent.idl b/Libraries/LibWeb/CSS/CSSTransformComponent.idl
index d24dec7c24c..4c0b24f8b04 100644
--- a/Libraries/LibWeb/CSS/CSSTransformComponent.idl
+++ b/Libraries/LibWeb/CSS/CSSTransformComponent.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#csstransformcomponent
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSTransformComponent {
stringifier;
[ImplementedAs=is_2d] attribute boolean is2D;
diff --git a/Libraries/LibWeb/CSS/CSSTransformValue.cpp b/Libraries/LibWeb/CSS/CSSTransformValue.cpp
deleted file mode 100644
index e173c1db1a6..00000000000
--- a/Libraries/LibWeb/CSS/CSSTransformValue.cpp
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSTransformValue.h"
-#include <AK/Utf16StringBuilder.h>
-#include <LibWeb/Bindings/CSSTransformValue.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/CSS/CSSTransformComponent.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/StyleValues/StyleValueList.h>
-#include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
-#include <LibWeb/Geometry/DOMMatrix.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSTransformValue);
-
-GC::Ref<CSSTransformValue> CSSTransformValue::create(ReadonlySpan<GC::Ref<CSSTransformComponent>> transforms)
-{
- GC::RootVector<GC::Ref<CSSTransformComponent>> converted_transforms;
- converted_transforms.ensure_capacity(transforms.size());
- for (auto const& transform : transforms)
- converted_transforms.append(transform);
- return GC::Heap::the().allocate<CSSTransformValue>(move(converted_transforms));
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformvalue-csstransformvalue
-WebIDL::ExceptionOr<GC::Ref<CSSTransformValue>> CSSTransformValue::create_for_constructor(ReadonlySpan<GC::Ref<CSSTransformComponent>> transforms)
-{
- // The CSSTransformValue(transforms) constructor must, when called, perform the following steps:
-
- // 1. If transforms is empty, throw a TypeError.
- if (transforms.is_empty())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSTransformValue's transforms list cannot be empty."_utf16 };
-
- // 2. Return a new CSSTransformValue whose values to iterate over is transforms.
- return CSSTransformValue::create(transforms);
-}
-
-CSSTransformValue::CSSTransformValue(Vector<GC::Ref<CSSTransformComponent>>&& transforms)
- : CSSStyleValue()
- , m_transforms(move(transforms))
-{
-}
-
-CSSTransformValue::~CSSTransformValue() = default;
-
-void CSSTransformValue::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_transforms);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformvalue-length
-WebIDL::UnsignedLong CSSTransformValue::length() const
-{
- // The length attribute indicates how many transform components are contained within the CSSTransformValue.
- return m_transforms.size();
-}
-
-GC::Ptr<CSSTransformComponent> CSSTransformValue::component_at(size_t index) const
-{
- if (index >= m_transforms.size())
- return {};
- return m_transforms[index];
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#ref-for-dfn-set-the-value-of-an-existing-indexed-property%E2%91%A0
-WebIDL::ExceptionOr<void> CSSTransformValue::set_value_of_existing_indexed_property(u32 n, GC::Ref<CSSTransformComponent> new_value)
-{
- // To set the value of an existing indexed property of a CSSTransformValue this, an index n, and a value new value,
- // let values be this’s [[values]] internal slot, and set values[n] to new value.
- m_transforms[n] = new_value;
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#ref-for-dfn-set-the-value-of-a-new-indexed-property①
-WebIDL::ExceptionOr<void> CSSTransformValue::set_value_of_new_indexed_property(u32 n, GC::Ref<CSSTransformComponent> new_value)
-{
- // To set the value of a new indexed property of a CSSTransformValue this, an index n, and a value new value, let
- // values be this’s [[values]] internal slot. If n is not equal to the size of values, throw a RangeError.
- // Otherwise, append new value to values.
- if (n != m_transforms.size())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Index out of range"_utf16 };
-
- m_transforms.append(new_value);
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformvalue-is2d
-bool CSSTransformValue::is_2d() const
-{
- // The is2D attribute of a CSSTransformValue this must, on getting, return true if, for each func in this’s values
- // to iterate over, the func’s is2D attribute would return true; otherwise, the attribute returns false.
- return all_of(m_transforms, [](auto& transform) { return transform->is_2d(); });
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformvalue-tomatrix
-WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSTransformValue::to_matrix() const
-{
- // The toMatrix() method of a CSSTransformValue this must, when called, perform the following steps:
-
- // 1. Let matrix be a new DOMMatrix, initialized to the identity matrix, with its is2D internal slot set to true.
- auto matrix = Geometry::DOMMatrix::create();
-
- // 2. For each func in this’s values to iterate over:
- for (auto const& function : m_transforms) {
- // 1. Let funcMatrix be the DOMMatrix returned by calling toMatrix() on func.
- // AD-HOC: This can throw exceptions.
- auto function_matrix = TRY(function->to_matrix());
-
- // 2. Set matrix to the result of multiplying matrix and the matrix represented by funcMatrix.
- matrix->multiply_self(*function_matrix);
- }
-
- // 3. Return matrix.
- return matrix;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-csstransformvalue
-WebIDL::ExceptionOr<Utf16String> CSSTransformValue::to_string() const
-{
- // 1. Return the result of serializing each item in this’s values to iterate over, then concatenating them
- // separated by " ".
- Utf16StringBuilder builder;
- bool first = true;
- for (auto const& transform : m_transforms) {
- if (!first)
- builder.append_ascii(' ');
- first = false;
- builder.append(TRY(transform->to_string()));
- }
- return builder.to_string();
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
-WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> CSSTransformValue::create_an_internal_representation(PropertyNameAndID const& property, PerformTypeCheck perform_type_check) const
-{
- // NB: This can become <transform-function> or <transform-list>, and we don't know which is wanted without performing the type checking.
- // We can worry about that if and when we ever do have a CSSTransformValue that isn't top-level.
- VERIFY(perform_type_check == PerformTypeCheck::Yes);
-
- // If value is a CSSStyleValue subclass,
- // If value does not match the grammar of a list-valued property iteration of property, throw a TypeError.
- //
- // If any component of property’s CSS grammar has a limited numeric range, and the corresponding part of value
- // is a CSSUnitValue that is outside of that range, replace that value with the result of wrapping it in a
- // fresh CSSMathSum whose values internal slot contains only that part of value.
- //
- // Return the value.
-
- // NB: We match <transform-function> if we have 1 transform. We match <transform-list> always.
- if (m_transforms.size() == 1 && property_accepts_type(property.id(), ValueType::TransformFunction))
- return TRY(m_transforms.first()->create_style_value(property));
-
- if (property_accepts_type(property.id(), ValueType::TransformList)) {
- StyleValueVector transforms;
- transforms.ensure_capacity(m_transforms.size());
- for (auto const transform : m_transforms)
- transforms.unchecked_append(TRY(transform->create_style_value(property)));
- return StyleValueList::create(move(transforms), StyleValueList::Separator::Space);
- }
-
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Property does not accept values of this type."_utf16 };
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSTransformValue.h b/Libraries/LibWeb/CSS/CSSTransformValue.h
deleted file mode 100644
index c70b2011146..00000000000
--- a/Libraries/LibWeb/CSS/CSSTransformValue.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSStyleValue.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#csstransformvalue
-class CSSTransformValue final : public CSSStyleValue {
- WEB_WRAPPABLE(CSSTransformValue, CSSStyleValue);
- GC_DECLARE_ALLOCATOR(CSSTransformValue);
-
-public:
- [[nodiscard]] static GC::Ref<CSSTransformValue> create(ReadonlySpan<GC::Ref<CSSTransformComponent>>);
- static WebIDL::ExceptionOr<GC::Ref<CSSTransformValue>> create_for_constructor(ReadonlySpan<GC::Ref<CSSTransformComponent>>);
-
- virtual ~CSSTransformValue() override;
-
- WebIDL::UnsignedLong length() const;
- GC::Ptr<CSSTransformComponent> component_at(size_t index) const;
- WebIDL::ExceptionOr<void> set_value_of_existing_indexed_property(u32, GC::Ref<CSSTransformComponent>);
- WebIDL::ExceptionOr<void> set_value_of_new_indexed_property(u32, GC::Ref<CSSTransformComponent>);
-
- bool is_2d() const;
- WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> to_matrix() const;
-
- virtual WebIDL::ExceptionOr<Utf16String> to_string() const override;
-
- virtual WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> create_an_internal_representation(PropertyNameAndID const&, PerformTypeCheck) const override;
-
-private:
- explicit CSSTransformValue(Vector<GC::Ref<CSSTransformComponent>>&&);
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- Vector<GC::Ref<CSSTransformComponent>> m_transforms;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSTransformValue.idl b/Libraries/LibWeb/CSS/CSSTransformValue.idl
index a1dbffa363a..23ad0909f4a 100644
--- a/Libraries/LibWeb/CSS/CSSTransformValue.idl
+++ b/Libraries/LibWeb/CSS/CSSTransformValue.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#csstransformvalue
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSTransformValue : CSSStyleValue {
constructor(sequence<CSSTransformComponent> transforms);
iterable<CSSTransformComponent>;
diff --git a/Libraries/LibWeb/CSS/CSSTranslate.cpp b/Libraries/LibWeb/CSS/CSSTranslate.cpp
deleted file mode 100644
index 57e5259406b..00000000000
--- a/Libraries/LibWeb/CSS/CSSTranslate.cpp
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSTranslate.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/CSSNumericValue.h>
-#include <LibWeb/CSS/CSSUnitValue.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
-#include <LibWeb/Geometry/DOMMatrix.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSTranslate);
-
-GC::Ref<CSSTranslate> CSSTranslate::create(Is2D is_2d, GC::Ref<CSSNumericValue> x, GC::Ref<CSSNumericValue> y, GC::Ref<CSSNumericValue> z)
-{
- return GC::Heap::the().allocate<CSSTranslate>(is_2d, x, y, z);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-csstranslate-csstranslate
-WebIDL::ExceptionOr<GC::Ref<CSSTranslate>> CSSTranslate::create_for_constructor(GC::Ref<CSSNumericValue> x, GC::Ref<CSSNumericValue> y, GC::Ptr<CSSNumericValue> z)
-{
- // The CSSTranslate(x, y, z) constructor must, when invoked, perform the following steps:
-
- // 1. If x or y don’t match <length-percentage>, throw a TypeError.
- if (!x->type().matches_length_percentage({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSTranslate x component doesn't match <length-percentage>"_utf16 };
-
- if (!y->type().matches_length_percentage({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSTranslate y component doesn't match <length-percentage>"_utf16 };
-
- // 2. If z was passed, but doesn’t match <length>, throw a TypeError.
- if (z && !z->type().matches_length({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSTranslate z component doesn't match <length>"_utf16 };
-
- // 3. Let this be a new CSSTranslate object, with its x and y internal slots set to x and y.
- // 4. If z was passed, set this’s z internal slot to z, and set this’s is2D internal slot to false.
- // 5. If z was not passed, set this’s z internal slot to a new unit value of (0, "px"), and set this’s is2D internal slot to true.
- Is2D is_2d = Is2D::No;
- if (!z) {
- is_2d = Is2D::Yes;
- z = CSSUnitValue::create(0, "px"_utf16_fly_string);
- }
- auto this_ = CSSTranslate::create(is_2d, x, y, z.as_nonnull());
-
- // 6. Return this.
- return this_;
-}
-
-CSSTranslate::CSSTranslate(Is2D is_2d, GC::Ref<CSSNumericValue> x, GC::Ref<CSSNumericValue> y, GC::Ref<CSSNumericValue> z)
- : CSSTransformComponent(is_2d)
- , m_x(x)
- , m_y(y)
- , m_z(z)
-{
-}
-
-CSSTranslate::~CSSTranslate() = default;
-
-void CSSTranslate::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_x);
- visitor.visit(m_y);
- visitor.visit(m_z);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-csstranslate
-WebIDL::ExceptionOr<Utf16String> CSSTranslate::to_string() const
-{
- // 1. Let s initially be the empty string.
- Utf16StringBuilder builder;
-
- // 2. If this’s is2D internal slot is false:
- if (!is_2d()) {
- // 1. Append "translate3d(" to s.
- builder.append_ascii("translate3d("sv);
-
- // 2. Serialize this’s x internal slot, and append it to s.
- m_x->serialize(builder, {});
-
- // 3. Append ", " to s.
- builder.append_ascii(", "sv);
-
- // 4. Serialize this’s y internal slot, and append it to s.
- m_y->serialize(builder, {});
-
- // 5. Append ", " to s.
- builder.append_ascii(", "sv);
-
- // 6. Serialize this’s z internal slot, and append it to s.
- m_z->serialize(builder, {});
-
- // 7. Append ")" to s, and return s.
- builder.append_ascii(')');
- return builder.to_string();
- }
- // 3. Otherwise:
- else {
- // 1. Append "translate(" to s.
- builder.append_ascii("translate("sv);
-
- // 2. Serialize this’s x internal slot, and append it to s.
- m_x->serialize(builder, {});
-
- // 3. Append ", " to s.
- builder.append_ascii(", "sv);
-
- // 4. Serialize this’s y internal slot, and append it to s.
- m_y->serialize(builder, {});
-
- // 5. Append ")" to s, and return s.
- builder.append_ascii(')');
- return builder.to_string();
- }
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-csstransformcomponent-tomatrix
-WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> CSSTranslate::to_matrix() const
-{
- // 1. Let matrix be a new DOMMatrix object, initialized to this’s equivalent 4x4 transform matrix, as defined in
- // CSS Transforms 1 § 12. Mathematical Description of Transform Functions, and with its is2D internal slot set
- // to the same value as this’s is2D internal slot.
- // NOTE: Recall that the is2D flag affects what transform, and thus what equivalent matrix, a
- // CSSTransformComponent represents.
- // As the entries of such a matrix are defined relative to the px unit, if any <length>s in this involved in
- // generating the matrix are not compatible units with px (such as relative lengths or percentages), throw a
- // TypeError.
- auto x = TRY(m_x->to("px"_utf16_fly_string))->value();
- auto y = TRY(m_y->to("px"_utf16_fly_string))->value();
-
- double z = 0;
- if (!is_2d())
- z = TRY(m_z->to("px"_utf16_fly_string))->value();
-
- return Geometry::DOMMatrix::create(Gfx::translation_matrix(Vector3<double> { x, y, z }), is_2d());
-}
-
-WebIDL::ExceptionOr<void> CSSTranslate::set_x(GC::Ref<CSSNumericValue> x)
-{
- // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
- // WPT expects this to throw for invalid values.
- if (!x->type().matches_length_percentage({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSTranslate x component doesn't match <length-percentage>"_utf16 };
- m_x = x;
- return {};
-}
-
-WebIDL::ExceptionOr<void> CSSTranslate::set_y(GC::Ref<CSSNumericValue> y)
-{
- // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
- // WPT expects this to throw for invalid values.
- if (!y->type().matches_length_percentage({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSTranslate y component doesn't match <length-percentage>"_utf16 };
- m_y = y;
- return {};
-}
-
-WebIDL::ExceptionOr<void> CSSTranslate::set_z(GC::Ref<CSSNumericValue> z)
-{
- // AD-HOC: Not specced. https://github.com/w3c/css-houdini-drafts/issues/1153
- // WPT expects this to throw for invalid values.
- if (!z->type().matches_length({}))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "CSSTranslate z component doesn't match <length>"_utf16 };
- m_z = z;
- return {};
-}
-
-WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> CSSTranslate::create_style_value(PropertyNameAndID const& property) const
-{
- if (is_2d()) {
- return TransformationStyleValue::create(property.id(), TransformFunction::Translate,
- {
- TRY(m_x->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- TRY(m_y->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- });
- }
-
- return TransformationStyleValue::create(property.id(), TransformFunction::Translate3d,
- {
- TRY(m_x->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- TRY(m_y->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- TRY(m_z->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::No)),
- });
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSTranslate.h b/Libraries/LibWeb/CSS/CSSTranslate.h
deleted file mode 100644
index 0c29455a53f..00000000000
--- a/Libraries/LibWeb/CSS/CSSTranslate.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSTransformComponent.h>
-
-namespace Web::CSS {
-
-// https://drafts.css-houdini.org/css-typed-om-1/#csstranslate
-class CSSTranslate final : public CSSTransformComponent {
- WEB_WRAPPABLE(CSSTranslate, CSSTransformComponent);
- GC_DECLARE_ALLOCATOR(CSSTranslate);
-
-public:
- static constexpr size_t x_offset() { return offsetof(CSSTranslate, m_x); }
- static constexpr size_t y_offset() { return offsetof(CSSTranslate, m_y); }
- static constexpr size_t z_offset() { return offsetof(CSSTranslate, m_z); }
- [[nodiscard]] static GC::Ref<CSSTranslate> create(Is2D, GC::Ref<CSSNumericValue> x, GC::Ref<CSSNumericValue> y, GC::Ref<CSSNumericValue> z);
- static WebIDL::ExceptionOr<GC::Ref<CSSTranslate>> create_for_constructor(GC::Ref<CSSNumericValue> x, GC::Ref<CSSNumericValue> y, GC::Ptr<CSSNumericValue> z = {});
-
- virtual ~CSSTranslate() override;
-
- virtual WebIDL::ExceptionOr<Utf16String> to_string() const override;
-
- virtual WebIDL::ExceptionOr<GC::Ref<Geometry::DOMMatrix>> to_matrix() const override;
-
- GC::Ref<CSSNumericValue> x() const { return m_x; }
- GC::Ref<CSSNumericValue> y() const { return m_y; }
- GC::Ref<CSSNumericValue> z() const { return m_z; }
- WebIDL::ExceptionOr<void> set_x(GC::Ref<CSSNumericValue> value);
- WebIDL::ExceptionOr<void> set_y(GC::Ref<CSSNumericValue> value);
- WebIDL::ExceptionOr<void> set_z(GC::Ref<CSSNumericValue> value);
-
- virtual WebIDL::ExceptionOr<NonnullRefPtr<TransformationStyleValue const>> create_style_value(PropertyNameAndID const&) const override;
-
-private:
- explicit CSSTranslate(Is2D, GC::Ref<CSSNumericValue> x, GC::Ref<CSSNumericValue> y, GC::Ref<CSSNumericValue> z);
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ref<CSSNumericValue> m_x;
- GC::Ref<CSSNumericValue> m_y;
- GC::Ref<CSSNumericValue> m_z;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSTranslate.idl b/Libraries/LibWeb/CSS/CSSTranslate.idl
index 217c46f28d6..7c4d352beb9 100644
--- a/Libraries/LibWeb/CSS/CSSTranslate.idl
+++ b/Libraries/LibWeb/CSS/CSSTranslate.idl
@@ -1,8 +1,8 @@
// https://drafts.css-houdini.org/css-typed-om-1/#csstranslate
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSTranslate : CSSTransformComponent {
constructor(CSSNumericValue x, CSSNumericValue y, optional CSSNumericValue z);
- [DirectGetter] attribute CSSNumericValue x;
- [DirectGetter] attribute CSSNumericValue y;
- [DirectGetter] attribute CSSNumericValue z;
+ attribute CSSNumericValue x;
+ attribute CSSNumericValue y;
+ attribute CSSNumericValue z;
};
diff --git a/Libraries/LibWeb/CSS/CSSUnitValue.cpp b/Libraries/LibWeb/CSS/CSSUnitValue.cpp
deleted file mode 100644
index 3f270c63b17..00000000000
--- a/Libraries/LibWeb/CSS/CSSUnitValue.cpp
+++ /dev/null
@@ -1,476 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSUnitValue.h"
-#include <LibGC/Heap.h>
-#include <LibWeb/CSS/PropertyNameAndID.h>
-#include <LibWeb/CSS/Serialize.h>
-#include <LibWeb/CSS/StyleValues/AngleStyleValue.h>
-#include <LibWeb/CSS/StyleValues/CalculatedStyleValue.h>
-#include <LibWeb/CSS/StyleValues/FlexStyleValue.h>
-#include <LibWeb/CSS/StyleValues/FrequencyStyleValue.h>
-#include <LibWeb/CSS/StyleValues/IntegerStyleValue.h>
-#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
-#include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
-#include <LibWeb/CSS/StyleValues/OpacityValueStyleValue.h>
-#include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
-#include <LibWeb/CSS/StyleValues/ResolutionStyleValue.h>
-#include <LibWeb/CSS/StyleValues/TimeStyleValue.h>
-#include <LibWeb/CSS/Units.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSUnitValue);
-
-GC::Ref<CSSUnitValue> CSSUnitValue::create(double value, Utf16FlyString unit)
-{
- // The type of a CSSUnitValue is the result of creating a type from its unit internal slot.
- // https://drafts.css-houdini.org/css-typed-om-1/#type-of-a-cssunitvalue
- auto numeric_type = NumericType::create_from_unit(unit);
- return GC::Heap::the().allocate<CSSUnitValue>(value, move(unit), numeric_type.release_value());
-}
-
-GC::Ptr<CSSUnitValue> CSSUnitValue::create_from_sum_value_item(SumValueItem const& item)
-{
- // 1. If item has more than one entry in its unit map, return failure.
- if (item.unit_map.size() > 1)
- return {};
-
- // 2. If item has no entries in its unit map, return a new CSSUnitValue whose unit internal slot is set to
- // "number", and whose value internal slot is set to item’s value.
- if (item.unit_map.is_empty())
- return CSSUnitValue::create(item.value, "number"_utf16_fly_string);
-
- // 3. Otherwise, item has a single entry in its unit map. If that entry’s value is anything other than 1, return
- // failure.
- auto single_type_entry = item.unit_map.begin();
- if (single_type_entry->value != 1)
- return {};
-
- // 4. Otherwise, return a new CSSUnitValue whose unit internal slot is set to that entry’s key, and whose value
- // internal slot is set to item’s value.
- return CSSUnitValue::create(item.value, single_type_entry->key);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssunitvalue-cssunitvalue
-WebIDL::ExceptionOr<GC::Ref<CSSUnitValue>> CSSUnitValue::construct_impl(double value, Utf16String unit)
-{
- // 1. If creating a type from unit returns failure, throw a TypeError and abort this algorithm.
- auto fly_unit = Utf16FlyString { move(unit) };
- auto numeric_type = NumericType::create_from_unit(fly_unit);
- if (!numeric_type.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create CSSUnitValue with unrecognized unit"_utf16 };
-
- // 2. Return a new CSSUnitValue with its value internal slot set to value and its unit set to unit.
- return GC::Heap::the().allocate<CSSUnitValue>(value, move(fly_unit), numeric_type.release_value());
-}
-
-CSSUnitValue::CSSUnitValue(double value, Utf16FlyString unit, NumericType type)
- : CSSNumericValue(move(type))
- , m_value(value)
- // AD-HOC: WPT expects the unit to be lowercase but this doesn't seem to be specified anywhere.
- , m_unit(unit.to_ascii_lowercase())
-{
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssunitvalue-value
-void CSSUnitValue::set_value(double value)
-{
- // AD-HOC: No definition: https://github.com/w3c/css-houdini-drafts/issues/1146
- m_value = value;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssunitvalue
-void CSSUnitValue::serialize_unit_value(Utf16StringBuilder& builder, Optional<double> minimum, Optional<double> maximum) const
-{
- // To serialize a CSSUnitValue this, with optional arguments minimum, a numeric value, and maximum, a numeric value:
-
- // 1. Let value and unit be this‘s value and unit internal slots.
-
- // 4. If minimum was passed and this is less than minimum, or if maximum was passed and this is greater than
- // maximum, or either minimum and/or maximum were passed and the relative size of this and minimum/maximum can’t
- // be determined with the available information at this time, prepend "calc(" to s, then append ")" to s.
- // NB: This step is done first to avoid prepending to the StringBuilder.
- // FIXME: "or either minimum and/or maximum were passed and the relative size of this and minimum/maximum can't be determined with the available information at this time"
- bool needs_calc_wrapper = (minimum.has_value() && m_value < minimum.value())
- || (maximum.has_value() && m_value > maximum.value());
-
- if (needs_calc_wrapper)
- builder.append_ascii("calc("sv);
-
- // 2. Set s to the result of serializing a <number> from value, per CSSOM §6.7.2 Serializing CSS Values.
- serialize_a_number(builder, m_value);
-
- // 3. If unit is:
- // -> "number"
- if (m_unit == "number"_utf16_fly_string) {
- // Do nothing.
- }
- // -> "percent"
- else if (m_unit == "percent"_utf16_fly_string) {
- // Append "%" to s.
- builder.append_ascii('%');
- }
- // -> anything else
- else {
- // Append unit to s.
- builder.append(m_unit.to_ascii_lowercase());
- }
-
- if (needs_calc_wrapper)
- builder.append_ascii(')');
-
- // 5. Return s.
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#convert-a-cssunitvalue
-GC::Ptr<CSSUnitValue> CSSUnitValue::converted_to_unit(Utf16FlyString const& unit) const
-{
- // 1. Let old unit be the value of this’s unit internal slot, and old value be the value of this’s value internal
- // slot.
- auto old_unit = m_unit;
- auto old_value = m_value;
-
- // 2. If old unit and unit are not compatible units, return failure.
- double ratio = 1.0;
- // NB: If the units are identical, they're always compatible. That also covers cases of `number` and `percent`
- // which aren't actually units.
- if (old_unit != unit) {
- auto old_dimension_type = dimension_for_unit(old_unit);
- auto new_dimension_type = dimension_for_unit(unit);
- if (!new_dimension_type.has_value() || old_dimension_type != new_dimension_type)
- return nullptr;
-
- switch (*new_dimension_type) {
- case DimensionType::Angle: {
- auto from = string_to_angle_unit(old_unit).release_value();
- auto to = string_to_angle_unit(unit).release_value();
- if (!units_are_compatible(from, to))
- return nullptr;
- ratio = ratio_between_units(from, to);
- break;
- }
- case DimensionType::Flex: {
- auto from = string_to_flex_unit(old_unit).release_value();
- auto to = string_to_flex_unit(unit).release_value();
- if (!units_are_compatible(from, to))
- return nullptr;
- ratio = ratio_between_units(from, to);
- break;
- }
- case DimensionType::Frequency: {
- auto from = string_to_frequency_unit(old_unit).release_value();
- auto to = string_to_frequency_unit(unit).release_value();
- if (!units_are_compatible(from, to))
- return nullptr;
- ratio = ratio_between_units(from, to);
- break;
- }
- case DimensionType::Length: {
- auto from = string_to_length_unit(old_unit).release_value();
- auto to = string_to_length_unit(unit).release_value();
- if (!units_are_compatible(from, to))
- return nullptr;
- ratio = ratio_between_units(from, to);
- break;
- }
- case DimensionType::Resolution: {
- auto from = string_to_resolution_unit(old_unit).release_value();
- auto to = string_to_resolution_unit(unit).release_value();
- if (!units_are_compatible(from, to))
- return nullptr;
- ratio = ratio_between_units(from, to);
- break;
- }
- case DimensionType::Time: {
- auto from = string_to_time_unit(old_unit).release_value();
- auto to = string_to_time_unit(unit).release_value();
- if (!units_are_compatible(from, to))
- return nullptr;
- ratio = ratio_between_units(from, to);
- break;
- }
- }
- }
-
- return CSSUnitValue::create(old_value * ratio, unit);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#equal-numeric-value
-bool CSSUnitValue::is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const
-{
- // NB: Only steps 1 and 2 are relevant.
- // 1. If value1 and value2 are not members of the same interface, return false.
- auto* other_unit_value = as_if<CSSUnitValue>(*other);
- if (!other_unit_value)
- return false;
-
- // 2. If value1 and value2 are both CSSUnitValues, return true if they have equal unit and value internal slots,
- // or false otherwise.
- return m_unit == other_unit_value->m_unit
- && m_value == other_unit_value->m_value;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-a-sum-value
-Optional<SumValue> CSSUnitValue::create_a_sum_value() const
-{
- // 1. Let unit be the value of this’s unit internal slot, and value be the value of this’s value internal slot.
- auto unit = m_unit;
- auto value = m_value;
-
- // 2. If unit is a member of a set of compatible units, and is not the set’s canonical unit, multiply value
- // by the conversion ratio between unit and the canonical unit, and change unit to the canonical unit.
- if (auto dimension_type = dimension_for_unit(unit); dimension_type.has_value()) {
- switch (*dimension_type) {
- case DimensionType::Angle: {
- auto angle_unit = string_to_angle_unit(unit).release_value();
- auto canonical_unit = canonical_angle_unit();
- if (angle_unit != canonical_unit && units_are_compatible(angle_unit, canonical_unit)) {
- value *= ratio_between_units(angle_unit, canonical_unit);
- unit = CSS::to_string(canonical_unit);
- }
- break;
- }
- case DimensionType::Flex: {
- auto flex_unit = string_to_flex_unit(unit).release_value();
- auto canonical_unit = canonical_flex_unit();
- if (flex_unit != canonical_unit && units_are_compatible(flex_unit, canonical_unit)) {
- value *= ratio_between_units(flex_unit, canonical_unit);
- unit = CSS::to_string(canonical_unit);
- }
- break;
- }
- case DimensionType::Frequency: {
- auto frequency_unit = string_to_frequency_unit(unit).release_value();
- auto canonical_unit = canonical_frequency_unit();
- if (frequency_unit != canonical_unit && units_are_compatible(frequency_unit, canonical_unit)) {
- value *= ratio_between_units(frequency_unit, canonical_unit);
- unit = CSS::to_string(canonical_unit);
- }
- break;
- }
- case DimensionType::Length: {
- auto length_unit = string_to_length_unit(unit).release_value();
- auto canonical_unit = canonical_length_unit();
- if (length_unit != canonical_unit && units_are_compatible(length_unit, canonical_unit)) {
- value *= ratio_between_units(length_unit, canonical_unit);
- unit = CSS::to_string(canonical_unit);
- }
- break;
- }
- case DimensionType::Resolution: {
- auto resolution_unit = string_to_resolution_unit(unit).release_value();
- auto canonical_unit = canonical_resolution_unit();
- if (resolution_unit != canonical_unit && units_are_compatible(resolution_unit, canonical_unit)) {
- value *= ratio_between_units(resolution_unit, canonical_unit);
- unit = CSS::to_string(canonical_unit);
- }
- break;
- }
- case DimensionType::Time: {
- auto time_unit = string_to_time_unit(unit).release_value();
- auto canonical_unit = canonical_time_unit();
- if (time_unit != canonical_unit && units_are_compatible(time_unit, canonical_unit)) {
- value *= ratio_between_units(time_unit, canonical_unit);
- unit = CSS::to_string(canonical_unit);
- }
- break;
- }
- }
- }
-
- // 3. If unit is "number", return «(value, «[ ]»)».
- if (unit == "number"_utf16_fly_string)
- return SumValue { SumValueItem { value, {} } };
-
- // 4. Otherwise, return «(value, «[unit → 1]»)».
- return SumValue { SumValueItem { value, { { unit, 1 } } } };
-}
-
-static Optional<CalcNodeRef::NumericValue> create_numeric_value(double value, Utf16FlyString const& unit)
-{
- if (unit == "number"_utf16_fly_string)
- return Number { Number::Type::Number, value };
-
- if (unit == "percent"_utf16_fly_string)
- return Percentage { value };
-
- if (auto dimension_type = dimension_for_unit(unit); dimension_type.has_value()) {
- switch (*dimension_type) {
- case DimensionType::Angle:
- return Angle { value, string_to_angle_unit(unit).release_value() };
- case DimensionType::Flex:
- return Flex { value, string_to_flex_unit(unit).release_value() };
- case DimensionType::Frequency:
- return Frequency { value, string_to_frequency_unit(unit).release_value() };
- case DimensionType::Length:
- return Length { value, string_to_length_unit(unit).release_value() };
- case DimensionType::Resolution:
- return Resolution { value, string_to_resolution_unit(unit).release_value() };
- case DimensionType::Time:
- return Time { value, string_to_time_unit(unit).release_value() };
- }
- }
-
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
-WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> CSSUnitValue::create_an_internal_representation(PropertyNameAndID const& property, PerformTypeCheck perform_type_check) const
-{
- // If value is a CSSStyleValue subclass,
- // If value does not match the grammar of a list-valued property iteration of property, throw a TypeError.
- //
- // If any component of property’s CSS grammar has a limited numeric range, and the corresponding part of value
- // is a CSSUnitValue that is outside of that range, replace that value with the result of wrapping it in a
- // fresh CSSMathSum whose values internal slot contains only that part of value.
- //
- // Return the value.
-
- auto wrap_in_math_sum = [this, &property](auto&& value) -> NonnullRefPtr<StyleValue const> {
- auto context = CalculationContext::for_property(property);
- Vector<CalcNodeRef> children;
- children.append(CalcNodeRef::numeric(value));
- auto math_sum_node = CalcNodeRef::sum(move(children));
- return CalculatedStyleValue::create(move(math_sum_node), NumericType::create_from_unit(m_unit).release_value(), context);
- };
-
- auto value = create_numeric_value(m_value, m_unit);
- if (!value.has_value()) {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Unrecognized unit."_utf16 };
- }
-
- if (perform_type_check == PerformTypeCheck::No) {
- return value->visit(
- [&](Number const& number) -> RefPtr<StyleValue const> {
- return NumberStyleValue::create(number.value());
- },
- [&](Percentage const& percentage) -> RefPtr<StyleValue const> {
- return PercentageStyleValue::create(percentage);
- },
- [&](Angle const& angle) -> RefPtr<StyleValue const> {
- return AngleStyleValue::create(angle);
- },
- [&](Flex const& flex) -> RefPtr<StyleValue const> {
- return FlexStyleValue::create(flex);
- },
- [&](Frequency const& frequency) -> RefPtr<StyleValue const> {
- return FrequencyStyleValue::create(frequency);
- },
- [&](Length const& length) -> RefPtr<StyleValue const> {
- return LengthStyleValue::create(length);
- },
- [&](Resolution const& resolution) -> RefPtr<StyleValue const> {
- return ResolutionStyleValue::create(resolution);
- },
- [&](Time const& time) -> RefPtr<StyleValue const> {
- return TimeStyleValue::create(time);
- })
- .release_nonnull();
- }
-
- auto style_value = value->visit(
- [&](Number const& number) -> RefPtr<StyleValue const> {
- // NB: Our parser represents an <opacity-value> as an opacity value that holds the number.
- if (property_accepts_type(property.id(), ValueType::OpacityValue))
- return OpacityValueStyleValue::create(NumberStyleValue::create(number.value()));
-
- // NB: Prefer <number> to <integer> when both are accepted.
- if (property_accepts_type(property.id(), ValueType::Number)) {
- if (property_accepts_number(property.id(), number.value()))
- return NumberStyleValue::create(number.value());
- return wrap_in_math_sum(number);
- }
-
- if (property_accepts_type(property.id(), ValueType::Integer)) {
- auto integer = round_to_nearest_integer(number.value());
- // NB: A number that is not an integer does not match <integer>, so it's wrapped in a CSSMathSum, like
- // a value outside of the accepted range. It then gets rounded when computed.
- if (static_cast<double>(integer) != number.value())
- return wrap_in_math_sum(number);
- if (property_accepts_integer(property.id(), integer))
- return IntegerStyleValue::create(integer);
- return wrap_in_math_sum(number);
- }
-
- return {};
- },
- [&](Percentage const& percentage) -> RefPtr<StyleValue const> {
- // NB: Our parser represents an <opacity-value> as an opacity value that holds the percentage.
- if (property_accepts_type(property.id(), ValueType::OpacityValue))
- return OpacityValueStyleValue::create(PercentageStyleValue::create(percentage));
-
- if (property_accepts_type(property.id(), ValueType::Percentage)) {
- if (property_accepts_percentage(property.id(), percentage))
- return PercentageStyleValue::create(percentage);
- return wrap_in_math_sum(percentage);
- }
-
- return {};
- },
- [&](Angle const& angle) -> RefPtr<StyleValue const> {
- if (property_accepts_type(property.id(), ValueType::Angle)) {
- if (property_accepts_angle(property.id(), angle))
- return AngleStyleValue::create(angle);
- return wrap_in_math_sum(angle);
- }
- return {};
- },
- [&](Flex const& flex) -> RefPtr<StyleValue const> {
- // NB: Out-of-range flex values cannot be deferred in a calculation.
- if (property_accepts_type(property.id(), ValueType::Flex) && property_accepts_flex(property.id(), flex))
- return FlexStyleValue::create(flex);
- return {};
- },
- [&](Frequency const& frequency) -> RefPtr<StyleValue const> {
- if (property_accepts_type(property.id(), ValueType::Frequency)) {
- if (property_accepts_frequency(property.id(), frequency))
- return FrequencyStyleValue::create(frequency);
- return wrap_in_math_sum(frequency);
- }
- return {};
- },
- [&](Length const& length) -> RefPtr<StyleValue const> {
- if (property_accepts_type(property.id(), ValueType::Length)) {
- if (property_accepts_length(property.id(), length))
- return LengthStyleValue::create(length);
- return wrap_in_math_sum(length);
- }
- return {};
- },
- [&](Resolution const& resolution) -> RefPtr<StyleValue const> {
- if (property_accepts_type(property.id(), ValueType::Resolution)) {
- if (property_accepts_resolution(property.id(), resolution))
- return ResolutionStyleValue::create(resolution);
- return wrap_in_math_sum(resolution);
- }
- return {};
- },
- [&](Time const& time) -> RefPtr<StyleValue const> {
- if (property_accepts_type(property.id(), ValueType::Time)) {
- if (property_accepts_time(property.id(), time))
- return TimeStyleValue::create(time);
- return wrap_in_math_sum(time);
- }
- return {};
- });
-
- if (!style_value)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Property does not accept values of this type."_utf16 };
- return style_value.release_nonnull();
-}
-
-WebIDL::ExceptionOr<CalcNodeRef> CSSUnitValue::create_calculation_node(CalculationContext const&) const
-{
- auto value = create_numeric_value(m_value, m_unit);
- if (!value.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Unable to create calculation node."_utf16 };
-
- return CalcNodeRef::numeric(value.release_value());
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSUnitValue.h b/Libraries/LibWeb/CSS/CSSUnitValue.h
index a3315d4df9d..0d735671adc 100644
--- a/Libraries/LibWeb/CSS/CSSUnitValue.h
+++ b/Libraries/LibWeb/CSS/CSSUnitValue.h
@@ -6,43 +6,20 @@
#pragma once
-#include <AK/Utf16FlyString.h>
+#include <LibWeb/Bindings/CSSUnitValue.h>
#include <LibWeb/CSS/CSSNumericValue.h>
namespace Web::CSS {
// https://drafts.css-houdini.org/css-typed-om-1/#cssunitvalue
-class CSSUnitValue final : public CSSNumericValue {
- WEB_WRAPPABLE(CSSUnitValue, CSSNumericValue);
- GC_DECLARE_ALLOCATOR(CSSUnitValue);
+class WEB_API CSSUnitValue final : public CSSNumericValue {
+ WEB_RUST_INTERFACE(CSSUnitValue, css_unit_value)
public:
- [[nodiscard]] static GC::Ref<CSSUnitValue> create(double value, Utf16FlyString unit);
- static GC::Ptr<CSSUnitValue> create_from_sum_value_item(SumValueItem const&);
- static WebIDL::ExceptionOr<GC::Ref<CSSUnitValue>> construct_impl(double value, Utf16String unit);
+ static GC::Ref<CSSUnitValue> create(double value, Utf16FlyString const& unit);
- virtual ~CSSUnitValue() override = default;
-
- double value() const { return m_value; }
- void set_value(double value);
-
- Utf16FlyString const& unit() const { return m_unit; }
-
- void serialize_unit_value(Utf16StringBuilder&, Optional<double> minimum, Optional<double> maximum) const;
-
- GC::Ptr<CSSUnitValue> converted_to_unit(Utf16FlyString const& unit) const;
-
- virtual bool is_equal_numeric_value(GC::Ref<CSSNumericValue> other) const override;
- virtual Optional<SumValue> create_a_sum_value() const override;
-
- virtual WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> create_an_internal_representation(PropertyNameAndID const&, PerformTypeCheck) const override;
- virtual WebIDL::ExceptionOr<CalcNodeRef> create_calculation_node(CalculationContext const&) const override;
-
-private:
- explicit CSSUnitValue(double value, Utf16FlyString unit, NumericType type);
-
- double m_value;
- Utf16FlyString m_unit;
+ double value() const;
+ Utf16FlyString unit() const;
};
}
diff --git a/Libraries/LibWeb/CSS/CSSUnitValue.idl b/Libraries/LibWeb/CSS/CSSUnitValue.idl
index 4203e601de9..d84f999b2e1 100644
--- a/Libraries/LibWeb/CSS/CSSUnitValue.idl
+++ b/Libraries/LibWeb/CSS/CSSUnitValue.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssunitvalue
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSUnitValue : CSSNumericValue {
constructor(double value, USVString unit);
attribute double value;
diff --git a/Libraries/LibWeb/CSS/CSSUnparsedValue.cpp b/Libraries/LibWeb/CSS/CSSUnparsedValue.cpp
deleted file mode 100644
index 48518a45105..00000000000
--- a/Libraries/LibWeb/CSS/CSSUnparsedValue.cpp
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSUnparsedValue.h"
-#include <AK/Utf16StringBuilder.h>
-#include <LibWeb/Bindings/CSSUnparsedValue.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/CSS/CSSVariableReferenceValue.h>
-#include <LibWeb/CSS/Parser/Parser.h>
-#include <LibWeb/CSS/StyleValues/UnresolvedStyleValue.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSUnparsedValue);
-
-GC::Ref<CSSUnparsedValue> CSSUnparsedValue::create(ReadonlySpan<CSSUnparsedSegment> value)
-{
- // NB: Convert our Span into a Vector of Refs.
- GC::ConservativeVector<CSSUnparsedSegment> converted_value;
- for (auto const& variant : value) {
- variant.visit(
- [&](GC::Ref<CSSVariableReferenceValue> it) { converted_value.append(it); },
- [&](Utf16String const& it) { converted_value.append(it); });
- }
-
- return GC::Heap::the().allocate<CSSUnparsedValue>(move(converted_value));
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssunparsedvalue-cssunparsedvalue
-WebIDL::ExceptionOr<GC::Ref<CSSUnparsedValue>> CSSUnparsedValue::create_for_constructor(ReadonlySpan<CSSUnparsedSegment> value)
-{
- // AD-HOC: There is no spec for this, see https://github.com/w3c/css-houdini-drafts/issues/1146
-
- return CSSUnparsedValue::create(move(value));
-}
-
-CSSUnparsedValue::CSSUnparsedValue(ReadonlySpan<CSSUnparsedSegment> value)
- : CSSStyleValue()
- , m_tokens(move(value))
-{
-}
-
-CSSUnparsedValue::~CSSUnparsedValue() = default;
-
-void CSSUnparsedValue::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- for (auto const& token : m_tokens) {
- if (auto* variable = token.get_pointer<GC::Ref<CSSVariableReferenceValue>>()) {
- visitor.visit(*variable);
- }
- }
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssunparsedvalue-length
-WebIDL::UnsignedLong CSSUnparsedValue::length() const
-{
- // The length attribute returns the size of the [[tokens]] internal slot.
- return m_tokens.size();
-}
-
-Optional<CSSUnparsedSegment> CSSUnparsedValue::token_at(size_t index) const
-{
- if (index >= m_tokens.size())
- return {};
- auto value = m_tokens[index];
- return value;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#ref-for-dfn-set-the-value-of-an-existing-indexed-property
-WebIDL::ExceptionOr<void> CSSUnparsedValue::set_value_of_existing_indexed_property(u32 n, CSSUnparsedSegment value)
-{
- // To set the value of an existing indexed property of a CSSUnparsedValue this, an index n, and a value new value,
- // let tokens be this’s [[tokens]] internal slot, and set tokens[n] to new value.
- m_tokens[n] = move(value);
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#ref-for-dfn-set-the-value-of-a-new-indexed-property
-WebIDL::ExceptionOr<void> CSSUnparsedValue::set_value_of_new_indexed_property(u32 n, CSSUnparsedSegment value)
-{
- // To set the value of a new indexed property of a CSSUnparsedValue this, an index n, and a value new value,
- // let tokens be this’s [[tokens]] internal slot. If n is not equal to the size of tokens, throw a RangeError.
- // Otherwise, append new value to tokens.
- if (n != m_tokens.size())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Index out of range"_utf16 };
-
- m_tokens.append(move(value));
- return {};
-}
-
-bool CSSUnparsedValue::contains_unparsed_value(CSSUnparsedValue const& needle) const
-{
- for (auto const& unparsed_segment : m_tokens) {
- if (auto const* variable_reference = unparsed_segment.get_pointer<GC::Ref<CSSVariableReferenceValue>>()) {
- auto fallback = (*variable_reference)->fallback();
- if (!fallback)
- continue;
- if (fallback.ptr() == &needle)
- return true;
- if (fallback->contains_unparsed_value(needle))
- return true;
- }
- }
- return false;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssunparsedvalue
-WebIDL::ExceptionOr<Utf16String> CSSUnparsedValue::to_string() const
-{
- // AD-HOC: It's possible for one of the m_tokens to contain this in its fallback slot, or a similar situation with
- // more levels of nesting. To avoid crashing, do a scan for that first and return the empty string.
- // Spec issue: https://github.com/w3c/css-houdini-drafts/issues/1158
- if (contains_unparsed_value(*this))
- return Utf16String {};
-
- // To serialize a CSSUnparsedValue this:
- // 1. Let s initially be the empty string.
- Utf16StringBuilder s;
-
- // 2. For each item in this’s [[tokens]] internal slot:
- for (auto const& item : m_tokens) {
- // FIXME: In order to match the expected test behaviour, this should insert comments, with the same rules as
- // serialize_a_series_of_component_values(). See https://github.com/w3c/css-houdini-drafts/issues/1148
- TRY(item.visit(
- // 1. If item is a USVString, append it to s.
- [&](Utf16String const& string) -> WebIDL::ExceptionOr<void> {
- s.append(string);
- return {};
- },
- // 2. Otherwise, item is a CSSVariableReferenceValue. Serialize it, then append the result to s.
- [&](GC::Ref<CSSVariableReferenceValue> const& variable) -> WebIDL::ExceptionOr<void> {
- s.append(TRY(variable->to_string()));
- return {};
- }));
- }
-
- // 3. Return s.
- return s.to_string();
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
-WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> CSSUnparsedValue::create_an_internal_representation(PropertyNameAndID const&, PerformTypeCheck) const
-{
- // If value is a CSSStyleValue subclass,
- // If value does not match the grammar of a list-valued property iteration of property, throw a TypeError.
- //
- // If any component of property’s CSS grammar has a limited numeric range, and the corresponding part of value
- // is a CSSUnitValue that is outside of that range, replace that value with the result of wrapping it in a
- // fresh CSSMathSum whose values internal slot contains only that part of value.
- //
- // Return the value.
-
- // https://drafts.css-houdini.org/css-typed-om-1/#cssstylevalue-match-a-grammar
- // A CSSUnparsedValue matches any grammar.
-
- // NB: CSSUnparsedValue stores a list of strings, each of which may contain any number of tokens. So the simplest
- // way to convert it to ComponentValues is to serialize and then parse it.
- auto utf16_string = TRY(to_string());
- Parser::SubstitutionFunctionsPresence substitution_presence;
-
- if (Parser::Parser::collect_arbitrary_substitution_function_presence(utf16_string, substitution_presence).is_error())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid arbitrary substitution function syntax"_utf16 };
-
- return UnresolvedStyleValue::create(move(utf16_string), substitution_presence, UnresolvedStyleValue::SourceTextMode::Preserve);
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSUnparsedValue.h b/Libraries/LibWeb/CSS/CSSUnparsedValue.h
deleted file mode 100644
index c23d6d6c9f5..00000000000
--- a/Libraries/LibWeb/CSS/CSSUnparsedValue.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/CSS/CSSStyleValue.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::CSS {
-
-using CSSUnparsedSegment = Variant<Utf16String, GC::Ref<CSSVariableReferenceValue>>;
-
-// https://drafts.css-houdini.org/css-typed-om-1/#cssunparsedvalue
-class CSSUnparsedValue final : public CSSStyleValue {
- WEB_WRAPPABLE(CSSUnparsedValue, CSSStyleValue);
- GC_DECLARE_ALLOCATOR(CSSUnparsedValue);
-
-public:
- [[nodiscard]] static GC::Ref<CSSUnparsedValue> create(ReadonlySpan<CSSUnparsedSegment>);
- static WebIDL::ExceptionOr<GC::Ref<CSSUnparsedValue>> create_for_constructor(ReadonlySpan<CSSUnparsedSegment>);
-
- virtual ~CSSUnparsedValue() override;
-
- WebIDL::UnsignedLong length() const;
- Optional<CSSUnparsedSegment> token_at(size_t index) const;
- WebIDL::ExceptionOr<void> set_value_of_existing_indexed_property(u32, CSSUnparsedSegment);
- WebIDL::ExceptionOr<void> set_value_of_new_indexed_property(u32, CSSUnparsedSegment);
-
- virtual WebIDL::ExceptionOr<Utf16String> to_string() const override;
- virtual WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> create_an_internal_representation(PropertyNameAndID const&, PerformTypeCheck) const override;
-
-private:
- explicit CSSUnparsedValue(ReadonlySpan<CSSUnparsedSegment>);
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- bool contains_unparsed_value(CSSUnparsedValue const&) const;
-
- // https://drafts.css-houdini.org/css-typed-om-1/#dom-cssunparsedvalue-tokens-slot
- // They have a [[tokens]] internal slot, which is a list of USVStrings and CSSVariableReferenceValue objects.
- // This list is the object’s values to iterate over.
- Vector<CSSUnparsedSegment> m_tokens;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSUnparsedValue.idl b/Libraries/LibWeb/CSS/CSSUnparsedValue.idl
index 8500b5f19ab..c3c46f90225 100644
--- a/Libraries/LibWeb/CSS/CSSUnparsedValue.idl
+++ b/Libraries/LibWeb/CSS/CSSUnparsedValue.idl
@@ -1,5 +1,5 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssunparsedvalue
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSUnparsedValue : CSSStyleValue {
constructor(sequence<CSSUnparsedSegment> members);
iterable<CSSUnparsedSegment>;
diff --git a/Libraries/LibWeb/CSS/CSSVariableReferenceValue.cpp b/Libraries/LibWeb/CSS/CSSVariableReferenceValue.cpp
deleted file mode 100644
index ece5fb212d2..00000000000
--- a/Libraries/LibWeb/CSS/CSSVariableReferenceValue.cpp
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include "CSSVariableReferenceValue.h"
-#include <AK/Utf16StringBuilder.h>
-#include <LibWeb/Bindings/CSSVariableReferenceValue.h>
-#include <LibWeb/Bindings/Intrinsics.h>
-#include <LibWeb/CSS/CSSUnparsedValue.h>
-#include <LibWeb/CSS/PropertyName.h>
-#include <LibWeb/HTML/CustomElements/CustomElementName.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::CSS {
-
-GC_DEFINE_ALLOCATOR(CSSVariableReferenceValue);
-GC::Ref<CSSVariableReferenceValue> CSSVariableReferenceValue::create(Utf16FlyString variable, GC::Ptr<CSSUnparsedValue> fallback)
-{
- return GC::Heap::the().allocate<CSSVariableReferenceValue>(move(variable), move(fallback));
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssvariablereferencevalue-cssvariablereferencevalue
-WebIDL::ExceptionOr<GC::Ref<CSSVariableReferenceValue>> CSSVariableReferenceValue::construct_impl(Utf16String variable, GC::Ptr<CSSUnparsedValue> fallback)
-{
- // The CSSVariableReferenceValue(variable, fallback) constructor must, when called, perform the following steps:
- // 1. If variable is not a custom property name string, throw a TypeError.
- if (!is_a_custom_property_name_string(variable))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("'{}' is not a valid CSS custom property name", variable) };
-
- // 2. Return a new CSSVariableReferenceValue with its variable internal slot set to variable and its fallback internal slot set to fallback.
- return CSSVariableReferenceValue::create(Utf16FlyString { move(variable) }, move(fallback));
-}
-
-CSSVariableReferenceValue::CSSVariableReferenceValue(Utf16FlyString variable, GC::Ptr<CSSUnparsedValue> fallback)
- : Bindings::GCAllocatedWrappable()
- , m_variable(move(variable))
- , m_fallback(move(fallback))
-{
-}
-
-CSSVariableReferenceValue::~CSSVariableReferenceValue() = default;
-
-void CSSVariableReferenceValue::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_fallback);
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssvariablereferencevalue-variable
-Utf16FlyString const& CSSVariableReferenceValue::variable() const
-{
- // The getter for the variable attribute of a CSSVariableReferenceValue this must return its variable internal slot.
- return m_variable;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssvariablereferencevalue-variable
-WebIDL::ExceptionOr<void> CSSVariableReferenceValue::set_variable(Utf16String variable)
-{
- // The variable attribute of a CSSVariableReferenceValue this must, on setting a variable variable, perform the following steps:
- // 1. If variable is not a custom property name string, throw a TypeError.
- if (!is_a_custom_property_name_string(variable))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("'{}' is not a valid CSS custom property name", variable) };
-
- // 2. Otherwise, set this’s variable internal slot to variable.
- m_variable = Utf16FlyString { move(variable) };
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssvariablereferencevalue-fallback
-GC::Ptr<CSSUnparsedValue> CSSVariableReferenceValue::fallback() const
-{
- // AD-HOC: No spec algorithm, see https://github.com/w3c/css-houdini-drafts/issues/1146#issuecomment-3188550133
- return m_fallback;
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssvariablereferencevalue-fallback
-WebIDL::ExceptionOr<void> CSSVariableReferenceValue::set_fallback(GC::Ptr<CSSUnparsedValue> fallback)
-{
- // AD-HOC: No spec algorithm, see https://github.com/w3c/css-houdini-drafts/issues/1146#issuecomment-3188550133
- m_fallback = move(fallback);
- return {};
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#serialize-a-cssvariablereferencevalue
-WebIDL::ExceptionOr<Utf16String> CSSVariableReferenceValue::to_string() const
-{
- // To serialize a CSSVariableReferenceValue this:
- // 1. Let s initially be "var(".
- Utf16StringBuilder s;
- s.append_ascii("var("sv);
-
- // 2. Append this’s variable internal slot to s.
- s.append(m_variable.to_utf16_string());
-
- // 3. If this’s fallback internal slot is not null, append ", " to s, then serialize the fallback internal slot and append it to s.
- if (m_fallback) {
- // AD-HOC: Tested behaviour requires we append "," without the space. https://github.com/w3c/css-houdini-drafts/issues/1148
- s.append_ascii(',');
- s.append(TRY(m_fallback->to_string()));
- }
-
- // 4. Append ")" to s and return s.
- s.append_ascii(')');
- return s.to_string();
-}
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSVariableReferenceValue.h b/Libraries/LibWeb/CSS/CSSVariableReferenceValue.h
deleted file mode 100644
index cc31393d18d..00000000000
--- a/Libraries/LibWeb/CSS/CSSVariableReferenceValue.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2025, Sam Atkins <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16FlyString.h>
-#include <AK/Utf16String.h>
-#include <LibWeb/Bindings/Wrappable.h>
-
-namespace Web::CSS {
-
-class CSSVariableReferenceValue : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(CSSVariableReferenceValue, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(CSSVariableReferenceValue);
-
-public:
- [[nodiscard]] static GC::Ref<CSSVariableReferenceValue> create(Utf16FlyString variable, GC::Ptr<CSSUnparsedValue> fallback = nullptr);
- static WebIDL::ExceptionOr<GC::Ref<CSSVariableReferenceValue>> construct_impl(Utf16String variable, GC::Ptr<CSSUnparsedValue> fallback);
-
- virtual ~CSSVariableReferenceValue() override;
-
- Utf16FlyString const& variable() const;
- WebIDL::ExceptionOr<void> set_variable(Utf16String);
-
- GC::Ptr<CSSUnparsedValue> fallback() const;
- WebIDL::ExceptionOr<void> set_fallback(GC::Ptr<CSSUnparsedValue>);
- static constexpr size_t fallback_offset() { return offsetof(CSSVariableReferenceValue, m_fallback); }
-
- WebIDL::ExceptionOr<Utf16String> to_string() const;
-
-private:
- CSSVariableReferenceValue(Utf16FlyString variable, GC::Ptr<CSSUnparsedValue> fallback);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- Utf16FlyString m_variable;
- GC::Ptr<CSSUnparsedValue> m_fallback;
-};
-
-}
diff --git a/Libraries/LibWeb/CSS/CSSVariableReferenceValue.idl b/Libraries/LibWeb/CSS/CSSVariableReferenceValue.idl
index 1d86c1d3d98..470b24d8651 100644
--- a/Libraries/LibWeb/CSS/CSSVariableReferenceValue.idl
+++ b/Libraries/LibWeb/CSS/CSSVariableReferenceValue.idl
@@ -1,7 +1,7 @@
// https://drafts.css-houdini.org/css-typed-om-1/#cssvariablereferencevalue
-[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet)]
+[Exposed=(Window, Worker, PaintWorklet, LayoutWorklet), ImplementedIn=Rust]
interface CSSVariableReferenceValue {
constructor(USVString variable, optional CSSUnparsedValue? fallback = null);
attribute USVString variable;
- [DirectGetter] readonly attribute CSSUnparsedValue? fallback;
+ readonly attribute CSSUnparsedValue? fallback;
};
diff --git a/Libraries/LibWeb/CSS/NumericType.cpp b/Libraries/LibWeb/CSS/NumericType.cpp
index f8ad01e295a..f246e8e46ba 100644
--- a/Libraries/LibWeb/CSS/NumericType.cpp
+++ b/Libraries/LibWeb/CSS/NumericType.cpp
@@ -5,34 +5,11 @@
*/
#include "NumericType.h"
-#include <LibWeb/CSS/Angle.h>
-#include <LibWeb/CSS/Flex.h>
-#include <LibWeb/CSS/Frequency.h>
-#include <LibWeb/CSS/Length.h>
-#include <LibWeb/CSS/Resolution.h>
-#include <LibWeb/CSS/Time.h>
#include <LibWeb/CSS/ValueType.h>
#include <LibWeb/StyleValueRustFFI.h>
namespace Web::CSS {
-// https://drafts.css-houdini.org/css-typed-om-1/#product-of-two-unit-maps
-UnitMap product_of_two_unit_maps(UnitMap const& units1, UnitMap const& units2)
-{
- // 1. Let result be a copy of units1.
- auto result = units1;
-
- // 2. For each unit → power in units2:
- for (auto const& [unit, power] : units2) {
- // 1. If result[unit] exists, increment result[unit] by power.
- // 2. Otherwise, set result[unit] to power.
- result.ensure(unit) += power;
- }
-
- // 3. Return result.
- return result;
-}
-
Optional<NumericType::BaseType> NumericType::base_type_from_value_type(ValueType value_type)
{
switch (value_type) {
@@ -56,112 +33,6 @@ Optional<NumericType::BaseType> NumericType::base_type_from_value_type(ValueType
}
}
-// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue-create-a-type
-Optional<NumericType> NumericType::create_from_unit(Utf16FlyString const& unit)
-{
- // To create a type from a string unit, follow the appropriate branch of the following:
-
- // unit is "number"
- if (unit == "number"_utf16_fly_string) {
- // Return «[ ]» (empty map)
- return NumericType {};
- }
-
- // unit is "percent"
- if (unit == "percent"_utf16_fly_string) {
- // Return «[ "percent" → 1 ]»
- return NumericType { BaseType::Percent, 1 };
- }
-
- if (auto dimension = dimension_for_unit(unit); dimension.has_value()) {
- switch (*dimension) {
- // unit is a <length> unit
- case DimensionType::Length:
- // Return «[ "length" → 1 ]»
- return NumericType { BaseType::Length, 1 };
-
- // unit is an <angle> unit
- case DimensionType::Angle:
- // Return «[ "angle" → 1 ]»
- return NumericType { BaseType::Angle, 1 };
-
- // unit is a <time> unit
- case DimensionType::Time:
- // Return «[ "time" → 1 ]»
- return NumericType { BaseType::Time, 1 };
-
- // unit is a <frequency> unit
- case DimensionType::Frequency:
- // Return «[ "frequency" → 1 ]»
- return NumericType { BaseType::Frequency, 1 };
-
- // unit is a <resolution> unit
- case DimensionType::Resolution:
- // Return «[ "resolution" → 1 ]»
- return NumericType { BaseType::Resolution, 1 };
-
- // unit is a <flex> unit
- case DimensionType::Flex:
- // Return «[ "flex" → 1 ]»
- return NumericType { BaseType::Flex, 1 };
- }
- }
-
- // anything else
- // Return failure.
- return {};
-
- // In all cases, the associated percent hint is null.
-}
-
-// https://drafts.css-houdini.org/css-typed-om-1/#create-a-type-from-a-unit-map
-Optional<NumericType> NumericType::create_from_unit_map(UnitMap const& unit_map)
-{
- // To create a type from a unit map unit map:
-
- // 1. Let types be an initially empty list.
- Vector<NumericType> types;
-
- // 2. For each unit → power in unit map:
- for (auto const& [unit, power] : unit_map) {
- // 1. Let type be the result of creating a type from unit.
- auto type = create_from_unit(unit).release_value();
-
- // 2. Set type’s sole value to power.
- auto sole_type = [&type] {
- for (auto i = 0; i < to_underlying(BaseType::__Count); ++i) {
- auto base_type = static_cast<BaseType>(i);
- if (type.exponent(base_type).has_value())
- return base_type;
- }
- VERIFY_NOT_REACHED();
- }();
- type.set_exponent(sole_type, power);
-
- // 3. Append type to types.
- types.empend(type);
- }
-
- // 3. Return the result of multiplying all the items of types.
- // NB: Multiplying no types at all, as for the empty unit map of a plain number, results in an empty type.
- if (types.is_empty())
- return NumericType {};
- auto result = types.first();
- bool first = true;
- for (auto const& type : types) {
- if (first) {
- first = false;
- continue;
- }
- if (auto multiplied_type = result.multiplied_by(type); multiplied_type.has_value()) {
- result = multiplied_type.release_value();
- } else {
- return {};
- }
- }
- return result;
-}
-
static StyleValueFFI::FfiNumericType to_ffi_numeric_type(NumericType const& type)
{
StyleValueFFI::FfiNumericType result {};
@@ -177,7 +48,7 @@ static StyleValueFFI::FfiNumericType to_ffi_numeric_type(NumericType const& type
return result;
}
-static Optional<NumericType> from_ffi_numeric_type(StyleValueFFI::FfiNumericType const& type)
+Optional<NumericType> NumericType::from_ffi(StyleValueFFI::FfiNumericType const& type)
{
if (!type.valid)
return {};
@@ -191,28 +62,6 @@ static Optional<NumericType> from_ffi_numeric_type(StyleValueFFI::FfiNumericType
return result;
}
-static Optional<NumericType> operate(StyleValueFFI::FfiNumericTypeOperation operation, NumericType const& first, NumericType const* second = nullptr)
-{
- auto ffi_first = to_ffi_numeric_type(first);
- auto ffi_second = second ? to_ffi_numeric_type(*second) : StyleValueFFI::FfiNumericType {};
- return from_ffi_numeric_type(StyleValueFFI::rust_numeric_type_operate(operation, &ffi_first, second ? &ffi_second : nullptr));
-}
-
-Optional<NumericType> NumericType::added_to(NumericType const& other) const
-{
- return operate(StyleValueFFI::FfiNumericTypeOperation::Add, *this, &other);
-}
-
-Optional<NumericType> NumericType::multiplied_by(NumericType const& other) const
-{
- return operate(StyleValueFFI::FfiNumericTypeOperation::Multiply, *this, &other);
-}
-
-NumericType NumericType::inverted() const
-{
- return operate(StyleValueFFI::FfiNumericTypeOperation::Invert, *this).release_value();
-}
-
static bool matches(StyleValueFFI::FfiNumericTypeMatch match_kind, NumericType const& type, NumericType::BaseType base_type, Optional<ValueType> percentages_resolve_as)
{
auto ffi_type = to_ffi_numeric_type(type);
diff --git a/Libraries/LibWeb/CSS/NumericType.h b/Libraries/LibWeb/CSS/NumericType.h
index f3a0e388993..979ae770044 100644
--- a/Libraries/LibWeb/CSS/NumericType.h
+++ b/Libraries/LibWeb/CSS/NumericType.h
@@ -14,14 +14,19 @@
#include <AK/Utf16FlyString.h>
#include <LibWeb/Forward.h>
-namespace Web::CSS {
+namespace Web::CSS::StyleValueFFI {
+
+struct FfiNumericType;
-using UnitMap = HashMap<Utf16FlyString, i32>;
-UnitMap product_of_two_unit_maps(UnitMap const&, UnitMap const&);
+}
+
+namespace Web::CSS {
// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue-type
class WEB_API NumericType {
public:
+ static Optional<NumericType> from_ffi(StyleValueFFI::FfiNumericType const&);
+
enum class BaseType {
Length,
Angle,
@@ -34,18 +39,12 @@ public:
};
static Optional<BaseType> base_type_from_value_type(ValueType);
- static Optional<NumericType> create_from_unit(Utf16FlyString const& unit);
- static Optional<NumericType> create_from_unit_map(UnitMap const&);
NumericType() = default;
NumericType(BaseType type, i32 power)
{
set_exponent(type, power);
}
- Optional<NumericType> added_to(NumericType const& other) const;
- Optional<NumericType> multiplied_by(NumericType const& other) const;
- NumericType inverted() const;
-
bool matches_angle(Optional<ValueType> percentages_resolve_as) const { return matches_dimension(BaseType::Angle, percentages_resolve_as); }
bool matches_flex(Optional<ValueType> percentages_resolve_as) const { return matches_dimension(BaseType::Flex, percentages_resolve_as); }
bool matches_frequency(Optional<ValueType> percentages_resolve_as) const { return matches_dimension(BaseType::Frequency, percentages_resolve_as); }
diff --git a/Libraries/LibWeb/CSS/StylePropertyMap.cpp b/Libraries/LibWeb/CSS/StylePropertyMap.cpp
index 0ebec80c949..e9c55465ccd 100644
--- a/Libraries/LibWeb/CSS/StylePropertyMap.cpp
+++ b/Libraries/LibWeb/CSS/StylePropertyMap.cpp
@@ -9,8 +9,6 @@
#include <LibWeb/CSS/CSSNumericValue.h>
#include <LibWeb/CSS/CSSStyleDeclaration.h>
#include <LibWeb/CSS/CSSStyleValue.h>
-#include <LibWeb/CSS/CSSUnparsedValue.h>
-#include <LibWeb/CSS/CSSVariableReferenceValue.h>
#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/PropertyName.h>
#include <LibWeb/CSS/PropertyNameAndID.h>
@@ -54,7 +52,7 @@ static bool any_have_non_matching_associated_property(Utf16FlyString const& prop
}
// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
-static WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> create_an_internal_representation(JS::VM& vm, PropertyNameAndID const& property, Variant<GC::Ref<CSSStyleValue>, Utf16String> const& value)
+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(
@@ -62,7 +60,7 @@ static WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> create_an_internal_r
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() && !is<CSSUnparsedValue>(*css_style_value) && !internal_representation->is_css_wide_keyword())
+ 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;
},
@@ -71,9 +69,9 @@ static WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> create_an_internal_r
// 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(vm, property.name(), css_text, CSSStyleValue::ParseMultiple::No));
+ 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.get<GC::Ref<CSSStyleValue>>()->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::Yes);
+ return result->create_an_internal_representation(property, CSSStyleValue::PerformTypeCheck::Yes);
}));
if (auto const* css_style_value = value.get_pointer<GC::Ref<CSSStyleValue>>();
@@ -196,7 +194,7 @@ WebIDL::ExceptionOr<void> StylePropertyMap::set(Utf16FlyString property_name, Re
// 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(vm(), property.value(), value));
+ 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)));
@@ -336,7 +334,7 @@ WebIDL::ExceptionOr<void> StylePropertyMap::append(Utf16FlyString property_name,
// 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(vm(), property.value(), value));
+ 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 };
diff --git a/Libraries/LibWeb/CSS/StylePropertyMapReadOnly.cpp b/Libraries/LibWeb/CSS/StylePropertyMapReadOnly.cpp
index 5e73c35eb7b..2a53ad613ff 100644
--- a/Libraries/LibWeb/CSS/StylePropertyMapReadOnly.cpp
+++ b/Libraries/LibWeb/CSS/StylePropertyMapReadOnly.cpp
@@ -76,8 +76,8 @@ static GC::Ref<CSSStyleValue> reify_property_value(StyleValue const& value, Prop
// 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 value.default_reify(property.name());
- return value.reify(property.name());
+ return CSSStyleValue::create(property.name(), value);
+ return CSSStyleValue::reify(value, property.name());
}
// https://drafts.css-houdini.org/css-typed-om-1/#dom-stylepropertymapreadonly-get
diff --git a/Libraries/LibWeb/CSS/StyleValues/AbstractImageStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/AbstractImageStyleValue.cpp
index 5f9b26a6d9c..49675013bf8 100644
--- a/Libraries/LibWeb/CSS/StyleValues/AbstractImageStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/AbstractImageStyleValue.cpp
@@ -5,7 +5,6 @@
*/
#include "AbstractImageStyleValue.h"
-#include <LibWeb/CSS/CSSImageValue.h>
#include <LibWeb/CSS/StyleValues/ImageSetStyleValue.h>
#include <LibWeb/CSS/StyleValues/ImageStyleValue.h>
#include <LibWeb/HTML/DecodedImageData.h>
@@ -13,13 +12,6 @@
namespace Web::CSS {
-// https://drafts.css-houdini.org/css-typed-om-1/#reify-stylevalue
-GC::Ref<CSSStyleValue> AbstractImageStyleValue::reify(Utf16FlyString const&) const
-{
- // AD-HOC: There's no spec description of how to reify as a CSSImageValue.
- return CSSImageValue::create(*this);
-}
-
void AbstractImageStyleValue::load_any_resources(Layout::NodeWithStyle const& layout_node)
{
load_any_resources(const_cast<DOM::Document&>(layout_node.document()));
diff --git a/Libraries/LibWeb/CSS/StyleValues/AbstractImageStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/AbstractImageStyleValue.h
index 584dd540aad..274c687c9c3 100644
--- a/Libraries/LibWeb/CSS/StyleValues/AbstractImageStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/AbstractImageStyleValue.h
@@ -31,8 +31,6 @@ public:
virtual Optional<Painting::ImagePaint> image_paint(Painting::ImagePaintRequest const&) const;
ImageStyleValue const* selected_image_style_value() const;
-
- GC::Ref<CSSStyleValue> reify(Utf16FlyString const& associated_property) const;
};
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/CalcNodeRef.h b/Libraries/LibWeb/CSS/StyleValues/CalcNodeRef.h
index 75cf83daace..fdbc1526365 100644
--- a/Libraries/LibWeb/CSS/StyleValues/CalcNodeRef.h
+++ b/Libraries/LibWeb/CSS/StyleValues/CalcNodeRef.h
@@ -9,7 +9,6 @@
#include <AK/Noncopyable.h>
#include <AK/Optional.h>
#include <AK/StdLibExtras.h>
-#include <AK/Vector.h>
#include <LibWeb/CSS/Enums.h>
#include <LibWeb/CSS/Keyword.h>
#include <LibWeb/CSS/NumericType.h>
@@ -26,8 +25,6 @@ class CalcNodeRef {
AK_MAKE_NONCOPYABLE(CalcNodeRef);
public:
- using NumericValue = CalculatedStyleValue::NumericValue;
-
CalcNodeRef(CalcNodeRef&& other)
: m_node(exchange(other.m_node, nullptr))
{
@@ -56,18 +53,6 @@ public:
// simplification entry points.
static CalcNodeRef adopt(StyleValueFFI::CalcNode const* node) { return CalcNodeRef { node }; }
- static CalcNodeRef numeric(NumericValue const&);
-
- static CalcNodeRef sum(Vector<CalcNodeRef>);
- static CalcNodeRef product(Vector<CalcNodeRef>);
- static CalcNodeRef min(Vector<CalcNodeRef>);
- static CalcNodeRef max(Vector<CalcNodeRef>);
-
- static CalcNodeRef negate(CalcNodeRef);
- static CalcNodeRef invert(CalcNodeRef);
-
- static CalcNodeRef clamp(CalcNodeRef minimum, CalcNodeRef center, CalcNodeRef maximum);
-
// https://drafts.csswg.org/css-values-4/#determine-the-type-of-a-calculation
// The type of the calculation this node roots, determined by the Rust
// core; nothing when the tree does not type-check.
diff --git a/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp
index 280b1bd0309..8a8b76c9af7 100644
--- a/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.cpp
@@ -9,15 +9,6 @@
#include "CalculatedStyleValue.h"
#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/CSS/CSSMathClamp.h>
-#include <LibWeb/CSS/CSSMathInvert.h>
-#include <LibWeb/CSS/CSSMathMax.h>
-#include <LibWeb/CSS/CSSMathMin.h>
-#include <LibWeb/CSS/CSSMathNegate.h>
-#include <LibWeb/CSS/CSSMathProduct.h>
-#include <LibWeb/CSS/CSSMathSum.h>
-#include <LibWeb/CSS/CSSNumericArray.h>
-#include <LibWeb/CSS/CSSUnitValue.h>
#include <LibWeb/CSS/Enums.h>
#include <LibWeb/CSS/Percentage.h>
#include <LibWeb/CSS/PropertyID.h>
@@ -103,12 +94,17 @@ CalculationContext CalculatedStyleValue::calculation_context() const
}
CalculationContext CalculationContext::for_property(PropertyNameAndID const& property)
+{
+ return for_property(property.id());
+}
+
+CalculationContext CalculationContext::for_property(PropertyID property_id)
{
// FIXME: Handle registered custom properties, which may limit which types they accept.
return {
- .percentages_resolve_as = property_resolves_percentages_relative_to(property.id()),
- .resolve_numbers_as_integers = property_accepts_type(property.id(), ValueType::Integer),
- .accepted_ranges_by_type = property_accepted_ranges_by_value_type(property.id()),
+ .percentages_resolve_as = property_resolves_percentages_relative_to(property_id),
+ .resolve_numbers_as_integers = property_accepts_type(property_id, ValueType::Integer),
+ .accepted_ranges_by_type = property_accepted_ranges_by_value_type(property_id),
};
}
@@ -288,175 +284,6 @@ bool CalculatedStyleValue::contains_percentage() const
return StyleValueFFI::rust_calc_node_contains_percentage(m_value->calculated._0->rust_calculation.node);
}
-// https://drafts.css-houdini.org/css-typed-om-1/#reify-a-math-expression
-static GC::Ptr<CSSNumericValue> reify_rust_calculation(StyleValueFFI::StyleValueData const* calculated_data)
-{
- struct Reification {
- StyleValueFFI::FfiCalcReification description;
- ~Reification() { StyleValueFFI::rust_calc_reification_release(description.storage); }
- } reification { StyleValueFFI::rust_calc_describe_for_typed_om(calculated_data) };
- if (reification.description.node_count == 0)
- return nullptr;
-
- auto nodes = ReadonlySpan<StyleValueFFI::FfiCalcReificationNode> { reification.description.nodes, reification.description.node_count };
- auto child_indices = ReadonlySpan<size_t> { reification.description.children, reification.description.child_count };
- GC::RootVector<GC::Ref<CSSNumericValue>> reified_nodes;
- reified_nodes.ensure_capacity(nodes.size());
- for (auto const& node : nodes) {
- auto numeric_type = from_ffi_numeric_type(node.numeric_type).release_value();
- VERIFY(node.child_start + node.child_count <= child_indices.size());
- auto children = child_indices.slice(node.child_start, node.child_count);
- auto child = [&](size_t index) -> GC::Ref<CSSNumericValue> {
- VERIFY(index < children.size());
- VERIFY(children[index] < reified_nodes.size());
- return reified_nodes[children[index]];
- };
-
- // NB: The reified objects get the types that their constructors would give them, computed from their
- // reified children. The internal calculation's type may differ, for example by carrying a percent hint
- // from the property that it belongs to.
- auto combined_type_of_children = [&](auto combine) {
- Optional<NumericType> type;
- for (auto index : children) {
- VERIFY(index < reified_nodes.size());
- auto const& child_type = reified_nodes[index]->type();
- type = type.has_value() ? combine(*type, child_type) : child_type;
- if (!type.has_value())
- return numeric_type;
- }
- return type.value_or(numeric_type);
- };
- auto added_types_of_children = [&]() {
- return combined_type_of_children([](NumericType const& a, NumericType const& b) { return a.added_to(b); });
- };
- auto multiplied_types_of_children = [&]() {
- return combined_type_of_children([](NumericType const& a, NumericType const& b) { return a.multiplied_by(b); });
- };
- auto reify_children = [&]() {
- GC::RootVector<GC::Ref<CSSNumericValue>> result;
- result.ensure_capacity(children.size());
- for (auto index : children) {
- VERIFY(index < reified_nodes.size());
- result.append(reified_nodes[index]);
- }
- return CSSNumericArray::create(move(result));
- };
-
- switch (node.kind) {
- case 0:
- switch (node.numeric_kind) {
- case 0:
- reified_nodes.append(CSSUnitValue::create(node.value, "number"_utf16_fly_string));
- break;
- case 1:
- reified_nodes.append(CSSUnitValue::create(node.value, Angle { node.value, static_cast<AngleUnit>(node.unit) }.unit_name()));
- break;
- case 2:
- reified_nodes.append(CSSUnitValue::create(node.value, Flex { node.value, static_cast<FlexUnit>(node.unit) }.unit_name()));
- break;
- case 3:
- reified_nodes.append(CSSUnitValue::create(node.value, Frequency { node.value, static_cast<FrequencyUnit>(node.unit) }.unit_name()));
- break;
- case 4:
- reified_nodes.append(CSSUnitValue::create(node.value, Length { node.value, static_cast<LengthUnit>(node.unit) }.unit_name()));
- break;
- case 5:
- reified_nodes.append(CSSUnitValue::create(node.value, "percent"_utf16_fly_string));
- break;
- case 6:
- reified_nodes.append(CSSUnitValue::create(node.value, Resolution { node.value, static_cast<ResolutionUnit>(node.unit) }.unit_name()));
- break;
- case 7:
- reified_nodes.append(CSSUnitValue::create(node.value, Time { node.value, static_cast<TimeUnit>(node.unit) }.unit_name()));
- break;
- default:
- VERIFY_NOT_REACHED();
- }
- break;
- case 2:
- reified_nodes.append(CSSMathSum::create(added_types_of_children(), reify_children()));
- break;
- case 3:
- reified_nodes.append(CSSMathProduct::create(multiplied_types_of_children(), reify_children()));
- break;
- case 4:
- VERIFY(children.size() == 1);
- reified_nodes.append(CSSMathNegate::create(child(0)->type(), child(0)));
- break;
- case 5:
- VERIFY(children.size() == 1);
- reified_nodes.append(CSSMathInvert::create(child(0)->type().inverted(), child(0)));
- break;
- case 6:
- reified_nodes.append(CSSMathMin::create(added_types_of_children(), reify_children()));
- break;
- case 7:
- reified_nodes.append(CSSMathMax::create(added_types_of_children(), reify_children()));
- break;
- case 8:
- VERIFY(children.size() == 3);
- reified_nodes.append(CSSMathClamp::create(added_types_of_children(), child(0), child(1), child(2)));
- break;
- default:
- VERIFY_NOT_REACHED();
- }
- }
- return reified_nodes.last();
-}
-
-GC::Ref<CSSStyleValue> CalculatedStyleValue::reify(Utf16FlyString const& associated_property) const
-{
- // NB: This spec algorithm is incomplete and assumes we do not already have a calculation tree.
- // Rust describes the existing tree in one batch instead.
- if (auto reified = reify_rust_calculation(m_value.operator->()))
- return *reified;
- // Some math functions are not reifiable yet. If we contain one, we have to fall back to CSSStyleValue.
- // https://github.com/w3c/css-houdini-drafts/issues/1090
- return default_reify(associated_property);
-}
-
-CalcNodeRef CalcNodeRef::numeric(NumericValue const& value)
-{
- return adopt(value.visit(
- [](Number const& number) { return StyleValueFFI::rust_calc_node_create_numeric_dimension(0, number.value(), to_underlying(number.type())); },
- [](Angle const& angle) { return StyleValueFFI::rust_calc_node_create_numeric_dimension(1, angle.raw_value(), to_underlying(angle.unit())); },
- [](Flex const& flex) { return StyleValueFFI::rust_calc_node_create_numeric_dimension(2, flex.raw_value(), to_underlying(flex.unit())); },
- [](Frequency const& frequency) { return StyleValueFFI::rust_calc_node_create_numeric_dimension(3, frequency.raw_value(), to_underlying(frequency.unit())); },
- [](Length const& length) { return StyleValueFFI::rust_calc_node_create_numeric_dimension(4, length.raw_value(), to_underlying(length.unit())); },
- [](Percentage const& percentage) { return StyleValueFFI::rust_calc_node_create_numeric_dimension(5, percentage.value(), 0); },
- [](Resolution const& resolution) { return StyleValueFFI::rust_calc_node_create_numeric_dimension(6, resolution.raw_value(), to_underlying(resolution.unit())); },
- [](Time const& time) { return StyleValueFFI::rust_calc_node_create_numeric_dimension(7, time.raw_value(), to_underlying(time.unit())); }));
-}
-
-static CalcNodeRef make_variadic_node(u8 kind, Vector<CalcNodeRef> children)
-{
- Vector<StyleValueFFI::CalcNode const*> handles;
- handles.ensure_capacity(children.size());
- for (auto& child : children)
- handles.unchecked_append(child.release());
- return CalcNodeRef::adopt(StyleValueFFI::rust_calc_node_create_variadic(kind, handles.data(), handles.size()));
-}
-
-CalcNodeRef CalcNodeRef::sum(Vector<CalcNodeRef> children) { return make_variadic_node(0, move(children)); }
-CalcNodeRef CalcNodeRef::product(Vector<CalcNodeRef> children) { return make_variadic_node(1, move(children)); }
-CalcNodeRef CalcNodeRef::min(Vector<CalcNodeRef> children) { return make_variadic_node(2, move(children)); }
-CalcNodeRef CalcNodeRef::max(Vector<CalcNodeRef> children) { return make_variadic_node(3, move(children)); }
-
-static CalcNodeRef make_unary_node(u8 kind, CalcNodeRef child)
-{
- return CalcNodeRef::adopt(StyleValueFFI::rust_calc_node_create_unary(kind, child.release()));
-}
-
-CalcNodeRef CalcNodeRef::negate(CalcNodeRef child) { return make_unary_node(0, move(child)); }
-CalcNodeRef CalcNodeRef::invert(CalcNodeRef child) { return make_unary_node(1, move(child)); }
-
-CalcNodeRef CalcNodeRef::clamp(CalcNodeRef minimum, CalcNodeRef center, CalcNodeRef maximum)
-{
- auto const* minimum_handle = minimum.release();
- auto const* center_handle = center.release();
- return adopt(StyleValueFFI::rust_calc_node_create_clamp(minimum_handle, center_handle, maximum.release()));
-}
-
Optional<NumericType> CalcNodeRef::determine_type(CalculationContext const& context) const
{
auto resolve_as_base = context.percentages_resolve_as.has_value()
diff --git a/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.h
index dd754a24e03..14e986d6b16 100644
--- a/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/CalculatedStyleValue.h
@@ -34,6 +34,7 @@ struct CalculationContext {
NumericRangesByValueType accepted_ranges_by_type {};
static CalculationContext for_property(PropertyNameAndID const&);
+ static CalculationContext for_property(PropertyID);
};
class CalculatedStyleValue : public StyleValue {
@@ -64,8 +65,6 @@ public:
bool contains_percentage() const;
- GC::Ref<CSSStyleValue> reify(Utf16FlyString const& associated_property) const;
-
private:
friend class StyleValue;
diff --git a/Libraries/LibWeb/CSS/StyleValues/CustomIdentStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/CustomIdentStyleValue.cpp
index 7093ca01077..ee7a0e377c0 100644
--- a/Libraries/LibWeb/CSS/StyleValues/CustomIdentStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/CustomIdentStyleValue.cpp
@@ -5,15 +5,7 @@
*/
#include "CustomIdentStyleValue.h"
-#include <LibWeb/CSS/CSSKeywordValue.h>
namespace Web::CSS {
-// https://drafts.css-houdini.org/css-typed-om-1/#reify-ident
-GC::Ref<CSSStyleValue> CustomIdentStyleValue::reify(Utf16FlyString const&) const
-{
- // 1. Return a new CSSKeywordValue with its value internal slot set to the serialization of ident.
- return CSSKeywordValue::create(custom_ident());
-}
-
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/CustomIdentStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/CustomIdentStyleValue.h
index d3a24618a14..612560420b2 100644
--- a/Libraries/LibWeb/CSS/StyleValues/CustomIdentStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/CustomIdentStyleValue.h
@@ -22,7 +22,6 @@ public:
virtual ~CustomIdentStyleValue() override = default;
Utf16FlyString custom_ident() const { return css_string_from_rust(&m_value->custom_ident.custom_ident); }
- GC::Ref<CSSStyleValue> reify(Utf16FlyString const&) const;
private:
friend class StyleValue;
diff --git a/Libraries/LibWeb/CSS/StyleValues/DimensionStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/DimensionStyleValue.cpp
index c2ee7804b5d..2e7acdc0f2f 100644
--- a/Libraries/LibWeb/CSS/StyleValues/DimensionStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/DimensionStyleValue.cpp
@@ -5,22 +5,7 @@
*/
#include "DimensionStyleValue.h"
-#include <LibWeb/CSS/CSSUnitValue.h>
namespace Web::CSS {
-// https://drafts.css-houdini.org/css-typed-om-1/#reify-a-numeric-value
-GC::Ref<CSSStyleValue> DimensionStyleValue::reify(Utf16FlyString const&) const
-{
- // NB: Steps 1 and 2 don't apply here.
- // 3. Return a new CSSUnitValue with its value internal slot set to the numeric value of num, and its unit internal
- // slot set to "number" if num is a <number>, "percent" if num is a <percentage>, and num’s unit if num is a
- // <dimension>.
- // If the value being reified is a computed value, the unit used must be the appropriate canonical unit for the
- // value’s type, with the numeric value scaled accordingly.
- // FIXME: Reify computed value correctly. That sounds like it should work by computing the value properly before we
- // reach this point.
- return CSSUnitValue::create(raw_value(), unit_name());
-}
-
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/DimensionStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/DimensionStyleValue.h
index 3ec17eb2b5e..dad7e7e2c1a 100644
--- a/Libraries/LibWeb/CSS/StyleValues/DimensionStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/DimensionStyleValue.h
@@ -17,7 +17,6 @@ public:
virtual double raw_value() const = 0;
virtual Utf16FlyString unit_name() const = 0;
- GC::Ref<CSSStyleValue> reify(Utf16FlyString const& associated_property) const;
protected:
DimensionStyleValue(Type type, StyleValueFFI::StyleValueData const* value)
diff --git a/Libraries/LibWeb/CSS/StyleValues/DisplayStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/DisplayStyleValue.cpp
index b8d33042221..df2d7847a0c 100644
--- a/Libraries/LibWeb/CSS/StyleValues/DisplayStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/DisplayStyleValue.cpp
@@ -5,8 +5,6 @@
*/
#include "DisplayStyleValue.h"
-#include <LibWeb/CSS/CSSKeywordValue.h>
-#include <LibWeb/CSS/CSSStyleValue.h>
namespace Web::CSS {
@@ -15,12 +13,4 @@ ValueComparingNonnullRefPtr<DisplayStyleValue const> DisplayStyleValue::create(D
return adopt_ref(*new (nothrow) DisplayStyleValue(display));
}
-GC::Ref<CSSStyleValue> DisplayStyleValue::reify(Utf16FlyString const& associated_property) const
-{
- if (auto keyword = display().to_keyword(); keyword.has_value())
- return CSSKeywordValue::create(utf16_fly_string_from_keyword(keyword.value()));
-
- return CSSStyleValue::create(associated_property, *this);
-}
-
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/DisplayStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/DisplayStyleValue.h
index 72000a1e757..7608c3d7fa3 100644
--- a/Libraries/LibWeb/CSS/StyleValues/DisplayStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/DisplayStyleValue.h
@@ -19,8 +19,6 @@ public:
Display display() const { return bit_cast<Display>(m_value->display.raw); }
- GC::Ref<CSSStyleValue> reify(Utf16FlyString const& associated_property) const;
-
private:
friend class StyleValue;
diff --git a/Libraries/LibWeb/CSS/StyleValues/IntegerStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/IntegerStyleValue.cpp
index 48f9bf62dfb..24db2981ca0 100644
--- a/Libraries/LibWeb/CSS/StyleValues/IntegerStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/IntegerStyleValue.cpp
@@ -5,34 +5,9 @@
*/
#include "IntegerStyleValue.h"
-#include <LibWeb/CSS/CSSUnitValue.h>
#include <LibWeb/CSS/PropertyID.h>
#include <LibWeb/CSS/PropertyNameAndID.h>
namespace Web::CSS {
-// https://drafts.css-houdini.org/css-typed-om-1/#reify-a-numeric-value
-GC::Ref<CSSStyleValue> IntegerStyleValue::reify(Utf16FlyString const& associated_property) const
-{
- // NB: Step 1 doesn't apply here.
- // 2. If num is the unitless value 0 and num is a <dimension>, return a new CSSUnitValue with its value internal
- // slot set to 0, and its unit internal slot set to "px".
- if (integer() == 0 && associated_property.is_ascii()) {
- // NB: Determine whether the associated property expects 0 to be a <length>.
- // FIXME: Do this for registered custom properties.
- if (auto property_id = property_id_from_string(associated_property); property_id.has_value()
- && property_id != PropertyID::Custom
- && property_accepts_type(*property_id, ValueType::Length)) {
- return CSSUnitValue::create(0, "px"_utf16_fly_string);
- }
- }
-
- // 3. Return a new CSSUnitValue with its value internal slot set to the numeric value of num, and its unit internal
- // slot set to "number" if num is a <number>, "percent" if num is a <percentage>, and num’s unit if num is a
- // <dimension>.
- // If the value being reified is a computed value, the unit used must be the appropriate canonical unit for the
- // value’s type, with the numeric value scaled accordingly.
- return CSSUnitValue::create(integer(), "number"_utf16_fly_string);
-}
-
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/IntegerStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/IntegerStyleValue.h
index 29bcbd303f3..99066231ca6 100644
--- a/Libraries/LibWeb/CSS/StyleValues/IntegerStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/IntegerStyleValue.h
@@ -34,8 +34,6 @@ public:
i32 integer() const { return m_value->integer.value; }
- GC::Ref<CSSStyleValue> reify(Utf16FlyString const& associated_property) const;
-
private:
friend class StyleValue;
diff --git a/Libraries/LibWeb/CSS/StyleValues/KeywordStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/KeywordStyleValue.cpp
index 91fbee0ae7c..254bc6bfcd6 100644
--- a/Libraries/LibWeb/CSS/StyleValues/KeywordStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/KeywordStyleValue.cpp
@@ -8,7 +8,6 @@
*/
#include "KeywordStyleValue.h"
-#include <LibWeb/CSS/CSSKeywordValue.h>
#include <LibWeb/CSS/StyleValues/ColorStyleValue.h>
namespace Web::CSS {
@@ -72,11 +71,4 @@ bool KeywordStyleValue::has_color() const
return is_color(keyword());
}
-// https://drafts.css-houdini.org/css-typed-om-1/#reify-ident
-GC::Ref<CSSStyleValue> KeywordStyleValue::reify(Utf16FlyString const&) const
-{
- // 1. Return a new CSSKeywordValue with its value internal slot set to the serialization of ident.
- return CSSKeywordValue::create(utf16_fly_string_from_keyword(keyword()));
-}
-
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/KeywordStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/KeywordStyleValue.h
index 483150207d9..754118fe39d 100644
--- a/Libraries/LibWeb/CSS/StyleValues/KeywordStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/KeywordStyleValue.h
@@ -37,7 +37,6 @@ public:
static bool is_color(Keyword);
bool has_color() const;
- GC::Ref<CSSStyleValue> reify(Utf16FlyString const& associated_property) const;
private:
friend class StyleValue;
diff --git a/Libraries/LibWeb/CSS/StyleValues/NumberStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/NumberStyleValue.cpp
index b9ecf03bba6..e1b683527b6 100644
--- a/Libraries/LibWeb/CSS/StyleValues/NumberStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/NumberStyleValue.cpp
@@ -8,7 +8,6 @@
*/
#include "NumberStyleValue.h"
-#include <LibWeb/CSS/CSSUnitValue.h>
#include <LibWeb/CSS/PropertyID.h>
#include <LibWeb/CSS/PropertyNameAndID.h>
#include <LibWeb/CSS/Serialize.h>
@@ -16,30 +15,4 @@
namespace Web::CSS {
-// https://drafts.css-houdini.org/css-typed-om-1/#reify-a-numeric-value
-GC::Ref<CSSStyleValue> NumberStyleValue::reify(Utf16FlyString const& associated_property) const
-{
- // NB: Step 1 doesn't apply here.
- // 2. If num is the unitless value 0 and num is a <dimension>, return a new CSSUnitValue with its value internal
- // slot set to 0, and its unit internal slot set to "px".
- if (number() == 0 && associated_property.is_ascii()) {
- // NB: Determine whether the associated property expects 0 to be a <length>.
- // FIXME: Do this for registered custom properties.
- if (auto property_id = property_id_from_string(associated_property); property_id.has_value()
- && property_id != PropertyID::Custom
- && property_accepts_type(*property_id, ValueType::Length)
- && !property_accepts_type(*property_id, ValueType::Number)
- && !property_accepts_type(*property_id, ValueType::Integer)) {
- return CSSUnitValue::create(0, "px"_utf16_fly_string);
- }
- }
-
- // 3. Return a new CSSUnitValue with its value internal slot set to the numeric value of num, and its unit internal
- // slot set to "number" if num is a <number>, "percent" if num is a <percentage>, and num’s unit if num is a
- // <dimension>.
- // If the value being reified is a computed value, the unit used must be the appropriate canonical unit for the
- // value’s type, with the numeric value scaled accordingly.
- return CSSUnitValue::create(number(), "number"_utf16_fly_string);
-}
-
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/NumberStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/NumberStyleValue.h
index 46ca4331a95..85bcfd93bad 100644
--- a/Libraries/LibWeb/CSS/StyleValues/NumberStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/NumberStyleValue.h
@@ -33,8 +33,6 @@ public:
double number() const { return m_value->number.value; }
- GC::Ref<CSSStyleValue> reify(Utf16FlyString const& associated_property) const;
-
private:
friend class StyleValue;
diff --git a/Libraries/LibWeb/CSS/StyleValues/OpacityValueStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/OpacityValueStyleValue.cpp
index ddf0ec17658..137dbf7da99 100644
--- a/Libraries/LibWeb/CSS/StyleValues/OpacityValueStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/OpacityValueStyleValue.cpp
@@ -9,9 +9,4 @@
namespace Web::CSS {
-GC::Ref<CSSStyleValue> OpacityValueStyleValue::reify(Utf16FlyString const& associated_property) const
-{
- return value()->reify(associated_property);
-}
-
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/OpacityValueStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/OpacityValueStyleValue.h
index ef27d66ef98..509a57cf03a 100644
--- a/Libraries/LibWeb/CSS/StyleValues/OpacityValueStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/OpacityValueStyleValue.h
@@ -19,8 +19,6 @@ public:
}
virtual ~OpacityValueStyleValue() override = default;
- GC::Ref<CSSStyleValue> reify(Utf16FlyString const& associated_property) const;
-
private:
friend class StyleValue;
diff --git a/Libraries/LibWeb/CSS/StyleValues/StyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/StyleValue.cpp
index 04c72827e39..d31f95c6200 100644
--- a/Libraries/LibWeb/CSS/StyleValues/StyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/StyleValue.cpp
@@ -11,8 +11,6 @@
#include <AK/Utf16StringBuilder.h>
#include <LibGfx/Font/Font.h>
#include <LibGfx/Font/FontStyleMapping.h>
-#include <LibWeb/CSS/CSSKeywordValue.h>
-#include <LibWeb/CSS/CSSStyleValue.h>
#include <LibWeb/CSS/ComputedValues.h>
#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/StyleComputeFFI.h>
@@ -467,85 +465,6 @@ bool StyleValue::has_auto() const
return is_keyword() && as_keyword().keyword() == Keyword::Auto;
}
-// https://drafts.css-houdini.org/css-typed-om-1/#reify-as-a-cssstylevalue
-GC::Ref<CSSStyleValue> StyleValue::reify(Utf16FlyString const& associated_property) const
-{
- switch (type()) {
- case Type::ConicGradient:
- case Type::Image:
- case Type::ImageSet:
- case Type::LinearGradient:
- case Type::RadialGradient:
- return as_abstract_image().reify(associated_property);
- case Type::Angle:
- case Type::Flex:
- case Type::Frequency:
- case Type::Length:
- case Type::Percentage:
- case Type::Resolution:
- case Type::Time:
- return as_dimension().reify(associated_property);
- case Type::BackgroundSize:
- // NB: A background size whose height is `auto` serializes as just its width, so reify it as that width. For
- // example, the `auto` keyword is parsed as a size of `auto auto`.
- if (as_background_size().size_y()->has_auto())
- return as_background_size().size_x()->reify(associated_property);
- break;
- case Type::Calculated:
- return as_calculated().reify(associated_property);
- case Type::CustomIdent:
- return as_custom_ident().reify(associated_property);
- case Type::Display:
- return as_display().reify(associated_property);
- case Type::Easing:
- // NB: Preserve authored step keywords until computation canonicalizes them to steps().
- if (m_value->easing._0->is_keyword)
- return CSSKeywordValue::create(m_value->easing._0->step_position == to_underlying(StepPosition::Start) ? "step-start"_utf16_fly_string : "step-end"_utf16_fly_string);
- break;
- case Type::Integer:
- return as_integer().reify(associated_property);
- case Type::Keyword:
- return as_keyword().reify(associated_property);
- case Type::Number:
- return as_number().reify(associated_property);
- case Type::OpacityValue:
- return as_opacity_value().reify(associated_property);
- case Type::GridTrackSizeList:
- // NB: A track list that is just one track size, as for `grid-auto-columns: 10px`, is that track size.
- if (auto const* track_size = StyleValueFFI::rust_style_value_grid_track_size_list_single_size(rust_style_value_data()))
- return adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(track_size))->reify(associated_property);
- break;
- case Type::TextIndent:
- // NB: A text-indent without the `hanging` or `each-line` keywords is just its length-percentage.
- if (!m_value->text_indent.hanging && !m_value->text_indent.each_line)
- return wrap_rust_child(m_value->text_indent.length_percentage)->reify(associated_property);
- break;
- case Type::Unresolved:
- return as_unresolved().reify(associated_property);
- case Type::ValueList:
- return as_value_list().reify(associated_property);
- default:
- break;
- }
-
- // AD-HOC: Some values that are just a single keyword are represented by a more specific type, for example
- // `font-style: italic`, `grid-auto-flow: row` or `font-variant-numeric: ordinal`. Reify those as the
- // keyword. Colors and shorthands are left alone, as they are not keywords on their own.
- if (type() != Type::Color && type() != Type::Shorthand) {
- auto serialized_value = to_utf16_string(SerializationMode::Normal);
- if (keyword_from_string(serialized_value).has_value())
- return CSSKeywordValue::create(Utf16FlyString { serialized_value });
- }
-
- return default_reify(associated_property);
-}
-
-GC::Ref<CSSStyleValue> StyleValue::default_reify(Utf16FlyString const& associated_property) const
-{
- // 1. Return a new CSSStyleValue object representing value whose [[associatedProperty]] internal slot is set to property.
- return CSSStyleValue::create(associated_property, *this);
-}
-
// https://drafts.css-houdini.org/css-typed-om-1/#subdivide-into-iterations
StyleValueVector StyleValue::subdivide_into_iterations(PropertyNameAndID const& property) const
{
diff --git a/Libraries/LibWeb/CSS/StyleValues/StyleValue.h b/Libraries/LibWeb/CSS/StyleValues/StyleValue.h
index c7d5377d1e8..38256ab327e 100644
--- a/Libraries/LibWeb/CSS/StyleValues/StyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/StyleValue.h
@@ -212,9 +212,6 @@ public:
Utf16String to_utf16_string(SerializationMode) const;
void serialize(StringBuilder&, SerializationMode) const;
void serialize(Utf16StringBuilder&, SerializationMode) const;
- GC::Ref<CSSStyleValue> reify(Utf16FlyString const& associated_property) const;
- // The default reification, used by types without a bespoke one and by impls that fall back.
- GC::Ref<CSSStyleValue> default_reify(Utf16FlyString const& associated_property) const;
StyleValueVector subdivide_into_iterations(PropertyNameAndID const&) const;
void set_style_sheet(StyleSheetState*);
diff --git a/Libraries/LibWeb/CSS/StyleValues/StyleValueList.cpp b/Libraries/LibWeb/CSS/StyleValues/StyleValueList.cpp
index 6844c12db55..d9bfe9ff7c0 100644
--- a/Libraries/LibWeb/CSS/StyleValues/StyleValueList.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/StyleValueList.cpp
@@ -9,8 +9,6 @@
#include "StyleValueList.h"
#include <LibGC/RootVector.h>
-#include <LibWeb/CSS/CSSTransformComponent.h>
-#include <LibWeb/CSS/CSSTransformValue.h>
#include <LibWeb/CSS/PropertyNameAndID.h>
#include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
@@ -22,42 +20,6 @@ void StyleValueList::set_style_sheet(StyleSheetState* style_sheet)
const_cast<StyleValue&>(*value).set_style_sheet(style_sheet);
}
-// https://drafts.css-houdini.org/css-typed-om-1/#reify-a-transform-list
-static GC::Ptr<CSSStyleValue> reify_a_transform_list(ReadonlySpan<ValueComparingNonnullRefPtr<StyleValue const>> values)
-{
- GC::RootVector<GC::Ref<CSSTransformComponent>> transform_components;
- for (auto const& transform : values) {
- auto reified_transform = transform->as_transformation().reify_a_transform_function();
-
- if (!reified_transform)
- return nullptr;
-
- // NB: Not all transform functions are reifiable, in which case we give up reifying as a transform list.
- transform_components.append(reified_transform.as_nonnull());
- }
- return CSSTransformValue::create(move(transform_components));
-}
-
-GC::Ref<CSSStyleValue> StyleValueList::reify(Utf16FlyString const& associated_property) const
-{
- auto values = this->values();
-
- // NB: <transform-list> is a StyleValueList that contains TransformStyleValues. If that's what we are, follow the
- // steps for reifying that.
- if (all_of(values, [](auto const& it) { return it->is_transformation(); })) {
- if (auto transform_list = reify_a_transform_list(values))
- return transform_list.as_nonnull();
- }
-
- // NB: A list with a single item, such as `text-decoration-line: underline`, is that item on its own. Reify the
- // item, so that a single keyword reifies as a CSSKeywordValue.
- if (values.size() == 1)
- return values.first()->reify(associated_property);
-
- // NB: Otherwise, there isn't an equivalent CSSStyleValue for StyleValueList, so just use the default.
- return default_reify(associated_property);
-}
-
// https://drafts.css-houdini.org/css-typed-om-1/#subdivide-into-iterations
StyleValueVector StyleValueList::subdivide_into_iterations(PropertyNameAndID const& property) const
{
diff --git a/Libraries/LibWeb/CSS/StyleValues/StyleValueList.h b/Libraries/LibWeb/CSS/StyleValues/StyleValueList.h
index fb448c955ee..6bf2494079c 100644
--- a/Libraries/LibWeb/CSS/StyleValues/StyleValueList.h
+++ b/Libraries/LibWeb/CSS/StyleValues/StyleValueList.h
@@ -47,7 +47,6 @@ public:
return value_at(i);
}
- GC::Ref<CSSStyleValue> reify(Utf16FlyString const& associated_property) const;
StyleValueVector subdivide_into_iterations(PropertyNameAndID const&) const;
Separator separator() const { return static_cast<Separator>(m_value->value_list.separator); }
diff --git a/Libraries/LibWeb/CSS/StyleValues/TransformationStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/TransformationStyleValue.cpp
index 67d6fae016d..ff6b77c4d93 100644
--- a/Libraries/LibWeb/CSS/StyleValues/TransformationStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/TransformationStyleValue.cpp
@@ -10,16 +10,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibWeb/CSS/CSSMatrixComponent.h>
-#include <LibWeb/CSS/CSSPerspective.h>
-#include <LibWeb/CSS/CSSRotate.h>
-#include <LibWeb/CSS/CSSScale.h>
-#include <LibWeb/CSS/CSSSkew.h>
-#include <LibWeb/CSS/CSSSkewX.h>
-#include <LibWeb/CSS/CSSSkewY.h>
-#include <LibWeb/CSS/CSSTransformComponent.h>
-#include <LibWeb/CSS/CSSTranslate.h>
-#include <LibWeb/CSS/CSSUnitValue.h>
#include <LibWeb/CSS/PropertyID.h>
#include <LibWeb/CSS/StyleValues/CalculatedStyleValue.h>
#include <LibWeb/CSS/StyleValues/KeywordStyleValue.h>
@@ -28,152 +18,9 @@
#include <LibWeb/CSS/StyleValues/StyleValueList.h>
#include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
#include <LibWeb/ComputedValuesRustFFI.h>
-#include <LibWeb/Geometry/DOMMatrix.h>
namespace Web::CSS {
-// https://drafts.css-houdini.org/css-typed-om-1/#reify-a-transform-function
-GC::Ptr<CSSTransformComponent> TransformationStyleValue::reify_a_transform_function() const
-{
- auto values = this->values();
-
- auto reify_numeric_argument = [&](size_t index) {
- return GC::Ref { as<CSSNumericValue>(*values[index]->reify({})) };
- };
- auto reify_0 = [&] { return CSSUnitValue::create(0, "number"_utf16_fly_string); };
- auto reify_1 = [&] { return CSSUnitValue::create(1, "number"_utf16_fly_string); };
- auto reify_0px = [&] { return CSSUnitValue::create(0, "px"_utf16_fly_string); };
- auto reify_0deg = [&] { return CSSUnitValue::create(0, "deg"_utf16_fly_string); };
-
- // To reify a <transform-function> func, perform the appropriate set of steps below, based on func:
- switch (transform_function()) {
- // -> matrix()
- // -> matrix3d()
- // 1. Return a new CSSMatrixComponent object, whose matrix internal slot is set to a 4x4 matrix representing the
- // same information as func, and whose is2D internal slot is true if func is matrix(), and false otherwise.
- case TransformFunction::Matrix:
- case TransformFunction::Matrix3d: {
- Array<float, 16> transform_as_matrix;
- bool is_2d_matrix = true;
- if (!ComputedValuesFFI::rust_transform_list_to_abstract_matrix(rust_style_value_data(), transform_as_matrix.span(), &is_2d_matrix))
- return nullptr;
-
- // NB: The matrix is row by row, as Gfx::Matrix4x4 takes it.
- Gfx::FloatMatrix4x4 matrix {
- transform_as_matrix[0], transform_as_matrix[1], transform_as_matrix[2], transform_as_matrix[3],
- transform_as_matrix[4], transform_as_matrix[5], transform_as_matrix[6], transform_as_matrix[7],
- transform_as_matrix[8], transform_as_matrix[9], transform_as_matrix[10], transform_as_matrix[11],
- transform_as_matrix[12], transform_as_matrix[13], transform_as_matrix[14], transform_as_matrix[15]
- };
-
- auto is_2d = transform_function() == TransformFunction::Matrix ? CSSTransformComponent::Is2D::Yes : CSSTransformComponent::Is2D::No;
- return CSSMatrixComponent::create(is_2d, Geometry::DOMMatrix::create(matrix));
- }
-
- // -> translate()
- // -> translateX()
- // -> translateY()
- // -> translate3d()
- // -> translateZ()
- // 1. Return a new CSSTranslate object, whose x, y, and z internal slots are set to the reification of the
- // specified x/y/z offsets, or the reification of 0px if not specified in func, and whose is2D internal slot
- // is true if func is translate(), translateX(), or translateY(), and false otherwise.
- case TransformFunction::Translate: {
- // NB: Default y to 0px if it's not specified.
- auto y = values.size() > 1 ? reify_numeric_argument(1) : reify_0px();
- return CSSTranslate::create(CSSTransformComponent::Is2D::Yes, reify_numeric_argument(0), y, reify_0px());
- }
- case TransformFunction::TranslateX:
- return CSSTranslate::create(CSSTransformComponent::Is2D::Yes, reify_numeric_argument(0), reify_0px(), reify_0px());
- case TransformFunction::TranslateY:
- return CSSTranslate::create(CSSTransformComponent::Is2D::Yes, reify_0px(), reify_numeric_argument(0), reify_0px());
- case TransformFunction::Translate3d:
- return CSSTranslate::create(CSSTransformComponent::Is2D::No, reify_numeric_argument(0), reify_numeric_argument(1), reify_numeric_argument(2));
- case TransformFunction::TranslateZ:
- return CSSTranslate::create(CSSTransformComponent::Is2D::No, reify_0px(), reify_0px(), reify_numeric_argument(0));
-
- // -> scale()
- // -> scaleX()
- // -> scaleY()
- // -> scale3d()
- // -> scaleZ()
- // 1. Return a new CSSScale object, whose x, y, and z internal slots are set to the specified x/y/z scales, or
- // to 1 if not specified in func and whose is2D internal slot is true if func is scale(), scaleX(), or
- // scaleY(), and false otherwise.
- case TransformFunction::Scale: {
- // NB: Default y to a copy of x if it's not specified.
- auto y = values.size() > 1 ? reify_numeric_argument(1) : reify_numeric_argument(0);
- return CSSScale::create(CSSTransformComponent::Is2D::Yes, reify_numeric_argument(0), y, reify_1());
- }
- case TransformFunction::ScaleX:
- return CSSScale::create(CSSTransformComponent::Is2D::Yes, reify_numeric_argument(0), reify_1(), reify_1());
- case TransformFunction::ScaleY:
- return CSSScale::create(CSSTransformComponent::Is2D::Yes, reify_1(), reify_numeric_argument(0), reify_1());
- case TransformFunction::Scale3d:
- return CSSScale::create(CSSTransformComponent::Is2D::No, reify_numeric_argument(0), reify_numeric_argument(1), reify_numeric_argument(2));
- case TransformFunction::ScaleZ:
- return CSSScale::create(CSSTransformComponent::Is2D::No, reify_1(), reify_1(), reify_numeric_argument(0));
-
- // -> rotate()
- // -> rotate3d()
- // -> rotateX()
- // -> rotateY()
- // -> rotateZ()
- // 1. Return a new CSSRotate object, whose angle internal slot is set to the reification of the specified angle,
- // and whose x, y, and z internal slots are set to the specified rotation axis coordinates, or the implicit
- // axis coordinates if not specified in func and whose is2D internal slot is true if func is rotate(), and
- // false otherwise.
- case TransformFunction::Rotate:
- return CSSRotate::create(CSSTransformComponent::Is2D::Yes, reify_0(), reify_0(), reify_1(), reify_numeric_argument(0));
- case TransformFunction::Rotate3d:
- return CSSRotate::create(CSSTransformComponent::Is2D::No, reify_numeric_argument(0), reify_numeric_argument(1), reify_numeric_argument(2), reify_numeric_argument(3));
- case TransformFunction::RotateX:
- return CSSRotate::create(CSSTransformComponent::Is2D::No, reify_1(), reify_0(), reify_0(), reify_numeric_argument(0));
- case TransformFunction::RotateY:
- return CSSRotate::create(CSSTransformComponent::Is2D::No, reify_0(), reify_1(), reify_0(), reify_numeric_argument(0));
- case TransformFunction::RotateZ:
- return CSSRotate::create(CSSTransformComponent::Is2D::No, reify_0(), reify_0(), reify_1(), reify_numeric_argument(0));
-
- // -> skew()
- // 1. Return a new CSSSkew object, whose ax and ay internal slots are set to the reification of the specified x
- // and y angles, or the reification of 0deg if not specified in func, and whose is2D internal slot is true.
- case TransformFunction::Skew: {
- // NB: Default y to 0deg if it's not specified.
- auto y = values.size() > 1 ? reify_numeric_argument(1) : reify_0deg();
- return CSSSkew::create(reify_numeric_argument(0), y);
- }
-
- // -> skewX()
- // 1. Return a new CSSSkewX object, whose ax internal slot is set to the reification of the specified x angle,
- // or the reification of 0deg if not specified in func, and whose is2D internal slot is true.
- case TransformFunction::SkewX:
- return CSSSkewX::create(reify_numeric_argument(0));
-
- // -> skewY()
- // 1. Return a new CSSSkewY object, whose ay internal slot is set to the reification of the specified y angle,
- // or the reification of 0deg if not specified in func, and whose is2D internal slot is true.
- case TransformFunction::SkewY:
- return CSSSkewY::create(reify_numeric_argument(0));
-
- // -> perspective()
- // 1. Return a new CSSPerspective object, whose length internal slot is set to the reification of the specified
- // length (see reify a numeric value if it is a length, and reify an identifier if it is the keyword none)
- // and whose is2D internal slot is false.
- case TransformFunction::Perspective: {
- CSSPerspectiveValueInternal length = [&]() -> CSSPerspectiveValueInternal {
- auto reified = values[0]->reify({});
- if (auto* keyword = as_if<CSSKeywordValue>(*reified))
- return GC::Ref { *keyword };
- if (auto* numeric = as_if<CSSNumericValue>(*reified))
- return GC::Ref { *numeric };
- VERIFY_NOT_REACHED();
- }();
- return CSSPerspective::create(length);
- }
- }
- VERIFY_NOT_REACHED();
-}
-
Vector<NonnullRefPtr<TransformationStyleValue const>> transformations_for_style_value(StyleValue const& value)
{
if (value.is_keyword() && value.to_keyword() == Keyword::None)
diff --git a/Libraries/LibWeb/CSS/StyleValues/TransformationStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/TransformationStyleValue.h
index af973c92a24..81e2404881c 100644
--- a/Libraries/LibWeb/CSS/StyleValues/TransformationStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/TransformationStyleValue.h
@@ -35,8 +35,6 @@ public:
return result;
}
- GC::Ptr<CSSTransformComponent> reify_a_transform_function() const;
-
private:
friend class StyleValue;
diff --git a/Libraries/LibWeb/CSS/StyleValues/UnresolvedStyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/UnresolvedStyleValue.cpp
index b3b4f4e11fa..a8ed107e85b 100644
--- a/Libraries/LibWeb/CSS/StyleValues/UnresolvedStyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/UnresolvedStyleValue.cpp
@@ -8,8 +8,6 @@
*/
#include <LibGC/ConservativeVector.h>
-#include <LibWeb/CSS/CSSUnparsedValue.h>
-#include <LibWeb/CSS/CSSVariableReferenceValue.h>
#include <LibWeb/CSS/StyleValues/UnresolvedStyleValue.h>
namespace Web::CSS {
@@ -49,41 +47,4 @@ ValueComparingNonnullRefPtr<UnresolvedStyleValue const> UnresolvedStyleValue::cr
return create_internal(move(token_source), substitution_presence, source_text_mode, true, move(parsed_value));
}
-// https://drafts.css-houdini.org/css-typed-om-1/#reify-a-list-of-component-values
-GC::Ref<CSSStyleValue> UnresolvedStyleValue::reify(Utf16FlyString const&) const
-{
- struct Frame {
- Optional<Utf16FlyString> variable;
- bool has_fallback { false };
- GC::ConservativeVector<CSSUnparsedSegment> segments;
- };
- Vector<Frame> frames;
- frames.empend();
- auto visit = [](void* context, u8 event, u16 const* text, size_t text_length, bool has_fallback) {
- auto& frames = *static_cast<Vector<Frame>*>(context);
- if (event == 0) {
- frames.last().segments.append(Utf16String::from_utf16({ reinterpret_cast<char16_t const*>(text), text_length }));
- return;
- }
- if (event == 1) {
- frames.empend(Frame {
- .variable = Utf16FlyString::from_utf16({ reinterpret_cast<char16_t const*>(text), text_length }),
- .has_fallback = has_fallback,
- .segments = {},
- });
- return;
- }
- VERIFY(event == 2);
- VERIFY(frames.size() > 1);
- auto frame = frames.take_last();
- GC::Ptr<CSSUnparsedValue> fallback;
- if (frame.has_fallback)
- fallback = CSSUnparsedValue::create(frame.segments);
- frames.last().segments.append(CSSVariableReferenceValue::create(frame.variable.release_value(), fallback));
- };
- StyleValueFFI::rust_unresolved_style_value_visit_reification(rust_style_value_data(), &frames, visit);
- VERIFY(frames.size() == 1);
- return CSSUnparsedValue::create(frames.take_last().segments);
-}
-
}
diff --git a/Libraries/LibWeb/CSS/StyleValues/UnresolvedStyleValue.h b/Libraries/LibWeb/CSS/StyleValues/UnresolvedStyleValue.h
index fa99438bf1d..c26ced07242 100644
--- a/Libraries/LibWeb/CSS/StyleValues/UnresolvedStyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/UnresolvedStyleValue.h
@@ -32,8 +32,6 @@ public:
bool contains_attr_tainted_values() const { return m_value->unresolved._0.pointer->contains_attr_tainted_values; }
RefPtr<StyleValue const> parsed_value() const { return wrap_rust_child_or_null(m_value->unresolved._0.pointer->parsed_value); }
- GC::Ref<CSSStyleValue> reify(Utf16FlyString const& associated_property) const;
-
private:
friend class StyleValue;
diff --git a/Libraries/LibWeb/CSS/TypedOM.cpp b/Libraries/LibWeb/CSS/TypedOM.cpp
new file mode 100644
index 00000000000..6d573c58ab4
--- /dev/null
+++ b/Libraries/LibWeb/CSS/TypedOM.cpp
@@ -0,0 +1,433 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibWeb/CSS/CSSKeywordValue.h>
+#include <LibWeb/CSS/CSSNumericValue.h>
+#include <LibWeb/CSS/CSSUnitValue.h>
+#include <LibWeb/CSS/Keyword.h>
+#include <LibWeb/CSS/Parser/Parser.h>
+#include <LibWeb/CSS/PropertyID.h>
+#include <LibWeb/CSS/PropertyNameAndID.h>
+#include <LibWeb/CSS/StyleValues/AngleStyleValue.h>
+#include <LibWeb/CSS/StyleValues/CalculatedStyleValue.h>
+#include <LibWeb/CSS/StyleValues/CustomIdentStyleValue.h>
+#include <LibWeb/CSS/StyleValues/FlexStyleValue.h>
+#include <LibWeb/CSS/StyleValues/FrequencyStyleValue.h>
+#include <LibWeb/CSS/StyleValues/IntegerStyleValue.h>
+#include <LibWeb/CSS/StyleValues/KeywordStyleValue.h>
+#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
+#include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
+#include <LibWeb/CSS/StyleValues/OpacityValueStyleValue.h>
+#include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
+#include <LibWeb/CSS/StyleValues/ResolutionStyleValue.h>
+#include <LibWeb/CSS/StyleValues/StyleValueList.h>
+#include <LibWeb/CSS/StyleValues/TimeStyleValue.h>
+
+// What the Rust implementation of the CSS Typed OM (Libraries/LibWeb/Bindings/Rust/src/css) and LibWeb's C++ code ask
+// of each other. The tables of the properties and the entry points of the parser are in C++ for now, so what depends
+// on them is here.
+
+namespace Web::CSS {
+
+using StyleValueData = StyleValueFFI::StyleValueData;
+using FfiNumericType = StyleValueFFI::FfiNumericType;
+using FfiCalcNode = StyleValueFFI::CalcNode;
+
+extern "C" {
+
+// Defined in Bindings/Rust/src/css/exports.rs.
+void* web_css_style_value_create(JSVM*, FlatPtr associated_property, StyleValueData const*, u8 serialization_mode);
+void* web_css_style_value_reify(JSVM*, StyleValueData const*, FlatPtr associated_property);
+void* web_css_style_value_parse(JSVM*, FlatPtr property, FlatPtr css_text, FlatPtr* error);
+bool web_css_style_value_associated_property(void* value, FlatPtr* associated_property);
+StyleValueData const* web_css_style_value_create_an_internal_representation(JSVM*, void* value, u16 property_id, FlatPtr property_name, bool perform_type_check, FlatPtr* error);
+u8 web_css_style_value_kind(void* value);
+void* web_css_numeric_value_create_sum(JSVM*, void* first, void* second);
+FfiNumericType web_css_numeric_value_type(void* value);
+FlatPtr web_css_numeric_value_to_string(void* value);
+FfiCalcNode const* web_css_numeric_value_create_calculation_node(void* value);
+void* web_css_unit_value_create(JSVM*, double value, FlatPtr unit);
+double web_css_unit_value_value(void* value);
+FlatPtr web_css_unit_value_unit(void* value);
+FlatPtr web_css_keyword_value_value(void* value);
+}
+
+// The order of `enum StyleValueKind` in Bindings/Rust/src/css/exports.rs.
+enum class StyleValueKind : u8 {
+ Other,
+ Numeric,
+ Unit,
+ Unparsed,
+};
+
+static JSVM* vm_abi()
+{
+ return JS::HostABI::vm_to_abi(JS::VM::the());
+}
+
+static StyleValueKind kind_of(CSSStyleValue const& value)
+{
+ return static_cast<StyleValueKind>(web_css_style_value_kind(const_cast<CSSStyleValue*>(&value)));
+}
+
+GC::Ref<CSSStyleValue> CSSStyleValue::create(Utf16FlyString associated_property, StyleValue const& source_value, SerializationMode serialization_mode)
+{
+ auto* value = web_css_style_value_create(vm_abi(), associated_property.to_utf16_string().into_raw(), StyleValueFFI::rust_style_value_retain(source_value.rust_style_value_data()), to_underlying(serialization_mode));
+ return GC::Ref { *static_cast<CSSStyleValue*>(value) };
+}
+
+GC::Ref<CSSStyleValue> CSSStyleValue::reify(StyleValue const& value, Utf16FlyString const& associated_property)
+{
+ auto* reified_value = web_css_style_value_reify(vm_abi(), StyleValueFFI::rust_style_value_retain(value.rust_style_value_data()), associated_property.to_utf16_string().into_raw());
+ return GC::Ref { *static_cast<CSSStyleValue*>(reified_value) };
+}
+
+WebIDL::ExceptionOr<GC::Ref<CSSStyleValue>> CSSStyleValue::parse_a_css_style_value(Utf16FlyString const& property, Utf16View css_text)
+{
+ FlatPtr error = 0;
+ auto* value = web_css_style_value_parse(vm_abi(), property.to_utf16_string().into_raw(), Utf16String::from_utf16(css_text).into_raw(), &error);
+ if (!value)
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::from_raw(error) };
+ return GC::Ref { *static_cast<CSSStyleValue*>(value) };
+}
+
+Optional<Utf16FlyString> CSSStyleValue::associated_property() const
+{
+ FlatPtr associated_property = 0;
+ if (!web_css_style_value_associated_property(const_cast<CSSStyleValue*>(this), &associated_property))
+ return {};
+ return Utf16FlyString { Utf16String::from_raw(associated_property) };
+}
+
+WebIDL::ExceptionOr<NonnullRefPtr<StyleValue const>> CSSStyleValue::create_an_internal_representation(PropertyNameAndID const& property, PerformTypeCheck perform_type_check) const
+{
+ FlatPtr error = 0;
+ auto const* value = web_css_style_value_create_an_internal_representation(vm_abi(), const_cast<CSSStyleValue*>(this), to_underlying(property.id()), property.name().to_utf16_string().into_raw(), perform_type_check == PerformTypeCheck::Yes, &error);
+ if (!value)
+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::from_raw(error) };
+ return NonnullRefPtr<StyleValue const> { *StyleValue::adopt_rust_style_value_data(value) };
+}
+
+bool CSSStyleValue::is_numeric_value() const
+{
+ auto kind = kind_of(*this);
+ return kind == StyleValueKind::Numeric || kind == StyleValueKind::Unit;
+}
+
+bool CSSStyleValue::is_unit_value() const
+{
+ return kind_of(*this) == StyleValueKind::Unit;
+}
+
+bool CSSStyleValue::is_unparsed_value() const
+{
+ return kind_of(*this) == StyleValueKind::Unparsed;
+}
+
+GC::Ref<CSSNumericValue> CSSNumericValue::create_sum(GC::Ref<CSSNumericValue> first, GC::Ref<CSSNumericValue> second)
+{
+ return GC::Ref { *static_cast<CSSNumericValue*>(web_css_numeric_value_create_sum(vm_abi(), first.ptr(), second.ptr())) };
+}
+
+NumericType CSSNumericValue::type() const
+{
+ return NumericType::from_ffi(web_css_numeric_value_type(const_cast<CSSNumericValue*>(this))).release_value();
+}
+
+Utf16String CSSNumericValue::to_string() const
+{
+ return Utf16String::from_raw(web_css_numeric_value_to_string(const_cast<CSSNumericValue*>(this)));
+}
+
+Optional<CalcNodeRef> CSSNumericValue::create_calculation_node() const
+{
+ auto const* node = web_css_numeric_value_create_calculation_node(const_cast<CSSNumericValue*>(this));
+ if (!node)
+ return {};
+ return CalcNodeRef::adopt(node);
+}
+
+GC::Ref<CSSUnitValue> CSSUnitValue::create(double value, Utf16FlyString const& unit)
+{
+ return GC::Ref { *static_cast<CSSUnitValue*>(web_css_unit_value_create(vm_abi(), value, unit.to_utf16_string().into_raw())) };
+}
+
+double CSSUnitValue::value() const
+{
+ return web_css_unit_value_value(const_cast<CSSUnitValue*>(this));
+}
+
+Utf16FlyString CSSUnitValue::unit() const
+{
+ return Utf16FlyString { Utf16String::from_raw(web_css_unit_value_unit(const_cast<CSSUnitValue*>(this))) };
+}
+
+Utf16String CSSKeywordValue::value() const
+{
+ return Utf16String::from_raw(web_css_keyword_value_value(const_cast<CSSKeywordValue*>(this)));
+}
+
+static StyleValueData const* into_rust(StyleValue const& value)
+{
+ return StyleValueFFI::rust_style_value_retain(value.rust_style_value_data());
+}
+
+static PropertyID property_id_from_abi(u16 property_id)
+{
+ return static_cast<PropertyID>(property_id);
+}
+
+// The order of `enum TypedOmValueType` in Bindings/Rust/src/css/typed_om.rs.
+enum class TypedOmValueType : u8 {
+ Image,
+ TransformFunction,
+ TransformList,
+};
+
+extern "C" {
+
+// Declared in Bindings/Rust/src/css/typed_om.rs.
+bool web_css_typed_om_property_accepts_type(u16 property_id, TypedOmValueType value_type);
+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_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);
+
+bool web_css_typed_om_property_accepts_type(u16 property_id, TypedOmValueType value_type)
+{
+ auto const to_value_type = [&] {
+ switch (value_type) {
+ case TypedOmValueType::Image:
+ return ValueType::Image;
+ case TypedOmValueType::TransformFunction:
+ return ValueType::TransformFunction;
+ case TypedOmValueType::TransformList:
+ return ValueType::TransformList;
+ }
+ VERIFY_NOT_REACHED();
+ };
+ return property_accepts_type(property_id_from_abi(property_id), to_value_type());
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+StyleValueData const* web_css_typed_om_numeric_style_value(u16 property_id_abi, StyleValueData const* value_data, FfiCalcNode const* calculation_data, FfiNumericType numeric_type)
+{
+ auto property_id = property_id_from_abi(property_id_abi);
+ auto value = StyleValue::adopt_rust_style_value_data(value_data);
+ auto calculation = CalcNodeRef::adopt(calculation_data);
+
+ // If any component of property’s CSS grammar has a limited numeric range, and the corresponding part of value is a
+ // CSSUnitValue that is outside of that range, replace that value with the result of wrapping it in a fresh
+ // CSSMathSum whose values internal slot contains only that part of value.
+ auto wrap_in_math_sum = [&] {
+ return into_rust(*CalculatedStyleValue::create(move(calculation), NumericType::from_ffi(numeric_type).release_value(), CalculationContext::for_property(property_id)));
+ };
+
+ if (value->is_number()) {
+ auto number = value->as_number().number();
+
+ // NB: Our parser represents an <opacity-value> as an opacity value that holds the number.
+ if (property_accepts_type(property_id, ValueType::OpacityValue))
+ return into_rust(*OpacityValueStyleValue::create(value));
+
+ // NB: Prefer <number> to <integer> when both are accepted.
+ if (property_accepts_type(property_id, ValueType::Number))
+ return property_accepts_number(property_id, number) ? into_rust(*value) : wrap_in_math_sum();
+
+ if (property_accepts_type(property_id, ValueType::Integer)) {
+ auto integer = round_to_nearest_integer(number);
+ // NB: A number that is not an integer does not match <integer>, so it's wrapped in a CSSMathSum, like a
+ // value outside of the accepted range. It then gets rounded when computed.
+ if (static_cast<double>(integer) != number)
+ return wrap_in_math_sum();
+ if (property_accepts_integer(property_id, integer))
+ return into_rust(*IntegerStyleValue::create(integer));
+ return wrap_in_math_sum();
+ }
+ return nullptr;
+ }
+
+ if (value->is_percentage()) {
+ // NB: Our parser represents an <opacity-value> as an opacity value that holds the percentage.
+ if (property_accepts_type(property_id, ValueType::OpacityValue))
+ return into_rust(*OpacityValueStyleValue::create(value));
+ if (!property_accepts_type(property_id, ValueType::Percentage))
+ return nullptr;
+ return property_accepts_percentage(property_id, value->as_percentage().percentage()) ? into_rust(*value) : wrap_in_math_sum();
+ }
+
+ if (value->is_flex()) {
+ // NB: Out-of-range flex values cannot be deferred in a calculation.
+ if (property_accepts_type(property_id, ValueType::Flex) && property_accepts_flex(property_id, value->as_flex().flex()))
+ return into_rust(*value);
+ return nullptr;
+ }
+
+ auto dimension_value = [&](ValueType value_type, bool is_accepted) -> StyleValueData const* {
+ if (!property_accepts_type(property_id, value_type))
+ return nullptr;
+ return is_accepted ? into_rust(*value) : wrap_in_math_sum();
+ };
+ if (value->is_angle())
+ return dimension_value(ValueType::Angle, property_accepts_angle(property_id, value->as_angle().angle()));
+ if (value->is_frequency())
+ return dimension_value(ValueType::Frequency, property_accepts_frequency(property_id, value->as_frequency().frequency()));
+ if (value->is_length())
+ return dimension_value(ValueType::Length, property_accepts_length(property_id, value->as_length().length()));
+ if (value->is_resolution())
+ return dimension_value(ValueType::Resolution, property_accepts_resolution(property_id, value->as_resolution().resolution()));
+ if (value->is_time())
+ return dimension_value(ValueType::Time, property_accepts_time(property_id, value->as_time().time()));
+ VERIFY_NOT_REACHED();
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+StyleValueData const* web_css_typed_om_calculated_style_value(u16 property_id_abi, FfiCalcNode const* calculation_data, FfiNumericType numeric_type, bool perform_type_check)
+{
+ auto property_id = property_id_from_abi(property_id_abi);
+ auto calculation = CalcNodeRef::adopt(calculation_data);
+ auto type = NumericType::from_ffi(numeric_type).release_value();
+ auto context = CalculationContext::for_property(property_id);
+
+ auto matches = [&] {
+ if (type.matches_angle(context.percentages_resolve_as))
+ return property_accepts_type(property_id, ValueType::Angle);
+ if (type.matches_flex(context.percentages_resolve_as)) {
+ // https://drafts.csswg.org/css-grid-2/#fr-unit
+ // NB: <flex> values "cannot be represented in or combined with other unit types in calc() expressions".
+ return property_id == PropertyID::Custom && property_accepts_type(property_id, ValueType::Flex);
+ }
+ if (type.matches_frequency(context.percentages_resolve_as))
+ return property_accepts_type(property_id, ValueType::Frequency);
+ if (type.matches_length(context.percentages_resolve_as))
+ return property_accepts_type(property_id, ValueType::Length);
+ if (type.matches_number(context.percentages_resolve_as))
+ return property_accepts_type(property_id, ValueType::Number) || property_accepts_type(property_id, ValueType::Integer) || property_accepts_type(property_id, ValueType::OpacityValue);
+ if (type.matches_percentage())
+ return property_accepts_type(property_id, ValueType::Percentage) || property_accepts_type(property_id, ValueType::OpacityValue);
+ if (type.matches_resolution(context.percentages_resolve_as))
+ return property_accepts_type(property_id, ValueType::Resolution);
+ if (type.matches_time(context.percentages_resolve_as))
+ return property_accepts_type(property_id, ValueType::Time);
+ return false;
+ }();
+ if (perform_type_check && !matches)
+ return nullptr;
+
+ auto is_number_or_percentage = type.matches_number({}) || type.matches_percentage();
+ auto calculated_value = CalculatedStyleValue::create(move(calculation), move(type), move(context));
+
+ // NB: Our parser represents an <opacity-value> as an opacity value that holds the calculation.
+ if (property_accepts_type(property_id, ValueType::OpacityValue) && is_number_or_percentage)
+ return into_rust(*OpacityValueStyleValue::create(move(calculated_value)));
+
+ return into_rust(*calculated_value);
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#create-an-internal-representation
+StyleValueData const* web_css_typed_om_keyword_style_value(u16 property_id_abi, FlatPtr raw_value, bool perform_type_check)
+{
+ auto property_id = property_id_from_abi(property_id_abi);
+ auto value = Utf16FlyString { Utf16String::from_raw(raw_value) };
+ auto keyword = keyword_from_string(value);
+
+ // https://drafts.css-houdini.org/css-typed-om-1/#cssstylevalue-match-a-grammar
+ // NB: The keywords listed for a property are not all valid on their own, like `hanging` for text-indent, and a
+ // property may accept identifiers that are not listed, like a <custom-ident> or the axis keywords of
+ // scroll-snap-type. So we check if the property accepts the value, as an identifier, when parsed.
+ auto const matches_grammar = [&] {
+ if (keyword.has_value() && is_css_wide_keyword(*keyword))
+ return true;
+ return parse_css_value(Parser::ParsingParams {}, serialize_an_identifier(value), property_id) != nullptr;
+ };
+ if (perform_type_check && !matches_grammar())
+ return nullptr;
+
+ if (keyword.has_value()) {
+ // NB: Style computation expects the same internal representation that the CSS parser produces for the
+ // property. For example, `display` keywords become a DisplayStyleValue, and keyword combinations like
+ // `text-decoration-line` or `white-space-trim` become a list even when only one keyword is given. So we
+ // parse the keyword as a value of the property to get that representation. List-valued properties are
+ // instead wrapped in a list by StylePropertyMap.
+ if (!is_css_wide_keyword(*keyword) && property_id != PropertyID::Custom && !property_is_list_valued(property_id)) {
+ if (auto parsed_value = parse_css_value(Parser::ParsingParams {}, value.view(), property_id))
+ return into_rust(*parsed_value);
+ }
+ return into_rust(*KeywordStyleValue::create(*keyword));
+ }
+ return into_rust(*CustomIdentStyleValue::create(value));
+}
+
+StyleValueData const* web_css_typed_om_style_value_list(StyleValueData const* const* values, size_t count)
+{
+ 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));
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#dom-cssnumericvalue-parse
+StyleValueData const* web_css_typed_om_parse_numeric_value(FlatPtr raw_css_text)
+{
+ auto css_text = Utf16String::from_raw(raw_css_text);
+ for (auto value_type : { ValueType::Number, ValueType::Percentage, ValueType::Length, ValueType::LengthPercentage, ValueType::Angle, ValueType::Time, ValueType::Frequency, ValueType::Resolution, ValueType::Flex }) {
+ if (auto value = parse_css_type(Parser::ParsingParams {}, css_text, value_type))
+ return into_rust(*value);
+ }
+ return nullptr;
+}
+
+// https://drafts.css-houdini.org/css-typed-om-1/#parse-a-cssstylevalue
+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)
+{
+ auto property_name = Utf16FlyString { Utf16String::from_raw(raw_property) };
+ auto css_text = Utf16String::from_raw(raw_css_text);
+
+ // 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()) {
+ *name_or_error = Utf16String::formatted("'{}' is not a valid CSS property", property_name).into_raw();
+ return false;
+ }
+
+ // 3. Attempt to parse cssText according to property’s grammar.
+ // If this fails, throw a TypeError.
+ // Otherwise, let whole value be the parsed result.
+ auto whole_value = parse_css_value(Parser::ParsingParams {}, css_text, property->id());
+ if (!whole_value) {
+ *name_or_error = Utf16String::formatted("Failed to parse '{}' as a value for '{}' property", css_text, property_name).into_raw();
+ return false;
+ }
+
+ // 4. Subdivide into iterations whole value, according to property, and let values be the result.
+ for (auto const& value : whole_value->subdivide_into_iterations(property.value()))
+ append(values, into_rust(*value));
+
+ *name_or_error = property->name().to_utf16_string().into_raw();
+ return true;
+}
+
+// Whether the property expects a 0 to be a <length>.
+bool web_css_typed_om_zero_is_a_length(FlatPtr raw_property, bool is_integer)
+{
+ auto property = Utf16String::from_raw(raw_property);
+ if (!property.is_ascii())
+ return false;
+ auto property_id = property_id_from_string(property);
+ if (!property_id.has_value() || property_id == PropertyID::Custom || !property_accepts_type(*property_id, ValueType::Length))
+ return false;
+ return is_integer || (!property_accepts_type(*property_id, ValueType::Number) && !property_accepts_type(*property_id, ValueType::Integer));
+}
+}
+
+}
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index abc9955653d..9bf0f3f7b2a 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -267,7 +267,6 @@ class CSSFontFeatureValuesRule;
class CSSFunctionDescriptors;
class CSSFunctionRule;
class CSSGroupingRule;
-class CSSImageValue;
class CSSImportRule;
class CSSKeyframeRule;
class CSSKeyframesRule;
@@ -275,34 +274,18 @@ class CSSKeywordValue;
class CSSLayerBlockRule;
class CSSLayerStatementRule;
class CSSMarginRule;
-class CSSMathClamp;
-class CSSMathInvert;
-class CSSMathMax;
-class CSSMathMin;
-class CSSMathNegate;
-class CSSMathProduct;
-class CSSMathSum;
-class CSSMathValue;
-class CSSMatrixComponent;
class CSSMediaRule;
class CSSNamespaceRule;
class CSSNestedDeclarations;
-class CSSNumericArray;
class CSSNumericValue;
class CSSPageRule;
class CSSPageDescriptors;
-class CSSPerspective;
class CSSPositionTryDescriptors;
class CSSPositionTryRule;
class CSSPropertyRule;
-class CSSRotate;
class CSSRule;
class CSSRuleList;
-class CSSScale;
class CSSScopeRule;
-class CSSSkew;
-class CSSSkewX;
-class CSSSkewY;
class CSSStyleDeclaration;
class CSSStyleProperties;
class CSSStyleRule;
@@ -310,12 +293,7 @@ class CSSStyleSheet;
class StyleSheetState;
class CSSStyleValue;
class CSSSupportsRule;
-class CSSTransformComponent;
-class CSSTransformValue;
-class CSSTranslate;
class CSSUnitValue;
-class CSSUnparsedValue;
-class CSSVariableReferenceValue;
class CursorStyleValue;
class CustomIdentStyleValue;
class DimensionStyleValue;
diff --git a/Libraries/LibWeb/Rust/src/css/calc.rs b/Libraries/LibWeb/Rust/src/css/calc.rs
index 89c557069b8..97b1053aaac 100644
--- a/Libraries/LibWeb/Rust/src/css/calc.rs
+++ b/Libraries/LibWeb/Rust/src/css/calc.rs
@@ -13,7 +13,7 @@
//! Nothing constructs these yet; the FFI construction surface follows with
//! the C++ staging.
-use crate::css::ffi_support::{OwnedArc, OwnedBox};
+use crate::css::ffi_support::OwnedArc;
use crate::css::style_value::{
AnchorPayload, AnchorSizePayload, CalculatedPayload, RandomValueSharingPayload, StyleValueBox,
};
@@ -145,7 +145,7 @@ impl CalcNumericType {
}
/// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue-add-two-types
- pub(crate) fn added_to(&self, other: &CalcNumericType) -> Option<CalcNumericType> {
+ pub fn added_to(&self, other: &CalcNumericType) -> Option<CalcNumericType> {
// To add two types type1 and type2, perform the following steps:
// 1. Replace type1 with a fresh copy of type1, and type2 with a fresh copy of type2.
@@ -227,7 +227,7 @@ impl CalcNumericType {
}
/// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue-multiply-two-types
- pub(crate) fn multiplied_by(&self, other: &CalcNumericType) -> Option<CalcNumericType> {
+ pub fn multiplied_by(&self, other: &CalcNumericType) -> Option<CalcNumericType> {
// To multiply two types type1 and type2, perform the following steps:
// 1. Replace type1 with a fresh copy of type1, and type2 with a fresh copy of type2.
@@ -269,7 +269,7 @@ impl CalcNumericType {
}
/// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue-invert-a-type
- pub(crate) fn inverted(&self) -> CalcNumericType {
+ pub fn inverted(&self) -> CalcNumericType {
// To invert a type type, perform the following steps:
// 1. Let result be a new type with an initially empty ordered map and a percent hint matching that of type.
@@ -474,7 +474,7 @@ pub struct FfiNumericType {
}
impl FfiNumericType {
- pub(crate) fn from_calc(value: Option<CalcNumericType>) -> Self {
+ pub fn from_calc(value: Option<CalcNumericType>) -> Self {
let mut result = FfiNumericType {
has_exponent_bits: 0,
exponents: [0; BASE_TYPE_COUNT],
@@ -497,7 +497,7 @@ impl FfiNumericType {
result
}
- pub(crate) fn to_calc(self) -> CalcNumericType {
+ pub fn to_calc(self) -> CalcNumericType {
let mut result = CalcNumericType::default();
for i in 0..BASE_TYPE_COUNT {
if self.has_exponent_bits & (1 << i) != 0 {
@@ -511,15 +511,6 @@ impl FfiNumericType {
}
}
-#[derive(Clone, Copy)]
-#[repr(u8)]
-#[expect(dead_code, reason = "C++ constructs the variants")]
-pub enum FfiNumericTypeOperation {
- Add,
- Multiply,
- Invert,
-}
-
#[derive(Clone, Copy)]
#[repr(u8)]
#[expect(dead_code, reason = "C++ constructs the variants")]
@@ -530,23 +521,6 @@ pub enum FfiNumericTypeMatch {
Number,
}
-/// Applies one numeric type algebra operation for C++ callers.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_numeric_type_operate(
- operation: FfiNumericTypeOperation,
- first: &FfiNumericType,
- second: Option<&FfiNumericType>,
-) -> FfiNumericType {
- let first = first.to_calc();
- let second = || second.expect("the operation has a second operand").to_calc();
- let result = match operation {
- FfiNumericTypeOperation::Add => first.added_to(&second()),
- FfiNumericTypeOperation::Multiply => first.multiplied_by(&second()),
- FfiNumericTypeOperation::Invert => Some(first.inverted()),
- };
- FfiNumericType::from_calc(result)
-}
-
/// Tests a numeric type against one of the CSS numeric matching categories.
#[unsafe(no_mangle)]
pub extern "C" fn rust_numeric_type_matches(
@@ -1270,14 +1244,6 @@ fn shared(node: CalcNode) -> Arc<CalcNode> {
Arc::new(node)
}
-/// Reconstructs the child Arcs from an array of transferred handles.
-///
-/// # Safety
-/// `children` must point at `count` valid transferred handles.
-unsafe fn children_from_raw(children: *const *const CalcNode, count: usize) -> Vec<Arc<CalcNode>> {
- (0..count).map(|i| unsafe { Arc::from_raw(*children.add(i)) }).collect()
-}
-
/// Creates a numeric leaf for a dimension: kind selects the dimension in the
/// order number, angle, flex, frequency, length, percentage, resolution, time.
#[unsafe(no_mangle)]
@@ -1299,53 +1265,6 @@ pub extern "C" fn rust_calc_node_create_numeric_dimension(kind: u8, value: f64,
handle(CalcNode::Numeric(numeric))
}
-/// Creates a variadic node: kind selects sum (0), product (1), min (2) or
-/// max (3).
-///
-/// # Safety
-/// `children` must point at `count` valid transferred handles.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_calc_node_create_variadic(
- kind: u8,
- children: *const *const CalcNode,
- count: usize,
-) -> *const CalcNode {
- let children = unsafe { children_from_raw(children, count) };
- let node = match kind {
- 0 => CalcNode::Sum(children),
- 1 => CalcNode::Product(children),
- 2 => CalcNode::Min(children),
- 3 => CalcNode::Max(children),
- _ => unreachable!("invalid variadic calc node kind {kind}"),
- };
- handle(node)
-}
-
-/// Creates a single-child node: kind selects negate (0) or invert (1).
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_calc_node_create_unary(kind: u8, child: OwnedArc<CalcNode>) -> *const CalcNode {
- let child = child.into_arc();
- let node = match kind {
- 0 => CalcNode::Negate(child),
- 1 => CalcNode::Invert(child),
- _ => unreachable!("invalid unary calc node kind {kind}"),
- };
- handle(node)
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_calc_node_create_clamp(
- min: OwnedArc<CalcNode>,
- center: OwnedArc<CalcNode>,
- max: OwnedArc<CalcNode>,
-) -> *const CalcNode {
- handle(CalcNode::Clamp {
- min: Some(min.into_arc()),
- center: center.into_arc(),
- max: Some(max.into_arc()),
- })
-}
-
#[unsafe(no_mangle)]
pub extern "C" fn rust_calc_node_release(node: OwnedArc<CalcNode>) {
drop(node);
@@ -1375,7 +1294,7 @@ pub extern "C" fn rust_calc_node_contains_percentage(node: &CalcNode) -> bool {
/// What percentages resolve against in the surrounding context.
#[derive(Clone, Copy, PartialEq, Eq)]
-pub(crate) enum ResolveAs {
+pub enum ResolveAs {
Number,
/// A base type index, in the numeric type order.
Base(u8),
@@ -1957,7 +1876,7 @@ impl CalcNumericType {
/// A type matches a dimension if its only non-zero entry is that base type
/// with value 1, and the percent hint is compatible with the context.
- pub(crate) fn matches_dimension(&self, base: usize, resolve_as: Option<ResolveAs>) -> bool {
+ pub fn matches_dimension(&self, base: usize, resolve_as: Option<ResolveAs>) -> bool {
if self.entry_with_value_1_while_all_others_are_0() != Some(base) {
return false;
}
@@ -1969,20 +1888,20 @@ impl CalcNumericType {
/// A type matches <percentage> if its only non-zero entry is percent with
/// value 1, and its percent hint is null or percent.
- pub(crate) fn matches_percentage(&self) -> bool {
+ pub fn matches_percentage(&self) -> bool {
if self.percent_hint.is_some() && self.percent_hint != Some(BASE_TYPE_PERCENT as u8) {
return false;
}
self.entry_with_value_1_while_all_others_are_0() == Some(BASE_TYPE_PERCENT)
}
- pub(crate) fn matches_dimension_percentage(&self, base: usize, resolve_as: Option<ResolveAs>) -> bool {
+ pub fn matches_dimension_percentage(&self, base: usize, resolve_as: Option<ResolveAs>) -> bool {
self.matches_percentage() || self.matches_dimension(base, resolve_as)
}
/// A type matches <number> if it has no non-zero entries, with the hint
/// compatible when percentages resolve against a non-number type.
- pub(crate) fn matches_number(&self, resolve_as: Option<ResolveAs>) -> bool {
+ pub fn matches_number(&self, resolve_as: Option<ResolveAs>) -> bool {
for i in 0..BASE_TYPE_COUNT {
if self.exponents[i].is_some() && self.exponents[i] != Some(0) {
return false;
@@ -5051,7 +4970,7 @@ fn node_kind_code(node: &CalcNode) -> u8 {
}
#[repr(C)]
-pub struct FfiCalcReificationNode {
+pub struct CalcReificationNode {
pub kind: u8,
pub numeric_kind: u8,
pub unit: u8,
@@ -5061,24 +4980,10 @@ pub struct FfiCalcReificationNode {
pub child_count: usize,
}
-#[repr(C)]
-pub struct FfiCalcReification {
- pub nodes: *const FfiCalcReificationNode,
- pub node_count: usize,
- pub children: *const usize,
- pub child_count: usize,
- pub storage: *mut std::ffi::c_void,
-}
-
-pub struct CalcReificationStorage {
- nodes: Box<[FfiCalcReificationNode]>,
- children: Box<[usize]>,
-}
-
fn append_reification_node(
node: &CalcNode,
percentage_leaf_type: &CalcNumericType,
- nodes: &mut Vec<FfiCalcReificationNode>,
+ nodes: &mut Vec<CalcReificationNode>,
children: &mut Vec<usize>,
) -> Option<usize> {
if !matches!(
@@ -5119,7 +5024,7 @@ fn append_reification_node(
_ => (0, 0.0, 0),
};
let index = nodes.len();
- nodes.push(FfiCalcReificationNode {
+ nodes.push(CalcReificationNode {
kind: node_kind_code(node),
numeric_kind,
unit,
@@ -5132,14 +5037,13 @@ fn append_reification_node(
}
/// https://drafts.css-houdini.org/css-typed-om-1/#reify-a-math-expression
-/// Describe a calculation tree in postorder so C++ can create its GC-owned Typed OM objects.
-/// Unsupported math functions return an empty description.
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_calc_describe_for_typed_om(
+/// Describes a calculation tree in postorder, for the objects of the Typed OM. Unsupported math functions result in
+/// nothing.
+pub(crate) fn reification_nodes(
calculated: &crate::css::style_value::StyleValueData,
-) -> FfiCalcReification {
+) -> Option<(Vec<CalcReificationNode>, Vec<usize>)> {
let crate::css::style_value::StyleValueData::Calculated(calculated_payload) = calculated else {
- unreachable!("rust_calc_describe_for_typed_om requires calculated value data");
+ unreachable!("reification_nodes requires calculated value data");
};
let CalculatedPayload {
rust_calculation,
@@ -5155,41 +5059,11 @@ pub extern "C" fn rust_calc_describe_for_typed_om(
));
let mut nodes = Vec::new();
let mut children = Vec::new();
- if append_reification_node(
+ append_reification_node(
rust_calculation.node(),
&percentage_leaf_type,
&mut nodes,
&mut children,
- )
- .is_none()
- {
- return FfiCalcReification {
- nodes: std::ptr::null(),
- node_count: 0,
- children: std::ptr::null(),
- child_count: 0,
- storage: std::ptr::null_mut(),
- };
- }
- let storage = Box::new(CalcReificationStorage {
- nodes: nodes.into_boxed_slice(),
- children: children.into_boxed_slice(),
- });
- let result = FfiCalcReification {
- nodes: storage.nodes.as_ptr(),
- node_count: storage.nodes.len(),
- children: storage.children.as_ptr(),
- child_count: storage.children.len(),
- storage: std::ptr::null_mut(),
- };
- let storage = Box::into_raw(storage);
- FfiCalcReification {
- storage: storage.cast(),
- ..result
- }
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn rust_calc_reification_release(storage: OwnedBox<CalcReificationStorage>) {
- drop(storage);
+ )?;
+ Some((nodes, children))
}
diff --git a/Libraries/LibWeb/Rust/src/css/ffi_support.rs b/Libraries/LibWeb/Rust/src/css/ffi_support.rs
index d7f8a31affa..73d43c49fc3 100644
--- a/Libraries/LibWeb/Rust/src/css/ffi_support.rs
+++ b/Libraries/LibWeb/Rust/src/css/ffi_support.rs
@@ -121,11 +121,6 @@ impl<T> OwnedArc<T> {
// SAFETY: A non-null pointer comes from `Arc::into_raw()`, and its reference is this handle's own.
(!pointer.is_null()).then(|| unsafe { std::sync::Arc::from_raw(pointer) })
}
-
- /// The reference, which must not be null.
- pub(crate) fn into_arc(mut self) -> std::sync::Arc<T> {
- self.take().expect("C++ hands over a live object")
- }
}
impl<T> Drop for OwnedArc<T> {
diff --git a/Libraries/LibWeb/Rust/src/css/mod.rs b/Libraries/LibWeb/Rust/src/css/mod.rs
index a9061aaa220..e88d1a4561a 100644
--- a/Libraries/LibWeb/Rust/src/css/mod.rs
+++ b/Libraries/LibWeb/Rust/src/css/mod.rs
@@ -68,6 +68,7 @@ pub(crate) mod style_value_arc;
pub mod table_group_builder;
pub(crate) mod thin_slice;
pub mod transition;
+pub mod typed_om;
pub(crate) mod value_codes;
pub(crate) mod dimension_units {
diff --git a/Libraries/LibWeb/Rust/src/css/serialize.rs b/Libraries/LibWeb/Rust/src/css/serialize.rs
index 76d419a29ac..9c0b2d29e92 100644
--- a/Libraries/LibWeb/Rust/src/css/serialize.rs
+++ b/Libraries/LibWeb/Rust/src/css/serialize.rs
@@ -42,7 +42,7 @@ pub(crate) enum SerializationMode {
}
impl SerializationMode {
- fn from_ffi(mode: u8) -> Self {
+ pub(crate) fn from_ffi(mode: u8) -> Self {
match mode {
0 => Self::Normal,
1 => Self::ResolvedValue,
diff --git a/Libraries/LibWeb/Rust/src/css/style_value.rs b/Libraries/LibWeb/Rust/src/css/style_value.rs
index 14a36c17bea..7dbd286c3ed 100644
--- a/Libraries/LibWeb/Rust/src/css/style_value.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_value.rs
@@ -28,7 +28,7 @@ use crate::css::serialize::{
pub(crate) use crate::css::css_string::{CssString, CssStringList};
-enum ReifiedUnresolvedSegment {
+pub enum ReifiedUnresolvedSegment {
Text(Vec<u16>),
Variable {
name: Vec<u16>,
@@ -138,31 +138,6 @@ fn reify_unresolved_segments(values: &[ComponentValue]) -> Vec<ReifiedUnresolved
output
}
-fn visit_reified_unresolved_segments(
- segments: &[ReifiedUnresolvedSegment],
- context: *mut c_void,
- visit: unsafe extern "C" fn(*mut c_void, u8, *const u16, usize, bool),
-) {
- for segment in segments {
- match segment {
- ReifiedUnresolvedSegment::Text(text) => unsafe {
- visit(context, 0, text.as_ptr(), text.len(), false);
- },
- ReifiedUnresolvedSegment::Variable { name, fallback } => {
- unsafe {
- visit(context, 1, name.as_ptr(), name.len(), fallback.is_some());
- }
- if let Some(fallback) = fallback {
- visit_reified_unresolved_segments(fallback, context, visit);
- }
- unsafe {
- visit(context, 2, std::ptr::null(), 0, false);
- }
- }
- }
- }
-}
-
// Appends the name of every custom property a `var()` or `inherit()` in `values` refers to, and returns whether every
// reference names its property with a plain identifier.
fn scan_custom_property_references<'a>(
@@ -208,23 +183,12 @@ pub(crate) fn custom_property_references(value: &StyleValueData) -> Option<(impl
Some((unresolved_payload.references(), unresolved_payload.references_visible()))
}
-/// Visits the Typed OM reification of an unresolved style value. Event 0 appends a text segment,
-/// event 1 begins a variable reference, and event 2 ends its optional fallback.
-///
-/// # Safety
-/// `value` must point at live unresolved style value data, and `visit` must remain callable for
-/// the duration of this function.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn rust_unresolved_style_value_visit_reification(
- value: *const c_void,
- context: *mut c_void,
- visit: unsafe extern "C" fn(*mut c_void, u8, *const u16, usize, bool),
-) {
- let StyleValueData::Unresolved(unresolved_payload) = (unsafe { &*value.cast::<StyleValueData>() }) else {
+/// The text and the variable references of an unresolved value, for a CSSUnparsedValue.
+pub(crate) fn reified_unresolved_segments(value: &StyleValueData) -> Vec<ReifiedUnresolvedSegment> {
+ let StyleValueData::Unresolved(unresolved_payload) = value else {
unreachable!("reification requires an unresolved style value");
};
- let segments = reify_unresolved_segments(&unresolved_payload.components());
- visit_reified_unresolved_segments(&segments, context, visit);
+ reify_unresolved_segments(&unresolved_payload.components())
}
#[cfg(test)]
diff --git a/Libraries/LibWeb/Rust/src/css/typed_om.rs b/Libraries/LibWeb/Rust/src/css/typed_om.rs
new file mode 100644
index 00000000000..51204897257
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/typed_om.rs
@@ -0,0 +1,625 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! What the objects of the CSS Typed OM are built from and turned into, without the objects themselves, which live in
+//! the bindings: units, numeric types and sum values, and the reification of style values.
+//! https://drafts.css-houdini.org/css-typed-om-1/
+
+use std::collections::BTreeMap;
+use std::sync::Arc;
+
+pub use crate::css::calc::{CalcNode, CalcNumericType as NumericType, FfiNumericType};
+use crate::css::calc::{CalcNumericValue, canonical_unit_code};
+use crate::css::css_enums::{keyword, keyword_from_ascii_case_insensitive};
+use crate::css::dimension_units::{
+ ANGLE_UNIT_CANONICAL_RATIOS, ANGLE_UNIT_NAMES, FLEX_UNIT_CANONICAL_RATIOS, FLEX_UNIT_NAMES,
+ FREQUENCY_UNIT_CANONICAL_RATIOS, FREQUENCY_UNIT_NAMES, RESOLUTION_UNIT_CANONICAL_RATIOS, RESOLUTION_UNIT_NAMES,
+ TIME_UNIT_CANONICAL_RATIOS, TIME_UNIT_NAMES,
+};
+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::property_metadata::is_custom_property_name;
+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;
+pub use crate::css::style_value::{ReifiedUnresolvedSegment, RetainedStyleValueData as RetainedStyleValue};
+
+/// The base types of a numeric type, as indices of [`NumericType::exponents`].
+pub const BASE_TYPE_LENGTH: usize = 0;
+pub const BASE_TYPE_ANGLE: usize = 1;
+pub const BASE_TYPE_TIME: usize = 2;
+pub const BASE_TYPE_FREQUENCY: usize = 3;
+pub const BASE_TYPE_RESOLUTION: usize = 4;
+pub const BASE_TYPE_FLEX: usize = 5;
+pub const BASE_TYPE_PERCENT: usize = 6;
+
+#[derive(Clone, Copy, Eq, PartialEq)]
+pub enum DimensionType {
+ Angle,
+ Flex,
+ Frequency,
+ Length,
+ Resolution,
+ Time,
+}
+
+impl DimensionType {
+ const ALL: [DimensionType; 6] = [
+ DimensionType::Angle,
+ DimensionType::Flex,
+ DimensionType::Frequency,
+ DimensionType::Length,
+ DimensionType::Resolution,
+ DimensionType::Time,
+ ];
+
+ fn unit_names(self) -> &'static [&'static str] {
+ match self {
+ DimensionType::Angle => &ANGLE_UNIT_NAMES,
+ DimensionType::Flex => &FLEX_UNIT_NAMES,
+ DimensionType::Frequency => &FREQUENCY_UNIT_NAMES,
+ DimensionType::Length => &LENGTH_UNIT_NAMES,
+ DimensionType::Resolution => &RESOLUTION_UNIT_NAMES,
+ DimensionType::Time => &TIME_UNIT_NAMES,
+ }
+ }
+
+ fn canonical_ratios(self) -> &'static [f64] {
+ match self {
+ DimensionType::Angle => &ANGLE_UNIT_CANONICAL_RATIOS,
+ DimensionType::Flex => &FLEX_UNIT_CANONICAL_RATIOS,
+ DimensionType::Frequency => &FREQUENCY_UNIT_CANONICAL_RATIOS,
+ DimensionType::Length => &LENGTH_UNIT_CANONICAL_PX_RATIOS,
+ DimensionType::Resolution => &RESOLUTION_UNIT_CANONICAL_RATIOS,
+ DimensionType::Time => &TIME_UNIT_CANONICAL_RATIOS,
+ }
+ }
+
+ fn base_type(self) -> usize {
+ match self {
+ DimensionType::Angle => BASE_TYPE_ANGLE,
+ DimensionType::Flex => BASE_TYPE_FLEX,
+ DimensionType::Frequency => BASE_TYPE_FREQUENCY,
+ DimensionType::Length => BASE_TYPE_LENGTH,
+ DimensionType::Resolution => BASE_TYPE_RESOLUTION,
+ DimensionType::Time => BASE_TYPE_TIME,
+ }
+ }
+
+ /// The name of the unit with the code.
+ pub fn unit_name(self, unit: u8) -> &'static str {
+ self.unit_names()[usize::from(unit)]
+ }
+}
+
+/// The dimension that the unit belongs to and its code, in any ASCII case.
+pub fn dimension_for_unit(unit: &str) -> Option<(DimensionType, u8)> {
+ DimensionType::ALL.iter().find_map(|dimension| {
+ let code = dimension
+ .unit_names()
+ .iter()
+ .position(|name| name.eq_ignore_ascii_case(unit))?;
+ Some((*dimension, u8::try_from(code).expect("a dimension has few units")))
+ })
+}
+
+/// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue-create-a-type
+pub fn create_a_type_from_unit(unit: &str) -> Option<NumericType> {
+ // To create a type from a string unit, follow the appropriate branch of the following:
+
+ // unit is "number"
+ if unit == "number" {
+ // Return «[ ]» (empty map)
+ return Some(NumericType::default());
+ }
+
+ let mut result = NumericType::default();
+
+ // unit is "percent"
+ if unit == "percent" {
+ // Return «[ "percent" → 1 ]»
+ result.exponents[BASE_TYPE_PERCENT] = Some(1);
+ return Some(result);
+ }
+
+ // unit is a <length> unit, an <angle> unit, a <time> unit, a <frequency> unit, a <resolution-unit> or a <flex> unit
+ let (dimension, _) = dimension_for_unit(unit)?;
+ result.exponents[dimension.base_type()] = Some(1);
+ Some(result)
+}
+
+/// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue-unit-map
+pub type UnitMap = BTreeMap<String, i32>;
+
+/// https://drafts.css-houdini.org/css-typed-om-1/#product-of-two-unit-maps
+pub fn product_of_two_unit_maps(units1: &UnitMap, units2: &UnitMap) -> UnitMap {
+ // 1. Let result be a copy of units1.
+ let mut result = units1.clone();
+
+ // 2. For each unit → power in units2:
+ for (unit, power) in units2 {
+ // 1. If result[unit] exists, increment result[unit] by power.
+ // 2. Otherwise, set result[unit] to power.
+ *result.entry(unit.clone()).or_insert(0) += power;
+ }
+
+ // 3. Return result.
+ result
+}
+
+/// https://drafts.css-houdini.org/css-typed-om-1/#create-a-type-from-a-unit-map
+pub fn create_a_type_from_a_unit_map(unit_map: &UnitMap) -> Option<NumericType> {
+ // 1. Let types be an initially empty list.
+ let mut types = Vec::new();
+
+ // 2. For each unit → power in unit map:
+ for (unit, power) in unit_map {
+ // 1. Let type be the result of creating a type from unit.
+ let mut r#type = create_a_type_from_unit(unit).expect("a unit map holds units");
+
+ // 2. Set type’s sole value to power.
+ let sole_type = r#type
+ .exponents
+ .iter()
+ .position(Option::is_some)
+ .expect("the type of a unit has a value");
+ r#type.exponents[sole_type] = Some(*power);
+
+ // 3. Append type to types.
+ types.push(r#type);
+ }
+
+ // 3. Return the result of multiplying all the items of types.
+ // NB: Multiplying no types at all, as for the empty unit map of a plain number, results in an empty type.
+ let mut types = types.into_iter();
+ let Some(mut result) = types.next() else {
+ return Some(NumericType::default());
+ };
+ for r#type in types {
+ result = result.multiplied_by(&r#type)?;
+ }
+ Some(result)
+}
+
+/// https://drafts.css-houdini.org/css-typed-om-1/#cssnumericvalue-sum-value
+#[derive(Clone)]
+pub struct SumValueItem {
+ pub value: f64,
+ pub unit_map: UnitMap,
+}
+
+pub type SumValue = Vec<SumValueItem>;
+
+/// The value in the canonical unit of the set of compatible units that the unit is a member of, with that unit.
+pub fn in_canonical_unit(value: f64, unit: &str) -> (f64, String) {
+ let Some((dimension, code)) = dimension_for_unit(unit) else {
+ return (value, unit.to_owned());
+ };
+ let ratios = dimension.canonical_ratios();
+ let ratio = ratios[usize::from(code)];
+ // NB: Relative units have no ratio, and are not members of the set of the canonical unit.
+ if ratio.is_nan() {
+ return (value, unit.to_owned());
+ }
+ let canonical_unit = canonical_unit_code(ratios);
+ if code == canonical_unit {
+ return (value, unit.to_owned());
+ }
+ (value * ratio, dimension.unit_name(canonical_unit).to_owned())
+}
+
+/// The ratio that converts a value in the unit `from` to the unit `to`, if they are compatible.
+pub fn conversion_ratio(from: &str, to: &str) -> Option<f64> {
+ // NB: If the units are identical, they're always compatible. That also covers cases of `number` and `percent`
+ // which aren't actually units.
+ if from == to {
+ return Some(1.0);
+ }
+ let (from_dimension, from_code) = dimension_for_unit(from)?;
+ let (to_dimension, to_code) = dimension_for_unit(to)?;
+ if from_dimension != to_dimension {
+ return None;
+ }
+ if from_code == to_code {
+ return Some(1.0);
+ }
+ let ratios = from_dimension.canonical_ratios();
+ let from_ratio = ratios[usize::from(from_code)];
+ let to_ratio = ratios[usize::from(to_code)];
+ if from_ratio.is_nan() || to_ratio.is_nan() {
+ return None;
+ }
+ Some(from_ratio / to_ratio)
+}
+
+/// A numeric value of a CSSUnitValue as the rest of the engine knows it.
+#[derive(Clone, Copy)]
+pub enum NumericValue {
+ Number(f64),
+ Percentage(f64),
+ Dimension {
+ dimension: DimensionType,
+ value: f64,
+ unit: u8,
+ },
+}
+
+impl NumericValue {
+ pub fn from_unit(value: f64, unit: &str) -> Option<Self> {
+ if unit == "number" {
+ return Some(Self::Number(value));
+ }
+ if unit == "percent" {
+ return Some(Self::Percentage(value));
+ }
+ let (dimension, unit) = dimension_for_unit(unit)?;
+ Some(Self::Dimension { dimension, value, unit })
+ }
+
+ pub fn calculation_node(self) -> Arc<CalcNode> {
+ let numeric = match self {
+ Self::Number(value) => CalcNumericValue::Number { value, number_type: 0 },
+ Self::Percentage(value) => CalcNumericValue::Percentage(value),
+ Self::Dimension { dimension, value, unit } => match dimension {
+ DimensionType::Angle => CalcNumericValue::Angle { value, unit },
+ DimensionType::Flex => CalcNumericValue::Flex { value, unit },
+ DimensionType::Frequency => CalcNumericValue::Frequency { value, unit },
+ DimensionType::Length => CalcNumericValue::Length { value, unit },
+ DimensionType::Resolution => CalcNumericValue::Resolution { value, unit },
+ DimensionType::Time => CalcNumericValue::Time { value, unit },
+ },
+ };
+ Arc::new(CalcNode::Numeric(numeric))
+ }
+
+ pub fn style_value(self) -> RetainedStyleValue {
+ RetainedStyleValue::from_owned(match self {
+ Self::Number(value) => StyleValueData::Number { value },
+ Self::Percentage(value) => StyleValueData::Percentage { value },
+ Self::Dimension { dimension, value, unit } => match dimension {
+ DimensionType::Angle => StyleValueData::Angle { unit, value },
+ DimensionType::Flex => StyleValueData::Flex { unit, value },
+ DimensionType::Frequency => StyleValueData::Frequency { unit, value },
+ DimensionType::Length => StyleValueData::Length { unit, value },
+ DimensionType::Resolution => StyleValueData::Resolution { unit, value },
+ DimensionType::Time => StyleValueData::Time { unit, value },
+ },
+ })
+ }
+}
+
+/// A number serialized with the rules of https://drafts.csswg.org/cssom/#serialize-a-css-value.
+pub fn serialize_a_number(s: &mut String, value: f64) {
+ let mut sink = TextSink::new();
+ crate::css::serialize::serialize_a_number(&mut sink, value, SerializationMode::Normal);
+ s.push_str(&String::from_utf16_lossy(&sink.into_utf16()));
+}
+
+/// https://drafts.csswg.org/cssom/#serialize-an-identifier
+pub fn serialize_an_identifier(identifier: &ak::Utf16String) -> ak::Utf16String {
+ let mut sink = TextSink::new();
+ let units = identifier.to_utf16();
+ crate::css::serialize::serialize_an_identifier(&mut sink, &crate::css::serialize::StringUnits::Utf16(&units));
+ ak::Utf16String::from_utf16(&sink.into_utf16())
+}
+
+/// https://drafts.csswg.org/css-variables/#custom-property
+pub fn is_a_custom_property_name_string(name: &ak::Utf16String) -> bool {
+ is_custom_property_name(&name.to_utf16())
+}
+
+/// An unresolved value of the text, which keeps the text as it is, or nothing if the arbitrary substitution functions
+/// in the text have invalid syntax.
+pub fn unresolved_style_value(text: &ak::Utf16String) -> Option<RetainedStyleValue> {
+ let units = text.to_utf16();
+ let values = component_values_from_source(units.as_ref()).ok()?;
+ let mut presence = SubstitutionFunctionsPresence::default();
+ collect_arbitrary_substitution_function_presence(&values, &mut presence).ok()?;
+ // NB: This is the C++ enumerator UnresolvedStyleValue::SourceTextMode::Preserve.
+ const SOURCE_TEXT_MODE_PRESERVE: u8 = 2;
+ // SAFETY: The units are readable for their length, and no parsed value is handed over.
+ Some(unsafe {
+ RetainedStyleValue::from_raw(
+ crate::css::style_value::rust_style_value_create_unresolved_from_source(
+ core::ptr::null(),
+ units.as_ptr(),
+ units.len(),
+ SOURCE_TEXT_MODE_PRESERVE,
+ presence.attr,
+ presence.dashed_function,
+ presence.env,
+ presence.if_,
+ presence.inherit,
+ presence.var,
+ false,
+ core::ptr::null(),
+ )
+ .cast(),
+ )
+ })
+}
+
+impl RetainedStyleValue {
+ /// The text of the value, in the numeric mode of the C++ enum SerializationMode.
+ pub fn serialize(&self, mode: u8) -> ak::Utf16String {
+ let mut sink = TextSink::new();
+ serialize_style_value(&mut sink, self.data(), SerializationMode::from_ffi(mode));
+ ak::Utf16String::from_utf16(&sink.into_utf16())
+ }
+
+ pub fn is_transformation(&self) -> bool {
+ matches!(self.data(), StyleValueData::Transformation(_))
+ }
+
+ /// Takes over one strong reference, which C++ hands over.
+ ///
+ /// # Safety
+ ///
+ /// `pointer` must be a non-null strong reference to a style value.
+ pub unsafe fn from_raw(pointer: *const core::ffi::c_void) -> Self {
+ // SAFETY: The caller hands over a strong reference.
+ unsafe { Self::from_retained_pointer(pointer.cast()) }
+ }
+
+ /// Gives up the strong reference, which the caller hands over to C++.
+ pub fn into_raw(self) -> *const core::ffi::c_void {
+ let pointer = self.pointer();
+ core::mem::forget(self);
+ pointer.cast()
+ }
+}
+
+/// What a style value reifies as, https://drafts.css-houdini.org/css-typed-om-1/#reify-stylevalue
+pub enum Reification {
+ /// A new CSSStyleValue that represents the value.
+ Default,
+ /// A new CSSImageValue that represents the value.
+ Image,
+ /// A new CSSKeywordValue with this value.
+ Keyword(ak::Utf16String),
+ /// A new CSSUnitValue with this value and unit.
+ Unit { value: f64, unit: String },
+ /// A <number> or <integer>, which is 0px in a property that expects a length.
+ Number { value: f64, is_integer: bool },
+ /// The reification of a value that this value holds.
+ Value(RetainedStyleValue),
+ /// The reification of a calculation.
+ Calculated,
+ /// The reification of a list of component values.
+ Unresolved(Vec<ReifiedUnresolvedSegment>),
+ /// The reification of a list of values.
+ List(Vec<RetainedStyleValue>),
+}
+
+fn dimension_reification(dimension: DimensionType, value: f64, unit: u8) -> Reification {
+ Reification::Unit {
+ value,
+ unit: dimension.unit_name(unit).to_owned(),
+ }
+}
+
+/// The steps of https://drafts.css-houdini.org/css-typed-om-1/#reify-stylevalue for the kind of the value.
+pub fn reification_of(value: &RetainedStyleValue) -> Reification {
+ match value.data() {
+ StyleValueData::ConicGradient(_)
+ | StyleValueData::Image(_)
+ | StyleValueData::ImageSet(_)
+ | StyleValueData::LinearGradient(_)
+ | StyleValueData::RadialGradient(_) => return Reification::Image,
+ StyleValueData::Angle { unit, value } => return dimension_reification(DimensionType::Angle, *value, *unit),
+ StyleValueData::Flex { unit, value } => return dimension_reification(DimensionType::Flex, *value, *unit),
+ StyleValueData::Frequency { unit, value } => {
+ return dimension_reification(DimensionType::Frequency, *value, *unit);
+ }
+ StyleValueData::Length { unit, value } => return dimension_reification(DimensionType::Length, *value, *unit),
+ StyleValueData::Percentage { value } => {
+ return Reification::Unit {
+ value: *value,
+ unit: "percent".to_owned(),
+ };
+ }
+ StyleValueData::Resolution { unit, value } => {
+ return dimension_reification(DimensionType::Resolution, *value, *unit);
+ }
+ StyleValueData::Time { unit, value } => return dimension_reification(DimensionType::Time, *value, *unit),
+ StyleValueData::BackgroundSize(size) => {
+ // NB: A background size whose height is `auto` serializes as just its width, so reify it as that width. For
+ // example, the `auto` keyword is parsed as a size of `auto auto`.
+ if matches!(size.size_y.data(), StyleValueData::Keyword { keyword } if *keyword == keyword::AUTO) {
+ return Reification::Value(size.size_x.clone());
+ }
+ }
+ StyleValueData::Calculated(_) => return Reification::Calculated,
+ StyleValueData::CustomIdent { custom_ident } => {
+ // https://drafts.css-houdini.org/css-typed-om-1/#reify-ident
+ // 1. Return a new CSSKeywordValue with its value internal slot set to the serialization of ident.
+ return Reification::Keyword(ak::Utf16String::from_utf16(custom_ident.units()));
+ }
+ StyleValueData::Easing(easing) => {
+ // NB: Preserve authored step keywords until computation canonicalizes them to steps().
+ if easing.is_keyword {
+ // NB: This is the C++ enumerator StepPosition::Start.
+ const STEP_POSITION_START: u8 = 4;
+ let keyword = if easing.step_position == STEP_POSITION_START {
+ "step-start"
+ } else {
+ "step-end"
+ };
+ return Reification::Keyword(ak::Utf16String::from_utf8(keyword));
+ }
+ }
+ StyleValueData::Integer { value } => {
+ return Reification::Number {
+ value: f64::from(*value),
+ is_integer: true,
+ };
+ }
+ StyleValueData::Keyword { .. } => {
+ // https://drafts.css-houdini.org/css-typed-om-1/#reify-ident
+ // 1. Return a new CSSKeywordValue with its value internal slot set to the serialization of ident.
+ return Reification::Keyword(value.serialize(0));
+ }
+ StyleValueData::Number { value } => {
+ return Reification::Number {
+ value: *value,
+ is_integer: false,
+ };
+ }
+ StyleValueData::OpacityValue { value } => return Reification::Value(value.clone()),
+ StyleValueData::GridTrackSizeList(_) => {
+ // NB: A track list that is just one track size, as for `grid-auto-columns: 10px`, is that track size.
+ let track_size = crate::css::style_value::rust_style_value_grid_track_size_list_single_size(value.data());
+ if !track_size.is_null() {
+ // SAFETY: The value holds the track size alive, and this takes its own strong reference.
+ return Reification::Value(unsafe {
+ RetainedStyleValue::from_raw(crate::css::style_value::rust_style_value_retain(track_size).cast())
+ });
+ }
+ }
+ StyleValueData::TextIndent {
+ hanging,
+ each_line,
+ length_percentage,
+ } => {
+ // NB: A text-indent without the `hanging` or `each-line` keywords is just its length-percentage.
+ if !hanging && !each_line {
+ return Reification::Value(length_percentage.clone());
+ }
+ }
+ StyleValueData::Unresolved(_) => {
+ return Reification::Unresolved(crate::css::style_value::reified_unresolved_segments(value.data()));
+ }
+ StyleValueData::ValueList { values, .. } => {
+ return Reification::List(values.as_slice().to_vec());
+ }
+ _ => {}
+ }
+
+ // AD-HOC: Some values that are just a single keyword are represented by a more specific type, for example
+ // `font-style: italic`, `grid-auto-flow: row` or `font-variant-numeric: ordinal`. Reify those as the
+ // keyword. Colors and shorthands are left alone, as they are not keywords on their own.
+ if !matches!(
+ value.data(),
+ StyleValueData::ColorFunction(_)
+ | StyleValueData::ColorMix(_)
+ | StyleValueData::ContrastColor { .. }
+ | StyleValueData::Shorthand(_)
+ ) {
+ let serialized_value = value.serialize(0);
+ if keyword_from_ascii_case_insensitive(&serialized_value.to_utf16()).is_some() {
+ return Reification::Keyword(serialized_value);
+ }
+ }
+
+ Reification::Default
+}
+
+/// The nodes of a calculation in postorder, and the indices of their children, if the calculation has no math function
+/// that is not reifiable yet.
+pub fn calculation_nodes(value: &RetainedStyleValue) -> Option<(Vec<CalcReificationNode>, Vec<usize>)> {
+ crate::css::calc::reification_nodes(value.data())
+}
+
+pub use crate::css::calc::CalcReificationNode;
+
+/// https://drafts.csswg.org/css-transforms-2/#typedef-transform-function
+#[derive(Clone, Copy, Eq, PartialEq)]
+#[repr(u8)]
+pub enum TransformFunction {
+ Matrix,
+ Matrix3d,
+ Perspective,
+ Translate,
+ Translate3d,
+ TranslateX,
+ TranslateY,
+ TranslateZ,
+ Scale,
+ Scale3d,
+ ScaleX,
+ ScaleY,
+ ScaleZ,
+ Rotate,
+ Rotate3d,
+ RotateX,
+ RotateY,
+ RotateZ,
+ Skew,
+ SkewX,
+ SkewY,
+}
+
+impl TransformFunction {
+ /// The functions, in the order of the codes that TransformFunctions.json gives them.
+ const ALL: [Self; 21] = [
+ Self::Matrix,
+ Self::Matrix3d,
+ Self::Perspective,
+ Self::Translate,
+ Self::Translate3d,
+ Self::TranslateX,
+ Self::TranslateY,
+ Self::TranslateZ,
+ Self::Scale,
+ Self::Scale3d,
+ Self::ScaleX,
+ Self::ScaleY,
+ Self::ScaleZ,
+ Self::Rotate,
+ Self::Rotate3d,
+ Self::RotateX,
+ Self::RotateY,
+ Self::RotateZ,
+ Self::Skew,
+ Self::SkewX,
+ Self::SkewY,
+ ];
+}
+
+/// A <transform-function> value of the property.
+pub fn transformation_style_value(
+ property_id: u16,
+ transform_function: TransformFunction,
+ values: Vec<RetainedStyleValue>,
+) -> RetainedStyleValue {
+ let values: Vec<_> = values.into_iter().map(|value| value.into_raw().cast()).collect();
+ // SAFETY: This hands over one strong reference to each of the values.
+ unsafe {
+ RetainedStyleValue::from_raw(
+ crate::css::style_value::rust_style_value_create_transformation(
+ property_id,
+ transform_function as u8,
+ values.as_ptr(),
+ values.len(),
+ )
+ .cast(),
+ )
+ }
+}
+
+/// The function and the arguments of a <transform-function> value.
+pub fn transformation_parts(value: &RetainedStyleValue) -> (TransformFunction, Vec<RetainedStyleValue>) {
+ let StyleValueData::Transformation(transformation) = value.data() else {
+ panic!("the value is a transform function");
+ };
+ (
+ TransformFunction::ALL[usize::from(transformation.transform_function)],
+ transformation.values.as_slice().to_vec(),
+ )
+}
+
+/// The matrix of a <transform-function> value, row by row, if it has one without a layout.
+pub fn transform_matrix(value: &RetainedStyleValue) -> Option<[f32; 16]> {
+ let mut matrix = [0.0_f32; 16];
+ let mut is_2d = true;
+ crate::css::table_group_builder::rust_transform_list_to_abstract_matrix(
+ value.data(),
+ ak::SpanMut::new(matrix.as_mut_slice()),
+ &mut is_2d,
+ )
+ .then_some(matrix)
+}
diff --git a/Libraries/LibWeb/Rust/src/lib.rs b/Libraries/LibWeb/Rust/src/lib.rs
index b5522003a2d..91f7d45030a 100644
--- a/Libraries/LibWeb/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Rust/src/lib.rs
@@ -34,6 +34,7 @@ pub(crate) mod svg;
// What libweb_bindings_rust, whose interfaces are implemented in Rust, uses of this crate.
pub use css::media_list::{MediaList as NativeMediaList, MediaListDeleteResult};
+pub use css::typed_om;
pub use svg::gfx_path_from_path_data;
/// The red, green, blue and alpha of a CSS <color> in ASCII that needs nothing to be resolved against, or None for any
diff --git a/Tests/LibWeb/Text/expected/css/typed-om-clamp-lower-above-upper.txt b/Tests/LibWeb/Text/expected/css/typed-om-clamp-lower-above-upper.txt
new file mode 100644
index 00000000000..955e5afa904
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/typed-om-clamp-lower-above-upper.txt
@@ -0,0 +1,4 @@
+value between the bounds: 5
+value below lower: 5
+value above upper: 5
+lower above upper: 10
diff --git a/Tests/LibWeb/Text/expected/css/typed-om-min-max-nan.txt b/Tests/LibWeb/Text/expected/css/typed-om-min-max-nan.txt
new file mode 100644
index 00000000000..b061936ccdd
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/typed-om-min-max-nan.txt
@@ -0,0 +1,4 @@
+min, NaN first: NaN
+min, NaN last: 1
+max, NaN first: NaN
+max, NaN last: 1
diff --git a/Tests/LibWeb/Text/input/css/typed-om-clamp-lower-above-upper.html b/Tests/LibWeb/Text/input/css/typed-om-clamp-lower-above-upper.html
new file mode 100644
index 00000000000..a8edd7e5a55
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/typed-om-clamp-lower-above-upper.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ test(() => {
+ const clamp = (lower, value, upper) => new CSSMathClamp(CSS.px(lower), CSS.px(value), CSS.px(upper)).to("px").value;
+ println(`value between the bounds: ${clamp(0, 5, 10)}`);
+ println(`value below lower: ${clamp(5, 0, 10)}`);
+ println(`value above upper: ${clamp(0, 10, 5)}`);
+ println(`lower above upper: ${clamp(10, 5, 0)}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/typed-om-min-max-nan.html b/Tests/LibWeb/Text/input/css/typed-om-min-max-nan.html
new file mode 100644
index 00000000000..26684e0fdc6
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/typed-om-min-max-nan.html
@@ -0,0 +1,12 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ test(() => {
+ const huge = CSS.px(1e308).mul(10);
+ const nan = huge.sub(huge);
+ println(`min, NaN first: ${nan.min(CSS.px(1)).value}`);
+ println(`min, NaN last: ${CSS.px(1).min(nan).value}`);
+ println(`max, NaN first: ${nan.max(CSS.px(1)).value}`);
+ println(`max, NaN last: ${CSS.px(1).max(nan).value}`);
+ });
+</script>