CSSHWB.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * Copyright (c) 2024, Sam Atkins <sam@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "CSSHWB.h"
  7. #include <AK/TypeCasts.h>
  8. #include <LibWeb/CSS/Serialize.h>
  9. namespace Web::CSS {
  10. Color CSSHWB::to_color(Optional<Layout::NodeWithStyle const&>) const
  11. {
  12. auto const h_val = resolve_hue(m_properties.h).value_or(0);
  13. auto const w_val = clamp(resolve_with_reference_value(m_properties.w, 100.0).value_or(0), 0, 100) / 100.0;
  14. auto const b_val = clamp(resolve_with_reference_value(m_properties.b, 100.0).value_or(0), 0, 100) / 100.0;
  15. auto const alpha_val = resolve_alpha(m_properties.alpha).value_or(1);
  16. if (w_val + b_val >= 1.0) {
  17. auto to_byte = [](double value) {
  18. return round_to<u8>(clamp(value * 255.0, 0.0, 255.0));
  19. };
  20. u8 gray = to_byte(w_val / (w_val + b_val));
  21. return Color(gray, gray, gray, to_byte(alpha_val));
  22. }
  23. float value = 1 - b_val;
  24. float saturation = 1 - (w_val / value);
  25. return Color::from_hsv(h_val, saturation, value).with_opacity(alpha_val);
  26. }
  27. bool CSSHWB::equals(CSSStyleValue const& other) const
  28. {
  29. if (type() != other.type())
  30. return false;
  31. auto const& other_color = other.as_color();
  32. if (color_type() != other_color.color_type())
  33. return false;
  34. auto const& other_hwb = verify_cast<CSSHWB>(other_color);
  35. return m_properties == other_hwb.m_properties;
  36. }
  37. // https://www.w3.org/TR/css-color-4/#serializing-sRGB-values
  38. String CSSHWB::to_string() const
  39. {
  40. // FIXME: Do this properly, taking unresolved calculated values into account.
  41. return serialize_a_srgb_value(to_color({}));
  42. }
  43. }