From 4bd4d777eb44506e6ebbf13d0b9a6a1adcd9758a Mon Sep 17 00:00:00 2001 From: Shannon Booth Date: Thu, 6 Mar 2025 15:33:19 +1300 Subject: [PATCH] LibWeb/HTML: Use a helper for converting 'time' value to string This will make it trivial to implement valueAsNumber for 'time' input type. --- Libraries/LibWeb/HTML/HTMLInputElement.cpp | 24 ++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/Libraries/LibWeb/HTML/HTMLInputElement.cpp b/Libraries/LibWeb/HTML/HTMLInputElement.cpp index ec44c4eefd2..47e7f0290fb 100644 --- a/Libraries/LibWeb/HTML/HTMLInputElement.cpp +++ b/Libraries/LibWeb/HTML/HTMLInputElement.cpp @@ -2228,6 +2228,21 @@ static String convert_number_to_date_string(double input) return MUST(date.to_string("%Y-%m-%d"sv, Core::DateTime::LocalTime::No)); } +// https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):concept-input-value-number-string +static String convert_number_to_time_string(double input) +{ + // The algorithm to convert a number to a string, given a number input, is as follows: Return a valid time + // string that represents the time that is input milliseconds after midnight on a day with no time changes. + auto seconds = JS::sec_from_time(input); + auto milliseconds = JS::ms_from_time(input); + if (seconds > 0) { + if (milliseconds > 0) + return MUST(String::formatted("{:02d}:{:02d}:{:02d}.{:3d}", JS::hour_from_time(input), JS::min_from_time(input), seconds, milliseconds)); + return MUST(String::formatted("{:02d}:{:02d}:{:02d}", JS::hour_from_time(input), JS::min_from_time(input), seconds)); + } + return MUST(String::formatted("{:02d}:{:02d}", JS::hour_from_time(input), JS::min_from_time(input))); +} + // https://html.spec.whatwg.org/multipage/input.html#concept-input-value-string-number String HTMLInputElement::convert_number_to_string(double input) const { @@ -2296,14 +2311,7 @@ String HTMLInputElement::covert_date_to_string(GC::Ref input) const if (type_state() == TypeAttributeState::Time) { // Return a valid time string that represents the UTC time component that is represented by input. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-time-string - auto seconds = JS::sec_from_time(input->date_value()); - auto milliseconds = JS::ms_from_time(input->date_value()); - if (seconds > 0) { - if (milliseconds > 0) - return MUST(String::formatted("{:02d}:{:02d}:{:02d}.{:3d}", JS::hour_from_time(input->date_value()), JS::min_from_time(input->date_value()), seconds, milliseconds)); - return MUST(String::formatted("{:02d}:{:02d}:{:02d}", JS::hour_from_time(input->date_value()), JS::min_from_time(input->date_value()), seconds)); - } - return MUST(String::formatted("{:02d}:{:02d}", JS::hour_from_time(input->date_value()), JS::min_from_time(input->date_value()))); + return convert_number_to_time_string(input->date_value()); } dbgln("HTMLInputElement::covert_date_to_string() not implemented for input type {}", type());