Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle keydown not being a KeyboardEvent #567

Merged
merged 1 commit into from
Sep 27, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions crates/livesplit-hotkey/src/wasm_web/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::KeyCode;
use wasm_bindgen::{prelude::*, JsCast};
use web_sys::{window, Gamepad, GamepadButton, KeyboardEvent};
use web_sys::{window, Event, Gamepad, GamepadButton, KeyboardEvent};

use std::{
cell::Cell,
Expand All @@ -26,7 +26,7 @@ pub type Result<T> = std::result::Result<T, Error>;
/// A hook allows you to listen to hotkeys.
pub struct Hook {
hotkeys: Arc<Mutex<HashMap<KeyCode, Box<dyn FnMut() + Send + 'static>>>>,
keyboard_callback: Closure<dyn FnMut(KeyboardEvent)>,
keyboard_callback: Closure<dyn FnMut(Event)>,
gamepad_callback: Closure<dyn FnMut()>,
interval_id: Cell<Option<i32>>,
}
Expand Down Expand Up @@ -80,15 +80,21 @@ impl Hook {
let window = window().ok_or(Error::FailedToCreateHook)?;

let hotkey_map = hotkeys.clone();
let keyboard_callback = Closure::wrap(Box::new(move |event: KeyboardEvent| {
if !event.repeat() {
if let Ok(code) = event.code().parse() {
if let Some(callback) = hotkey_map.lock().unwrap().get_mut(&code) {
callback();
let keyboard_callback = Closure::wrap(Box::new(move |event: Event| {
// Despite all sorts of documentation claiming that `keydown` events
// pass you a `KeyboardEvent`, this is not actually always the case
// in browsers. At least in Chrome selecting an element of an
// `input` sends a `keydown` event that is not a `KeyboardEvent`.
if let Ok(event) = event.dyn_into::<KeyboardEvent>() {
if !event.repeat() {
if let Ok(code) = event.code().parse() {
if let Some(callback) = hotkey_map.lock().unwrap().get_mut(&code) {
callback();
}
}
}
}
}) as Box<dyn FnMut(KeyboardEvent)>);
}) as Box<dyn FnMut(Event)>);

window
.add_event_listener_with_callback("keydown", keyboard_callback.as_ref().unchecked_ref())
Expand Down