Skip to content

Truly independent web browser

LibWeb: Edit date and time inputs one field at a time

Andreas Klingcc3bdf732b24
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 0af11050749..b359171c75c 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -516,6 +516,7 @@ set(SOURCES
HTML/HTMLIFrameElement.cpp
HTML/HTMLImageElement.cpp
HTML/HTMLInputElement.cpp
+ HTML/HTMLInputElementDateTimeFields.cpp
HTML/HTMLInsertion.cpp
HTML/HTMLLabelElement.cpp
HTML/HTMLLegendElement.cpp
diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp
index da6f4a3ff74..756fc911ad2 100644
--- a/Libraries/LibWeb/DOM/Element.cpp
+++ b/Libraries/LibWeb/DOM/Element.cpp
@@ -7275,7 +7275,7 @@ bool Element::should_indicate_focus() const
// triggers a virtual keyboard to be shown on focus if a physical keyboard were not present), indicate focus.
if (is<HTML::HTMLTextAreaElement>(this) || is_editable_or_editing_host())
return true;
- if (auto const* input = as_if<HTML::HTMLInputElement>(this); input && input->has_selectable_text())
+ if (auto const* input = as_if<HTML::HTMLInputElement>(this); input && (input->has_selectable_text() || input->has_date_picker()))
return true;
// INTEROP: A select element takes keyboard input to pick an option, and indicates focus when clicked.
if (is<HTML::HTMLSelectElement>(this))
diff --git a/Libraries/LibWeb/HTML/HTMLInputElement.cpp b/Libraries/LibWeb/HTML/HTMLInputElement.cpp
index 6d8ec6c1777..ae930fe921e 100644
--- a/Libraries/LibWeb/HTML/HTMLInputElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLInputElement.cpp
@@ -130,6 +130,9 @@ void HTMLInputElement::visit_edges(Cell::Visitor& visitor)
Base::visit_edges(visitor);
visitor.visit(m_inner_text_element);
visitor.visit(m_text_node);
+ visitor.visit(m_date_time_fields_container);
+ for (auto const& field : m_date_time_fields)
+ visitor.visit(field.element);
visitor.visit(m_image_button_alt_text_node);
visitor.visit(m_placeholder_element);
visitor.visit(m_placeholder_text_node);
@@ -806,6 +809,12 @@ WebIDL::ExceptionOr<void> HTMLInputElement::set_value(Utf16View value)
set_the_selection_range(m_value.length_in_code_units(), m_value.length_in_code_units());
update_shadow_tree();
+ } else if (!m_date_time_fields.is_empty()) {
+ // NB: Setting the value replaces what the user typed into the date and time fields, even when the value
+ // stays the same, as it does for fields that do not yet make a value.
+ m_date_time_fields_value = {};
+ CSS::Invalidation::invalidate_style_after_validity_change(*this);
+ update_shadow_tree();
}
break;
@@ -974,6 +983,7 @@ void HTMLInputElement::update_button_input_shadow_tree()
void HTMLInputElement::update_text_input_shadow_tree()
{
update_placeholder_visibility();
+ update_date_time_fields();
if (m_type == TypeAttributeState::Number && m_up_button_element && m_down_button_element) {
// The `textfield` appearance is used to hide the stepper buttons.
@@ -1251,13 +1261,26 @@ void HTMLInputElement::create_text_input_shadow_tree()
MUST(element->append_child(*text_container));
}
+ m_date_time_fields_container = nullptr;
+ m_date_time_fields.clear();
+ if (has_date_picker()) {
+ // NB: Date and time inputs are edited one field at a time, so they have no editable text.
+ m_inner_text_element = nullptr;
+ m_text_node = nullptr;
+ m_date_time_fields_container = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
+ m_date_time_fields_container->set_attribute_value(HTML::AttributeNames::style, "flex: 1; min-width: 0; height: 1lh; overflow: hidden; white-space: pre;"_utf16);
+ MUST(text_container->append_child(*m_date_time_fields_container));
+ create_date_time_fields();
+ }
+
// https://drafts.csswg.org/css-ui-4/#input-rules
- m_inner_text_element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
- {
- static auto& style = *new GC::Root<CSS::CSSStyleProperties>;
- if (!style) {
- style = CSS::CSSStyleProperties::create({}, {});
- style->set_declarations_from_text(R"~~~(
+ if (!has_date_picker()) {
+ m_inner_text_element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
+ {
+ static auto& style = *new GC::Root<CSS::CSSStyleProperties>;
+ if (!style) {
+ style = CSS::CSSStyleProperties::create({}, {});
+ style->set_declarations_from_text(R"~~~(
width: 100%;
height: 1lh;
overflow: auto;
@@ -1265,16 +1288,17 @@ void HTMLInputElement::create_text_input_shadow_tree()
text-overflow: clip;
white-space: pre;
)~~~"sv);
+ }
+ set_own_inline_style(*m_inner_text_element, *style);
}
- set_own_inline_style(*m_inner_text_element, *style);
- }
- MUST(text_container->append_child(*m_inner_text_element));
+ MUST(text_container->append_child(*m_inner_text_element));
- m_text_node = DOM::Text::create(document(), m_value);
- if (type_state() == TypeAttributeState::Password)
- m_text_node->set_is_password_input({}, true);
- handle_maxlength_attribute();
- MUST(m_inner_text_element->append_child(*m_text_node));
+ m_text_node = DOM::Text::create(document(), m_value);
+ if (type_state() == TypeAttributeState::Password)
+ m_text_node->set_is_password_input({}, true);
+ handle_maxlength_attribute();
+ MUST(m_inner_text_element->append_child(*m_text_node));
+ }
m_placeholder_element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
MUST(text_container->append_child(*m_placeholder_element));
@@ -1730,6 +1754,14 @@ void HTMLInputElement::suggestions_source_element_did_change()
void HTMLInputElement::did_receive_focus()
{
+ if (!m_date_time_fields.is_empty()) {
+ // NB: Keyboard focus starts at the first field; a click picks the field it lands on.
+ if (document().last_focus_trigger() == FocusTrigger::Key)
+ m_active_date_time_field = 0;
+ m_date_time_field_typed_digits = 0;
+ update_date_time_field_elements();
+ }
+
if (!m_text_node)
return;
m_text_node->set_needs_repaint(InvalidateDisplayList::PaintCommands);
@@ -1749,6 +1781,11 @@ void HTMLInputElement::did_lose_focus()
{
reveal_cursor_if_pending();
+ if (!m_date_time_fields.is_empty()) {
+ m_date_time_field_typed_digits = 0;
+ update_date_time_field_elements();
+ }
+
if (m_text_node)
m_text_node->set_needs_repaint(InvalidateDisplayList::PaintCommands);
@@ -1845,6 +1882,8 @@ void HTMLInputElement::form_associated_element_attribute_changed(Utf16FlyString
m_value = value_sanitization_algorithm(m_value);
update_shadow_tree();
}
+ if (name == HTML::AttributeNames::step)
+ update_date_time_fields_for_step();
} else if (name == HTML::AttributeNames::size) {
// size feeds the element's default preferred width, which reaches layout only
// through the replaced-content facts; nothing else schedules a relayout.
@@ -1926,6 +1965,8 @@ void HTMLInputElement::type_attribute_changed(TypeAttributeState old_state, Type
auto should_materialize_shadow_tree = shadow_root() || has_style();
set_shadow_root(nullptr);
m_image_button_alt_text_node = nullptr;
+ m_date_time_fields_container = nullptr;
+ m_date_time_fields.clear();
if (should_materialize_shadow_tree)
create_shadow_tree_if_needed();
@@ -2453,6 +2494,8 @@ void HTMLInputElement::reset_algorithm()
if (m_value != old_value)
relevant_value_was_changed();
+ // NB: Resetting the value also forgets what the user typed into the date and time fields.
+ m_date_time_fields_value = {};
update_shadow_tree();
}
@@ -2490,6 +2533,8 @@ void HTMLInputElement::clear_algorithm()
if (m_value != old_value)
relevant_value_was_changed();
+ // NB: Clearing the value also forgets what the user typed into the date and time fields.
+ m_date_time_fields_value = {};
update_shadow_tree();
}
@@ -3921,20 +3966,13 @@ bool HTMLInputElement::checked_applies() const
bool HTMLInputElement::has_selectable_text() const
{
- // Potential FIXME: Date, Month, Week, Time and LocalDateAndTime are rendered as a basic text input for now,
- // thus they have selectable text, this need to change when we will have a visual date/time selector.
-
+ // NB: Date, Month, Week, Time and LocalDateAndTime are edited one field at a time, and hold no text to select.
switch (type_state()) {
case TypeAttributeState::Text:
case TypeAttributeState::Search:
case TypeAttributeState::Telephone:
case TypeAttributeState::URL:
case TypeAttributeState::Password:
- case TypeAttributeState::Date:
- case TypeAttributeState::Month:
- case TypeAttributeState::Week:
- case TypeAttributeState::Time:
- case TypeAttributeState::LocalDateAndTime:
case TypeAttributeState::Number:
case TypeAttributeState::Email:
return true;
@@ -4344,22 +4382,32 @@ bool HTMLInputElement::suffering_from_bad_input() const
case TypeAttributeState::Date:
// https://html.spec.whatwg.org/multipage/input.html#date-state-(type%3Ddate)%3Asuffering-from-bad-input
// While the user interface describes input that the user agent cannot convert to a valid date string, the control is suffering from bad input.
+ if (!m_date_time_fields.is_empty())
+ return date_time_fields_describe_bad_input();
return !relevant_value.is_empty() && !is_valid_date_string(relevant_value);
case TypeAttributeState::Month:
// https://html.spec.whatwg.org/multipage/input.html#month-state-(type%3Dmonth)%3Asuffering-from-bad-input
// While the user interface describes input that the user agent cannot convert to a valid month string, the control is suffering from bad input.
+ if (!m_date_time_fields.is_empty())
+ return date_time_fields_describe_bad_input();
return !relevant_value.is_empty() && !is_valid_month_string(relevant_value);
case TypeAttributeState::Week:
// https://html.spec.whatwg.org/multipage/input.html#week-state-(type%3Dweek)%3Asuffering-from-bad-input
// While the user interface describes input that the user agent cannot convert to a valid week string, the control is suffering from bad input.
+ if (!m_date_time_fields.is_empty())
+ return date_time_fields_describe_bad_input();
return !relevant_value.is_empty() && !is_valid_week_string(relevant_value);
case TypeAttributeState::Time:
// https://html.spec.whatwg.org/multipage/#time-state-(type=time):suffering-from-bad-input
// While the user interface describes input that the user agent cannot convert to a valid time string, the control is suffering from bad input.
+ if (!m_date_time_fields.is_empty())
+ return date_time_fields_describe_bad_input();
return !relevant_value.is_empty() && !is_valid_time_string(relevant_value);
case TypeAttributeState::LocalDateAndTime:
// https://html.spec.whatwg.org/multipage/input.html#local-date-and-time-state-(type%3Ddatetime-local)%3Asuffering-from-bad-input
// While the user interface describes input that the user agent cannot convert to a valid normalized local date and time string, the control is suffering from bad input.
+ if (!m_date_time_fields.is_empty())
+ return date_time_fields_describe_bad_input();
return !relevant_value.is_empty() && !is_valid_local_date_and_time_string(relevant_value);
case TypeAttributeState::Number:
// https://html.spec.whatwg.org/multipage/input.html#number-state-(type%3Dnumber)%3Asuffering-from-bad-input
@@ -4398,18 +4446,19 @@ void HTMLInputElement::did_pick_date(Optional<Utf16String> picked_value)
set_is_open(false);
if (!has_date_picker() || !picked_value.has_value() || !is_mutable())
return;
+ commit_date_time_value(value_sanitization_algorithm(*picked_value));
+}
+
+void HTMLInputElement::commit_date_time_value(Utf16String new_value)
+{
+ if (new_value == m_value)
+ return;
- auto old_value = m_value;
// then when the user changes the element's value
m_dirty_value = true;
- m_value = value_sanitization_algorithm(*picked_value);
- if (m_value == old_value)
- return;
- if (m_text_node) {
- m_text_node->set_data(m_value);
- update_placeholder_visibility();
- }
+ m_value = move(new_value);
relevant_value_was_changed();
+ update_shadow_tree();
// the user agent must queue an element task on the user interaction task source
user_interaction_did_change_input_value();
diff --git a/Libraries/LibWeb/HTML/HTMLInputElement.h b/Libraries/LibWeb/HTML/HTMLInputElement.h
index af405894ee4..08cb1cbfce6 100644
--- a/Libraries/LibWeb/HTML/HTMLInputElement.h
+++ b/Libraries/LibWeb/HTML/HTMLInputElement.h
@@ -23,6 +23,7 @@
#include <LibWeb/WebIDL/DOMException.h>
#include <LibWebCommon/HTML/ColorPickerUpdateState.h>
#include <LibWebCommon/HTML/FileFilter.h>
+#include <LibWebCommon/UIEvents/KeyCode.h>
#include <LibWebCommon/WebIDL/Types.h>
namespace JS {
@@ -127,6 +128,25 @@ public:
void did_pick_color(Optional<Color> picked_color, ColorPickerUpdateState state);
void did_pick_date(Optional<Utf16String> picked_value);
bool has_date_picker() const;
+ bool handle_date_time_field_key(UIEvents::KeyCode, u32 modifiers, u32 code_point);
+ void activate_last_date_time_field();
+ void update_date_time_fields_for_step();
+
+ struct DateTimeField {
+ enum class Kind : u8 {
+ Year,
+ Month,
+ Day,
+ Week,
+ Hour,
+ Minute,
+ Second,
+ DayPeriod,
+ };
+ Kind kind;
+ Optional<i32> value;
+ GC::Ptr<DOM::Element> element;
+ };
enum class MultipleHandling {
Replace,
@@ -403,6 +423,29 @@ private:
void update_button_input_shadow_tree();
void update_text_input_shadow_tree();
+
+ void create_date_time_fields();
+ void update_date_time_fields();
+ void update_date_time_field_elements();
+ void set_active_date_time_field(size_t index);
+ void date_time_fields_did_change();
+ void commit_date_time_value(Utf16String new_value);
+ bool date_time_fields_want_seconds() const;
+ bool date_time_fields_use_12_hour_clock() const;
+ bool date_time_fields_describe_bad_input() const;
+ Optional<DateTimeField const&> date_time_field(DateTimeField::Kind) const;
+ Optional<i32> date_time_field_value(DateTimeField::Kind) const;
+ i32 date_time_field_minimum(DateTimeField::Kind) const;
+ i32 date_time_field_maximum(DateTimeField::Kind) const;
+
+ GC::Ptr<DOM::Element> m_date_time_fields_container;
+ Vector<DateTimeField> m_date_time_fields;
+ Vector<Utf16String> m_day_period_names;
+ Optional<Utf16String> m_date_time_fields_value;
+ size_t m_active_date_time_field { 0 };
+ u8 m_date_time_field_typed_digits { 0 };
+ bool m_date_time_fields_show_seconds { false };
+
GC::Ptr<DOM::Element> m_inner_text_element;
GC::Ptr<DOM::Text> m_text_node;
GC::Ptr<DOM::Text> m_image_button_alt_text_node;
diff --git a/Libraries/LibWeb/HTML/HTMLInputElementDateTimeFields.cpp b/Libraries/LibWeb/HTML/HTMLInputElementDateTimeFields.cpp
new file mode 100644
index 00000000000..ec70acf7c11
--- /dev/null
+++ b/Libraries/LibWeb/HTML/HTMLInputElementDateTimeFields.cpp
@@ -0,0 +1,573 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Time.h>
+#include <LibJS/Runtime/NativeFunction.h>
+#include <LibUnicode/DateTimeFormat.h>
+#include <LibUnicode/Locale.h>
+#include <LibWeb/CSS/Invalidation/FormControlInvalidator.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/DOM/ElementFactory.h>
+#include <LibWeb/DOM/IDLEventListener.h>
+#include <LibWeb/DOM/Text.h>
+#include <LibWeb/HTML/HTMLInputElement.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/Namespace.h>
+#include <LibWeb/UIEvents/EventNames.h>
+#include <LibWeb/WebIDL/CallbackType.h>
+
+namespace Web::HTML {
+
+// NB: Date and time inputs show their value as a row of fields, one for each component of the value, in the order
+// and with the separators the user's locale uses. Each field is edited on its own with the keyboard, and the
+// value only becomes non-empty once every field holds a number.
+
+using FieldKind = HTMLInputElement::DateTimeField::Kind;
+
+static constexpr i32 maximum_year = 275760;
+
+// NB: A moment whose components all differ from each other, which tells the formatter's parts apart.
+static constexpr double sample_epoch_milliseconds = 1793454965000.0; // 2026-10-31T13:56:05Z
+
+static i32 current_year()
+{
+ auto days = UnixDateTime::now().seconds_since_epoch() / 86400;
+ i32 year = 1970;
+ while (days >= static_cast<i64>(days_in_year(year))) {
+ days -= days_in_year(year);
+ ++year;
+ }
+ return year;
+}
+
+static Optional<FieldKind> field_kind_for_part_type(Utf16View type)
+{
+ if (type == u"year"sv)
+ return FieldKind::Year;
+ if (type == u"month"sv)
+ return FieldKind::Month;
+ if (type == u"day"sv)
+ return FieldKind::Day;
+ if (type == u"hour"sv)
+ return FieldKind::Hour;
+ if (type == u"minute"sv)
+ return FieldKind::Minute;
+ if (type == u"second"sv)
+ return FieldKind::Second;
+ if (type == u"dayPeriod"sv)
+ return FieldKind::DayPeriod;
+ return {};
+}
+
+static Utf16View field_placeholder(FieldKind kind)
+{
+ switch (kind) {
+ case FieldKind::Year:
+ return u"yyyy"sv;
+ case FieldKind::Month:
+ return u"mm"sv;
+ case FieldKind::Day:
+ return u"dd"sv;
+ case FieldKind::Week:
+ case FieldKind::Hour:
+ case FieldKind::Minute:
+ case FieldKind::Second:
+ case FieldKind::DayPeriod:
+ return u"--"sv;
+ }
+ VERIFY_NOT_REACHED();
+}
+
+bool HTMLInputElement::date_time_fields_use_12_hour_clock() const
+{
+ return any_of(m_date_time_fields, [](auto const& field) { return field.kind == FieldKind::DayPeriod; });
+}
+
+// NB: Fields the user filled in that do not make a value, because some are still empty or they name a day that does
+// not exist, describe input that cannot be converted to a valid string.
+bool HTMLInputElement::date_time_fields_describe_bad_input() const
+{
+ return m_value.is_empty() && any_of(m_date_time_fields, [](auto const& field) { return field.value.has_value(); });
+}
+
+Optional<HTMLInputElement::DateTimeField const&> HTMLInputElement::date_time_field(DateTimeField::Kind kind) const
+{
+ for (auto const& field : m_date_time_fields) {
+ if (field.kind == kind)
+ return field;
+ }
+ return {};
+}
+
+Optional<i32> HTMLInputElement::date_time_field_value(DateTimeField::Kind kind) const
+{
+ if (auto field = date_time_field(kind); field.has_value())
+ return field->value;
+ return {};
+}
+
+i32 HTMLInputElement::date_time_field_minimum(DateTimeField::Kind kind) const
+{
+ switch (kind) {
+ case FieldKind::Year:
+ case FieldKind::Month:
+ case FieldKind::Day:
+ case FieldKind::Week:
+ return 1;
+ case FieldKind::Hour:
+ return date_time_fields_use_12_hour_clock() ? 1 : 0;
+ case FieldKind::Minute:
+ case FieldKind::Second:
+ case FieldKind::DayPeriod:
+ return 0;
+ }
+ VERIFY_NOT_REACHED();
+}
+
+i32 HTMLInputElement::date_time_field_maximum(DateTimeField::Kind kind) const
+{
+ switch (kind) {
+ case FieldKind::Year:
+ return maximum_year;
+ case FieldKind::Month:
+ return 12;
+ case FieldKind::Day:
+ // NB: A day the month does not have leaves the value empty, as the user may change the month next.
+ return 31;
+ case FieldKind::Week:
+ return 53;
+ case FieldKind::Hour:
+ return date_time_fields_use_12_hour_clock() ? 12 : 23;
+ case FieldKind::Minute:
+ case FieldKind::Second:
+ return 59;
+ case FieldKind::DayPeriod:
+ return 1;
+ }
+ VERIFY_NOT_REACHED();
+}
+
+bool HTMLInputElement::date_time_fields_want_seconds() const
+{
+ if (!first_is_one_of(type_state(), TypeAttributeState::Time, TypeAttributeState::LocalDateAndTime))
+ return false;
+
+ // NB: The value carries seconds when its time has more than hours and minutes.
+ auto value = m_value.utf16_view();
+ if (auto separator = value.find_code_unit_offset(u'T'); separator.has_value())
+ value = value.substring_view(*separator + 1);
+ if (value.length_in_code_units() > 5)
+ return true;
+
+ // NB: A step that is not a whole number of minutes lets the user pick seconds.
+ if (auto step = get_attribute(AttributeNames::step); step.has_value()) {
+ if (auto parsed = step->utf16_view().to_number<double>(); parsed.has_value() && *parsed > 0 && fmod(*parsed, 60) != 0)
+ return true;
+ }
+ return false;
+}
+
+void HTMLInputElement::create_date_time_fields()
+{
+ VERIFY(m_date_time_fields_container);
+ m_date_time_fields_container->remove_all_children();
+ m_date_time_fields.clear();
+ m_day_period_names.clear();
+ m_active_date_time_field = 0;
+ m_date_time_field_typed_digits = 0;
+ m_date_time_fields_show_seconds = date_time_fields_want_seconds();
+
+ Vector<Variant<FieldKind, Utf16String>> parts;
+
+ if (type_state() == TypeAttributeState::Week) {
+ parts.append("Week "_utf16);
+ parts.append(FieldKind::Week);
+ parts.append(", "_utf16);
+ parts.append(FieldKind::Year);
+ } else {
+ Unicode::CalendarPattern pattern;
+ if (type_state() != TypeAttributeState::Time) {
+ pattern.year = Unicode::CalendarPatternStyle::Numeric;
+ pattern.month = Unicode::CalendarPatternStyle::TwoDigit;
+ if (type_state() != TypeAttributeState::Month)
+ pattern.day = Unicode::CalendarPatternStyle::TwoDigit;
+ }
+ if (first_is_one_of(type_state(), TypeAttributeState::Time, TypeAttributeState::LocalDateAndTime)) {
+ pattern.hour = Unicode::CalendarPatternStyle::TwoDigit;
+ pattern.minute = Unicode::CalendarPatternStyle::TwoDigit;
+ if (m_date_time_fields_show_seconds)
+ pattern.second = Unicode::CalendarPatternStyle::TwoDigit;
+ }
+
+ auto formatter = Unicode::DateTimeFormat::create_for_pattern_options(Unicode::default_locale(), u"UTC"sv, pattern);
+ for (auto const& part : formatter->format_to_parts(sample_epoch_milliseconds)) {
+ if (auto kind = field_kind_for_part_type(part.type); kind.has_value())
+ parts.append(*kind);
+ else if (part.type == u"literal"sv)
+ parts.append(part.value);
+ }
+
+ if (pattern.hour.has_value()) {
+ // NB: The names of the two day periods, as the formatter writes them for a morning and an afternoon hour.
+ for (auto hour : { 1, 13 }) {
+ for (auto const& part : formatter->format_to_parts(hour * 3600000.0)) {
+ if (part.type == u"dayPeriod"sv)
+ m_day_period_names.append(part.value);
+ }
+ }
+ }
+ }
+
+ auto& realm = HTML::relevant_realm(*this);
+ for (auto const& part : parts) {
+ if (auto const* literal = part.get_pointer<Utf16String>()) {
+ MUST(m_date_time_fields_container->append_child(DOM::Text::create(document(), *literal)));
+ continue;
+ }
+
+ auto kind = part.get<FieldKind>();
+ if (kind == FieldKind::DayPeriod && m_day_period_names.size() != 2)
+ continue;
+
+ auto element = MUST(DOM::create_element(document(), HTML::TagNames::span, Namespace::HTML));
+ MUST(element->append_child(DOM::Text::create(document(), {})));
+ MUST(m_date_time_fields_container->append_child(element));
+
+ auto index = m_date_time_fields.size();
+ auto mousedown_function = JS::NativeFunction::create(
+ realm, [this, index](JS::VM&) {
+ if (index < m_date_time_fields.size())
+ set_active_date_time_field(index);
+ return JS::js_undefined();
+ },
+ 0, Utf16FlyString {}, &realm);
+ auto mousedown_callback = GC::Heap::the().allocate<WebIDL::CallbackType>(*mousedown_function, realm);
+ element->add_event_listener_without_options(UIEvents::EventNames::mousedown, DOM::IDLEventListener::create(mousedown_callback));
+
+ m_date_time_fields.append({ .kind = kind, .value = {}, .element = element });
+ }
+
+ m_date_time_fields_value = {};
+ update_date_time_fields();
+}
+
+void HTMLInputElement::update_date_time_fields()
+{
+ if (!m_date_time_fields_container)
+ return;
+
+ // NB: Script and the picker change the value; the fields then show it. Fields the user is still filling in keep
+ // their numbers while the value stays empty.
+ if (m_date_time_fields_value != m_value) {
+ // NB: Only a value from outside the fields decides whether they show seconds, so that clearing a field the
+ // user is editing does not build the fields again and lose what they typed into the others.
+ if (date_time_fields_want_seconds() != m_date_time_fields_show_seconds) {
+ create_date_time_fields();
+ return;
+ }
+
+ m_date_time_fields_value = m_value;
+ m_date_time_field_typed_digits = 0;
+ for (auto& field : m_date_time_fields)
+ field.value = {};
+
+ auto set = [&](FieldKind kind, Optional<i32> value) {
+ for (auto& field : m_date_time_fields) {
+ if (field.kind == kind)
+ field.value = value;
+ }
+ };
+
+ // NB: The value is sanitized, so its components are where its type puts them.
+ auto value = m_value.utf16_view();
+ Utf16View date_part;
+ Utf16View time_part;
+ switch (type_state()) {
+ case TypeAttributeState::Date:
+ case TypeAttributeState::Month:
+ case TypeAttributeState::Week:
+ date_part = value;
+ break;
+ case TypeAttributeState::Time:
+ time_part = value;
+ break;
+ case TypeAttributeState::LocalDateAndTime:
+ if (auto separator = value.find_code_unit_offset(u'T'); separator.has_value()) {
+ date_part = value.substring_view(0, *separator);
+ time_part = value.substring_view(*separator + 1);
+ }
+ break;
+ default:
+ VERIFY_NOT_REACHED();
+ }
+
+ if (!date_part.is_empty()) {
+ if (type_state() == TypeAttributeState::Week) {
+ auto components = date_part.split_view(u"-W"sv, SplitBehavior::Nothing);
+ if (components.size() == 2) {
+ set(FieldKind::Year, components[0].to_number<i32>());
+ set(FieldKind::Week, components[1].to_number<i32>());
+ }
+ } else {
+ auto components = date_part.split_view(u'-', SplitBehavior::Nothing);
+ if (components.size() >= 2) {
+ set(FieldKind::Year, components[0].to_number<i32>());
+ set(FieldKind::Month, components[1].to_number<i32>());
+ }
+ if (components.size() >= 3)
+ set(FieldKind::Day, components[2].to_number<i32>());
+ }
+ }
+
+ if (!time_part.is_empty()) {
+ auto components = time_part.split_view(u':', SplitBehavior::Nothing);
+ if (components.size() >= 2) {
+ auto hour = components[0].to_number<i32>();
+ if (hour.has_value() && date_time_fields_use_12_hour_clock()) {
+ set(FieldKind::DayPeriod, *hour >= 12 ? 1 : 0);
+ hour = *hour % 12 == 0 ? 12 : *hour % 12;
+ }
+ set(FieldKind::Hour, hour);
+ set(FieldKind::Minute, components[1].to_number<i32>());
+ }
+ if (components.size() >= 3)
+ set(FieldKind::Second, components[2].substring_view(0, AK::min(2uz, components[2].length_in_code_units())).to_number<i32>());
+ }
+ }
+
+ update_date_time_field_elements();
+}
+
+void HTMLInputElement::update_date_time_field_elements()
+{
+ bool const is_focused = document().focused_area().ptr() == this;
+ for (size_t index = 0; index < m_date_time_fields.size(); ++index) {
+ auto const& field = m_date_time_fields[index];
+
+ Utf16String text;
+ if (!field.value.has_value())
+ text = Utf16String::from_utf16(field_placeholder(field.kind));
+ else if (field.kind == FieldKind::DayPeriod)
+ text = m_day_period_names[*field.value];
+ else if (field.kind == FieldKind::Year)
+ text = Utf16String::formatted("{:04}", *field.value);
+ else
+ text = Utf16String::formatted("{:02}", *field.value);
+
+ auto& text_node = as<DOM::Text>(*field.element->first_child());
+ if (text_node.data() != text)
+ text_node.set_data(text);
+
+ bool const is_active = is_focused && index == m_active_date_time_field;
+ auto style = is_active
+ ? "font-variant-numeric: tabular-nums; border-radius: 2px; background-color: AccentColor; color: AccentColorText;"_utf16
+ : "font-variant-numeric: tabular-nums; border-radius: 2px;"_utf16;
+ if (field.element->get_attribute_value(HTML::AttributeNames::style) != style)
+ field.element->set_attribute_value(HTML::AttributeNames::style, style);
+ }
+}
+
+void HTMLInputElement::set_active_date_time_field(size_t index)
+{
+ VERIFY(index < m_date_time_fields.size());
+ m_active_date_time_field = index;
+ m_date_time_field_typed_digits = 0;
+ update_date_time_field_elements();
+}
+
+// NB: A step that is not a whole number of minutes adds a seconds field to a time input, and one that is takes it away.
+void HTMLInputElement::update_date_time_fields_for_step()
+{
+ if (m_date_time_fields_container && date_time_fields_want_seconds() != m_date_time_fields_show_seconds)
+ create_date_time_fields();
+}
+
+// NB: Moving focus backwards into the input lands on its last field, so that the fields are reached in reverse.
+void HTMLInputElement::activate_last_date_time_field()
+{
+ if (!m_date_time_fields.is_empty())
+ set_active_date_time_field(m_date_time_fields.size() - 1);
+}
+
+void HTMLInputElement::date_time_fields_did_change()
+{
+ Utf16String new_value;
+
+ auto all_fields_filled = all_of(m_date_time_fields, [](auto const& field) { return field.value.has_value(); });
+ if (all_fields_filled && !m_date_time_fields.is_empty()) {
+ auto value_of = [&](FieldKind kind) { return date_time_field_value(kind).value_or(0); };
+
+ auto hour = value_of(FieldKind::Hour);
+ if (date_time_fields_use_12_hour_clock())
+ hour = (hour % 12) + (value_of(FieldKind::DayPeriod) == 1 ? 12 : 0);
+ auto time = date_time_field(FieldKind::Second).has_value()
+ ? Utf16String::formatted("{:02}:{:02}:{:02}", hour, value_of(FieldKind::Minute), value_of(FieldKind::Second))
+ : Utf16String::formatted("{:02}:{:02}", hour, value_of(FieldKind::Minute));
+
+ switch (type_state()) {
+ case TypeAttributeState::Date:
+ new_value = Utf16String::formatted("{:04}-{:02}-{:02}", value_of(FieldKind::Year), value_of(FieldKind::Month), value_of(FieldKind::Day));
+ break;
+ case TypeAttributeState::Month:
+ new_value = Utf16String::formatted("{:04}-{:02}", value_of(FieldKind::Year), value_of(FieldKind::Month));
+ break;
+ case TypeAttributeState::Week:
+ new_value = Utf16String::formatted("{:04}-W{:02}", value_of(FieldKind::Year), value_of(FieldKind::Week));
+ break;
+ case TypeAttributeState::Time:
+ new_value = time;
+ break;
+ case TypeAttributeState::LocalDateAndTime:
+ new_value = Utf16String::formatted("{:04}-{:02}-{:02}T{}", value_of(FieldKind::Year), value_of(FieldKind::Month), value_of(FieldKind::Day), time);
+ break;
+ default:
+ VERIFY_NOT_REACHED();
+ }
+
+ // NB: Fields that do not make a valid value together, such as the 31st of a 30-day month, leave the value
+ // empty.
+ new_value = value_sanitization_algorithm(new_value);
+ }
+
+ // NB: The fields already show the value they make, so it must not be parsed back into them.
+ m_date_time_fields_value = new_value;
+ update_date_time_field_elements();
+ // AD-HOC: Whether the fields describe bad input changes which validity pseudo-classes match, even when the
+ // value stays empty.
+ CSS::Invalidation::invalidate_style_after_validity_change(*this);
+ commit_date_time_value(move(new_value));
+}
+
+bool HTMLInputElement::handle_date_time_field_key(UIEvents::KeyCode key, u32 modifiers, u32 code_point)
+{
+ if (m_date_time_fields.is_empty())
+ return false;
+ if (modifiers & (UIEvents::Mod_Ctrl | UIEvents::Mod_Alt | UIEvents::Mod_Super))
+ return false;
+
+ auto field_count = m_date_time_fields.size();
+ auto move_to = [&](size_t index) {
+ set_active_date_time_field(index);
+ return true;
+ };
+
+ // NB: Tab moves between the fields before it moves focus away from the input.
+ if (key == UIEvents::Key_Tab) {
+ if (modifiers & UIEvents::Mod_Shift) {
+ if (m_active_date_time_field > 0)
+ return move_to(m_active_date_time_field - 1);
+ } else if (m_active_date_time_field + 1 < field_count) {
+ return move_to(m_active_date_time_field + 1);
+ }
+ return false;
+ }
+ if (key == UIEvents::Key_Left)
+ return move_to(m_active_date_time_field > 0 ? m_active_date_time_field - 1 : 0);
+ if (key == UIEvents::Key_Right)
+ return move_to(AK::min(m_active_date_time_field + 1, field_count - 1));
+ if (key == UIEvents::Key_Home)
+ return move_to(0);
+ if (key == UIEvents::Key_End)
+ return move_to(field_count - 1);
+
+ auto& field = m_date_time_fields[m_active_date_time_field];
+ auto minimum = date_time_field_minimum(field.kind);
+ auto maximum = date_time_field_maximum(field.kind);
+
+ if (key == UIEvents::Key_Up || key == UIEvents::Key_Down) {
+ if (!is_mutable())
+ return true;
+ bool const up = key == UIEvents::Key_Up;
+ if (!field.value.has_value()) {
+ // NB: An empty year starts at the current one; other fields start at the end of their range.
+ if (field.kind == FieldKind::Year)
+ field.value = current_year();
+ else
+ field.value = up ? minimum : maximum;
+ } else if (up) {
+ field.value = *field.value >= maximum ? minimum : *field.value + 1;
+ } else {
+ field.value = *field.value <= minimum ? maximum : *field.value - 1;
+ }
+ m_date_time_field_typed_digits = 0;
+ date_time_fields_did_change();
+ return true;
+ }
+
+ if (key == UIEvents::Key_Backspace || key == UIEvents::Key_Delete) {
+ if (!is_mutable())
+ return true;
+ field.value = {};
+ m_date_time_field_typed_digits = 0;
+ date_time_fields_did_change();
+ return true;
+ }
+
+ if (code_point == 0 || code_point < ' ')
+ return false;
+
+ if (!is_mutable())
+ return true;
+
+ if (field.kind == FieldKind::DayPeriod) {
+ // NB: A day period is chosen by the first letter of its name.
+ for (size_t index = 0; index < m_day_period_names.size(); ++index) {
+ auto name = m_day_period_names[index].utf16_view();
+ if (name.is_empty())
+ continue;
+ auto first = name.code_point_at(0);
+ if (to_ascii_lowercase(first) == to_ascii_lowercase(code_point)) {
+ field.value = static_cast<i32>(index);
+ date_time_fields_did_change();
+ // NB: The change event can change the type of the input, which builds other fields or none.
+ if (m_active_date_time_field + 1 < m_date_time_fields.size())
+ set_active_date_time_field(m_active_date_time_field + 1);
+ return true;
+ }
+ }
+ return true;
+ }
+
+ if (is_ascii_digit(code_point)) {
+ auto digit = static_cast<i32>(code_point - '0');
+ auto maximum_digits = field.kind == FieldKind::Year ? 4 : 2;
+
+ i32 typed = digit;
+ if (m_date_time_field_typed_digits > 0 && field.value.has_value())
+ typed = *field.value * 10 + digit;
+ if (typed > maximum) {
+ // NB: A digit that would overflow the field starts the field over.
+ typed = digit;
+ m_date_time_field_typed_digits = 0;
+ }
+ ++m_date_time_field_typed_digits;
+
+ // NB: The field is done once no further digit could keep it in range.
+ bool const is_complete = m_date_time_field_typed_digits >= maximum_digits || static_cast<i64>(typed) * 10 > maximum;
+ field.value = is_complete ? AK::max(typed, minimum) : typed;
+
+ if (is_complete) {
+ m_date_time_field_typed_digits = 0;
+ if (m_active_date_time_field + 1 < field_count)
+ m_active_date_time_field = m_active_date_time_field + 1;
+ }
+ date_time_fields_did_change();
+ return true;
+ }
+
+ // NB: A separator ends the field being typed into.
+ if (m_date_time_field_typed_digits > 0) {
+ if (field.value.has_value())
+ field.value = AK::max(*field.value, minimum);
+ m_date_time_field_typed_digits = 0;
+ if (m_active_date_time_field + 1 < field_count)
+ m_active_date_time_field = m_active_date_time_field + 1;
+ date_time_fields_did_change();
+ }
+ return true;
+}
+
+}
diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cpp
index 2ef8704815b..0fb2bcd54b3 100644
--- a/Libraries/LibWeb/Page/EventHandler.cpp
+++ b/Libraries/LibWeb/Page/EventHandler.cpp
@@ -2020,6 +2020,12 @@ EventResult EventHandler::handle_keydown(UIEvents::KeyCode key, u32 modifiers, u
return EventResult::Handled;
}
+ // NB: A focused date or time input edits its fields with the keyboard.
+ if (auto* input = as_if<HTML::HTMLInputElement>(document->focused_area().ptr()); input && input->has_date_picker()) {
+ if (input->handle_date_time_field_key(key, modifiers & ~UIEvents::Mod_Keypad, code_point))
+ return EventResult::Handled;
+ }
+
if (!(modifiers & UIEvents::KeyModifier::Mod_Ctrl)) {
if (key == UIEvents::KeyCode::Key_Tab)
return focus_sequentially(modifiers & UIEvents::KeyModifier::Mod_Shift ? HTML::SequentialFocusDirection::Backward : HTML::SequentialFocusDirection::Forward);
@@ -3299,9 +3305,17 @@ EventResult EventHandler::focus_sequentially(HTML::SequentialFocusDirection dire
// direction, and selection mechanism.
auto candidate = HTML::sequential_navigation_search(starting_point, direction, selection_mechanism);
+ auto focus_candidate = [&](DOM::Element& candidate) {
+ HTML::run_focusing_steps(&candidate, nullptr, HTML::FocusTrigger::Key);
+ if (direction != HTML::SequentialFocusDirection::Backward)
+ return;
+ if (auto* input = as_if<HTML::HTMLInputElement>(candidate); input && document->focused_area().ptr() == input)
+ input->activate_last_date_time_field();
+ };
+
// 6. If candidate is not null, then run the focusing steps for candidate and return.
if (candidate) {
- HTML::run_focusing_steps(candidate, nullptr, HTML::FocusTrigger::Key);
+ focus_candidate(*candidate);
return EventResult::Handled;
}
@@ -3320,7 +3334,7 @@ EventResult EventHandler::focus_sequentially(HTML::SequentialFocusDirection dire
candidate = HTML::sequential_navigation_search(GC::Ref<HTML::LocalNavigable> { *m_navigable }, direction, HTML::SelectionMechanism::Sequential);
if (!candidate)
return EventResult::Dropped;
- HTML::run_focusing_steps(candidate, nullptr, HTML::FocusTrigger::Key);
+ focus_candidate(*candidate);
return EventResult::Handled;
}
diff --git a/Tests/LibWeb/Crash/HTML/input-date-to-checkbox-value-change.html b/Tests/LibWeb/Crash/HTML/input-date-to-checkbox-value-change.html
new file mode 100644
index 00000000000..87a174efba8
--- /dev/null
+++ b/Tests/LibWeb/Crash/HTML/input-date-to-checkbox-value-change.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<input id="checkbox" type="date" value="2024-01-01">
+<input id="hidden" type="date" value="2024-01-01">
+<script>
+ for (const [input, type] of [[checkbox, "checkbox"], [hidden, "hidden"]]) {
+ input.offsetWidth;
+ input.type = type;
+ input.setAttribute("value", "x");
+ input.offsetWidth;
+ }
+</script>
diff --git a/Tests/LibWeb/Crash/HTML/input-time-day-period-change-type.html b/Tests/LibWeb/Crash/HTML/input-time-day-period-change-type.html
new file mode 100644
index 00000000000..51a2daf8ea5
--- /dev/null
+++ b/Tests/LibWeb/Crash/HTML/input-time-day-period-change-type.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<input id="input" type="time">
+<script>
+ input.addEventListener("change", () => {
+ input.type = "date";
+ input.type = "text";
+ });
+ input.focus();
+ internals.sendText(input, "12:30");
+ internals.sendText(input, "p");
+</script>
diff --git a/Tests/LibWeb/Layout/expected/input-time.txt b/Tests/LibWeb/Layout/expected/input-time.txt
index 2e0552c3f88..1248641a109 100644
--- a/Tests/LibWeb/Layout/expected/input-time.txt
+++ b/Tests/LibWeb/Layout/expected/input-time.txt
@@ -6,8 +6,24 @@ Viewport <#document> at [0,0] [0+0+0 800 0+0+0] [0+0+0 600 0+0+0] [BFC] children
Box <div> at [13,11] flex-container(row) [0+0+0 240 0+0+0] [0+0+0 20 0+0+0] [FFC] children: not-inline
Box <div> at [13,11] flex-container(row) flex-item [0+0+0 216 0+0+0] [0+0+0 20 0+0+0] [FFC] children: not-inline
BlockContainer <div> at [13,11] flex-item [0+0+0 216 0+0+0] [0+0+0 20 0+0+0] [BFC] children: inline
- frag 0 from TextNode start: 0, length: 0, rect: [13,11 0x20] baseline: 16
+ frag 0 from TextNode start: 0, length: 1, rect: [29.21875,11 4.734375x20] baseline: 16
+ ":"
+ frag 1 from TextNode start: 0, length: 1, rect: [50.171875,11 10x20] baseline: 16
+ " "
+ InlineNode <span> at [13,11] [0+0+0 16.21875 0+0+0] [0+0+0 20 0+0+0]
+ frag 0 from TextNode start: 0, length: 2, rect: [13,11 16.21875x20] baseline: 16
+ "--"
+ TextNode <#text> (not painted)
TextNode <#text> (not painted)
+ InlineNode <span> at [33.953125,11] [0+0+0 16.21875 0+0+0] [0+0+0 20 0+0+0]
+ frag 0 from TextNode start: 0, length: 2, rect: [33.953125,11 16.21875x20] baseline: 16
+ "--"
+ TextNode <#text> (not painted)
+ TextNode <#text> (not painted)
+ InlineNode <span> at [60.171875,11] [0+0+0 16.21875 0+0+0] [0+0+0 20 0+0+0]
+ frag 0 from TextNode start: 0, length: 2, rect: [60.171875,11 16.21875x20] baseline: 16
+ "--"
+ TextNode <#text> (not painted)
Box <div> at [233,11] flex-container(row) flex-item [0+0+4 20 0+0+0] [0+0+0 20 0+0+0] [FFC] children: not-inline
SVGSVGBox <svg> at [233,11] flex-item [0+0+0 20 0+0+0] [0+0+0 20 0+0+0] viewport-transform=[0.8333333 0 0 0.8333333 0 0] [SVG] children: not-inline
SVGGeometryBox <path> at [2,2] [0+0+0 20 0+0+0] [0+0+0 20 0+0+0] children: not-inline
diff --git a/Tests/LibWeb/Text/expected/HTML/input-date-time-fields-keyboard.txt b/Tests/LibWeb/Text/expected/HTML/input-date-time-fields-keyboard.txt
new file mode 100644
index 00000000000..276932735c7
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/input-date-time-fields-keyboard.txt
@@ -0,0 +1,17 @@
+date after month and day: value="" events=[]
+date after year: value="2026-10-31" events=[input,change,input,change,input,change,input,change]
+date year up: value="2027-10-31" events=[input,change]
+date month down: value="" events=[input,change]
+date day cleared: value="" events=[]
+date day 31 in September: value="" events=[input,change,input,change]
+date month typed with a separator: value="2027-01-31" events=[input,change]
+date month up wraps after script set the value: value="1999-01-31" events=[input,change]
+time without day period: value="" events=[]
+time with PM: value="12:30" events=[input,change]
+time hour 9: value="21:30" events=[input,change]
+time with AM: value="09:30" events=[input,change]
+month: value="2026-02" events=[input,change,input,change,input,change,input,change]
+week 53 of 2027: value="" events=[input,change,input,change]
+week 52 of 2027: value="2027-W52" events=[input,change,input,change]
+datetime-local: value="2028-02-29T23:59" events=[input,change]
+readonly: value="2026-10-31" events=[]
diff --git a/Tests/LibWeb/Text/expected/HTML/input-date-time-fields-reset.txt b/Tests/LibWeb/Text/expected/HTML/input-date-time-fields-reset.txt
new file mode 100644
index 00000000000..5ce8cdeeee3
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/input-date-time-fields-reset.txt
@@ -0,0 +1,6 @@
+time minute cleared: value="" badInput=true
+time minute typed again: value="13:30:05"
+date partly typed: value="" badInput=true
+date after setting an empty value: value="" badInput=false
+date partly typed again: value="" badInput=true
+date after form reset: value="" badInput=false
diff --git a/Tests/LibWeb/Text/expected/HTML/input-date-time-fields-step-and-reverse-focus.txt b/Tests/LibWeb/Text/expected/HTML/input-date-time-fields-step-and-reverse-focus.txt
new file mode 100644
index 00000000000..a29e8d04724
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/input-date-time-fields-step-and-reverse-focus.txt
@@ -0,0 +1,4 @@
+focused after Shift+Tab: date
+date with the year typed first: value="2026-10-31"
+time with step 1: value="01:30:05"
+time with step 60: value="01:30:05"
diff --git a/Tests/LibWeb/Text/expected/input-bad-input-validity.txt b/Tests/LibWeb/Text/expected/input-bad-input-validity.txt
index 5dc550f1313..066e39fdc81 100644
--- a/Tests/LibWeb/Text/expected/input-bad-input-validity.txt
+++ b/Tests/LibWeb/Text/expected/input-bad-input-validity.txt
@@ -1,12 +1,12 @@
number "2026": value="2026" badInput=false
number "2026 JUN": value="2026" badInput=true
-date "2026-06-08": value="2026-06-08" badInput=false
-date "2026-99-99": value="" badInput=true
-month "2026-06": value="2026-06" badInput=false
-month "2026-13": value="" badInput=true
-week "2026-W23": value="2026-W23" badInput=false
-week "2026-W99": value="" badInput=true
-time "12:30": value="12:30" badInput=false
-time "25:99": value="" badInput=true
-datetime-local "2026-06-08T12:30": value="2026-06-08T12:30" badInput=false
-datetime-local "not a date": value="" badInput=true
+date "06082026": value="2026-06-08" badInput=false
+date "02312026": value="" badInput=true
+month "062026": value="2026-06" badInput=false
+month "06": value="" badInput=true
+week "232026": value="2026-W23" badInput=false
+week "532027": value="" badInput=true
+time "1230p": value="12:30" badInput=false
+time "12": value="" badInput=true
+datetime-local "060820261230p": value="2026-06-08T12:30" badInput=false
+datetime-local "0608": value="" badInput=true
diff --git a/Tests/LibWeb/Text/expected/input-time-typing.txt b/Tests/LibWeb/Text/expected/input-time-typing.txt
index 0ef8709a6f4..729be92b5a0 100644
--- a/Tests/LibWeb/Text/expected/input-time-typing.txt
+++ b/Tests/LibWeb/Text/expected/input-time-typing.txt
@@ -2,4 +2,5 @@ after '1': value=""
after '2': value=""
after ':': value=""
after '3': value=""
-after '0': value="12:30"
+after '0': value=""
+after 'p': value="12:30"
diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/selectors/user-valid.txt b/Tests/LibWeb/Text/expected/wpt-import/css/selectors/user-valid.txt
index 1e821c8124c..3b0929ae10e 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/css/selectors/user-valid.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/css/selectors/user-valid.txt
@@ -2,10 +2,10 @@ Harness status: OK
Found 5 tests
-2 Pass
-3 Fail
+3 Pass
+2 Fail
Pass :user-valid selector should respond to user action
Pass :user-valid selector properly interacts with submit & reset buttons
Fail Checkboxes should match :user-valid after the user clicks on it.
Fail Radios should match :user-valid after the user clicks on it.
-Fail Date inputs should match :user-valid after the user types a value into it.
\ No newline at end of file
+Pass Date inputs should match :user-valid after the user types a value into it.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/HTML/input-date-time-fields-keyboard.html b/Tests/LibWeb/Text/input/HTML/input-date-time-fields-keyboard.html
new file mode 100644
index 00000000000..9471743e55f
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/input-date-time-fields-keyboard.html
@@ -0,0 +1,87 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<input id="date" type="date">
+<input id="time" type="time">
+<input id="month" type="month">
+<input id="week" type="week">
+<input id="local" type="datetime-local">
+<input id="readonly" type="date" value="2026-10-31" readonly>
+<script>
+ test(() => {
+ let events = [];
+ for (const input of document.querySelectorAll("input")) {
+ input.addEventListener("input", () => events.push("input"));
+ input.addEventListener("change", () => events.push("change"));
+ }
+ const report = (label, input) => {
+ println(`${label}: value="${input.value}" events=[${events.join(",")}]`);
+ events = [];
+ };
+
+ const date = document.getElementById("date");
+ date.focus();
+ internals.sendText(date, "1031");
+ report("date after month and day", date);
+ internals.sendText(date, "2026");
+ report("date after year", date);
+ internals.sendKey(date, "Up");
+ report("date year up", date);
+ internals.sendKey(date, "Home");
+ internals.sendKey(date, "Down");
+ report("date month down", date);
+ internals.sendKey(date, "Tab");
+ internals.sendKey(date, "Backspace");
+ report("date day cleared", date);
+ internals.sendText(date, "31");
+ report("date day 31 in September", date);
+ internals.sendKey(date, "Home");
+ internals.sendText(date, "1");
+ internals.sendText(date, "/");
+ report("date month typed with a separator", date);
+
+ date.value = "1999-12-31";
+ internals.sendKey(date, "Home");
+ internals.sendKey(date, "Up");
+ report("date month up wraps after script set the value", date);
+
+ const time = document.getElementById("time");
+ time.focus();
+ internals.sendText(time, "12:30");
+ report("time without day period", time);
+ internals.sendText(time, "p");
+ report("time with PM", time);
+ internals.sendKey(time, "Tab", 4);
+ internals.sendKey(time, "Tab", 4);
+ internals.sendText(time, "9");
+ report("time hour 9", time);
+ internals.sendKey(time, "End");
+ internals.sendText(time, "a");
+ report("time with AM", time);
+
+ const month = document.getElementById("month");
+ month.focus();
+ internals.sendText(month, "022026");
+ report("month", month);
+
+ const week = document.getElementById("week");
+ week.focus();
+ internals.sendText(week, "532027");
+ report("week 53 of 2027", week);
+ internals.sendKey(week, "Home");
+ internals.sendText(week, "52");
+ report("week 52 of 2027", week);
+
+ const local = document.getElementById("local");
+ local.focus();
+ internals.sendText(local, "02292028");
+ internals.sendText(local, "1159p");
+ report("datetime-local", local);
+
+ const readonly = document.getElementById("readonly");
+ readonly.focus();
+ internals.sendKey(readonly, "Up");
+ internals.sendText(readonly, "5");
+ internals.sendKey(readonly, "Backspace");
+ report("readonly", readonly);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/HTML/input-date-time-fields-reset.html b/Tests/LibWeb/Text/input/HTML/input-date-time-fields-reset.html
new file mode 100644
index 00000000000..a4f01907763
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/input-date-time-fields-reset.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<form>
+<input id="time" type="time" value="13:56:05">
+<input id="date" type="date">
+</form>
+<script>
+ test(() => {
+ const time = document.getElementById("time");
+ time.focus();
+ internals.sendKey(time, "Tab");
+ internals.sendKey(time, "Backspace");
+ println(`time minute cleared: value="${time.value}" badInput=${time.validity.badInput}`);
+ internals.sendText(time, "30");
+ println(`time minute typed again: value="${time.value}"`);
+
+ const date = document.getElementById("date");
+ date.focus();
+ internals.sendText(date, "10");
+ println(`date partly typed: value="${date.value}" badInput=${date.validity.badInput}`);
+ date.value = "";
+ println(`date after setting an empty value: value="${date.value}" badInput=${date.validity.badInput}`);
+
+ internals.sendText(date, "10");
+ println(`date partly typed again: value="${date.value}" badInput=${date.validity.badInput}`);
+ document.querySelector("form").reset();
+ println(`date after form reset: value="${date.value}" badInput=${date.validity.badInput}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/HTML/input-date-time-fields-step-and-reverse-focus.html b/Tests/LibWeb/Text/input/HTML/input-date-time-fields-step-and-reverse-focus.html
new file mode 100644
index 00000000000..b3258f37427
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/input-date-time-fields-step-and-reverse-focus.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<input id="date" type="date">
+<button id="after">After</button>
+<input id="time" type="time">
+<script>
+ test(() => {
+ const date = document.getElementById("date");
+ const after = document.getElementById("after");
+ after.focus();
+ internals.sendKey(after, "Tab", 4);
+ println(`focused after Shift+Tab: ${document.activeElement.id}`);
+ internals.sendText(date, "2026");
+ internals.sendKey(date, "Home");
+ internals.sendText(date, "1031");
+ println(`date with the year typed first: value="${date.value}"`);
+
+ const time = document.getElementById("time");
+ time.step = 1;
+ time.focus();
+ internals.sendText(time, "013005a");
+ println(`time with step 1: value="${time.value}"`);
+ time.step = 60;
+ println(`time with step 60: value="${time.value}"`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/input-bad-input-validity.html b/Tests/LibWeb/Text/input/input-bad-input-validity.html
index b37d72dc86d..9ca23ea8219 100644
--- a/Tests/LibWeb/Text/input/input-bad-input-validity.html
+++ b/Tests/LibWeb/Text/input/input-bad-input-validity.html
@@ -13,15 +13,15 @@
check("number", "2026");
check("number", "2026 JUN");
- check("date", "2026-06-08");
- check("date", "2026-99-99");
- check("month", "2026-06");
- check("month", "2026-13");
- check("week", "2026-W23");
- check("week", "2026-W99");
- check("time", "12:30");
- check("time", "25:99");
- check("datetime-local", "2026-06-08T12:30");
- check("datetime-local", "not a date");
+ check("date", "06082026");
+ check("date", "02312026");
+ check("month", "062026");
+ check("month", "06");
+ check("week", "232026");
+ check("week", "532027");
+ check("time", "1230p");
+ check("time", "12");
+ check("datetime-local", "060820261230p");
+ check("datetime-local", "0608");
});
</script>
diff --git a/Tests/LibWeb/Text/input/input-time-typing.html b/Tests/LibWeb/Text/input/input-time-typing.html
index 40fc9a4c3cc..65a9f24fbc2 100644
--- a/Tests/LibWeb/Text/input/input-time-typing.html
+++ b/Tests/LibWeb/Text/input/input-time-typing.html
@@ -5,9 +5,8 @@
test(() => {
const input = document.getElementById("time");
input.focus();
- // Each keystroke leaves an invalid partial time until the last; the raw text must persist across them
- // for the final value to parse as "12:30".
- for (const ch of "12:30") {
+ // Each keystroke fills in a field of the time; the value stays empty until the day period is chosen too.
+ for (const ch of "12:30p") {
internals.sendText(input, ch);
println(`after '${ch}': value="${input.value}"`);
}