From 14f45ac78c4af8e41a62ceb28f68ee3c78d3c432 Mon Sep 17 00:00:00 2001 From: Lucas CHOLLET Date: Fri, 13 Dec 2024 16:22:16 -0500 Subject: [PATCH] LibWeb/CSS: Consider unresolved `calc()` when serializing in Normal mode Unfortunately, there is no explicit and step-by-step spec to perform the serialization of `color()` declared values, so while being spec-informed, this is quite ad-hoc. Fixes 81 subtests in: - css/css-color/parsing/color-valid-color-function.html --- Libraries/LibWeb/CSS/StyleValues/CSSColor.cpp | 38 ++++++++++++++++++- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/Libraries/LibWeb/CSS/StyleValues/CSSColor.cpp b/Libraries/LibWeb/CSS/StyleValues/CSSColor.cpp index 8d55fc045041..3ec0ea45c8f3 100644 --- a/Libraries/LibWeb/CSS/StyleValues/CSSColor.cpp +++ b/Libraries/LibWeb/CSS/StyleValues/CSSColor.cpp @@ -8,6 +8,7 @@ #include #include #include +#include namespace Web::CSS { @@ -90,9 +91,42 @@ CSSColor::Resolved CSSColor::resolve_properties() const } // https://www.w3.org/TR/css-color-4/#serializing-color-function-values -String CSSColor::to_string(SerializationMode) const +String CSSColor::to_string(SerializationMode mode) const { - // FIXME: Do this properly, taking unresolved calculated values into account. + if (mode == SerializationMode::Normal) { + auto convert_percentage = [](ValueComparingNonnullRefPtr const& value) -> RemoveReference { + if (is(*value)) + return NumberStyleValue::create(value->as_percentage().value() / 100); + return value; + }; + + auto alpha = convert_percentage(m_properties.alpha); + + bool const is_alpha_required = [&]() { + if (is(*alpha)) + return alpha->as_number().value() < 1; + return true; + }(); + + if (is(*alpha) && alpha->as_number().value() < 0) + alpha = NumberStyleValue::create(0); + + if (is_alpha_required) { + return MUST(String::formatted("color({} {} {} {} / {})", + string_view_from_color_type(m_color_type), + convert_percentage(m_properties.channels[0])->to_string(mode), + convert_percentage(m_properties.channels[1])->to_string(mode), + convert_percentage(m_properties.channels[2])->to_string(mode), + alpha->to_string(mode))); + } + + return MUST(String::formatted("color({} {} {} {})", + string_view_from_color_type(m_color_type), + convert_percentage(m_properties.channels[0])->to_string(mode), + convert_percentage(m_properties.channels[1])->to_string(mode), + convert_percentage(m_properties.channels[2])->to_string(mode))); + } + auto resolved = resolve_properties(); if (resolved.alpha == 1) { return MUST(String::formatted("color({} {} {} {})",