96
loading...
This website collects cookies to deliver better user experience
degit jbarszczewski/tauri-svelte-template pass-gen-tutorial
Use this template
button./src
contains front-end code with the main view defined in App.svelte
file./src-tauri
here lives 'back-end' Rust code.README.md
provides basic instructions how to work with Tauri.rand
, that generates random numbers. Open src-tauri/Cargo.toml
and add rand = "0.8.0"
under dependencies. At this point run yarn
and thenyarn tauri dev
command (from the project main directory) to view the changes in 'real-time'./src-tauri/src/commands.rs
file and replace the existing content with the following:use rand::Rng;
static CHARS: [char; 70] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's','t', 'u', 'v', 'w', 'x', 'y', 'z','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S','T', 'U', 'V', 'W', 'X', 'Y', 'Z', '!','@','#','$','%','^','&','*'];
#[tauri::command]
fn generate_password(length: u32) -> String{
let mut rng = rand::thread_rng();
let mut result = String::new();
for _x in 0..length {
result.push(CHARS[rng.gen_range(0..70)]);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generates_string() {
let result = generate_password(8);
assert_eq!(result.len(), 8);
}
}
rand
package.generate_password
that accepts password length as an integer.CHARS
arraycargo test
from /src-tauri
directory). Of course there is a room for improvement, like adding options to select types of characters to be used (only lowercase, no symbols etc.) and expand tests for better coverage. But as mentioned at the beginning this is just a simple app to demonstrate the template.main.rs
to generate_password
rather than standard my_custom_command
and Rust code is ready to be used!App.svelte
and let's start adding those changes.<script>
section replace code after imports with following one:let input: string = '8';
let result: string = '';
const handleClick = async () => {
result = await invoke('generate_password', {
length: +input,
});
};
input
+input
<main>
tag will also look very similar, we update texts and change input to be a range
type:<Container>
<Card class="mb-3">
<CardHeader>
<CardTitle>Password Generator</CardTitle>
</CardHeader>
<CardBody>
<CardSubtitle>Generate random password</CardSubtitle>
<CardText>Press 'Generate' button to create password with length: {input}.</CardText>
<input
type="range"
id="exampleRange"
bind:value="{input}"
min="{1}"
max="{32}"
step="{1}"
/>
<button color="primary" on:click="{handleClick}">Generate</button>
</CardBody>
<CardFooter> {#if result.length !== 0} {result} {:else} No result yet. {/if} </CardFooter>
</Card>
</Container>