feat(core): implement CommandArg for AppHandle (#2037)

This commit is contained in:
Lucas Fernandes Nogueira 2021-06-21 14:00:34 -03:00 committed by GitHub
parent 1006c1cf3b
commit 59784c7e55
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 27 additions and 1 deletions

View File

@ -0,0 +1,5 @@
---
"tauri": patch
---
Allow accessing an `AppHandle` instance on a command through dependency injection.

View File

@ -9,6 +9,7 @@ pub(crate) mod tray;
use crate::{
api::assets::Assets,
api::config::{Config, WindowUrl},
command::{CommandArg, CommandItem},
hooks::{InvokeHandler, OnPageLoad, PageLoadPayload, SetupHook},
manager::{Args, WindowManager},
plugin::{Plugin, PluginStore},
@ -19,7 +20,7 @@ use crate::{
Dispatch, MenuId, Params, RunEvent, Runtime,
},
sealed::{ManagerBase, RuntimeOrDispatch},
Context, Invoke, Manager, StateManager, Window,
Context, Invoke, InvokeError, Manager, StateManager, Window,
};
use tauri_utils::PackageInfo;
@ -133,6 +134,13 @@ impl<P: Params> Clone for AppHandle<P> {
}
}
impl<'de, P: Params> CommandArg<'de, P> for AppHandle<P> {
/// Grabs the [`Window`] from the [`CommandItem`] and returns the associated [`AppHandle`]. This will never fail.
fn from_command(command: CommandItem<'de, P>) -> Result<Self, InvokeError> {
Ok(command.message.window().app_handle)
}
}
impl<P: Params> AppHandle<P> {
/// Removes the system tray.
#[cfg(all(windows, feature = "system-tray"))]

View File

@ -137,6 +137,19 @@ async fn my_custom_command(window: tauri::Window) {
}
```
## Accessing an AppHandle in Commands
Commands can access an `AppHandle` instance:
```rust
#[tauri::command]
async fn my_custom_command(app_handle: tauri::AppHandle) {
let app_dir = app_handle.path_resolver().app_dir();
use tauri::GlobalShortcutManager;
app_handle.global_shortcut_manager().register("CTRL + U", move || {});
}
```
## Accessing managed state
Tauri can manage state using the `manage` function on `tauri::Builder`.