Skip to content

Truly independent web browser

LibWeb: Serialize CSS declaration blocks in Rust

Andreas Kling8cb0dd34be7c
diff --git a/Libraries/LibWeb/CSS/CSSStyleProperties.cpp b/Libraries/LibWeb/CSS/CSSStyleProperties.cpp
index 5f2aa90259c..61ac78f84ff 100644
--- a/Libraries/LibWeb/CSS/CSSStyleProperties.cpp
+++ b/Libraries/LibWeb/CSS/CSSStyleProperties.cpp
@@ -1815,275 +1815,7 @@ WebIDL::ExceptionOr<void> CSSStyleProperties::set_css_float(Utf16View value)
// https://www.w3.org/TR/cssom/#serialize-a-css-declaration-block
Utf16String CSSStyleProperties::serialized() const
{
- // 1. Let list be an empty array.
- Vector<Utf16String> list;
-
- // 2. Let already serialized be an empty array.
- HashTable<PropertyID> already_serialized;
-
- Function<void(PropertyID)> append_property_to_already_serialized = [&](auto property) {
- already_serialized.set(property);
-
- // AD-HOC: The spec assumes that we only store values against expanded longhands, there are however limited
- // circumstances where we store against shorthands directly in addition to the expanded longhands. For
- // example if the value of the shorthand is unresolved we store an UnresolvedStyleValue against the
- // shorthand directly and a PendingSubstitutionStyleValue against each of the longhands. In the case we
- // serialize a shorthand directly we should also mark it's longhands as serialized to avoid serializing
- // them separately.
- if (property_is_shorthand(property)) {
- for (auto longhand : longhands_for_shorthand(property))
- append_property_to_already_serialized(longhand);
- }
- };
-
- // NB: The spec treats custom properties the same as any other property, and expects the above loop to handle them.
- // However, our implementation separates them from regular properties, so we need to handle them separately here.
- // FIXME: Is the relative order of custom properties and regular properties supposed to be preserved?
- for (auto const& declaration : custom_properties()) {
- // 1. Let property be declaration’s property name.
- auto const& property = declaration.key;
-
- // 2. If property is in already serialized, continue with the steps labeled declaration loop.
- // NB: It is never in already serialized, as there are no shorthands for custom properties.
-
- // 3. If property maps to one or more shorthand properties, let shorthands be an array of those shorthand properties, in preferred order.
- // NB: There are no shorthands for custom properties.
-
- // 4. Shorthand loop: For each shorthand in shorthands, follow these substeps: ...
- // NB: There are no shorthands for custom properties.
-
- // 5. Let value be the result of invoking serialize a CSS value of declaration.
- auto value = declaration.value.value->to_utf16_string(Web::CSS::SerializationMode::Normal);
-
- // 6. Let serialized declaration be the result of invoking serialize a CSS declaration with property name property, value value,
- // and the important flag set if declaration has its important flag set.
- auto serialized_declaration = serialize_a_css_declaration_to_utf16(property, value, declaration.value.important);
-
- // 7. Append serialized declaration to list.
- list.append(move(serialized_declaration));
-
- // 8. Append property to already serialized.
- // NB: We don't need to do this, as we don't have shorthands for custom properties.
- }
-
- // 3. Declaration loop: For each CSS declaration declaration in declaration block’s declarations, follow these substeps:
- for (auto& declaration : properties()) {
- // 1. Let property be declaration’s property name.
- auto property = declaration.property_id;
-
- // 2. If property is in already serialized, continue with the steps labeled declaration loop.
- if (already_serialized.contains(property))
- continue;
-
- // AD-HOC: A shorthand pending an outer shorthand has no value of its own to serialize. The outer shorthand
- // serializes for it, or else each of its longhands does.
- if (property_is_shorthand(property) && declaration.value->is_pending_substitution())
- continue;
-
- // 3. If property maps to one or more shorthand properties, let shorthands be an array of those shorthand properties, in preferred order.
- if (property_maps_to_shorthand(property)) {
- auto shorthands = shorthands_for_longhand(property);
-
- // 4. Shorthand loop: For each shorthand in shorthands, follow these substeps:
- for (auto shorthand : shorthands) {
- // 1. Let longhands be an array consisting of all CSS declarations in declaration block’s declarations
- // that are not in already serialized and have a property name that maps to one of the shorthand
- // properties in shorthands.
- Vector<StyleProperty> longhands;
-
- for (auto const& longhand_declaration : properties()) {
- if (!already_serialized.contains(longhand_declaration.property_id) && shorthands_for_longhand(longhand_declaration.property_id).contains_slow(shorthand))
- longhands.append(longhand_declaration);
- }
-
- // 2. If not all properties that map to shorthand are present in longhands, continue with the steps labeled shorthand loop.
- if (any_of(expanded_longhands_for_shorthand(shorthand), [&](auto longhand_id) { return !any_of(longhands, [&](auto const& longhand_declaration) { return longhand_declaration.property_id == longhand_id; }); }))
- continue;
-
- // 3. Let current longhands be an empty array.
- Vector<StyleProperty> current_longhands;
-
- // 4. Append all CSS declarations in longhands that have a property name that maps to shorthand to current longhands.
- for (auto const& longhand : longhands) {
- if (shorthands_for_longhand(longhand.property_id).contains_slow(shorthand))
- current_longhands.append(longhand);
- }
-
- // 5. If there are one or more CSS declarations in current longhands have their important flag set and
- // one or more with it unset, continue with the steps labeled shorthand loop.
- auto all_declarations_have_same_important_flag = true;
-
- for (size_t i = 1; i < current_longhands.size(); ++i) {
- if (current_longhands[i].important != current_longhands[0].important) {
- all_declarations_have_same_important_flag = false;
- break;
- }
- }
-
- if (!all_declarations_have_same_important_flag)
- continue;
-
- // 6. If there is any declaration in declaration block in between the first and the last longhand
- // in current longhands which belongs to the same logical property group, but has a different
- // mapping logic as any of the longhands in current longhands, and is not in current
- // longhands, continue with the steps labeled shorthand loop.
- auto first_current_longhand_index = properties().find_first_index_if([&](StyleProperty const& current_declaration) { return current_declaration.property_id == current_longhands[0].property_id; });
- auto last_current_longhand_index = properties().find_first_index_if([&](StyleProperty const& current_declaration) { return current_declaration.property_id == current_longhands[current_longhands.size() - 1].property_id; });
-
- VERIFY(first_current_longhand_index.has_value());
- VERIFY(last_current_longhand_index.has_value());
-
- bool should_continue = false;
-
- for (auto current_declaration_index = first_current_longhand_index.value(); current_declaration_index <= last_current_longhand_index.value(); ++current_declaration_index) {
- // NB: Declaration is in current longhands
- if (any_of(current_longhands, [&](auto const& current_longhand) { return current_longhand.property_id == properties()[current_declaration_index].property_id; }))
- continue;
-
- auto logical_property_group_for_current_declaration = logical_property_group_for_property(properties()[current_declaration_index].property_id);
-
- if (!logical_property_group_for_current_declaration.has_value())
- continue;
-
- auto current_declaration_is_logical_alias = property_is_logical_alias(properties()[current_declaration_index].property_id);
-
- // NB: Declaration has any counterpart in current longhands with same logical property group but different mapping logic
- if (any_of(current_longhands, [&](auto const& current_longhand) { return logical_property_group_for_property(current_longhand.property_id) == logical_property_group_for_current_declaration && property_is_logical_alias(current_longhand.property_id) != current_declaration_is_logical_alias; })) {
- should_continue = true;
- break;
- }
- }
-
- if (should_continue)
- continue;
-
- // 7. Let value be the result of invoking serialize a CSS value with current longhands.
- auto value = serialize_a_css_value_to_utf16(current_longhands);
-
- // 8. If value is the empty string, continue with the steps labeled shorthand loop.
- if (value.is_empty())
- continue;
-
- // 9. Let serialized declaration be the result of invoking serialize a CSS declaration with property
- // name shorthand, value value, and the important flag set if the CSS declarations in current
- // longhands have their important flag set.
- auto serialized_declaration = serialize_a_css_declaration_to_utf16(string_from_property_id(shorthand), value, current_longhands.first().important);
-
- // 10. Append serialized declaration to list.
- list.append(move(serialized_declaration));
-
- // 11. Append the property names of all items of current longhands to already serialized.
- for (auto const& longhand : current_longhands)
- append_property_to_already_serialized(longhand.property_id);
-
- // 12. Continue with the steps labeled declaration loop.
- }
- }
-
- // FIXME: File spec issue that this should only be run if we haven't serialized this declaration in the above shorthand loop.
- if (!already_serialized.contains(declaration.property_id)) {
- // 5. Let value be the result of invoking serialize a CSS value of declaration.
- auto value = serialize_a_css_value_to_utf16(declaration);
-
- // 6. Let serialized declaration be the result of invoking serialize a CSS declaration with property name property, value value,
- // and the important flag set if declaration has its important flag set.
- auto serialized_property_name = property_is_legacy_shorthand(property)
- ? string_from_property_id(longhands_for_shorthand(property).first())
- : string_from_property_id(property);
- auto serialized_declaration = serialize_a_css_declaration_to_utf16(serialized_property_name, value, declaration.important);
-
- // 7. Append serialized declaration to list.
- list.append(move(serialized_declaration));
-
- // 8. Append property to already serialized.
- append_property_to_already_serialized(declaration.property_id);
- }
- }
-
- // 4. Return list joined with " " (U+0020).
- Utf16StringBuilder builder;
- for (size_t i = 0; i < list.size(); ++i) {
- if (i != 0)
- builder.append_ascii(' ');
- builder.append(list[i]);
- }
- return builder.to_string();
-}
-
-// https://www.w3.org/TR/cssom/#serialize-a-css-value
-Utf16String CSSStyleProperties::serialize_a_css_value_to_utf16(StyleProperty const& declaration) const
-{
- // 1. If If this algorithm is invoked with a list list:
- // NOTE: This is handled in other other overload of this method
-
- // 2. Represent the value of the declaration as a list of CSS component values components that, when parsed
- // according to the property’s grammar, would represent that value. Additionally:
- // - If certain component values can appear in any order without changing the meaning of the value (a pattern
- // typically represented by a double bar || in the value syntax), reorder the component values to use the
- // canonical order of component values as given in the property definition table.
- // - If component values can be omitted or replaced with a shorter representation without changing the meaning
- // of the value, omit/replace them.
- // - If either of the above syntactic translations would be less backwards-compatible, do not perform them.
-
- // Spec Note: The rules described here outlines the general principles of serialization. For legacy reasons, some
- // properties serialize in a different manner, which is intentionally undefined here due to lack of
- // resources. Please consult your local reverse-engineer for details.
-
- // 3. Remove any <whitespace-token>s from components.
- // 4. Replace each component value in components with the result of invoking serialize a CSS component value.
- // 5. Join the items of components into a single string, inserting " " (U+0020 SPACE) between each pair of items
- // unless the second item is a "," (U+002C COMMA) Return the result.
-
- // AD-HOC: As the spec is vague we don't follow it exactly here.
- return declaration.value->to_utf16_string(Web::CSS::SerializationMode::Normal);
-}
-
-// https://www.w3.org/TR/cssom/#serialize-a-css-value
-Utf16String CSSStyleProperties::serialize_a_css_value_to_utf16(Vector<StyleProperty> list) const
-{
- if (list.is_empty())
- return {};
-
- // 1. Let shorthand be the first shorthand property, in preferred order, that exactly maps to all of the longhand properties in list.
- Optional<PropertyID> shorthand = shorthands_for_longhand(list.first().property_id).first_matching([&](PropertyID shorthand) {
- auto longhands_for_potential_shorthand = expanded_longhands_for_shorthand(shorthand);
-
- // The potential shorthand exactly maps to all of the longhand properties in list if:
- // a. The number of longhand properties in the list is equal to the number of longhand properties that the potential shorthand maps to.
- if (longhands_for_potential_shorthand.size() != list.size())
- return false;
-
- // b. All longhand properties in the list are contained in the list of longhands for the potential shorthand.
- return all_of(longhands_for_potential_shorthand, [&](auto longhand) { return any_of(list, [&](auto const& declaration) { return declaration.property_id == longhand; }); });
- });
-
- // 2. If there is no such shorthand or shorthand cannot exactly represent the values of all the properties in list, return the empty string.
- if (!shorthand.has_value())
- return {};
-
- // https://drafts.csswg.org/css-values-5/#pending-substitution-value
- // If any of the component longhand properties for a given shorthand are pending-substitution
- // values, or contain arbitrary substitution functions of their own that have not yet been substituted, the
- // shorthand property must serialize to the empty string.
- if (any_of(list, [](auto const& declaration) { return declaration.value->is_pending_substitution() || declaration.value->is_unresolved(); }))
- return {};
-
- // 3. Otherwise, serialize a CSS value from a hypothetical declaration of the property shorthand with its value representing the combined values of the declarations in list.
- Function<ValueComparingNonnullRefPtr<ShorthandStyleValue const>(PropertyID)> make_shorthand_value = [&](PropertyID shorthand_id) {
- auto longhand_ids = longhands_for_shorthand(shorthand_id);
- Vector<ValueComparingNonnullRefPtr<StyleValue const>> longhand_values;
-
- for (auto longhand_id : longhand_ids) {
- if (property_is_shorthand(longhand_id))
- longhand_values.append(make_shorthand_value(longhand_id));
- else
- longhand_values.append(list.first_matching([&](auto declaration) { return declaration.property_id == longhand_id; })->value);
- }
-
- return ShorthandStyleValue::create(shorthand_id, longhand_ids, longhand_values);
- };
-
- return make_shorthand_value(shorthand.value())->to_utf16_string(SerializationMode::Normal);
+ return Utf16String::adopt_raw(Parser::ValueParserFFI::rust_declaration_block_serialize(m_declarations.handle()));
}
// https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-csstext
diff --git a/Libraries/LibWeb/CSS/CSSStyleProperties.h b/Libraries/LibWeb/CSS/CSSStyleProperties.h
index dc86ea68f03..1e2e464fdfe 100644
--- a/Libraries/LibWeb/CSS/CSSStyleProperties.h
+++ b/Libraries/LibWeb/CSS/CSSStyleProperties.h
@@ -68,8 +68,6 @@ public:
WebIDL::ExceptionOr<void> set_css_float(Utf16View);
virtual Utf16String serialized() const final override;
- Utf16String serialize_a_css_value_to_utf16(StyleProperty const&) const;
- Utf16String serialize_a_css_value_to_utf16(Vector<StyleProperty>) const;
virtual WebIDL::ExceptionOr<void> set_css_text(Utf16View) override;
void set_declarations_from_text(Utf16View);
diff --git a/Libraries/LibWeb/CSS/Serialize.cpp b/Libraries/LibWeb/CSS/Serialize.cpp
index e6fb06a9fc7..5753cd4af60 100644
--- a/Libraries/LibWeb/CSS/Serialize.cpp
+++ b/Libraries/LibWeb/CSS/Serialize.cpp
@@ -247,70 +247,4 @@ String serialize_a_url(Utf16View url)
return builder.to_string_without_validation();
}
-// https://drafts.csswg.org/cssom/#serialize-a-css-declaration
-Utf16String serialize_a_css_declaration_to_utf16(Utf16View property, Utf16View value, Important important)
-{
- // 1. Let s be the empty string.
- Utf16StringBuilder builder;
-
- // 2. Append property to s.
- // AD-HOC: There's no place currently on the spec where the property name properly escaped,
- // and this needs to be done when custom properties have special characters.
- // Related spec issues:
- // - https://github.com/w3c/csswg-drafts/issues/11729
- // - https://github.com/w3c/csswg-drafts/issues/12258
- serialize_an_identifier(builder, property);
-
- // 3. Append ": " (U+003A U+0020) to s.
- builder.append_ascii(": "sv);
-
- // 4. If value contains any non-whitespace characters, append value to s.
- if (!value.is_ascii_whitespace())
- builder.append(value);
-
- // 5. If the important flag is set, append " !important" (U+0020 U+0021 U+0069 U+006D U+0070 U+006F U+0072 U+0074
- // U+0061 U+006E U+0074) to s.
- if (important == Important::Yes)
- builder.append_ascii(" !important"sv);
-
- // 6. Append ";" (U+003B) to s.
- builder.append_ascii(';');
-
- // 7. Return s.
- return builder.to_string();
-}
-
-// https://drafts.csswg.org/cssom/#serialize-a-css-declaration
-Utf16String serialize_a_css_declaration_to_utf16(StringView property, Utf16View value, Important important)
-{
- // 1. Let s be the empty string.
- Utf16StringBuilder builder;
-
- // 2. Append property to s.
- // AD-HOC: There's no place currently on the spec where the property name properly escaped,
- // and this needs to be done when custom properties have special characters.
- // Related spec issues:
- // - https://github.com/w3c/csswg-drafts/issues/11729
- // - https://github.com/w3c/csswg-drafts/issues/12258
- serialize_an_identifier(builder, property);
-
- // 3. Append ": " (U+003A U+0020) to s.
- builder.append_ascii(": "sv);
-
- // 4. If value contains any non-whitespace characters, append value to s.
- if (!value.is_ascii_whitespace())
- builder.append(value);
-
- // 5. If the important flag is set, append " !important" (U+0020 U+0021 U+0069 U+006D U+0070 U+006F U+0072 U+0074
- // U+0061 U+006E U+0074) to s.
- if (important == Important::Yes)
- builder.append_ascii(" !important"sv);
-
- // 6. Append ";" (U+003B) to s.
- builder.append_ascii(';');
-
- // 7. Return s.
- return builder.to_string();
-}
-
}
diff --git a/Libraries/LibWeb/CSS/Serialize.h b/Libraries/LibWeb/CSS/Serialize.h
index 98d4572cedf..a1ea5acab28 100644
--- a/Libraries/LibWeb/CSS/Serialize.h
+++ b/Libraries/LibWeb/CSS/Serialize.h
@@ -34,7 +34,4 @@ Utf16String serialize_an_identifier_to_utf16(Utf16View ident);
String serialize_a_string(Utf16View string);
String serialize_a_url(Utf16View url);
-Utf16String serialize_a_css_declaration_to_utf16(StringView property, Utf16View value, Important = Important::No);
-Utf16String serialize_a_css_declaration_to_utf16(Utf16View property, Utf16View value, Important = Important::No);
-
}
diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rs
index 85dc7923214..2189bf9ce8e 100644
--- a/Libraries/LibWeb/Rust/build.rs
+++ b/Libraries/LibWeb/Rust/build.rs
@@ -1106,6 +1106,7 @@ fn generate_property_metadata(manifest_dir: &Path, out_dir: &Path) -> Result<(),
// Shorthand expansion tables for the cascade. The "all" shorthand expands to every
// longhand except direction and unicode-bidi, mirroring the C++ generator.
let mut shorthand_rows = Vec::new();
+ let mut immediate_longhands = Vec::new();
for name in &shorthands {
let longhand_names: Vec<String> = if name == "all" {
properties
@@ -1130,6 +1131,7 @@ fn generate_property_metadata(manifest_dir: &Path, out_dir: &Path) -> Result<(),
};
let ids_row: Vec<u16> = longhand_names.iter().map(|longhand| ids[longhand]).collect();
shorthand_rows.push(format!(" &{ids_row:?},"));
+ immediate_longhands.push(longhand_names);
}
output.push_str(&format!(
"pub(crate) static SHORTHAND_EXPANSIONS: [&[u16]; {}] = [\n{}\n];\n\n",
@@ -1486,6 +1488,68 @@ fn generate_property_metadata(manifest_dir: &Path, out_dir: &Path) -> Result<(),
.map(|name| logical_group_by_property.get(name).copied().unwrap_or(0))
.collect();
let expanded_longhand_counts: Vec<usize> = expanded_shorthand_longhands.iter().map(Vec::len).collect();
+ let expanded_longhand_rows: Vec<String> = expanded_shorthand_longhands
+ .iter()
+ .map(|longhands| {
+ let row: Vec<u16> = longhands.iter().map(|longhand| ids[longhand]).collect();
+ format!(" &{row:?},")
+ })
+ .collect();
+
+ // Each property's shorthands, in preferred order: the most longhands first, then those not starting with "-",
+ // then those starting with "-webkit-", then lexicographically.
+ // https://drafts.csswg.org/cssom/#concept-shorthands-preferred-order
+ let is_legacy_shorthand = |name: &str| {
+ properties[name]
+ .get("legacy-shorthand")
+ .and_then(|value| value.as_bool())
+ };
+ let mut immediate_shorthands = std::collections::HashMap::<&str, Vec<&str>>::new();
+ for (name, longhands) in shorthands.iter().zip(&immediate_longhands) {
+ if is_legacy_shorthand(name) == Some(true) {
+ continue;
+ }
+ for longhand in longhands {
+ immediate_shorthands.entry(longhand).or_default().push(name);
+ }
+ }
+ fn shorthands_of<'a>(
+ property: &str,
+ immediate_shorthands: &std::collections::HashMap<&str, Vec<&'a str>>,
+ result: &mut Vec<&'a str>,
+ ) {
+ for shorthand in immediate_shorthands.get(property).into_iter().flatten() {
+ result.push(shorthand);
+ shorthands_of(shorthand, immediate_shorthands, result);
+ }
+ }
+ let expanded_longhand_count = |shorthand: &str| {
+ let index = shorthands.iter().position(|name| name == shorthand).unwrap();
+ expanded_longhand_counts[index]
+ };
+ let shorthands_for_longhand_rows: Vec<String> = property_names
+ .iter()
+ .map(|name| {
+ let mut result = Vec::new();
+ shorthands_of(name, &immediate_shorthands, &mut result);
+ result.sort_by_key(|shorthand| {
+ (
+ std::cmp::Reverse(expanded_longhand_count(shorthand)),
+ shorthand.starts_with('-'),
+ !shorthand.starts_with("-webkit-"),
+ *shorthand,
+ )
+ });
+ let row: Vec<u16> = result.iter().map(|shorthand| ids[*shorthand]).collect();
+ format!(" &{row:?},")
+ })
+ .collect();
+ let mut legacy_shorthands: Vec<u16> = shorthands
+ .iter()
+ .filter(|name| is_legacy_shorthand(name) == Some(true))
+ .map(|name| ids[name])
+ .collect();
+ legacy_shorthands.sort_unstable();
// Accepted property keywords are a property's valid identifiers and the
// keywords of the enums in its valid types.
@@ -1646,6 +1710,19 @@ fn generate_property_metadata(manifest_dir: &Path, out_dir: &Path) -> Result<(),
physical_to_logical_alias.len(),
physical_to_logical_alias
));
+ output.push_str(&format!(
+ "pub(crate) static EXPANDED_LONGHANDS_FOR_SHORTHAND: [&[u16]; {}] = [\n{}\n];\n\n",
+ expanded_longhand_rows.len(),
+ expanded_longhand_rows.join("\n")
+ ));
+ output.push_str(&format!(
+ "pub(crate) static SHORTHANDS_FOR_LONGHAND: [&[u16]; {}] = [\n{}\n];\n\n",
+ shorthands_for_longhand_rows.len(),
+ shorthands_for_longhand_rows.join("\n")
+ ));
+ output.push_str(&format!(
+ "pub(crate) static LEGACY_SHORTHANDS: &[u16] = &{legacy_shorthands:?};\n\n"
+ ));
output.push_str(&format!(
"pub(crate) static SHORTHAND_EXPANDED_LONGHAND_COUNTS: [usize; {}] = {:?};\n\n",
expanded_longhand_counts.len(),
diff --git a/Libraries/LibWeb/Rust/src/css/declaration_block.rs b/Libraries/LibWeb/Rust/src/css/declaration_block.rs
index ff44ca84c7c..4aa67593c4f 100644
--- a/Libraries/LibWeb/Rust/src/css/declaration_block.rs
+++ b/Libraries/LibWeb/Rust/src/css/declaration_block.rs
@@ -968,6 +968,12 @@ pub(crate) fn visit_declaration_images(data: &DeclarationBlockHeader, visit: &mu
}
}
+/// The block serialized, as a raw AK::Utf16String the caller adopts.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_declaration_block_serialize(block: &DeclarationBlock) -> usize {
+ crate::css::serialize::sink_into_raw(crate::css::serialize::serialize_a_css_declaration_block(&block.data()))
+}
+
#[unsafe(no_mangle)]
pub extern "C" fn rust_declaration_block_prefetch_header(block: &DeclarationBlock) {
block.prefetch_header();
diff --git a/Libraries/LibWeb/Rust/src/css/property_metadata.rs b/Libraries/LibWeb/Rust/src/css/property_metadata.rs
index 93c25a0e9f9..63495dccbaa 100644
--- a/Libraries/LibWeb/Rust/src/css/property_metadata.rs
+++ b/Libraries/LibWeb/Rust/src/css/property_metadata.rs
@@ -326,6 +326,23 @@ pub fn longhands_for_shorthand(property_id: u16) -> &'static [u16] {
SHORTHAND_EXPANSIONS[(property_id - FIRST_SHORTHAND_PROPERTY_ID) as usize]
}
+/// The longhands of a shorthand, through any shorthand nested in it.
+pub(crate) fn expanded_longhands_for_shorthand(property_id: u16) -> &'static [u16] {
+ if !property_is_shorthand(property_id) {
+ return &[];
+ }
+ EXPANDED_LONGHANDS_FOR_SHORTHAND[(property_id - FIRST_SHORTHAND_PROPERTY_ID) as usize]
+}
+
+/// The shorthands a property maps to, in preferred order.
+pub(crate) fn shorthands_for_longhand(property_id: u16) -> &'static [u16] {
+ SHORTHANDS_FOR_LONGHAND[property_index(property_id)]
+}
+
+pub(crate) fn property_is_legacy_shorthand(property_id: u16) -> bool {
+ LEGACY_SHORTHANDS.binary_search(&property_id).is_ok()
+}
+
pub(crate) fn property_is_positional_value_list_shorthand(property_id: u16) -> bool {
POSITIONAL_VALUE_LIST_SHORTHANDS.binary_search(&property_id).is_ok()
}
diff --git a/Libraries/LibWeb/Rust/src/css/serialize.rs b/Libraries/LibWeb/Rust/src/css/serialize.rs
index 9c0b2d29e92..da297929213 100644
--- a/Libraries/LibWeb/Rust/src/css/serialize.rs
+++ b/Libraries/LibWeb/Rust/src/css/serialize.rs
@@ -22,11 +22,14 @@ use crate::css::style_value::{
};
use std::fmt::Write;
+mod declarations;
mod shorthand;
use crate::css::css_enums::keyword;
use crate::css::css_tokenizer::TokenizerInput;
use crate::css::parser::component_value::{ComponentSerializationMode, serialize_component_values_into};
+pub(crate) use declarations::serialize_a_css_declaration_block;
+
use crate::css::style_value::{
BasicShapeData, COUNTER_FUNCTION_COUNTERS, RetainedColorStopList, RetainedString, StyleValueData,
};
diff --git a/Libraries/LibWeb/Rust/src/css/serialize/declarations.rs b/Libraries/LibWeb/Rust/src/css/serialize/declarations.rs
new file mode 100644
index 00000000000..6b7ae5e8fc9
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/serialize/declarations.rs
@@ -0,0 +1,345 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Serialization of a CSS declaration block.
+
+use super::*;
+use crate::css::declaration_block::{DeclarationBlockHeader, DeclarationRef};
+use crate::css::property_metadata::{
+ expanded_longhands_for_shorthand, longhands_for_shorthand, property_is_legacy_shorthand,
+ property_is_logical_alias_including_shorthands, property_is_shorthand, property_logical_group, property_name,
+ shorthands_for_longhand,
+};
+use crate::css::style_value::{RetainedPropertyIdList, RetainedStyleValueData, RetainedStyleValueDataList};
+use crate::css::style_value::{ShorthandPayload, StyleValueBox};
+use crate::css::style_value_arc::StyleValueArc;
+use std::collections::HashSet;
+
+fn append_property_to_already_serialized(already_serialized: &mut HashSet<u16>, property: u16) {
+ already_serialized.insert(property);
+
+ // AD-HOC: The spec assumes that we only store values against expanded longhands, there are however limited
+ // circumstances where we store against shorthands directly in addition to the expanded longhands. For
+ // example if the value of the shorthand is unresolved we store an UnresolvedStyleValue against the
+ // shorthand directly and a PendingSubstitutionStyleValue against each of the longhands. In the case we
+ // serialize a shorthand directly we should also mark it's longhands as serialized to avoid serializing
+ // them separately.
+ if property_is_shorthand(property) {
+ for &longhand in longhands_for_shorthand(property) {
+ append_property_to_already_serialized(already_serialized, longhand);
+ }
+ }
+}
+
+// https://drafts.csswg.org/cssom/#serialize-a-css-declaration
+fn serialize_a_css_declaration(list: &mut Vec<TextSink>, property: &StringUnits, value: TextSink, important: bool) {
+ // 1. Let s be the empty string.
+ let mut s = TextSink::new();
+
+ // 2. Append property to s.
+ // AD-HOC: There's no place currently on the spec where the property name properly escaped,
+ // and this needs to be done when custom properties have special characters.
+ // Related spec issues:
+ // - https://github.com/w3c/csswg-drafts/issues/11729
+ // - https://github.com/w3c/csswg-drafts/issues/12258
+ serialize_an_identifier(&mut s, property);
+
+ // 3. Append ": " (U+003A U+0020) to s.
+ s.push_ascii(": ");
+
+ // 4. If value contains any non-whitespace characters, append value to s.
+ let value = value.into_utf16();
+ if !value.iter().all(|&unit| unit == 0x20 || (0x09..=0x0D).contains(&unit)) {
+ for unit in value {
+ s.push_code_unit(unit);
+ }
+ }
+
+ // 5. If the important flag is set, append " !important" (U+0020 U+0021 U+0069 U+006D U+0070 U+006F U+0072
+ // U+0061 U+006E U+0074) to s.
+ if important {
+ s.push_ascii(" !important");
+ }
+
+ // 6. Append ";" (U+003B) to s.
+ s.push_ascii(";");
+
+ // 7. Return s.
+ list.push(s);
+}
+
+fn make_shorthand_value(shorthand: u16, list: &[DeclarationRef]) -> StyleValueArc {
+ let longhand_ids = longhands_for_shorthand(shorthand);
+ let longhand_values = longhand_ids
+ .iter()
+ .map(|&longhand_id| {
+ RetainedStyleValueData::from_arc(if property_is_shorthand(longhand_id) {
+ make_shorthand_value(longhand_id, list)
+ } else {
+ list.iter()
+ .find(|declaration| declaration.property_id == longhand_id)
+ .expect("the list holds every longhand of the shorthand")
+ .value
+ .clone()
+ })
+ })
+ .collect();
+ StyleValueArc::new(StyleValueData::Shorthand(StyleValueBox::new(ShorthandPayload {
+ shorthand_property: shorthand,
+ sub_properties: RetainedPropertyIdList::from_property_ids(longhand_ids.to_vec()),
+ values: RetainedStyleValueDataList::from_retained_values(longhand_values),
+ })))
+}
+
+// https://www.w3.org/TR/cssom/#serialize-a-css-value
+fn serialize_a_css_value_of_list(list: &[DeclarationRef]) -> TextSink {
+ let mut value = TextSink::new();
+ let Some(first) = list.first() else {
+ return value;
+ };
+
+ // 1. Let shorthand be the first shorthand property, in preferred order, that exactly maps to all of the longhand
+ // properties in list.
+ let shorthand = shorthands_for_longhand(first.property_id).iter().find(|&&shorthand| {
+ let longhands_for_potential_shorthand = expanded_longhands_for_shorthand(shorthand);
+
+ // The potential shorthand exactly maps to all of the longhand properties in list if:
+ // a. The number of longhand properties in the list is equal to the number of longhand properties that the
+ // potential shorthand maps to.
+ if longhands_for_potential_shorthand.len() != list.len() {
+ return false;
+ }
+
+ // b. All longhand properties in the list are contained in the list of longhands for the potential shorthand.
+ longhands_for_potential_shorthand
+ .iter()
+ .all(|&longhand| list.iter().any(|declaration| declaration.property_id == longhand))
+ });
+
+ // 2. If there is no such shorthand or shorthand cannot exactly represent the values of all the properties in
+ // list, return the empty string.
+ let Some(&shorthand) = shorthand else {
+ return value;
+ };
+
+ // https://drafts.csswg.org/css-values-5/#pending-substitution-value
+ // If any of the component longhand properties for a given shorthand are pending-substitution
+ // values, or contain arbitrary substitution functions of their own that have not yet been substituted, the
+ // shorthand property must serialize to the empty string.
+ if list.iter().any(|declaration| {
+ matches!(
+ &**declaration.value,
+ StyleValueData::PendingSubstitution { .. } | StyleValueData::Unresolved(_)
+ )
+ }) {
+ return value;
+ }
+
+ // 3. Otherwise, serialize a CSS value from a hypothetical declaration of the property shorthand with its value
+ // representing the combined values of the declarations in list.
+ serialize_style_value(
+ &mut value,
+ &make_shorthand_value(shorthand, list),
+ SerializationMode::Normal,
+ );
+ value
+}
+
+// https://drafts.csswg.org/cssom/#serialize-a-css-declaration-block
+pub(crate) fn serialize_a_css_declaration_block(block: &DeclarationBlockHeader) -> TextSink {
+ // 1. Let list be an empty array.
+ let mut list = Vec::new();
+
+ // 2. Let already serialized be an empty array.
+ let mut already_serialized = HashSet::new();
+
+ // NB: The spec treats custom properties the same as any other property, and expects the loop below to handle
+ // them. However, our implementation separates them from regular properties, so we handle them here.
+ // FIXME: Is the relative order of custom properties and regular properties supposed to be preserved?
+ for declaration in block.custom_properties().iter() {
+ // 5. Let value be the result of invoking serialize a CSS value of declaration.
+ let mut value = TextSink::new();
+ serialize_style_value(&mut value, declaration.declaration.value, SerializationMode::Normal);
+
+ // 6. Let serialized declaration be the result of invoking serialize a CSS declaration with property name
+ // property, value value, and the important flag set if declaration has its important flag set.
+ // 7. Append serialized declaration to list.
+ serialize_a_css_declaration(
+ &mut list,
+ &StringUnits::Utf16(declaration.name.units()),
+ value,
+ declaration.declaration.important,
+ );
+ }
+
+ let declarations: Vec<DeclarationRef> = block.properties().iter().collect();
+
+ // 3. Declaration loop: For each CSS declaration declaration in declaration block's declarations, follow these
+ // substeps:
+ for declaration in &declarations {
+ // 1. Let property be declaration's property name.
+ let property = declaration.property_id;
+
+ // 2. If property is in already serialized, continue with the steps labeled declaration loop.
+ if already_serialized.contains(&property) {
+ continue;
+ }
+
+ // AD-HOC: A shorthand pending an outer shorthand has no value of its own to serialize. The outer shorthand
+ // serializes for it, or else each of its longhands does.
+ if property_is_shorthand(property) && matches!(&**declaration.value, StyleValueData::PendingSubstitution { .. })
+ {
+ continue;
+ }
+
+ // 3. If property maps to one or more shorthand properties, let shorthands be an array of those shorthand
+ // properties, in preferred order.
+ let shorthands = shorthands_for_longhand(property);
+
+ // 4. Shorthand loop: For each shorthand in shorthands, follow these substeps:
+ for &shorthand in shorthands {
+ // 1. Let longhands be an array consisting of all CSS declarations in declaration block's declarations
+ // that are not in already serialized and have a property name that maps to one of the shorthand
+ // properties in shorthands.
+ let longhands: Vec<DeclarationRef> = declarations
+ .iter()
+ .filter(|longhand| {
+ !already_serialized.contains(&longhand.property_id)
+ && shorthands_for_longhand(longhand.property_id).contains(&shorthand)
+ })
+ .copied()
+ .collect();
+
+ // 2. If not all properties that map to shorthand are present in longhands, continue with the steps
+ // labeled shorthand loop.
+ if expanded_longhands_for_shorthand(shorthand)
+ .iter()
+ .any(|&longhand_id| !longhands.iter().any(|longhand| longhand.property_id == longhand_id))
+ {
+ continue;
+ }
+
+ // 3. Let current longhands be an empty array.
+ // 4. Append all CSS declarations in longhands that have a property name that maps to shorthand to current
+ // longhands.
+ // NB: longhands holds only those already, as it is made for this shorthand alone.
+ let current_longhands = longhands;
+
+ // 5. If there are one or more CSS declarations in current longhands have their important flag set and
+ // one or more with it unset, continue with the steps labeled shorthand loop.
+ if current_longhands
+ .iter()
+ .any(|longhand| longhand.important != current_longhands[0].important)
+ {
+ continue;
+ }
+
+ // 6. If there is any declaration in declaration block in between the first and the last longhand
+ // in current longhands which belongs to the same logical property group, but has a different
+ // mapping logic as any of the longhands in current longhands, and is not in current
+ // longhands, continue with the steps labeled shorthand loop.
+ let index_of = |property_id: u16| {
+ declarations
+ .iter()
+ .position(|current_declaration| current_declaration.property_id == property_id)
+ .expect("current longhands are declarations of the block")
+ };
+ let first_current_longhand_index = index_of(current_longhands[0].property_id);
+ let last_current_longhand_index = index_of(current_longhands[current_longhands.len() - 1].property_id);
+ let has_conflicting_declaration = declarations[first_current_longhand_index..=last_current_longhand_index]
+ .iter()
+ .any(|current_declaration| {
+ // NB: Declaration is in current longhands
+ if current_longhands
+ .iter()
+ .any(|longhand| longhand.property_id == current_declaration.property_id)
+ {
+ return false;
+ }
+
+ let Some(group) = property_logical_group(current_declaration.property_id) else {
+ return false;
+ };
+ let is_logical_alias =
+ property_is_logical_alias_including_shorthands(current_declaration.property_id);
+
+ // NB: Declaration has any counterpart in current longhands with same logical property group but
+ // different mapping logic
+ current_longhands.iter().any(|longhand| {
+ property_logical_group(longhand.property_id) == Some(group)
+ && property_is_logical_alias_including_shorthands(longhand.property_id) != is_logical_alias
+ })
+ });
+ if has_conflicting_declaration {
+ continue;
+ }
+
+ // 7. Let value be the result of invoking serialize a CSS value with current longhands.
+ let value = serialize_a_css_value_of_list(&current_longhands);
+
+ // 8. If value is the empty string, continue with the steps labeled shorthand loop.
+ if value.len() == 0 {
+ continue;
+ }
+
+ // 9. Let serialized declaration be the result of invoking serialize a CSS declaration with property
+ // name shorthand, value value, and the important flag set if the CSS declarations in current
+ // longhands have their important flag set.
+ // 10. Append serialized declaration to list.
+ serialize_a_css_declaration(
+ &mut list,
+ &StringUnits::Ascii(property_name(shorthand).as_bytes()),
+ value,
+ current_longhands[0].important,
+ );
+
+ // 11. Append the property names of all items of current longhands to already serialized.
+ for longhand in &current_longhands {
+ append_property_to_already_serialized(&mut already_serialized, longhand.property_id);
+ }
+
+ // 12. Continue with the steps labeled declaration loop.
+ // NB: The check below skips the rest of the declaration loop, and the remaining shorthands no longer have
+ // all of their longhands in longhands.
+ }
+
+ // FIXME: File spec issue that this should only be run if we haven't serialized this declaration in the above
+ // shorthand loop.
+ if !already_serialized.contains(&property) {
+ // 5. Let value be the result of invoking serialize a CSS value of declaration.
+ let mut value = TextSink::new();
+ serialize_style_value(&mut value, declaration.value, SerializationMode::Normal);
+
+ // 6. Let serialized declaration be the result of invoking serialize a CSS declaration with property name
+ // property, value value, and the important flag set if declaration has its important flag set.
+ // 7. Append serialized declaration to list.
+ let serialized_property_name = if property_is_legacy_shorthand(property) {
+ longhands_for_shorthand(property)[0]
+ } else {
+ property
+ };
+ serialize_a_css_declaration(
+ &mut list,
+ &StringUnits::Ascii(property_name(serialized_property_name).as_bytes()),
+ value,
+ declaration.important,
+ );
+
+ // 8. Append property to already serialized.
+ append_property_to_already_serialized(&mut already_serialized, property);
+ }
+ }
+
+ // 4. Return list joined with " " (U+0020).
+ let mut result = TextSink::new();
+ for (index, declaration) in list.into_iter().enumerate() {
+ if index != 0 {
+ result.push_ascii(" ");
+ }
+ result.push_sink(&declaration);
+ }
+ result
+}