Skip to content

Commit

Permalink
refactor!(global-shortcut): better APIs DX (#969)
Browse files Browse the repository at this point in the history
* feat(global-shortcut): add `GlobalShortcutExt::register_with_handler`

ref: #965

* clippy

* refactor apis to take closure by default

* change file

* Update .changes/global-shortcut-refactor.md

Co-authored-by: Simon Hyll <[email protected]>

* Update global-shortcut-refactor.md

* use option instead

* clippy

* update readme

* on_shortcut and with_shortcut

* map handler

* simplify events

* lint

---------

Co-authored-by: Simon Hyll <[email protected]>
Co-authored-by: Lucas Nogueira <[email protected]>
  • Loading branch information
3 people authored Mar 7, 2024
1 parent 644eb44 commit 62dafda
Show file tree
Hide file tree
Showing 3 changed files with 168 additions and 92 deletions.
9 changes: 9 additions & 0 deletions .changes/global-shortcut-refactor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"global-shortcut": "patch"
---

**Breaking change** Refactored the plugin Rust APIs for better DX and flexibility:

- Changed `Builder::with_handler` to be a method instead of a static method, it will also be triggered for any and all shortcuts even if the shortcut is registered through JS.
- Added `Builder::with_shortcut` and `Builder::with_shortcuts` to register shortcuts on the plugin builder.
- Added `on_shortcut` and `on_all_shortcuts` to register shortcuts with a handler.
24 changes: 13 additions & 11 deletions plugins/global-shortcut/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,20 +57,22 @@ fn main() {
.setup(|app| {
#[cfg(desktop)]
{
use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt, Modifiers, Shortcut};
use tauri::Manager;
use tauri_plugin_global_shortcut::{Code, Modifiers};

let ctrl_n_shortcut = Shortcut::new(Some(Modifiers::CONTROL), Code::KeyN);
app.handle().plugin(
tauri_plugin_global_shortcut::Builder::with_handler(move |_app, shortcut| {
println!("{:?}", shortcut);
if shortcut == &ctrl_n_shortcut {
println!("Ctrl-N Detected!");
}
})
.build(),
tauri_plugin_global_shortcut::Builder::new()
.with_shortcuts(["ctrl+d", "alt+space"])?
.with_handler(|app, shortcut| {
if shortcut.matches(Modifiers::CONTROL, Code::KeyD) {
let _ = app.emit("shortcut-event", "Ctrl+D triggered");
}
if shortcut.matches(Modifiers::ALT, Code::Space) {
let _ = app.emit("shortcut-event", "Alt+Space triggered");
}
})
.build(),
)?;

app.global_shortcut().register(ctrl_n_shortcut)?;
}

Ok(())
Expand Down
Loading

0 comments on commit 62dafda

Please sign in to comment.