add more examples

This commit is contained in:
Fractal-Tess
2023-05-18 10:44:36 +03:00
parent a177cf16c2
commit e5bb812718
7 changed files with 174 additions and 71 deletions

View File

@@ -1,19 +1,28 @@
// This module shows examples of how to use IPC command handlers that can be invoked from the frontend.
use sha2::{Digest, Sha256};
use specta::collect_types;
use tauri::{Builder, Wry};
use tauri::{Builder, State, Wry};
use tauri_specta::ts;
use crate::state::Store;
// Exports a function for the tauri app instance to use and register all commands defined as frontend IPC command handlers.
pub fn register_commands(builder: Builder<Wry>) -> Builder<Wry> {
// Specta generating typed binding interfaces
#[cfg(debug_assertions)]
ts::export(
collect_types![hello_tauri, hash256sum],
"../src/lib/bindings.ts",
collect_types![hello_tauri, hash256sum, store_set_key, store_read_key],
"../src/lib/ipc.ts",
)
.expect("unable to generate specta types");
builder.invoke_handler(tauri::generate_handler![hash256sum, hello_tauri])
builder.invoke_handler(tauri::generate_handler![
hash256sum,
hello_tauri,
store_set_key,
store_read_key
])
}
// An example command
@@ -32,3 +41,17 @@ fn hash256sum(hash_input: String) -> String {
let result = hasher.finalize();
format!("{:X}", result)
}
// Example command using managed state
#[tauri::command]
#[specta::specta]
fn store_set_key(key: String, value: String, store: State<Store>) -> () {
store.add_key_val(key, value);
}
// Another example command using managed state
#[tauri::command]
#[specta::specta]
fn store_read_key(key: String, store: State<Store>) -> Option<String> {
store.read_key(&key)
}

View File

