feat: implement JS onOpenUrl fn

pull/504/head
Lucas Nogueira 2 years ago
parent e37accc64b
commit eb62d51f2a
No known key found for this signature in database
GPG Key ID: 7C32FCA95C8C95D7

@ -2976,7 +2976,7 @@ checksum = "df8e77cb757a61f51b947ec4a7e3646efd825b73561db1c232a8ccb639e611a0"
[[package]]
name = "tauri"
version = "2.0.0-alpha.10"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#b6bd17ece0bc57fef296e2b78d4defe303a56ded"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#46e7d58fc1ec2265324606689e2b528e6b6b739d"
dependencies = [
"anyhow",
"bytes",
@ -3021,7 +3021,7 @@ dependencies = [
[[package]]
name = "tauri-build"
version = "2.0.0-alpha.6"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#b6bd17ece0bc57fef296e2b78d4defe303a56ded"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#46e7d58fc1ec2265324606689e2b528e6b6b739d"
dependencies = [
"anyhow",
"cargo_toml",
@ -3040,7 +3040,7 @@ dependencies = [
[[package]]
name = "tauri-codegen"
version = "2.0.0-alpha.6"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#b6bd17ece0bc57fef296e2b78d4defe303a56ded"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#46e7d58fc1ec2265324606689e2b528e6b6b739d"
dependencies = [
"base64",
"brotli",
@ -3065,7 +3065,7 @@ dependencies = [
[[package]]
name = "tauri-macros"
version = "2.0.0-alpha.6"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#b6bd17ece0bc57fef296e2b78d4defe303a56ded"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#46e7d58fc1ec2265324606689e2b528e6b6b739d"
dependencies = [
"heck",
"proc-macro2",
@ -3091,7 +3091,7 @@ dependencies = [
[[package]]
name = "tauri-runtime"
version = "0.13.0-alpha.6"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#b6bd17ece0bc57fef296e2b78d4defe303a56ded"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#46e7d58fc1ec2265324606689e2b528e6b6b739d"
dependencies = [
"gtk",
"http",
@ -3111,7 +3111,7 @@ dependencies = [
[[package]]
name = "tauri-runtime-wry"
version = "0.13.0-alpha.6"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#b6bd17ece0bc57fef296e2b78d4defe303a56ded"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#46e7d58fc1ec2265324606689e2b528e6b6b739d"
dependencies = [
"cocoa",
"gtk",
@ -3131,7 +3131,7 @@ dependencies = [
[[package]]
name = "tauri-utils"
version = "2.0.0-alpha.6"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#b6bd17ece0bc57fef296e2b78d4defe303a56ded"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#46e7d58fc1ec2265324606689e2b528e6b6b739d"
dependencies = [
"brotli",
"ctor",

@ -141,7 +141,10 @@ fn main() {
Afterwards all the plugin's APIs are available through the JavaScript guest bindings:
```javascript
import { onOpenUrl } from "@tauri-apps/plugin-deep-link";
await onOpenUrl((urls) => {
console.log('deep link:', urls);
});
```
## Contributing

@ -19,7 +19,7 @@ import app.tauri.plugin.Invoke
class DeepLinkPlugin(private val activity: Activity): Plugin(activity) {
//private val implementation = Example()
private var webView: WebView? = null
private var lastUrl: String? = null
private var currentUrl: String? = null
private var channel: Channel? = null
companion object {
@ -27,9 +27,9 @@ class DeepLinkPlugin(private val activity: Activity): Plugin(activity) {
}
@Command
fun getLastLink(invoke: Invoke) {
fun getCurrent(invoke: Invoke) {
val ret = JSObject()
ret.put("url", this.lastUrl)
ret.put("url", this.currentUrl)
invoke.resolve(ret)
}
@ -37,7 +37,7 @@ class DeepLinkPlugin(private val activity: Activity): Plugin(activity) {
fun registerListenerRust(invoke: Invoke) {
val value = invoke.getString("value") ?: ""
val ret = JSObject()
ret.put("value", this.lastUrl ?: "none")
ret.put("value", this.currentUrl ?: "none")
invoke.resolve(ret)
} */
@ -59,10 +59,9 @@ class DeepLinkPlugin(private val activity: Activity): Plugin(activity) {
if (intent.action == Intent.ACTION_VIEW) {
// TODO: check if it makes sense to split up init url and last url
this.lastUrl = intent.data.toString()
// TODO: Test if emitting it here makes sense timing wise
this.currentUrl = intent.data.toString()
val event = JSObject()
event.put("url", this.lastUrl)
event.put("url", this.currentUrl)
this.channel?.send(event)
}
@ -72,10 +71,9 @@ class DeepLinkPlugin(private val activity: Activity): Plugin(activity) {
override fun onNewIntent(intent: Intent) {
if (intent.action == Intent.ACTION_VIEW) {
this.lastUrl = intent.data.toString()
// TODO: Emit event
this.currentUrl = intent.data.toString()
val event = JSObject()
event.put("url", this.lastUrl)
event.put("url", this.currentUrl)
this.channel?.send(event)
}
}

@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::Deserialize;
use std::process::exit;
#[path = "src/config.rs"]

@ -11,8 +11,7 @@
},
"dependencies": {
"@tauri-apps/api": "^2.0.0-alpha.5",
"@tauri-apps/plugin-shell": "^2.0.0-alpha.0",
"@tauri-apps/plugin-window": "^2.0.0-alpha.0"
"@tauri-apps/plugin-deep-link": "^1.0.0"
},
"devDependencies": {
"@tauri-apps/cli": "^2.0.0-alpha.10",

@ -2987,7 +2987,7 @@ checksum = "1b1c7f239eb94671427157bd93b3694320f3668d4e1eff08c7285366fd777fac"
[[package]]
name = "tauri"
version = "2.0.0-alpha.10"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#b6bd17ece0bc57fef296e2b78d4defe303a56ded"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#46e7d58fc1ec2265324606689e2b528e6b6b739d"
dependencies = [
"anyhow",
"bytes",
@ -3032,7 +3032,7 @@ dependencies = [
[[package]]
name = "tauri-build"
version = "2.0.0-alpha.6"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#b6bd17ece0bc57fef296e2b78d4defe303a56ded"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#46e7d58fc1ec2265324606689e2b528e6b6b739d"
dependencies = [
"anyhow",
"cargo_toml",
@ -3051,7 +3051,7 @@ dependencies = [
[[package]]
name = "tauri-codegen"
version = "2.0.0-alpha.6"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#b6bd17ece0bc57fef296e2b78d4defe303a56ded"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#46e7d58fc1ec2265324606689e2b528e6b6b739d"
dependencies = [
"base64",
"brotli",
@ -3076,7 +3076,7 @@ dependencies = [
[[package]]
name = "tauri-macros"
version = "2.0.0-alpha.6"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#b6bd17ece0bc57fef296e2b78d4defe303a56ded"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#46e7d58fc1ec2265324606689e2b528e6b6b739d"
dependencies = [
"heck",
"proc-macro2",
@ -3102,7 +3102,7 @@ dependencies = [
[[package]]
name = "tauri-runtime"
version = "0.13.0-alpha.6"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#b6bd17ece0bc57fef296e2b78d4defe303a56ded"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#46e7d58fc1ec2265324606689e2b528e6b6b739d"
dependencies = [
"gtk",
"http",
@ -3122,7 +3122,7 @@ dependencies = [
[[package]]
name = "tauri-runtime-wry"
version = "0.13.0-alpha.6"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#b6bd17ece0bc57fef296e2b78d4defe303a56ded"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#46e7d58fc1ec2265324606689e2b528e6b6b739d"
dependencies = [
"cocoa",
"gtk",
@ -3142,7 +3142,7 @@ dependencies = [
[[package]]
name = "tauri-utils"
version = "2.0.0-alpha.6"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#b6bd17ece0bc57fef296e2b78d4defe303a56ded"
source = "git+https://github.com/lucasfernog/tauri?branch=feat/ipc-custom-protocol#46e7d58fc1ec2265324606689e2b528e6b6b739d"
dependencies = [
"brotli",
"ctor",

@ -27,7 +27,3 @@ serde_json = "1"
# If you use cargo directly instead of tauri's cli you can use this feature flag to switch between tauri's `dev` and `build` modes.
# DO NOT REMOVE!!
custom-protocol = [ "tauri/custom-protocol" ]
#[patch."https://github.com/lucasfernog/tauri"]
#tauri-build = { path = "C:/Users/Fabian-Lars/dev/FabianLars/tauri-lucas/core/tauri-build" }
#tauri = { path = "C:/Users/Fabian-Lars/dev/FabianLars/tauri-lucas/core/tauri" }

@ -2,49 +2,34 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
import { listen } from "@tauri-apps/api/event";
import { transformCallback } from "@tauri-apps/api/tauri";
import { onOpenUrl, getCurrent as getCurrentDeepLinkUrls } from "@tauri-apps/plugin-deep-link";
declare global {
interface Window {
__TAURI_INVOKE__: <T>(cmd: string, args?: unknown) => Promise<T>;
}
}
function handler(event: { payload?: string }) {
console.log(event);
function handler(urls: string[]) {
console.log(urls);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const updateIntentEl = document.querySelector("#event-intent")!;
updateIntentEl.textContent = event.payload ?? "empty event";
updateIntentEl.textContent = JSON.stringify(urls);
}
window.addEventListener("DOMContentLoaded", () => {
listen("deep-link://new-url", console.log);
// TODO: Replace with `listen` on next alpha
window.__TAURI_INVOKE__<number>("plugin:event|listen", {
event: "deep-link://new-url",
windowLabel: "main",
handler: transformCallback(handler),
});
onOpenUrl(handler);
document.querySelector("#intent-form")?.addEventListener("submit", (e) => {
e.preventDefault();
window
.__TAURI_INVOKE__<string | null>("plugin:deep-link|get_last_link")
getCurrentDeepLinkUrls()
.then((res) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const updateIntentEl = document.querySelector("#update-intent")!;
updateIntentEl.textContent = res ?? "none";
updateIntentEl.textContent = res ? JSON.stringify(res) : "none";
})
.catch(console.error);
});
window
.__TAURI_INVOKE__<string | null>("plugin:deep-link|get_last_link")
getCurrentDeepLinkUrls()
.then((res) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const initialIntentEl = document.querySelector("#initial-intent")!;
initialIntentEl.textContent = res ?? "none";
initialIntentEl.textContent = res ? JSON.stringify(res) : "none";
})
.catch(console.error);
});

@ -2,14 +2,33 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
import { transformCallback } from "@tauri-apps/api/tauri";
declare global {
interface Window {
__TAURI_INVOKE__: <T>(cmd: string, args?: unknown) => Promise<T>;
}
}
export async function getLastLink(): Promise<string[] | null> {
return await window.__TAURI_INVOKE__("plugin:deep-link|get_last_link");
export async function getCurrent(): Promise<string[] | null> {
// TODO: replace with `invoke` on next alpha
return await window
.__TAURI_INVOKE__<string[] | null>("plugin:deep-link|get_current")
// return await invoke("plugin:deep-link|get_current");
}
// TODO: onUrlEvent function (helper function for the event listener)
export async function onOpenUrl(handler: (urls: string[]) => void): Promise<void> {
const current = await getCurrent()
if (current != null) {
handler(current)
}
// TODO: Replace with `listen` on next alpha
return await window.__TAURI_INVOKE__("plugin:event|listen", {
event: "deep-link://new-url",
windowLabel: "main",
handler: transformCallback((event) => handler(event.payload)),
});
//return await listen<string[]>("deep-link://new-url", (event) => handler(event.payload))
}

@ -1 +1 @@
if("__TAURI__"in window){var __TAURI_DEEPLINK__=function(_){"use strict";return _.getLastLink=async function(){return await window.__TAURI_INVOKE__("plugin:deep-link|get_last_link")},_}({});Object.defineProperty(window.__TAURI__,"deepLink",{value:__TAURI_DEEPLINK__})}
if("__TAURI__"in window){var __TAURI_DEEPLINK__=function(e){"use strict";var n=Object.defineProperty,t=(e,n,t)=>{if(!n.has(e))throw TypeError("Cannot "+t)},r=(e,n,r)=>(t(e,n,"read from private field"),r?r.call(e):n.get(e)),i=(e,n,r,i)=>(t(e,n,"write to private field"),i?i.call(e,r):n.set(e,r),r);function a(e,n=!1){let t=window.crypto.getRandomValues(new Uint32Array(1))[0],r=`_${t}`;return Object.defineProperty(window,r,{value:t=>(n&&Reflect.deleteProperty(window,r),e?.(t)),writable:!1,configurable:!0}),t}((e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})})({},{Channel:()=>l,PluginListener:()=>s,addPluginListener:()=>_,convertFileSrc:()=>d,invoke:()=>c,transformCallback:()=>a});var o,l=class{constructor(){this.__TAURI_CHANNEL_MARKER__=!0,((e,n,t)=>{if(n.has(e))throw TypeError("Cannot add the same private member more than once");n instanceof WeakSet?n.add(e):n.set(e,t)})(this,o,(()=>{})),this.id=a((e=>{r(this,o).call(this,e)}))}set onmessage(e){i(this,o,e)}get onmessage(){return r(this,o)}toJSON(){return`__CHANNEL__:${this.id}`}};o=new WeakMap;var s=class{constructor(e,n,t){this.plugin=e,this.event=n,this.channelId=t}async unregister(){return c(`plugin:${this.plugin}|remove_listener`,{event:this.event,channelId:this.channelId})}};async function _(e,n,t){let r=new l;return r.onmessage=t,c(`plugin:${e}|register_listener`,{event:n,handler:r}).then((()=>new s(e,n,r.id)))}async function c(e,n={}){return new Promise(((t,r)=>{let i=a((e=>{t(e),Reflect.deleteProperty(window,`_${o}`)}),!0),o=a((e=>{r(e),Reflect.deleteProperty(window,`_${i}`)}),!0);window.__TAURI_IPC__({cmd:e,callback:i,error:o,...n})}))}function d(e,n="asset"){let t=encodeURIComponent(e);return navigator.userAgent.includes("Windows")?`https://${n}.localhost/${t}`:`${n}://localhost/${t}`}async function u(){return await window.__TAURI_INVOKE__("plugin:deep-link|get_current")}return e.getCurrent=u,e.onOpenUrl=async function(e){const n=await u();return null!=n&&e(n),await window.__TAURI_INVOKE__("plugin:event|listen",{event:"deep-link://new-url",windowLabel:"main",handler:a((n=>e(n.payload)))})},e}({});Object.defineProperty(window.__TAURI__,"deepLink",{value:__TAURI_DEEPLINK__})}

@ -7,18 +7,10 @@ use tauri::{AppHandle, command, Runtime, Window, State};
use crate::{DeepLink, Result};
#[command]
pub(crate) async fn execute<R: Runtime>(
_app: AppHandle<R>,
_window: Window<R>,
) -> Result<String> {
Ok("success".to_string())
}
#[command]
pub(crate) async fn get_last_link<R: Runtime>(
pub(crate) async fn get_current<R: Runtime>(
_app: AppHandle<R>,
_window: Window<R>,
deep_link: State<'_, DeepLink<R>>
) -> Result<Option<Vec<url::Url>>> {
deep_link.get_last_link()
deep_link.get_current()
}

@ -59,7 +59,7 @@ fn init_deep_link<R: Runtime, C: DeserializeOwned>(
#[cfg(not(target_os = "android"))]
Ok(DeepLink {
app: app.clone(),
last_link: Default::default(),
current: Default::default(),
})
}
@ -78,7 +78,7 @@ mod imp {
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LastUrl {
pub struct GetCurrentResponse {
pub url: Option<url::Url>,
}
@ -86,10 +86,10 @@ mod imp {
pub struct DeepLink<R: Runtime>(pub(crate) PluginHandle<R>);
impl<R: Runtime> DeepLink<R> {
/// Get the last saved URL that triggered the deep link.
pub fn get_last_link(&self) -> crate::Result<Option<Vec<url::Url>>> {
/// Get the current URLs that triggered the deep link.
pub fn get_current(&self) -> crate::Result<Option<Vec<url::Url>>> {
self.0
.run_mobile_plugin::<LastUrl>("getLastLink", ())
.run_mobile_plugin::<GetCurrentResponse>("getCurrent", ())
.map(|v| v.url.map(|url| vec![url]))
.map_err(Into::into)
}
@ -105,13 +105,13 @@ mod imp {
pub struct DeepLink<R: Runtime> {
#[allow(dead_code)]
pub(crate) app: AppHandle<R>,
pub(crate) last_link: Mutex<Option<Vec<url::Url>>>,
pub(crate) current: Mutex<Option<Vec<url::Url>>>,
}
impl<R: Runtime> DeepLink<R> {
/// Get the last saved URL that triggered the deep link.
pub fn get_last_link(&self) -> crate::Result<Option<Vec<url::Url>>> {
Ok(self.last_link.lock().unwrap().clone())
/// Get the current URLs that triggered the deep link.
pub fn get_current(&self) -> crate::Result<Option<Vec<url::Url>>> {
Ok(self.current.lock().unwrap().clone())
}
}
}
@ -133,10 +133,7 @@ impl<R: Runtime, T: Manager<R>> crate::DeepLinkExt<R> for T {
pub fn init<R: Runtime>() -> TauriPlugin<R, Option<config::Config>> {
Builder::new("deep-link")
.js_init_script(include_str!("api-iife.js").to_string())
.invoke_handler(tauri::generate_handler![
commands::execute,
commands::get_last_link
])
.invoke_handler(tauri::generate_handler![commands::get_current])
.setup(|app, api| {
app.manage(init_deep_link(app, api)?);
Ok(())
@ -146,7 +143,7 @@ pub fn init<R: Runtime>() -> TauriPlugin<R, Option<config::Config>> {
if let tauri::RunEvent::Opened { urls } = _event {
let _ = _app.emit_all("deep-link://new-url", urls);
_app.state::<DeepLink<R>>()
.last_link
.current
.lock()
.unwrap()
.replace(urls.clone());

@ -198,12 +198,9 @@ importers:
'@tauri-apps/api':
specifier: ^2.0.0-alpha.5
version: 2.0.0-alpha.5
'@tauri-apps/plugin-shell':
specifier: ^2.0.0-alpha.0
version: link:../../../shell
'@tauri-apps/plugin-window':
specifier: ^2.0.0-alpha.0
version: link:../../../window
'@tauri-apps/plugin-deep-link':
specifier: ^1.0.0
version: link:../..
devDependencies:
'@tauri-apps/cli':
specifier: ^2.0.0-alpha.10

Loading…
Cancel
Save