LibWeb/HTML: Implement date conversions for month and week inputs

This implements the conversion algorithms between strings and dates for
inputs of the types month and week.
This commit is contained in:
Glenn Skrzypczak 2025-08-26 22:03:46 +02:00 committed by Jelle Raaijmakers
commit bd34b11ca2
Notes: github-actions[bot] 2025-08-27 13:11:23 +00:00
5 changed files with 283 additions and 0 deletions

View file

@ -2374,6 +2374,15 @@ static Utf16String convert_number_to_month_string(double input)
return Utf16String::formatted("{:04d}-{:02d}", static_cast<int>(year), static_cast<int>(months) + 1);
}
// https://html.spec.whatwg.org/multipage/input.html#month-state-(type=month):concept-input-value-date-string
static Utf16String convert_date_to_month_string(double input)
{
// The algorithm to convert a number to a string, given a number input, is as follows: Return a valid month
// string that represents the month that has input months between it and January 1970.
auto date = AK::UnixDateTime::from_milliseconds_since_epoch(input);
return date.to_utf16_string("%Y-%m"sv, AK::UnixDateTime::LocalTime::No);
}
// https://html.spec.whatwg.org/multipage/input.html#concept-input-value-number-string
static Utf16String convert_number_to_week_string(double input)
{
@ -2488,6 +2497,31 @@ WebIDL::ExceptionOr<GC::Ptr<JS::Date>> HTMLInputElement::convert_string_to_date(
return JS::Date::create(realm(), JS::make_date(JS::make_day(date.year, date.month - 1, date.day), 0));
}
// https://html.spec.whatwg.org/multipage/input.html#month-state-(type=month):concept-input-value-string-date
if (type_state() == TypeAttributeState::Month) {
// If parsing a month from input results in an error, then return an error;
auto maybe_year_and_month = parse_a_month_string(input);
if (!maybe_year_and_month.has_value())
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Can't parse month string"sv };
auto year_and_month = maybe_year_and_month.value();
// otherwise, return a new Date object representing midnight UTC on the morning of the first day of the parsed month.
return JS::Date::create(realm(), JS::make_date(JS::make_day(year_and_month.year, year_and_month.month - 1, 1), 0));
}
// https://html.spec.whatwg.org/multipage/input.html#week-state-(type=week):concept-input-value-string-date
if (type_state() == TypeAttributeState::Week) {
// If parsing a week from input results in an error, then return an error;
auto maybe_week = parse_a_week_string(input);
if (!maybe_week.has_value())
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Can't parse week string"sv };
auto week = maybe_week.value();
// otherwise, return a new Date object representing midnight UTC on the morning of the Monday of the parsed week.
auto datetime = UnixDateTime::from_iso8601_week(week.week_year, week.week);
return JS::Date::create(realm(), datetime.milliseconds_since_epoch());
}
// https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):concept-input-value-string-date
if (type_state() == TypeAttributeState::Time) {
// If parsing a time from input results in an error, then return an error;
@ -2522,6 +2556,20 @@ Utf16String HTMLInputElement::convert_date_to_string(GC::Ref<JS::Date> input) co
return convert_number_to_date_string(input->date_value());
}
// https://html.spec.whatwg.org/multipage/input.html#month-state-(type=month):concept-input-value-date-string
if (type_state() == TypeAttributeState::Month) {
// Return a valid month string that represents the month current at the time represented by input in the UTC time zone.
// https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-month-string
return convert_date_to_month_string(input->date_value());
}
// https://html.spec.whatwg.org/multipage/input.html#week-state-(type=week):concept-input-value-date-string
if (type_state() == TypeAttributeState::Week) {
// Return a valid week string that represents the week current at the time represented by input in the UTC time zone.
// https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-week-string
return convert_number_to_week_string(input->date_value());
}
// https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):concept-input-value-string-date
if (type_state() == TypeAttributeState::Time) {
// Return a valid time string that represents the UTC time component that is represented by input.

View file

@ -0,0 +1,9 @@
Harness status: OK
Found 4 tests
4 Pass
Pass date should step correctly
Pass time should step correctly
Pass month should step correctly
Pass week should step correctly

View file

@ -0,0 +1,35 @@
Harness status: OK
Found 30 tests
30 Pass
Pass valueAsDate getter on type date (with value: "")
Pass valueAsDate getter on type date (with value: "0000-12-10")
Pass valueAsDate getter on type date (with value: "2019-00-12")
Pass valueAsDate getter on type date (with value: "2019-12-00")
Pass valueAsDate getter on type date (with value: "2019-13-10")
Pass valueAsDate getter on type date (with value: "2019-02-29")
Pass valueAsDate getter on type date (with value: "2019-12-10")
Pass valueAsDate getter on type date (with value: "2016-02-29")
Pass valueAsDate setter on type date (new Date("2019-12-10T00:00:00.000Z"))
Pass valueAsDate setter on type date (new Date("2016-02-29T00:00:00.000Z"))
Pass valueAsDate getter on type month (with value: "")
Pass valueAsDate getter on type month (with value: "0000-12")
Pass valueAsDate getter on type month (with value: "2019-00")
Pass valueAsDate getter on type month (with value: "2019-12")
Pass valueAsDate setter on type month (new Date("2019-12-01T00:00:00.000Z"))
Pass valueAsDate getter on type week (with value: "")
Pass valueAsDate getter on type week (with value: "0000-W50")
Pass valueAsDate getter on type week (with value: "2019-W00")
Pass valueAsDate getter on type week (with value: "2019-W60")
Pass valueAsDate getter on type week (with value: "2019-W50")
Pass valueAsDate setter on type week (new Date("2019-12-09T00:00:00.000Z"))
Pass valueAsDate getter on type time (with value: "")
Pass valueAsDate getter on type time (with value: "24:00")
Pass valueAsDate getter on type time (with value: "00:60")
Pass valueAsDate getter on type time (with value: "00:00")
Pass valueAsDate getter on type time (with value: "12:00")
Pass valueAsDate getter on type time (with value: "23:59")
Pass valueAsDate setter on type time (new Date("1970-01-01T00:00:00.000Z"))
Pass valueAsDate setter on type time (new Date("1970-01-01T12:00:00.000Z"))
Pass valueAsDate setter on type time (new Date("1970-01-01T23:59:00.000Z"))

View file

@ -0,0 +1,83 @@
<!DOCTYPE HTML>
<html>
<head>
<title>valueAsDate stepping</title>
<script src="../../../../resources/testharness.js"></script>
<script src="../../../../resources/testharnessreport.js"></script>
</head>
<body>
<p>
<h3>input_valueAsDate_stepping</h3>
<!-- This test verifies that valueAsDate reads and writes Date values,
that those values step by the correct default step, and that the values
represent the correct times.
-->
</p>
<hr>
<div id="log"></div>
<form method="post"
enctype="application/x-www-form-urlencoded"
action=""
name="input_form">
<p><input type='date' id='input_date'></p>
<p><input type='time' id='input_time'></p>
<p><input type='week' id='input_week'></p>
<p><input type='month' id='input_month'></p>
</form>
<script>
function test_stepping(inputType, stringValue, steppedString, baseMillis, stepAmount) {
test(function() {
// put date in, constructed from a UTC timestamp so the test doesn't
// vary by local timezone
input = document.getElementById("input_" + inputType);
input.valueAsDate = new Date(baseMillis)
// get string out (using startsWith here to allow for optional
// seconds and milliseconds)
var sanitizedStr = input.value;
assert_true(sanitizedStr.startsWith(stringValue),
"The input value [" + sanitizedStr + "] must resemble [" + stringValue + "]");
// get date out
var sanitized = input.valueAsDate;
assert_equals(sanitized.getTime(), baseMillis, "The input valueAsDate must represent the same time as the original Date.")
// step up, get new date out
input.stepUp()
var steppedDate = input.valueAsDate;
assert_equals(steppedDate.getTime(), baseMillis + stepAmount, "Stepping must be by the correct amount")
// get new string out
var steppedStrOut = input.value;
assert_true(steppedStrOut.startsWith(steppedString),
"The changed input value [" + steppedStrOut + "] must resemble ["+steppedString+"]");
// step back down, get first date out again
input.stepDown()
var backDown = input.valueAsDate;
assert_equals(backDown.getTime(), baseMillis, "Stepping back down must return the date to its original value");
}, inputType + " should step correctly");
}
var millis_per_day = 24 * 60 * 60 * 1000;
// jan 1 midnight, step 1 day to jan 2
test_stepping("date", "1970-01-01", "1970-01-02", 0, millis_per_day);
// jan 1 midnight, step 1 minute to 00:01:00
test_stepping("time", "00:00", "00:01", 0, 60 * 1000);
// jan 1 midnight, step 31 days to feb 1
test_stepping("month", "1970-01", "1970-02", 0, 31 * millis_per_day);
// monday jan 5 1970 midnight, step 7 days to jan 12
// (this has to start on a monday for stepping up and down to return)
test_stepping("week", "1970-W02", "1970-W03", 4 * millis_per_day, 7 * millis_per_day);
</script>
</body>
</html>

View file

@ -0,0 +1,108 @@
<!DOCTYPE HTML>
<meta charset="utf-8">
<html>
<head>
<title>HTMLInputElement valueAsDate</title>
<link rel="author" title="pmdartus" href="mailto:dartus.pierremarie@gmail.com">
<link rel=help href="https://html.spec.whatwg.org/#dom-input-valueasdate">
<script src="../../../../resources/testharness.js"></script>
<script src="../../../../resources/testharnessreport.js"></script>
</head>
<body>
<h3>input_valueAsDate</h3>
<hr>
<div id="log"></div>
<input id="input_date" type="date" />
<input id="input_month" type="month" />
<input id="input_week" type="week" />
<input id="input_time" type="time" />
<script>
"use strict";
function testValueAsDateGetter(type, element, cases) {
for (const [actualValue, expectedValueAsDate] of cases) {
test(
() => {
element.value = actualValue;
const actualValueAsDate = element.valueAsDate;
if (actualValueAsDate instanceof Date) {
assert_equals(
actualValueAsDate.getTime(),
expectedValueAsDate.getTime(),
`valueAsDate returns an invalid date (actual: ${actualValueAsDate.toISOString()}, ` +
`expected: ${expectedValueAsDate.toISOString()})`
);
} else {
assert_equals(actualValueAsDate, expectedValueAsDate);
}
},
`valueAsDate getter on type ${type} (with value: ${JSON.stringify(actualValue)})`
);
}
}
function testValueAsDateSetter(type, element, cases) {
for (const [valueDateStr, expectedValue] of cases) {
test(() => {
element.valueAsDate = new Date(valueDateStr);
assert_equals(element.value, expectedValue);
}, `valueAsDate setter on type ${type} (new Date(${JSON.stringify(valueDateStr)}))`);
}
}
const dateInput = document.getElementById("input_date");
testValueAsDateGetter("date", dateInput, [
["", null],
["0000-12-10", null],
["2019-00-12", null],
["2019-12-00", null],
["2019-13-10", null],
["2019-02-29", null],
["2019-12-10", new Date("2019-12-10T00:00:00.000Z")],
["2016-02-29", new Date("2016-02-29T00:00:00.000Z")] // Leap year
]);
testValueAsDateSetter("date", dateInput, [
["2019-12-10T00:00:00.000Z", "2019-12-10"],
["2016-02-29T00:00:00.000Z", "2016-02-29"] // Leap year
]);
const monthInput = document.getElementById("input_month");
testValueAsDateGetter("month", monthInput, [
["", null],
["0000-12", null],
["2019-00", null],
["2019-12", new Date("2019-12-01T00:00:00.000Z")]
]);
testValueAsDateSetter("month", monthInput, [["2019-12-01T00:00:00.000Z", "2019-12"]]);
const weekInput = document.getElementById("input_week");
testValueAsDateGetter("week", weekInput, [
["", null],
["0000-W50", null],
["2019-W00", null],
["2019-W60", null],
["2019-W50", new Date("2019-12-09T00:00:00.000Z")]
]);
testValueAsDateSetter("week", weekInput, [["2019-12-09T00:00:00.000Z", "2019-W50"]]);
const timeInput = document.getElementById("input_time");
testValueAsDateGetter("time", timeInput, [
["", null],
["24:00", null],
["00:60", null],
["00:00", new Date("1970-01-01T00:00:00.000Z")],
["12:00", new Date("1970-01-01T12:00:00.000Z")],
["23:59", new Date("1970-01-01T23:59:00.000Z")]
]);
testValueAsDateSetter("time", timeInput, [
["1970-01-01T00:00:00.000Z", "00:00"],
["1970-01-01T12:00:00.000Z", "12:00"],
["1970-01-01T23:59:00.000Z", "23:59"]
]);
</script>
</body>
</html>