Skip to main content

dioxus_native/
hooks.rs

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
11/// Register an event handler that runs when a winit event is processed.
12pub 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
30/// Register a handler that runs when the back button is pressed.
31///
32/// This builds on top of [`use_window_event`]: the back button is delivered by `winit` as a
33/// [`WindowEvent::KeyboardInput`] whose logical key is [`NamedKey::BrowserBack`]. This most
34/// commonly comes from the Android hardware/system back button, but may also be produced by a
35/// keyboard or mouse back key on other platforms. The provided `handler` is called once each
36/// time the button is pressed (key repeats are ignored).
37///
38/// Returns a [`WinitEventHandlerId`] which can be used to remove the handler.
39pub 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}