1use crate::event_handlers::{WindowEventHandlers, WinitEventHandlerId};
2
3use dioxus_core::{Runtime, consume_context, current_scope_id, use_hook_with_cleanup};
4use std::rc::Rc;
5use winit::{
6 event::{ElementState, WindowEvent},
7 event_loop::ActiveEventLoop,
8 keyboard::{Key, NamedKey},
9};
10
11pub fn use_window_event(
13 mut handler: impl FnMut(&WindowEvent, &dyn ActiveEventLoop) + 'static,
14) -> WinitEventHandlerId {
15 let runtime = Runtime::current();
16 let scope_id = current_scope_id();
17 let window_id = crate::use_window().id();
18
19 use_hook_with_cleanup(
20 move || {
21 let handlers: Rc<WindowEventHandlers> = consume_context();
22 handlers.add(window_id, move |event, target| {
23 runtime.in_scope(scope_id, || handler(event, target))
24 })
25 },
26 move |handler| handler.remove(),
27 )
28}
29
30pub fn use_back_button(mut handler: impl FnMut() + 'static) -> WinitEventHandlerId {
40 use_window_event(move |event, _target| {
41 if let WindowEvent::KeyboardInput { event, .. } = event
42 && event.state == ElementState::Pressed
43 && !event.repeat
44 && event.logical_key == Key::Named(NamedKey::BrowserBack)
45 {
46 handler();
47 }
48 })
49}