@@ -4,22 +4,28 @@
)]
use commands::register_commands;
use prelude::*;
use state::register_managed_state;
use tauri::{Builder as TauriBuilder, RunEvent};
use tauri::RunEvent;
mod commands;
mod error;
mod prelude;
mod state;
fn main() {
let app =
tauri::Builder::default().plugin(tauri_plugin_window_state::Builder::default().build());
// App builder
let app = TauriBuilder::default().plugin(tauri_plugin_window_state::Builder::default().build());
let app = register_commands(app)
.build(tauri::generate_context!())
.expect("error while running tauri application");
// Register app commands
let app = register_commands(app);
app.run(|_, e| match e {
// Register app managed state
let app = register_managed_state(app);
// Run the app
app.build(tauri::generate_context!())
.expect("error while running tauri application")
.run(|_, e| match e {
RunEvent::Ready => {
println!("Window is ready");
}

32
src-tauri/src/state.rs Normal file
View File

@@ -0,0 +1,32 @@
// This module shows examples of how to use managed custom state.
use std::{collections::HashMap, sync::Mutex};
use tauri::{Builder, Wry};
pub struct Store {
store: Mutex<HashMap<String, String>>,
}
impl Store {
pub fn add_key_val(&self, key: String, val: String) {
self.store
.lock()
.expect("cannot lock store")
.insert(key, val);
}
pub fn read_key(&self, key: &String) -> Option<String> {
match self.store.lock().expect("cannot lock store").get(key) {
Some(s) => Some(s.to_string()),
None => None,
}
}
}
// Exports a function for the tauri app instance to use and register all commands defined as frontend IPC command handlers.
pub fn register_managed_state(builder: Builder<Wry>) -> Builder<Wry> {
let store = Store {
store: Mutex::from(HashMap::new()),
};
builder.manage(store)
}

View File

@@ -26,11 +26,8 @@
</a>
</li>
<li>
<a
use:link
href="/#call_tauri"
class="transition-colors hover:text-secondary">
Call Tauri
<a use:link href="/#IPC" class="transition-colors hover:text-secondary">
IPC
</a>
</li>

View File

@@ -2,12 +2,12 @@
import Router from 'svelte-spa-router';
import Index from '$lib/router/routes/Index.svelte';
import CallTauri from '$router/routes/CallTauri.svelte';
import IPC from '$lib/router/routes/IPC.svelte';
import Versions from '$router/routes/Versions.svelte';
const routes = {
'/': Index,
'/#call_tauri': CallTauri,
'/#ipc': IPC,
'/#versions': Versions
};
</script>

View File

@@ -1,47 +0,0 @@
<script lang="ts">
import { fade } from 'svelte/transition';
import { invoke } from '@tauri-apps/api';
let hashInput = 'Hello world';
let hashOutput = '';
$: (async () => {
hashOutput = await invoke('hash256sum', { hashInput });
})();
let message = '';
async function callTauri() {
message = await invoke('called_from_js');
}
</script>
<div
class="form-control h-full flex-1 items-center justify-center gap-y-8
[&>section]:form-control [&>section]:items-center [&>section]:justify-center [&>section]:gap-y-4">
<section class="">
<button
on:click={callTauri}
class="btn-outline btn-primary btn-md btn font-extrabold"
>Call Tauri</button>
<div class="flex h-20 items-center">
{#key message}
<p
class="whitespace-nowrap border-b-2 border-accent
text-2xl"
in:fade={{ duration: 300 }}>
{message}
</p>
{/key}
</div>
</section>
<section>
<label class="input-group flex max-w-max">
<span>Hash string</span>
<input
bind:value={hashInput}
type="text"
class="input-bordered input-secondary input focus:border-secondary focus:outline-none focus:ring-secondary" />
</label>
<p class="text-center text-lg">{hashOutput}</p>
</section>
</div>

View File

@@ -0,0 +1,92 @@
<script lang="ts">
import { fade } from 'svelte/transition';
import { hash256sum, helloTauri, storeSetKey, storeReadKey } from '$ipc';
// Or you can also do this if you prefer
// import * as ipc from '$ipc';
// message = await ipc.helloTauri()
// Calling the hash256 function any time the `hashInput` variable changes
let hashInput = 'Hello world';
let hashOutput = '';
$: (async () => {
hashOutput = await hash256sum(hashInput);
})();
// Calling the `helloTauri` when we click the call tauri button
let message = '';
async function callTauri() {
message = await helloTauri();
}
let storeMessage = '';
let key = '';
let val = '';
async function setKeyVal() {
await storeSetKey(key, val);
storeMessage = `You have set the key '${key}' to be the value of '${val}''`;
}
async function readValFromKey() {
const val = await storeReadKey(key);
storeMessage = `Using the key '${key}', you have just retrieved the value of '${val}''`;
}
</script>
<div
class="form-control h-full flex-1 items-center justify-center gap-y-8
[&>section]:form-control [&>section]:items-center [&>section]:justify-center [&>section]:gap-y-4">
<section class="">
<button
on:click={callTauri}
class="btn-outline btn-primary btn text-2xl capitalize"
>Call Tauri</button>
<div class="flex h-20 items-center">
{#key message}
<p
class="whitespace-nowrap border-b-2 border-accent
text-2xl"
in:fade={{ duration: 300 }}>
{message}
</p>
{/key}
</div>
</section>
<section>
<label class="input-group flex max-w-max">
<span>Hash string</span>
<input
bind:value={hashInput}
type="text"
class="input-bordered input-secondary input focus:border-secondary focus:outline-none focus:ring-secondary" />
</label>
<p class="text-center text-lg">{hashOutput}</p>
</section>
<div class="grid grid-cols-2 gap-4">
<label class="input-group flex max-w-max">
<span>Key</span>
<input
bind:value={key}
type="text"
class="input-bordered input-secondary input focus:border-secondary focus:outline-none focus:ring-secondary" />
</label>
<label class="input-group flex max-w-max">
<span>Value</span>
<input
bind:value={val}
type="text"
class="input-bordered input-secondary input focus:border-secondary focus:outline-none focus:ring-secondary" />
</label>
<button on:click={setKeyVal} class="btn-outline btn-primary btn capitalize"
>Set key</button>
<button
on:click={readValFromKey}
class="btn-outline btn-primary btn capitalize">Read key</button>
<p class="text-bold font-2xl col-span-full text-center text-primary">
{storeMessage}
</p>
</div>
</div>