Time.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright (c) 2022-2023, Sam Atkins <atkinssj@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Time.h"
  7. #include <LibWeb/CSS/Percentage.h>
  8. #include <LibWeb/CSS/StyleValues/CSSMathValue.h>
  9. namespace Web::CSS {
  10. Time::Time(double value, Type type)
  11. : m_type(type)
  12. , m_value(value)
  13. {
  14. }
  15. Time Time::make_seconds(double value)
  16. {
  17. return { value, Type::S };
  18. }
  19. Time Time::percentage_of(Percentage const& percentage) const
  20. {
  21. return Time { percentage.as_fraction() * m_value, m_type };
  22. }
  23. String Time::to_string() const
  24. {
  25. return MUST(String::formatted("{}s", to_seconds()));
  26. }
  27. double Time::to_seconds() const
  28. {
  29. switch (m_type) {
  30. case Type::S:
  31. return m_value;
  32. case Type::Ms:
  33. return m_value / 1000.0;
  34. }
  35. VERIFY_NOT_REACHED();
  36. }
  37. double Time::to_milliseconds() const
  38. {
  39. switch (m_type) {
  40. case Type::S:
  41. return m_value * 1000.0;
  42. case Type::Ms:
  43. return m_value;
  44. }
  45. VERIFY_NOT_REACHED();
  46. }
  47. StringView Time::unit_name() const
  48. {
  49. switch (m_type) {
  50. case Type::S:
  51. return "s"sv;
  52. case Type::Ms:
  53. return "ms"sv;
  54. }
  55. VERIFY_NOT_REACHED();
  56. }
  57. Optional<Time::Type> Time::unit_from_name(StringView name)
  58. {
  59. if (name.equals_ignoring_ascii_case("s"sv)) {
  60. return Type::S;
  61. } else if (name.equals_ignoring_ascii_case("ms"sv)) {
  62. return Type::Ms;
  63. }
  64. return {};
  65. }
  66. Time Time::resolve_calculated(NonnullRefPtr<CSSMathValue> const& calculated, Layout::Node const&, Time const& reference_value)
  67. {
  68. return calculated->resolve_time_percentage(reference_value).value();
  69. }
  70. }