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