feat(tauri.js) add API endpoint proxy, closes #197 (#241)

* feat(tauri.js) add API endpoint proxy

* feat(tauri.js) always resolve/reject proxy promise

* chore(proxy) wait for onTauriInit to start direct proxy to window.tauri
This commit is contained in:
Lucas Fernandes Nogueira 2019-12-29 09:14:49 -03:00 committed by GitHub
parent 36aca61572
commit 548ab94810
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 65 additions and 18 deletions

56
cli/tauri.js/api.js Normal file
View File

@ -0,0 +1,56 @@
const cache = {}
let initialized = false
const proxy = new Proxy({
__consume () {
for (const key in cache) {
if (key in window.tauri) {
const queue = cache[key]
for (const call of queue) {
try {
const ret = window.tauri[key].apply(window.tauri, call.arguments)
if (ret instanceof Promise) {
ret.then(call.resolve, call.reject)
} else {
call.resolve()
}
} catch (e) {
call.reject(e)
}
}
}
}
initialized = true
}
}, {
get (obj, prop) {
if (prop === '__consume') {
return obj[prop]
}
if (initialized && 'tauri' in window) {
return window.tauri[prop].bind(window.tauri)
}
if (!(prop in cache)) {
cache[prop] = []
}
return function () {
const promise = new Promise((resolve, reject) => {
cache[prop].push({
arguments: arguments,
resolve,
reject
})
});
return promise;
}
}
})
window.onTauriInit = () => {
proxy.__consume()
}
export default proxy

View File

@ -385,10 +385,6 @@ try {
}, true)
}
if (window.onTauriInit !== void 0) {
window.onTauriInit()
}
document.addEventListener('error', function (e) {
var target = e.target
while (target != null) {

View File

@ -36,7 +36,7 @@
"eslint-plugin-promise": "4.2.1",
"eslint-plugin-standard": "4.0.1",
"eslint-plugin-vue": "6.0.1",
"tauri": "0.2.1"
"tauri": "file:../../../cli/tauri.js"
},
"engines": {
"node": ">= 8.9.0",

View File

@ -9,14 +9,7 @@
<script>
import { uid } from 'quasar'
function __onTauriInit (cb) {
if (window.tauri) {
cb()
} else {
window.onTauriInit = cb
}
}
import tauri from 'tauri/api'
export default {
name: 'HelloWorld',
@ -26,16 +19,14 @@ export default {
}
},
mounted () {
__onTauriInit(() => {
window.tauri.listen('reply', res => {
this.msg = res.payload.msg
})
tauri.listen('reply', res => {
this.msg = res.payload.msg
})
},
methods: {
// set up an event listener
eventToRust () {
window.tauri.emit('hello', uid())
tauri.emit('hello', uid())
}
}
}

View File

@ -35,6 +35,10 @@ pub(crate) fn handle<T: 'static>(webview: &mut WebView<'_, T>, arg: &str) -> boo
}}
}})
}}
}}
if (window.onTauriInit !== void 0) {{
window.onTauriInit()
}}",
fn = crate::event::emit_function_name(),
listeners = crate::event::event_listeners_object_name(),