1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 04:57:44 +00:00

LibWeb: Implement CSS hypot()

This commit is contained in:
stelar7 2023-05-28 11:43:04 +02:00 committed by Sam Atkins
parent 0d30fb5a6e
commit fa37bb8b76
4 changed files with 145 additions and 0 deletions

View file

@ -1344,6 +1344,82 @@ ErrorOr<void> SqrtCalculationNode::dump(StringBuilder& builder, int indent) cons
return {};
}
ErrorOr<NonnullOwnPtr<HypotCalculationNode>> HypotCalculationNode::create(Vector<NonnullOwnPtr<Web::CSS::CalculationNode>> values)
{
return adopt_nonnull_own_or_enomem(new (nothrow) HypotCalculationNode(move(values)));
}
HypotCalculationNode::HypotCalculationNode(Vector<NonnullOwnPtr<CalculationNode>> values)
: CalculationNode(Type::Hypot)
, m_values(move(values))
{
}
HypotCalculationNode::~HypotCalculationNode() = default;
ErrorOr<String> HypotCalculationNode::to_string() const
{
StringBuilder builder;
TRY(builder.try_append("hypot("sv));
for (size_t i = 0; i < m_values.size(); ++i) {
if (i != 0)
TRY(builder.try_append(", "sv));
TRY(builder.try_append(TRY(m_values[i]->to_string())));
}
TRY(builder.try_append(")"sv));
return builder.to_string();
}
Optional<CalculatedStyleValue::ResolvedType> HypotCalculationNode::resolved_type() const
{
// NOTE: We check during parsing that all values have the same type.
return m_values[0]->resolved_type();
}
bool HypotCalculationNode::contains_percentage() const
{
for (auto const& value : m_values) {
if (value->contains_percentage())
return true;
}
return false;
}
CalculatedStyleValue::CalculationResult HypotCalculationNode::resolve(Optional<Length::ResolutionContext const&> context, CalculatedStyleValue::PercentageBasis const& percentage_basis) const
{
double square_sum = 0.0;
for (auto const& value : m_values) {
auto child_resolved = value->resolve(context, percentage_basis);
auto child_value = resolve_value(child_resolved.value(), context);
square_sum += child_value * child_value;
}
auto result = sqrt(square_sum);
return to_resolved_type(resolved_type().value(), result);
}
ErrorOr<void> HypotCalculationNode::for_each_child_node(Function<ErrorOr<void>(NonnullOwnPtr<CalculationNode>&)> const& callback)
{
for (auto& value : m_values) {
TRY(value->for_each_child_node(callback));
TRY(callback(value));
}
return {};
}
ErrorOr<void> HypotCalculationNode::dump(StringBuilder& builder, int indent) const
{
TRY(builder.try_appendff("{: >{}}HYPOT:\n", "", indent));
for (auto const& value : m_values)
TRY(value->dump(builder, indent + 2));
return {};
}
void CalculatedStyleValue::CalculationResult::add(CalculationResult const& other, Optional<Length::ResolutionContext const&> context, PercentageBasis const& percentage_basis)
{
add_or_subtract_internal(SumOperation::Add, other, context, percentage_basis);