Bladeren bron

feat(api): add `convertFileSrc` helper (#2138)

Lucas Fernandes Nogueira 4 jaren geleden
bovenliggende
commit
51a5cfe4b5

+ 5 - 0
.changes/api-convert-file-url.md

@@ -0,0 +1,5 @@
+---
+"api": patch
+---
+
+Adds `convertFileSrc` helper to the `tauri` module, simplifying the process of using file paths as webview source (`img`, `video`, etc).

File diff suppressed because it is too large
+ 0 - 0
core/tauri/scripts/bundle.js


File diff suppressed because it is too large
+ 0 - 0
examples/api/public/build/bundle.js


File diff suppressed because it is too large
+ 0 - 0
examples/api/public/build/bundle.js.map


+ 2 - 2
examples/api/src-tauri/tauri.conf.json

@@ -79,10 +79,10 @@
       }
     ],
     "security": {
-      "csp": "default-src blob: data: filesystem: ws: wss: http: https: tauri: 'unsafe-eval' 'unsafe-inline' 'self' img-src: 'self'"
+      "csp": "default-src blob: data: filesystem: ws: wss: http: https: tauri: asset: 'unsafe-eval' 'unsafe-inline' 'self' img-src: 'self'"
     },
     "systemTray": {
       "iconPath": "../../.icons/icon.png"
     }
   }
-}
+}

+ 9 - 0
examples/api/src/components/FileSystem.svelte

@@ -1,9 +1,11 @@
 <script>
   import { readBinaryFile, readDir, Dir } from "@tauri-apps/api/fs";
+  import { convertFileSrc } from "@tauri-apps/api/tauri";
 
   export let onMessage;
 
   let pathToRead = "";
+  let img;
 
   function getDir() {
     const dirSelect = document.getElementById("dir");
@@ -71,6 +73,10 @@
       })
       .catch(onMessage);
   }
+
+  function setSrc() {
+    img.src = convertFileSrc(pathToRead)
+  }
 </script>
 
 <form on:submit|preventDefault={read}>
@@ -86,4 +92,7 @@
     bind:value={pathToRead}
   />
   <button class="button" id="read">Read</button>
+  <button class="button" type="button" on:click={setSrc}>Use as img src</button>
+
+  <img alt="file" bind:this={img}>
 </form>

+ 15 - 1
tooling/api/src/tauri.ts

@@ -88,6 +88,20 @@ async function invoke<T>(cmd: string, args: InvokeArgs = {}): Promise<T> {
   })
 }
 
+/**
+ * Convert a device file path to an URL that can be loaded by the webview.
+ * Note that `asset:` must be allowed on the `csp` value configured on `tauri.conf.json`.
+ *
+ * @param  filePath the file path. On Windows, the drive name must be omitted, i.e. using `/Users/user/file.png` instead of `C:/Users/user/file.png`.
+ *
+ * @return the URL that can be used as source on the webview
+ */
+function convertFileSrc(filePath: string): string {
+  return navigator.userAgent.includes('Windows')
+    ? `https://custom.protocol.asset_${filePath}`
+    : `asset://${filePath}`
+}
+
 export type { InvokeArgs }
 
-export { transformCallback, invoke }
+export { transformCallback, invoke, convertFileSrc }

Some files were not shown because too many files changed in this diff