on 00a42e3 help sign in
82 lines 2.5 kB history raw
1use dodrio::bumpalo::{self, Bump};
2use dodrio::{Node, Render};
3use wasm_bindgen::prelude::*;
4use wasm_bindgen::JsCast;
6/// Say hello to someone.
7struct SayHelloTo {
8 /// Who to say hello to.
9 who: String,
12impl SayHelloTo {
13 /// Construct a new `SayHelloTo` component.
14 fn new<S: Into<String>>(who: S) -> SayHelloTo {
15 let who = who.into();
16 SayHelloTo { who }
17 }
19 /// Update who to say hello to.
20 fn set_who(&mut self, who: String) {
21 self.who = who;
22 }
25// The `Render` implementation has a text `<input>` and a `<div>` that shows a
26// greeting to the `<input>`'s value.
27impl Render for SayHelloTo {
28 fn render<'a, 'bump>(&'a self, bump: &'bump Bump) -> Node<'bump>
29 where
30 'a: 'bump,
31 {
32 use dodrio::builder::*;
34 div(bump)
35 .children([
36 input(bump)
37 .attr("type", "text")
38 .attr("value", &self.who)
39 .on("input", |root, vdom, event| {
40 // If the event's target is our input...
41 let input = match event
42 .target()
43 .and_then(|t| t.dyn_into::<web_sys::HtmlInputElement>().ok())
44 {
45 None => return,
46 Some(input) => input,
47 };
49 // ...then get its value and update who we are greeting.
50 let value = input.value();
51 let hello = root.unwrap_mut::<SayHelloTo>();
52 hello.set_who(value);
54 // Finally, re-render the component on the next animation frame.
55 vdom.schedule_render();
56 })
57 .finish(),
58 text(bumpalo::format!(in bump, "Hello, {}!", self.who).into_bump_str()),
59 ])
60 .finish()
61 }
64#[wasm_bindgen(start)]
65pub fn run() {
66 // Initialize debugging for when/if something goes wrong.
67 console_error_panic_hook::set_once();
69 // Get the document's `<body>`.
70 let window = web_sys::window().unwrap();
71 let document = window.document().unwrap();
72 let body = document.body().unwrap();
74 // Construct a new `SayHelloTo` rendering component.
75 let say_hello = SayHelloTo::new("World");
77 // Mount the component to the `<body>`.
78 let vdom = dodrio::Vdom::new(&body, say_hello);
80 // Run the component forever.
81 vdom.forget();