Time.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Time.h"
  7. #include <LibWeb/CSS/StyleValue.h>
  8. namespace Web::CSS {
  9. Time::Time(int value, Type type)
  10. : m_type(type)
  11. , m_value(value)
  12. {
  13. }
  14. Time::Time(float value, Type type)
  15. : m_type(type)
  16. , m_value(value)
  17. {
  18. }
  19. Time Time::make_calculated(NonnullRefPtr<CalculatedStyleValue> calculated_style_value)
  20. {
  21. Time frequency { 0, Type::Calculated };
  22. frequency.m_calculated_style = move(calculated_style_value);
  23. return frequency;
  24. }
  25. Time Time::make_seconds(float value)
  26. {
  27. return { value, Type::S };
  28. }
  29. Time Time::percentage_of(Percentage const& percentage) const
  30. {
  31. VERIFY(!is_calculated());
  32. return Time { percentage.as_fraction() * m_value, m_type };
  33. }
  34. ErrorOr<String> Time::to_string() const
  35. {
  36. if (is_calculated())
  37. return m_calculated_style->to_string();
  38. return String::formatted("{}{}", m_value, unit_name());
  39. }
  40. float Time::to_seconds() const
  41. {
  42. switch (m_type) {
  43. case Type::Calculated:
  44. return m_calculated_style->resolve_time()->to_seconds();
  45. case Type::S:
  46. return m_value;
  47. case Type::Ms:
  48. return m_value / 1000.0f;
  49. }
  50. VERIFY_NOT_REACHED();
  51. }
  52. StringView Time::unit_name() const
  53. {
  54. switch (m_type) {
  55. case Type::Calculated:
  56. return "calculated"sv;
  57. case Type::S:
  58. return "s"sv;
  59. case Type::Ms:
  60. return "ms"sv;
  61. }
  62. VERIFY_NOT_REACHED();
  63. }
  64. Optional<Time::Type> Time::unit_from_name(StringView name)
  65. {
  66. if (name.equals_ignoring_ascii_case("s"sv)) {
  67. return Type::S;
  68. } else if (name.equals_ignoring_ascii_case("ms"sv)) {
  69. return Type::Ms;
  70. }
  71. return {};
  72. }
  73. NonnullRefPtr<CalculatedStyleValue> Time::calculated_style_value() const
  74. {
  75. VERIFY(!m_calculated_style.is_null());
  76. return *m_calculated_style;
  77. }
  78. }