LibWeb: Add helpers to convert a MouseButton to/from its DOM event code

Move the helper to convert MouseButton to its DOM event code to a public
header. And add a helper to convert in the opposite direction.
This commit is contained in:
Timothy Flynn 2024-09-27 10:19:23 -04:00 committed by Andreas Kling
parent 1217e7733f
commit 5e99715377
Notes: github-actions[bot] 2024-10-01 09:04:08 +00:00
2 changed files with 38 additions and 20 deletions

View file

@ -6,7 +6,9 @@
#pragma once
#include <AK/Assertions.h>
#include <AK/EnumBits.h>
#include <AK/Types.h>
namespace Web::UIEvents {
@ -21,4 +23,39 @@ enum MouseButton : u8 {
AK_ENUM_BITWISE_OPERATORS(MouseButton);
// https://www.w3.org/TR/uievents/#dom-mouseevent-button
constexpr i16 mouse_button_to_button_code(MouseButton button)
{
switch (button) {
case MouseButton::Primary:
return 0;
case MouseButton::Middle:
return 1;
case MouseButton::Secondary:
return 2;
case MouseButton::Backward:
return 3;
case MouseButton::Forward:
return 4;
default:
VERIFY_NOT_REACHED();
}
}
// https://www.w3.org/TR/uievents/#dom-mouseevent-button
constexpr MouseButton button_code_to_mouse_button(i16 button)
{
if (button == 0)
return MouseButton::Primary;
if (button == 1)
return MouseButton::Middle;
if (button == 2)
return MouseButton::Secondary;
if (button == 3)
return MouseButton::Backward;
if (button == 4)
return MouseButton::Forward;
return MouseButton::None;
}
}

View file

@ -123,25 +123,6 @@ void MouseEvent::init_mouse_event(String const& type, bool bubbles, bool cancela
m_related_target = related_target;
}
// https://www.w3.org/TR/uievents/#dom-mouseevent-button
static i16 determine_button(unsigned mouse_button)
{
switch (mouse_button) {
case MouseButton::Primary:
return 0;
case MouseButton::Middle:
return 1;
case MouseButton::Secondary:
return 2;
case MouseButton::Backward:
return 3;
case MouseButton::Forward:
return 4;
default:
VERIFY_NOT_REACHED();
}
}
JS::NonnullGCPtr<MouseEvent> MouseEvent::create(JS::Realm& realm, FlyString const& event_name, MouseEventInit const& event_init, double page_x, double page_y, double offset_x, double offset_y)
{
return realm.heap().allocate<MouseEvent>(realm, realm, event_name, event_init, page_x, page_y, offset_x, offset_y);
@ -167,7 +148,7 @@ WebIDL::ExceptionOr<JS::NonnullGCPtr<MouseEvent>> MouseEvent::create_from_platfo
event_init.movement_x = movement.value().x().to_double();
event_init.movement_y = movement.value().y().to_double();
}
event_init.button = determine_button(button);
event_init.button = mouse_button_to_button_code(static_cast<MouseButton>(button));
event_init.buttons = buttons;
auto event = MouseEvent::create(realm, event_name, event_init, page.x().to_double(), page.y().to_double(), offset.x().to_double(), offset.y().to_double());
event->set_is_trusted(true);