feat(plugins): inject API on window.__TAURI__ (#383)

This commit is contained in:
Lucas Fernandes Nogueira
2023-05-23 10:20:14 -07:00
committed by GitHub
parent 3c8577bc9a
commit b131bc8f7c
78 changed files with 754 additions and 337 deletions
+16 -7
View File
@@ -2,7 +2,14 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
import { invoke, transformCallback } from "@tauri-apps/api/tauri";
declare global {
interface Window {
__TAURI_INVOKE__: <T>(cmd: string, args?: unknown) => Promise<T>;
__TAURI__: {
transformCallback: <T>(cb: (payload: T) => void) => number;
};
}
}
export interface MessageKind<T, D> {
type: T;
@@ -36,11 +43,13 @@ export default class WebSocket {
listeners.forEach((l) => l(message));
};
return await invoke<number>("plugin:websocket|connect", {
url,
callbackFunction: transformCallback(handler),
options,
}).then((id) => new WebSocket(id, listeners));
return await window
.__TAURI_INVOKE__<number>("plugin:websocket|connect", {
url,
callbackFunction: window.__TAURI__.transformCallback(handler),
options,
})
.then((id) => new WebSocket(id, listeners));
}
addListener(cb: (arg: Message) => void): void {
@@ -60,7 +69,7 @@ export default class WebSocket {
"invalid `message` type, expected a `{ type: string, data: any }` object, a string or a numeric array"
);
}
return await invoke("plugin:websocket|send", {
return await window.__TAURI_INVOKE__("plugin:websocket|send", {
id: this.id,
message: m,
});
+1
View File
@@ -0,0 +1 @@
if("__TAURI__"in window){var __TAURI_WEBSOCKET__=function(){"use strict";class e{constructor(e,t){this.id=e,this.listeners=t}static async connect(t,n){const i=[];return await window.__TAURI_INVOKE__("plugin:websocket|connect",{url:t,callbackFunction:window.__TAURI__.transformCallback((e=>{i.forEach((t=>t(e)))})),options:n}).then((t=>new e(t,i)))}addListener(e){this.listeners.push(e)}async send(e){let t;if("string"==typeof e)t={type:"Text",data:e};else if("object"==typeof e&&"type"in e)t=e;else{if(!Array.isArray(e))throw new Error("invalid `message` type, expected a `{ type: string, data: any }` object, a string or a numeric array");t={type:"Binary",data:e}}return await window.__TAURI_INVOKE__("plugin:websocket|send",{id:this.id,message:t})}async disconnect(){return await this.send({type:"Close",data:{code:1e3,reason:"Disconnected by client"}})}}return e}();Object.defineProperty(window.__TAURI__,"websocket",{value:__TAURI_WEBSOCKET__})}
+1
View File
@@ -165,6 +165,7 @@ async fn send(
pub fn init<R: Runtime>() -> TauriPlugin<R> {
PluginBuilder::new("websocket")
.js_init_script(include_str!("api-iife.js").to_string())
.invoke_handler(tauri::generate_handler![connect, send])
.setup(|app, _api| {
app.manage(ConnectionManager::default());