瀏覽代碼

feat(core/tauri): add `try_get_item` for SystemTray and WindowMenu, closes #5491 (#6408)

* feat: try_get_item() for window menu

Add a method in the MenuHandle struct, that will return an Optional MenuItemHandle

feat: try_get_item() for systemtray

Add a method in the SystemTrayHandle struct, that will return an Optional SystemTrayMenuItemHandle

docs: features documented in ./changes/minor.md

fix: suggested changes

fix CI

* Update .changes/tray_get_item.md

---------
Jack Wills 2 年之前
父節點
當前提交
441f964654
共有 3 個文件被更改,包括 32 次插入0 次删除
  1. 5 0
      .changes/tray_get_item.md
  2. 13 0
      core/tauri/src/app/tray.rs
  3. 14 0
      core/tauri/src/window/menu.rs

+ 5 - 0
.changes/tray_get_item.md

@@ -0,0 +1,5 @@
+---
+'tauri': minor
+---
+
+Add `MenuHandle::try_get_item` and `SystemTrayHandle::try_get_item` which returns a `Option` instead of panicking.

+ 13 - 0
core/tauri/src/app/tray.rs

@@ -610,6 +610,19 @@ impl<R: Runtime> SystemTrayHandle<R> {
     panic!("item id not found")
   }
 
+  /// Attempts to get a handle to the menu item that has the specified `id`, return an error if `id` is not found.
+  pub fn try_get_item(&self, id: MenuIdRef<'_>) -> Option<SystemTrayMenuItemHandle<R>> {
+    self
+      .ids
+      .lock()
+      .unwrap()
+      .iter()
+      .find(|i| i.1 == id)
+      .map(|i| SystemTrayMenuItemHandle {
+        id: *i.0,
+        tray_handler: self.inner.clone(),
+      })
+  }
   /// Updates the tray icon.
   pub fn set_icon(&self, icon: Icon) -> crate::Result<()> {
     self.inner.set_icon(icon.try_into()?).map_err(Into::into)

+ 14 - 0
core/tauri/src/window/menu.rs

@@ -80,6 +80,20 @@ impl<R: Runtime> MenuHandle<R> {
     panic!("item id not found")
   }
 
+  /// Attempts to get a handle to the menu item that has the specified `id`, return an error if `id` is not found.
+  pub fn try_get_item(&self, id: MenuIdRef<'_>) -> Option<MenuItemHandle<R>> {
+    self
+      .ids
+      .lock()
+      .unwrap()
+      .iter()
+      .find(|i| i.1 == id)
+      .map(|i| MenuItemHandle {
+        id: *i.0,
+        dispatcher: self.dispatcher.clone(),
+      })
+  }
+
   /// Shows the menu.
   pub fn show(&self) -> crate::Result<()> {
     self.dispatcher.show_menu().map_err(Into::into)