Ver Fonte

feat(example) add API showcase to communication example (#511)

Lucas Fernandes Nogueira há 5 anos atrás
pai
commit
b4a08e88fd

+ 9 - 7
cli/tauri.js/src/runner.ts

@@ -11,8 +11,7 @@ import logger from './helpers/logger'
 import onShutdown from './helpers/on-shutdown'
 import { spawn, spawnSync } from './helpers/spawn'
 import { TauriConfig } from './types/config'
-// eslint-disable-next-line @typescript-eslint/no-var-requires
-const getTauriConfig = require('./helpers/tauri-config')
+import getTauriConfig from './helpers/tauri-config'
 
 const log = logger('app:tauri', 'green')
 const warn = logger('app:tauri (runner)', 'red')
@@ -105,17 +104,20 @@ class Runner {
           path.join(tauriDir, 'build.rs'),
           path.join(tauriDir, 'tauri.conf.json'),
           ...tauriPaths
-        ],
+        ].concat(runningDevServer ? [] : [devPath]),
         {
-          ignoreInitial: true
+          ignoreInitial: true,
+          ignored: runningDevServer ? null : path.join(devPath, 'index.tauri.html')
         }
       )
       .on(
         'change',
-        debounce((path: string) => {
+        debounce((changedPath: string) => {
           (this.pid ? this.__stopCargo() : Promise.resolve())
             .then(() => {
-              if (path.includes('tauri.conf.json')) {
+              const shouldTriggerRun = changedPath.includes('tauri.conf.json') ||
+                changedPath.startsWith(devPath)
+              if (shouldTriggerRun) {
                 this.run(getTauriConfig({ ctx: cfg.ctx })).catch(e => {
                   throw e
                 })
@@ -243,7 +245,7 @@ class Runner {
         })
       }
 
-      if (cfg.tauri.embeddedServer.active || !cfg.tauri.inliner.active) {
+      if ((!cfg.ctx.dev && cfg.tauri.embeddedServer.active) || !cfg.tauri.inliner.active) {
         rewriteHtml(readFileSync(indexPath).toString(), domInterceptor)
         resolve(inlinedAssets)
       } else {

+ 11 - 31
cli/tauri.js/templates/tauri.js

@@ -267,7 +267,7 @@ window.tauri = {
       if (_typeof(cfg) === 'object') {
         Object.freeze(cfg);
       }
-      this.invoke({
+      return this.promisified({
         cmd: 'writeFile',
         file: cfg.file,
         contents: cfg.contents
@@ -282,45 +282,25 @@ window.tauri = {
 
   <% if (ctx.dev) { %>
     /**
-     * @name listFiles
-     * @description Get the files in a path.
-     * Permissions based on the app's PID owner
-     * @param {String} path
-     * @returns {*|Promise<any>|Promise}
-     */
-  <% } %>
-  listFiles: function listFiles(path) {
-    <% if (tauri.whitelist.listFiles === true || tauri.whitelist.all === true) { %>
-      return this.promisified({
-        cmd: 'listFiles',
-        path: path
-      });
-    <% } else { %>
-      <% if (ctx.dev) { %>
-          return __whitelistWarning('listDirs')
-          <% } %>
-        return __reject()
-        <% } %>
-  },
-
-  <% if (ctx.dev) { %>
-    /**
-     * @name listDirs
-     * @description Get the directories in a path.
+     * @name readDir
+     * @description Reads a directory
      * Permissions based on the app's PID owner
      * @param {String} path
+     * @param {Object} [options]
+     * @param {Boolean} [options.recursive]
      * @returns {*|Promise<any>|Promise}
      */
   <% } %>
-  listDirs: function listDirs(path) {
-    <% if (tauri.whitelist.listDirs === true || tauri.whitelist.all === true) { %>
+  readDir: function readDir(path, options) {
+    <% if (tauri.whitelist.readDir === true || tauri.whitelist.all === true) { %>
       return this.promisified({
-        cmd: 'listDirs',
-        path: path
+        cmd: 'readDir',
+        path: path,
+        options: options
       });
     <% } else { %>
       <% if (ctx.dev) { %>
-          return __whitelistWarning('listDirs')
+          return __whitelistWarning('readDir')
           <% } %>
         return __reject()
         <% } %>

+ 29 - 0
tauri/examples/communication/dist/communication.js

@@ -0,0 +1,29 @@
+window.onTauriInit = function () {
+  window.tauri.listen('rust-event', function (res) {
+    document.getElementById('response').innerHTML = JSON.stringify(res)
+  })
+}
+
+document.getElementById('log').addEventListener('click', function () {
+  window.tauri.invoke({
+    cmd: 'logOperation',
+    event: 'tauri-click',
+    payload: 'this payload is optional because we used Option in Rust'
+  })
+})
+
+document.getElementById('request').addEventListener('click', function () {
+  window.tauri.promisified({
+    cmd: 'performRequest',
+    endpoint: 'dummy endpoint arg',
+    body: {
+      id: 5,
+      name: 'test'
+    }
+  }).then(registerResponse).catch(registerResponse)
+})
+
+document.getElementById('event').addEventListener('click', function () {
+  window.tauri.emit('js-event', 'this is the payload string')
+})
+

+ 46 - 0
tauri/examples/communication/dist/fs.js

@@ -0,0 +1,46 @@
+function arrayBufferToBase64(buffer, callback) {
+  var blob = new Blob([buffer], {
+    type: 'application/octet-binary'
+  })
+  var reader = new FileReader()
+  reader.onload = function (evt) {
+    var dataurl = evt.target.result
+    callback(dataurl.substr(dataurl.indexOf(',') + 1))
+  }
+  reader.readAsDataURL(blob)
+}
+
+var pathInput = document.getElementById('path-to-read')
+
+addClickEnterHandler(
+  document.getElementById('read'),
+  pathInput,
+  function () {
+    var pathToRead = pathInput.value
+    var isFile = pathToRead.match(/\S+\.\S+$/g)
+    var promise = isFile ? window.tauri.readBinaryFile(pathToRead) : window.tauri.readDir(pathToRead)
+    promise.then(function (response) {
+      if (isFile) {
+        if (pathToRead.includes('.png') || pathToRead.includes('.jpg')) {
+          arrayBufferToBase64(new Uint8Array(response), function (base64) {
+            var src = 'data:image/png;base64,' + base64
+            registerResponse('<img src="' + src + '"></img>')
+          })
+        } else {
+          var value = String.fromCharCode.apply(null, response)
+          registerResponse('<textarea id="file-response" style="height: 400px"></textarea><button id="file-save">Save</button>')
+          var fileInput = document.getElementById('file-response')
+          fileInput.value = value
+          document.getElementById('file-save').addEventListener('click', function () {
+            window.tauri.writeFile({
+              file: pathToRead,
+              contents: fileInput.value
+            }).catch(registerResponse)
+          })
+        }
+      } else {
+        registerResponse(response)
+      }
+    }).catch(registerResponse)
+  }
+)

+ 32 - 28
tauri/examples/communication/dist/index.html

@@ -5,39 +5,43 @@
       <button id="log">Call Log API</button>
       <button id="request">Call Request (async) API</button>
       <button id="event">Send event to Rust</button>
-      <div id="response"></div>
     </div>
+
+    <div style="margin-top: 24px">
+      <input id="path-to-read" placeholder="Type the path to read...">
+      <button id="read">Read</button>
+    </div>
+
+    <div style="margin-top: 24px">
+      <input id="url" value="https://tauri.studio">
+      <button id="open-url">Open URL</button>
+    </div>
+
+    <div style="margin-top: 24px">
+      <input id="title" value="Awesome Tauri Example!">
+      <button id="set-title">Set title</button>
+    </div>
+
+    <div id="response"></div>
+
     <script>
-      window.onTauriInit = function () {
-        window.tauri.listen('rust-event', function (res) {
-          document.getElementById('response').innerHTML = JSON.stringify(res)
-        })
+      function registerResponse (response) {
+        document.getElementById('response').innerHTML = typeof response === 'object'
+          ? JSON.stringify(response)
+          : response
       }
 
-      document.getElementById('log').addEventListener('click', function () {
-        window.tauri.invoke({
-          cmd: 'logOperation',
-          event: 'tauri-click',
-          payload: 'this payload is optional because we used Option in Rust'
-        })
-      })
-
-      document.getElementById('request').addEventListener('click', function () {
-        window.tauri.promisified({
-          cmd: 'performRequest',
-          endpoint: 'dummy endpoint arg',
-          body: {
-            id: 5,
-            name: 'test'
+      function addClickEnterHandler (button, input, handler) {
+        button.addEventListener('click', handler)
+        input.addEventListener('keyup', function (e) {
+          if (e.keyCode === 13) {
+            handler()
           }
-        }).then(function (response) {
-          document.getElementById('response').innerHTML = JSON.stringify(response)
         })
-      })
-
-      document.getElementById('event').addEventListener('click', function () {
-        window.tauri.emit('js-event', 'this is the payload string')
-      })
+      }
     </script>
+    <script src="communication.js"></script>
+    <script src="fs.js"></script>
+    <script src="window.js"></script>
   </body>
-</html>
+</html>

Diff do ficheiro suprimidas por serem muito extensas
+ 118 - 70
tauri/examples/communication/dist/index.tauri.html


+ 19 - 0
tauri/examples/communication/dist/window.js

@@ -0,0 +1,19 @@
+var urlInput = document.getElementById('url')
+
+addClickEnterHandler(
+  document.getElementById('open-url'),
+  urlInput,
+  function () {
+    window.tauri.open(urlInput.value)
+  }
+)
+
+var titleInput = document.getElementById('title')
+
+addClickEnterHandler(
+  document.getElementById('set-title'),
+  titleInput,
+  function () {
+    window.tauri.setTitle(titleInput.value)
+  }
+)

Alguns ficheiros não foram mostrados porque muitos ficheiros mudaram neste diff