Skip to content

Commit

Permalink
LibWeb/CSS: Consider unresolved calc() when serializing in Normal mode
Browse files Browse the repository at this point in the history
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
  • Loading branch information
LucasChollet committed Dec 22, 2024
1 parent 89061dd commit 14f45ac
Showing 1 changed file with 36 additions and 2 deletions.
38 changes: 36 additions & 2 deletions Libraries/LibWeb/CSS/StyleValues/CSSColor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <AK/TypeCasts.h>
#include <LibWeb/CSS/Serialize.h>
#include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
#include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>

namespace Web::CSS {

Expand Down Expand Up @@ -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<CSSStyleValue> const& value) -> RemoveReference<decltype(value)> {
if (is<PercentageStyleValue>(*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<NumberStyleValue>(*alpha))
return alpha->as_number().value() < 1;
return true;
}();

if (is<NumberStyleValue>(*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({} {} {} {})",
Expand Down

0 comments on commit 14f45ac

Please sign in to comment.