Truly independent web browser
LibWeb: Step number inputs with the arrow keys and fire beforeinput
Andreas Kling3a3b0a15825c
diff --git a/Libraries/LibWeb/HTML/HTMLInputElement.cpp b/Libraries/LibWeb/HTML/HTMLInputElement.cppindex 8642eaa2815..c1612ff5e56 100644--- a/Libraries/LibWeb/HTML/HTMLInputElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLInputElement.cpp@@ -65,6 +65,7 @@#include <LibWeb/Selection/Selection.h>#include <LibWeb/UIEvents/EventNames.h>#include <LibWeb/UIEvents/InputEvent.h>+#include <LibWeb/UIEvents/InputTypes.h>#include <LibWeb/UIEvents/MouseEvent.h>#include <LibWeb/WebIDL/DOMException.h>#include <LibWeb/WebIDL/ExceptionOr.h>@@ -823,6 +824,7 @@ void HTMLInputElement::commit_pending_changes()// or else when the control loses focusswitch (type_state()) {case TypeAttributeState::Email:+ case TypeAttributeState::Number:case TypeAttributeState::Password:case TypeAttributeState::Search:case TypeAttributeState::Telephone:@@ -1290,10 +1292,7 @@ void HTMLInputElement::create_text_input_shadow_tree()auto up_callback_function = JS::NativeFunction::create(HTML::relevant_realm(*this), [this](JS::VM&) {- if (type_state() == TypeAttributeState::Number && is_mutable() && allowed_value_step().has_value()) {- MUST(step_up());- user_interaction_did_change_input_value();- }+ step_for_user_interaction(StepDirection::Up, CommitChange::No);return JS::js_undefined();},0, Utf16FlyString {}, &HTML::relevant_realm(*this));@@ -1320,10 +1319,7 @@ void HTMLInputElement::create_text_input_shadow_tree()auto down_callback_function = JS::NativeFunction::create(HTML::relevant_realm(*this), [this](JS::VM&) {- if (type_state() == TypeAttributeState::Number && is_mutable() && allowed_value_step().has_value()) {- MUST(step_down());- user_interaction_did_change_input_value();- }+ step_for_user_interaction(StepDirection::Down, CommitChange::No);return JS::js_undefined();},0, Utf16FlyString {}, &HTML::relevant_realm(*this));@@ -3355,17 +3351,19 @@ WebIDL::ExceptionOr<void> HTMLInputElement::set_value_as_number(double value)// https://html.spec.whatwg.org/multipage/input.html#dom-input-stepupWebIDL::ExceptionOr<void> HTMLInputElement::step_up(WebIDL::Long n){- return step_up_or_down(false, n);+ TRY(step_up_or_down(false, n));+ return {};}// https://html.spec.whatwg.org/multipage/input.html#dom-input-stepdownWebIDL::ExceptionOr<void> HTMLInputElement::step_down(WebIDL::Long n){- return step_up_or_down(true, n);+ TRY(step_up_or_down(true, n));+ return {};}// https://html.spec.whatwg.org/multipage/input.html#dom-input-stepup-WebIDL::ExceptionOr<void> HTMLInputElement::step_up_or_down(bool is_down, WebIDL::Long n)+WebIDL::ExceptionOr<HTMLInputElement::StepResult> HTMLInputElement::step_up_or_down(bool is_down, WebIDL::Long n, StepTrigger trigger){// 1. If the stepDown() and stepUp() methods do not apply, as defined for the input element's type attribute's current state, then throw an "InvalidStateError" DOMException.if (!step_up_or_down_applies())@@ -3381,12 +3379,12 @@ WebIDL::ExceptionOr<void> HTMLInputElement::step_up_or_down(bool is_down, WebIDLauto maybe_minimum = min();auto maybe_maximum = max();if (maybe_minimum.has_value() && maybe_maximum.has_value() && *maybe_minimum > *maybe_maximum)- return {};+ return StepResult::NotStepped;// 4. If the element has a minimum and a maximum and there is no value greater than or equal to the element's minimum and less than// or equal to the element's maximum that, when subtracted from the step base, is an integral multiple of the allowed value step, then return.if (maybe_minimum.has_value() && maybe_maximum.has_value() && ceil((*maybe_minimum - step_base()) / allowed_value_step) > floor((*maybe_maximum - step_base()) / allowed_value_step))- return {};+ return StepResult::NotStepped;// 5. If applying the algorithm to convert a string to a number to the string given by the element's value does not result in an error,// then let value be the result of that algorithm. Otherwise, let value be zero.@@ -3439,18 +3437,52 @@ WebIDL::ExceptionOr<void> HTMLInputElement::step_up_or_down(bool is_down, WebIDL// element without a value always gives it one.if (maybe_value.has_value()) {if (is_down && value > value_before_stepping)- return {};+ return StepResult::NotStepped;if (!is_down && value < value_before_stepping)- return {};+ return StepResult::NotStepped;}// 11. Let value as string be the result of running the algorithm to convert a number to a string,// as defined for the input element's type attribute's current state, on value.auto value_as_string = convert_number_to_string(value);+ // INTEROP: When the user steps the value, other engines first fire a cancelable beforeinput event with the new+ // value, and leave the value alone if that event is canceled or makes the element's node document no+ // longer fully active.+ // We also leave it alone if the event changes the element's type or makes it immutable.+ if (trigger == StepTrigger::UserInteraction) {+ auto type_state_before_event = type_state();+ UIEvents::InputEventInit before_input_event_init;+ before_input_event_init.input_type = UIEvents::InputTypes::insertText;+ before_input_event_init.data = value_as_string;+ auto before_input_event = UIEvents::InputEvent::create_from_platform_event(UIEvents::EventNames::beforeinput, before_input_event_init, {}, HighResolutionTime::current_high_resolution_time(relevant_global_object(*this)));+ if (!dispatch_event(before_input_event) || !document().is_fully_active())+ return StepResult::NotStepped;+ if (type_state() != type_state_before_event || !is_mutable())+ return StepResult::NotStepped;+ }+// 12. Set the value of the element to value as string.+ auto value_before_setting = this->value();TRY(set_value(value_as_string));- return {};+ return this->value() == value_before_setting ? StepResult::NotStepped : StepResult::Stepped;+}++// AD-HOC: Steps the value of the element for the user's interaction with its spin buttons or arrow keys, and fires the+// events that such a change of the value fires.+void HTMLInputElement::step_for_user_interaction(StepDirection direction, CommitChange commit_change)+{+ if (type_state() != TypeAttributeState::Number || !is_mutable() || !allowed_value_step().has_value())+ return;++ auto result = step_up_or_down(direction == StepDirection::Down, 1, StepTrigger::UserInteraction);+ if (result.is_error() || result.value() == StepResult::NotStepped)+ return;++ m_has_uncommitted_changes = true;+ user_interaction_did_change_input_value(UIEvents::InputTypes::insertText, value());+ if (commit_change == CommitChange::Yes)+ commit_pending_changes();}Optional<ARIA::Role> HTMLInputElement::default_role() constdiff --git a/Libraries/LibWeb/HTML/HTMLInputElement.h b/Libraries/LibWeb/HTML/HTMLInputElement.hindex c2620830c7e..de436c58dfb 100644--- a/Libraries/LibWeb/HTML/HTMLInputElement.h+++ b/Libraries/LibWeb/HTML/HTMLInputElement.h@@ -170,6 +170,16 @@ public:WebIDL::ExceptionOr<void> step_up(WebIDL::Long n = 1);WebIDL::ExceptionOr<void> step_down(WebIDL::Long n = 1);+ enum class StepDirection : u8 {+ Up,+ Down,+ };+ enum class CommitChange : u8 {+ No,+ Yes,+ };+ void step_for_user_interaction(StepDirection, CommitChange);+WebIDL::ExceptionOr<void> show_picker();// ^EventTarget@@ -331,7 +341,15 @@ private:double step_scale_factor() const;Optional<double> allowed_value_step() const;double step_base() const;- WebIDL::ExceptionOr<void> step_up_or_down(bool is_down, WebIDL::Long n);+ enum class StepTrigger : u8 {+ Script,+ UserInteraction,+ };+ enum class StepResult : u8 {+ NotStepped,+ Stepped,+ };+ WebIDL::ExceptionOr<StepResult> step_up_or_down(bool is_down, WebIDL::Long n, StepTrigger = StepTrigger::Script);static TypeAttributeState parse_type_attribute(Utf16View);diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cppindex 90e8d2e9192..7423cff1385 100644--- a/Libraries/LibWeb/Page/EventHandler.cpp+++ b/Libraries/LibWeb/Page/EventHandler.cpp@@ -2049,6 +2049,15 @@ EventResult EventHandler::handle_keydown(UIEvents::KeyCode key, u32 modifiers, ureturn EventResult::Handled;}+ // AD-HOC: Like in other engines, the up and down arrow keys step the value of a number input.+ if ((key == UIEvents::KeyCode::Key_Up || key == UIEvents::KeyCode::Key_Down) && (modifiers & ~UIEvents::Mod_Keypad) == UIEvents::Mod_None) {+ if (auto* input_element = as_if<HTML::HTMLInputElement>(document->focused_area().ptr()); input_element && input_element->type_state() == HTML::HTMLInputElement::TypeAttributeState::Number) {+ auto direction = key == UIEvents::KeyCode::Key_Up ? HTML::HTMLInputElement::StepDirection::Up : HTML::HTMLInputElement::StepDirection::Down;+ input_element->step_for_user_interaction(direction, HTML::HTMLInputElement::CommitChange::Yes);+ return EventResult::Handled;+ }+ }+if (key == UIEvents::KeyCode::Key_Up || key == UIEvents::KeyCode::Key_Down) {auto collapse = modifiers & UIEvents::Mod_Shift ? InputEventsTarget::CollapseSelection::No : InputEventsTarget::CollapseSelection::Yes;if (key == UIEvents::KeyCode::Key_Up) {diff --git a/Tests/LibWeb/Crash/HTML/number-input-arrow-key-type-change-in-beforeinput.html b/Tests/LibWeb/Crash/HTML/number-input-arrow-key-type-change-in-beforeinput.htmlnew file mode 100644index 00000000000..dec0944b00a--- /dev/null+++ b/Tests/LibWeb/Crash/HTML/number-input-arrow-key-type-change-in-beforeinput.html@@ -0,0 +1,9 @@+<!DOCTYPE html>+<input type="number" id="input" value="1">+<script>+ input.addEventListener("beforeinput", () => {+ input.type = "file";+ });+ input.focus();+ internals.sendKey(input, "Up");+</script>diff --git a/Tests/LibWeb/Text/expected/HTML/number-input-arrow-key-events.txt b/Tests/LibWeb/Text/expected/HTML/number-input-arrow-key-events.txtnew file mode 100644index 00000000000..bc30a5c4845--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/number-input-arrow-key-events.txt@@ -0,0 +1,23 @@+ArrowUp:+beforeinput: inputType="insertText" data="6" cancelable=true value="5"+input: inputType="insertText" data="6" cancelable=false value="6"+change: inputType=undefined data=undefined cancelable=false value="6"+ArrowDown:+beforeinput: inputType="insertText" data="5" cancelable=true value="6"+input: inputType="insertText" data="5" cancelable=false value="5"+change: inputType=undefined data=undefined cancelable=false value="5"+ArrowUp with a canceled beforeinput that sets the value:+beforeinput: inputType="insertText" data="6" cancelable=true value="5"+value="100"+ArrowUp with a beforeinput that makes the input read-only:+beforeinput: inputType="insertText" data="101" cancelable=true value="100"+value="100"+ArrowUp with a beforeinput that changes the type to text:+beforeinput: inputType="insertText" data="101" cancelable=true value="100"+type="text" value="100"+ArrowUp with an input listener that blurs the input:+beforeinput: inputType="insertText" data="101" cancelable=true value="100"+input: inputType="insertText" data="101" cancelable=false value="101"+change: inputType=undefined data=undefined cancelable=false value="101"+value="101"+Blur without a change:diff --git a/Tests/LibWeb/Text/expected/wpt-import/input-events/input-events-arrow-key-on-number-input-delete-document.txt b/Tests/LibWeb/Text/expected/wpt-import/input-events/input-events-arrow-key-on-number-input-delete-document.txtindex ed7cf612d25..ba84da43838 100644--- a/Tests/LibWeb/Text/expected/wpt-import/input-events/input-events-arrow-key-on-number-input-delete-document.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/input-events/input-events-arrow-key-on-number-input-delete-document.txt@@ -2,5 +2,5 @@ Harness status: OKFound 1 tests-1 Fail-Fail Number input should not crash and not fire subsequent events when event handler removes document\ No newline at end of file+1 Pass+Pass Number input should not crash and not fire subsequent events when event handler removes document\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/input-events/input-events-arrow-key-on-number-input-prevent-default.txt b/Tests/LibWeb/Text/expected/wpt-import/input-events/input-events-arrow-key-on-number-input-prevent-default.txtindex dc3e5aec10c..8526e89bdf3 100644--- a/Tests/LibWeb/Text/expected/wpt-import/input-events/input-events-arrow-key-on-number-input-prevent-default.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/input-events/input-events-arrow-key-on-number-input-prevent-default.txt@@ -2,5 +2,5 @@ Harness status: OKFound 1 tests-1 Fail-Fail Number input should not fire input and change event if the beforeinput event is default prevented\ No newline at end of file+1 Pass+Pass Number input should not fire input and change event if the beforeinput event is default prevented\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/input-events/input-events-arrow-key-on-number-input.txt b/Tests/LibWeb/Text/expected/wpt-import/input-events/input-events-arrow-key-on-number-input.txtindex 297c2c33f65..5d2fc4a30d0 100644--- a/Tests/LibWeb/Text/expected/wpt-import/input-events/input-events-arrow-key-on-number-input.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/input-events/input-events-arrow-key-on-number-input.txt@@ -2,5 +2,5 @@ Harness status: OKFound 1 tests-1 Fail-Fail Number input should fire beforeinput event before the input and change event\ No newline at end of file+1 Pass+Pass Number input should fire beforeinput event before the input and change event\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/HTML/number-input-arrow-key-events.html b/Tests/LibWeb/Text/input/HTML/number-input-arrow-key-events.htmlnew file mode 100644index 00000000000..b1db0726618--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/number-input-arrow-key-events.html@@ -0,0 +1,67 @@+<!doctype html>+<script src="../include.js"></script>+<input type="number" id="input" value="5" />+<script>+ test(() => {+ const log = event => {+ const inputType = event.inputType === undefined ? "undefined" : `"${event.inputType}"`;+ const data = event.data === undefined || event.data === null ? String(event.data) : `"${event.data}"`;+ println(+ `${event.type}: inputType=${inputType} data=${data} cancelable=${event.cancelable} value="${input.value}"`+ );+ };+ input.addEventListener("beforeinput", log);+ input.addEventListener("input", log);+ input.addEventListener("change", log);+ input.focus();++ println("ArrowUp:");+ internals.sendKey(input, "Up");+ println("ArrowDown:");+ internals.sendKey(input, "Down");++ println("ArrowUp with a canceled beforeinput that sets the value:");+ const setValueAndCancel = event => {+ input.value = "100";+ event.preventDefault();+ };+ input.addEventListener("beforeinput", setValueAndCancel);+ internals.sendKey(input, "Up");+ input.removeEventListener("beforeinput", setValueAndCancel);+ println(`value="${input.value}"`);++ println("ArrowUp with a beforeinput that makes the input read-only:");+ const makeReadOnly = () => {+ input.readOnly = true;+ };+ input.addEventListener("beforeinput", makeReadOnly);+ internals.sendKey(input, "Up");+ input.removeEventListener("beforeinput", makeReadOnly);+ input.readOnly = false;+ println(`value="${input.value}"`);++ println("ArrowUp with a beforeinput that changes the type to text:");+ const changeType = () => {+ input.type = "text";+ };+ input.addEventListener("beforeinput", changeType);+ internals.sendKey(input, "Up");+ input.removeEventListener("beforeinput", changeType);+ println(`type="${input.type}" value="${input.value}"`);++ println("ArrowUp with an input listener that blurs the input:");+ input.type = "number";+ input.focus();+ const blurInput = () => {+ input.blur();+ };+ input.addEventListener("input", blurInput);+ internals.sendKey(input, "Up");+ input.removeEventListener("input", blurInput);+ println(`value="${input.value}"`);++ println("Blur without a change:");+ input.focus();+ input.blur();+ });+</script>