diff --git a/src/platform_impl/web/event_loop/window_target.rs b/src/platform_impl/web/event_loop/window_target.rs index 46200d3b..5d2f06b2 100644 --- a/src/platform_impl/web/event_loop/window_target.rs +++ b/src/platform_impl/web/event_loop/window_target.rs @@ -80,6 +80,14 @@ impl WindowTarget { }); }); + let runner = self.runner.clone(); + canvas.on_key_press(move |char_code| { + runner.send_event(Event::WindowEvent { + window_id: WindowId(window::Id), + event: WindowEvent::ReceivedCharacter(char_code), + }); + }); + let runner = self.runner.clone(); canvas.on_mouse_out(move |pointer_id| { runner.send_event(Event::WindowEvent { diff --git a/src/platform_impl/web/web_sys/canvas.rs b/src/platform_impl/web/web_sys/canvas.rs index 6007ba82..ab7cd571 100644 --- a/src/platform_impl/web/web_sys/canvas.rs +++ b/src/platform_impl/web/web_sys/canvas.rs @@ -14,6 +14,7 @@ pub struct Canvas { on_blur: Option>, on_key_up: Option>, on_key_down: Option>, + on_key_press: Option>, on_mouse_out: Option>, on_mouse_over: Option>, on_mouse_up: Option>, @@ -59,6 +60,7 @@ impl Canvas { on_focus: None, on_key_up: None, on_key_down: None, + on_key_press: None, on_mouse_out: None, on_mouse_over: None, on_mouse_up: None, @@ -148,6 +150,15 @@ impl Canvas { })); } + pub fn on_key_press(&mut self, mut handler: F) + where + F: 'static + FnMut(char), + { + self.on_key_press = Some(self.add_event("keypress", move |event: KeyboardEvent| { + handler(event::codepoint(&event)); + })); + } + pub fn on_mouse_out(&mut self, mut handler: F) where F: 'static + FnMut(i32), @@ -183,14 +194,7 @@ impl Canvas { where F: 'static + FnMut(i32, MouseButton, ModifiersState), { - let canvas = self.raw.clone(); - self.on_mouse_down = Some(self.add_event("pointerdown", move |event: PointerEvent| { - // We focus the canvas manually when the user clicks on it. - // This is necessary because we are preventing the default event behavior - // in `add_event` - canvas.focus().expect("Failed to focus canvas"); - handler( event.pointer_id(), event::mouse_button(&event), @@ -231,7 +235,6 @@ impl Canvas { let closure = Closure::wrap(Box::new(move |event: E| { { let event_ref = event.as_ref(); - event_ref.prevent_default(); event_ref.stop_propagation(); event_ref.cancel_bubble(); } diff --git a/src/platform_impl/web/web_sys/event.rs b/src/platform_impl/web/web_sys/event.rs index a2914ccd..876fbc22 100644 --- a/src/platform_impl/web/web_sys/event.rs +++ b/src/platform_impl/web/web_sys/event.rs @@ -218,3 +218,7 @@ pub fn keyboard_modifiers(event: &KeyboardEvent) -> ModifiersState { logo: event.meta_key(), } } + +pub fn codepoint(event: &KeyboardEvent) -> char { + event.key().chars().next().unwrap() +}