Create use_muda_event_handler hook (#2367)

* create use_muda_event_handler hook

* fix use_muda_event_handler re-export
This commit is contained in:
Evan Almloff 2024-04-25 12:32:34 -05:00 committed by GitHub
parent 790b984e61
commit 72ef58b95e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 34 additions and 4 deletions

View file

@ -1,7 +1,7 @@
//! This example shows how to use a custom menu bar with Dioxus desktop.
//! This example is not supported on the mobile or web renderers.
use dioxus::desktop::muda::*;
use dioxus::desktop::{muda::*, use_muda_event_handler};
use dioxus::prelude::*;
fn main() {
@ -18,6 +18,7 @@ fn main() {
&PredefinedMenuItem::copy(None),
&PredefinedMenuItem::paste(None),
&PredefinedMenuItem::select_all(None),
&MenuItem::with_id("switch-text", "Switch text", true, None),
])
.unwrap();
@ -31,5 +32,18 @@ fn main() {
}
fn app() -> Element {
rsx! {"Hello World!"}
let mut text = use_signal(String::new);
// You can use the `use_muda_event_handler` hook to run code when a menu event is triggered.
use_muda_event_handler(move |muda_event| {
if muda_event.id() == "switch-text" {
text.set("Switched to text".to_string());
}
});
rsx! {
div {
h1 { "Custom Menu" }
p { "Text: {text}" }
}
}
}

View file

@ -18,7 +18,7 @@ pub fn use_window() -> DesktopContext {
use_hook(consume_context::<DesktopContext>)
}
/// Get a closure that executes any JavaScript in the WebView context.
/// Register an event handler that runs when a wry event is processed.
pub fn use_wry_event_handler(
handler: impl FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static,
) -> WryEventHandler {
@ -28,6 +28,22 @@ pub fn use_wry_event_handler(
)
}
/// Register an event handler that runs when a muda event is processed.
#[cfg_attr(
docsrs,
doc(cfg(any(target_os = "windows", target_os = "linux", target_os = "macos")))
)]
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
pub fn use_muda_event_handler(
mut handler: impl FnMut(&muda::MenuEvent) + 'static,
) -> WryEventHandler {
use_wry_event_handler(move |event, _| {
if let Event::UserEvent(UserWindowEvent::MudaMenuEvent(event)) = event {
handler(event);
}
})
}
/// Provide a callback to handle asset loading yourself.
///
/// The callback takes a path as requested by the web view, and it should return `Some(response)`

View file

@ -44,6 +44,6 @@ pub use assets::AssetRequest;
pub use config::{Config, WindowCloseBehaviour};
pub use desktop_context::{window, DesktopContext, DesktopService};
pub use event_handlers::WryEventHandler;
pub use hooks::{use_asset_handler, use_global_shortcut, use_window, use_wry_event_handler};
pub use hooks::*;
pub use shortcut::{ShortcutHandle, ShortcutRegistryError};
pub use wry::RequestAsyncResponder;