/
app.rs
73 lines (64 loc) · 2.28 KB
/
app.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use crate::agent::{Worker, WorkerInput, WorkerOutput};
use web_sys::HtmlInputElement;
use yew::prelude::*;
use yew_agent::{Bridge, Bridged};
pub struct Model {
clicker_value: u32,
input_ref: NodeRef,
worker: Box<dyn Bridge<Worker>>,
fibonacci_output: String,
}
pub enum Message {
Click,
RunWorker,
WorkerMsg(WorkerOutput),
}
impl Component for Model {
type Message = Message;
type Properties = ();
fn create(ctx: &Context<Self>) -> Self {
let worker = Worker::bridge(ctx.link().callback(Self::Message::WorkerMsg));
Self {
clicker_value: 0,
input_ref: NodeRef::default(),
worker,
fibonacci_output: String::from("Try out some fibonacci calculations!"),
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Self::Message::Click => {
self.clicker_value += 1;
}
Self::Message::RunWorker => {
if let Some(input) = self.input_ref.cast::<HtmlInputElement>() {
// start the worker off!
self.worker.send(WorkerInput {
n: input.value_as_number() as u32,
});
}
}
Self::Message::WorkerMsg(output) => {
// the worker is done!
self.fibonacci_output = format!("Fibonacci value: {}", output.value);
}
}
true
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<>
<h1>{ "Web worker demo" }</h1>
<p>{ "Submit a value to calculate, then increase the counter on the main thread!"} </p>
<p>{ "Large numbers will take some time!" }</p>
<h3>{ "Output: " } { &self.fibonacci_output }</h3>
<br />
<input ref={self.input_ref.clone()} type="number" value="44" max="50"/>
<button onclick={ctx.link().callback(|_| Message::RunWorker)}>{ "submit" }</button>
<br /> <br />
<h3>{ "Main thread value: " } { self.clicker_value }</h3>
<button onclick={ctx.link().callback(|_| Message::Click)}>{ "click!" }</button>
</>
}
}
}