on 9e2e4cb help sign in
67 lines 2.0 kB history raw
1use dodrio::bumpalo::Bump;
2use dodrio::{Node, Render, Vdom};
3use dodrio_js_api::JsRender;
4use js_sys::Object;
5use wasm_bindgen::prelude::*;
7#[wasm_bindgen]
8extern "C" {
9 // Import the JS `Greeting` class.
10 #[wasm_bindgen(extends = Object)]
11 #[derive(Clone, Debug)]
12 type Greeting;
14 // And the `Greeting` class's constructor.
15 #[wasm_bindgen(constructor)]
16 fn new(who: &str) -> Greeting;
19/// This is our Rust rendering component that wraps the JS rendering component.
20pub struct GreetingViaJs {
21 js: JsRender,
24impl GreetingViaJs {
25 /// Create a new `GreetingViaJs`, which will internally create a new JS
26 /// `Greeting`.
27 pub fn new(who: &str) -> GreetingViaJs {
28 let js = JsRender::new(Greeting::new(who));
29 GreetingViaJs { js }
30 }
33/// Here's the `Render` implementation! This adds a `<p>` element and some text
34/// around whatever the inner JS `Greeting` component renders.
35impl Render for GreetingViaJs {
36 fn render<'a, 'bump>(&'a self, bump: &'bump Bump) -> Node<'bump>
37 where
38 'a: 'bump,
39 {
40 use dodrio::builder::*;
41 p(bump)
42 .children([text("JavaScript says: "), self.js.render(bump)])
43 .finish()
44 }
47/// Finally our main initialization function that kicks everything off!
48#[wasm_bindgen(start)]
49pub fn run() {
50 // Set up the panic hook for debugging when things go wrong.
51 console_error_panic_hook::set_once();
53 // Grab the document's `<body>`.
54 let window = web_sys::window().unwrap_throw();
55 let document = window.document().unwrap_throw();
56 let body = document.body().unwrap_throw();
58 // Create a new `GreetingViaJs` render component.
59 let component = GreetingViaJs::new("World");
61 // Create a virtual DOM and mount it and the `Hello` render component to the
62 // `<body>`.
63 let vdom = Vdom::new(body.as_ref(), component);
65 // Run the virtual DOM forever and don't unmount it.
66 vdom.forget();