Parcourir la source

feat(core): add AssetManager::iter (#8288)

This new function allows users to iterate on all embedded assets, important if you want to AssetManager::get an asset you are not sure exists.
Lucas Nogueira il y a 1 an
Parent
commit
b3e53e7243

+ 5 - 0
.changes/asset-iter.md

@@ -0,0 +1,5 @@
+---
+"tauri": patch:enhance
+---
+
+Added `AssetResolver::iter` to iterate on all embedded assets.

+ 7 - 0
core/tauri-utils/src/assets.rs

@@ -109,6 +109,9 @@ pub trait Assets: Send + Sync + 'static {
   /// Get the content of the passed [`AssetKey`].
   fn get(&self, key: &AssetKey) -> Option<Cow<'_, [u8]>>;
 
+  /// Iterator for the assets.
+  fn iter(&self) -> Box<dyn Iterator<Item = (&&str, &&[u8])> + '_>;
+
   /// Gets the hashes for the CSP tag of the HTML on the given path.
   fn csp_hashes(&self, html_path: &AssetKey) -> Box<dyn Iterator<Item = CspHash<'_>> + '_>;
 }
@@ -163,6 +166,10 @@ impl Assets for EmbeddedAssets {
       .map(|a| Cow::Owned(a.to_vec()))
   }
 
+  fn iter(&self) -> Box<dyn Iterator<Item = (&&str, &&[u8])> + '_> {
+    Box::new(self.assets.into_iter())
+  }
+
   fn csp_hashes(&self, html_path: &AssetKey) -> Box<dyn Iterator<Item = CspHash<'_>> + '_> {
     Box::new(
       self

+ 5 - 0
core/tauri/src/app.rs

@@ -357,6 +357,11 @@ impl<R: Runtime> AssetResolver<R> {
   pub fn get(&self, path: String) -> Option<Asset> {
     self.manager.get_asset(path).ok()
   }
+
+  /// Iterate on all assets.
+  pub fn iter(&self) -> Box<dyn Iterator<Item = (&&str, &&[u8])> + '_> {
+    self.manager.asset_iter()
+  }
 }
 
 /// A handle to the currently running application.

+ 4 - 0
core/tauri/src/manager.rs

@@ -627,6 +627,10 @@ impl<R: Runtime> WindowManager<R> {
     })
   }
 
+  pub fn asset_iter(&self) -> Box<dyn Iterator<Item = (&&str, &&[u8])> + '_> {
+    self.inner.assets.iter()
+  }
+
   pub fn get_asset(&self, mut path: String) -> Result<Asset, Box<dyn std::error::Error>> {
     let assets = &self.inner.assets;
     if path.ends_with('/') {

+ 6 - 0
core/tauri/src/test/mod.rs

@@ -99,6 +99,7 @@ struct Ipc(Mutex<HashMap<IpcKey, Sender<std::result::Result<JsonValue, JsonValue
 
 /// An empty [`Assets`] implementation.
 pub struct NoopAsset {
+  assets: HashMap<&'static str, &'static [u8]>,
   csp_hashes: Vec<CspHash<'static>>,
 }
 
@@ -107,6 +108,10 @@ impl Assets for NoopAsset {
     None
   }
 
+  fn iter(&self) -> Box<dyn Iterator<Item = (&&str, &&[u8])> + '_> {
+    Box::new(self.assets.iter())
+  }
+
   fn csp_hashes(&self, html_path: &AssetKey) -> Box<dyn Iterator<Item = CspHash<'_>> + '_> {
     Box::new(self.csp_hashes.iter().copied())
   }
@@ -115,6 +120,7 @@ impl Assets for NoopAsset {
 /// Creates a new empty [`Assets`] implementation.
 pub fn noop_assets() -> NoopAsset {
   NoopAsset {
+    assets: Default::default(),
     csp_hashes: Default::default(),
   }
 }