CSSLCHLike.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright (c) 2024, Sam Atkins <sam@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "CSSLCHLike.h"
  7. #include <AK/Math.h>
  8. #include <AK/TypeCasts.h>
  9. #include <LibWeb/CSS/Serialize.h>
  10. #include <LibWeb/CSS/StyleValues/CSSMathValue.h>
  11. #include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
  12. #include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
  13. namespace Web::CSS {
  14. bool CSSLCHLike::equals(CSSStyleValue const& other) const
  15. {
  16. if (type() != other.type())
  17. return false;
  18. auto const& other_color = other.as_color();
  19. if (color_type() != other_color.color_type())
  20. return false;
  21. auto const& other_oklch_like = verify_cast<CSSLCHLike>(other_color);
  22. return m_properties == other_oklch_like.m_properties;
  23. }
  24. Color CSSLCH::to_color(Optional<Layout::NodeWithStyle const&>) const
  25. {
  26. auto const l_val = clamp(resolve_with_reference_value(m_properties.l, 100).value_or(0), 0, 100);
  27. auto const c_val = resolve_with_reference_value(m_properties.c, 150).value_or(0);
  28. auto const h_val = AK::to_radians(resolve_hue(m_properties.h).value_or(0));
  29. auto const alpha_val = resolve_alpha(m_properties.alpha).value_or(1);
  30. return Color::from_lab(l_val, c_val * cos(h_val), c_val * sin(h_val), alpha_val);
  31. }
  32. // https://www.w3.org/TR/css-color-4/#serializing-lab-lch
  33. String CSSLCH::to_string() const
  34. {
  35. // FIXME: Do this properly, taking unresolved calculated values into account.
  36. return serialize_a_srgb_value(to_color({}));
  37. }
  38. Color CSSOKLCH::to_color(Optional<Layout::NodeWithStyle const&>) const
  39. {
  40. auto const l_val = clamp(resolve_with_reference_value(m_properties.l, 1.0).value_or(0), 0, 1);
  41. auto const c_val = max(resolve_with_reference_value(m_properties.c, 0.4).value_or(0), 0);
  42. auto const h_val = AK::to_radians(resolve_hue(m_properties.h).value_or(0));
  43. auto const alpha_val = resolve_alpha(m_properties.alpha).value_or(1);
  44. return Color::from_oklab(l_val, c_val * cos(h_val), c_val * sin(h_val), alpha_val);
  45. }
  46. // https://www.w3.org/TR/css-color-4/#serializing-oklab-oklch
  47. String CSSOKLCH::to_string() const
  48. {
  49. // FIXME: Do this properly, taking unresolved calculated values into account.
  50. return serialize_a_srgb_value(to_color({}));
  51. }
  52. }