on master help sign in
Add READMEs and comments for examples
commit307c8d1cdc786c6716befa835ee147d1b121802b authorNick Fitzgerald <fitzgen@gmail.com> dateSun 10 Feb 2019, 15:50 (8 years ago) parent8c4eb4c
6 files changed+90−76
examples/counter/README.md+12−20 examples/counter/src/lib.rs+25−7 examples/hello-world/README.md+12−20 examples/hello-world/src/lib.rs+11−7 examples/input-form/README.md+13−20 examples/input-form/src/lib.rs+17−2
examples/counter/README.md+12−20
@@ -1,29 +1,21 @@
1−# 🦀🕸 `rust-webpack-template`
1+# Counter
22
3−> **Kickstart your Rust, WebAssembly, and Webpack project!**
3+A counter that can be incremented and decremented.
44
5−This template is designed for creating monorepo-style Web applications with
6−Rust-generated WebAssembly and Webpack without publishing your wasm to NPM.
5+## Source
76
8−* Want to create and publish NPM packages with Rust and WebAssembly? [Check out
9− `wasm-pack-template`.](https://github.com/rustwasm/wasm-pack-template)
7+See `src/lib.rs`.
108
11−## 🔋 Batteries Included
9+## Build
1210
13−This template comes pre-configured with all the boilerplate for compiling Rust
14−to WebAssembly and hooking into a Webpack build pipeline.
15−
16−* `npm run start` -- Serve the project locally for development at
17− `http://localhost:8080`.
18−
19−* `npm run build` -- Bundle the project (in production mode).
20−
21−## 🚴 Using This Template
11+```
12+wasm-pack build --target no-modules
13+```
2214
23−First, [install `wasm-pack`!](https://rustwasm.github.io/wasm-pack/installer/)
15+## Serve
2416
25−Then, use `npm init` to clone this template:
17+Use any HTTP server, for example:
2618
27−```sh
28−npm init rust-webpack my-app
19+```
20+python -m SimpleHTTPServer
2921```
examples/counter/src/lib.rs+25−7
@@ -3,30 +3,37 @@ use dodrio::{on, Node, Render};
33use log::*;
44use wasm_bindgen::prelude::*;
55
6+/// A counter that can be incremented and decrmented!
67struct Counter {
7− val: isize,
8+ count: isize,
89}
910
1011impl Counter {
12+ /// Construct a new, zeroed counter.
1113 fn new() -> Counter {
12− Counter { val: 0 }
14+ Counter { count: 0 }
1315 }
1416
17+ /// Increment this counter's count.
1518 fn increment(&mut self) {
16− self.val += 1;
19+ self.count += 1;
1720 }
1821
22+ /// Decrement this counter's count.
1923 fn decrement(&mut self) {
20− self.val -= 1;
24+ self.count -= 1;
2125 }
2226}
2327
28+// The `Render` implementation for `Counter`s displays the current count and has
29+// buttons to increment and decrement the count.
2430impl Render for Counter {
2531 fn render<'a, 'bump>(&'a self, bump: &'bump Bump) -> dodrio::Node<'bump>
2632 where
2733 'a: 'bump,
2834 {
29− let val = bumpalo::format!(in bump, "{}", self.val);
35+ // Stringify the count as a bump-allocated string.
36+ let count = bumpalo::format!(in bump, "{}", self.count);
3037
3138 Node::element(
3239 bump,
@@ -38,17 +45,26 @@ impl Render for Counter {
3845 bump,
3946 "button",
4047 [on(bump, "click", |root, vdom, _event| {
41− root.unwrap_mut::<Counter>().increment();
48+ // Cast the root render component to a `Counter`, since
49+ // we know that's what it is.
50+ let counter = root.unwrap_mut::<Counter>();
51+
52+ // Increment the counter.
53+ counter.increment();
54+
55+ // Since the count has updated, we should re-render the
56+ // counter on the next animation frame.
4257 vdom.schedule_render();
4358 })],
4459 [],
4560 [Node::text("+")],
4661 ),
47− Node::text(val.into_bump_str()),
62+ Node::text(count.into_bump_str()),
4863 Node::element(
4964 bump,
5065 "button",
5166 [on(bump, "click", |root, vdom, _event| {
67+ // Same as above, but decrementing instead of incrementing.
5268 root.unwrap_mut::<Counter>().decrement();
5369 vdom.schedule_render();
5470 })],
@@ -62,9 +78,11 @@ impl Render for Counter {
6278
6379#[wasm_bindgen(start)]
6480pub fn run() {
81+ // Initialize debug logging for if/when things go wrong.
6582 console_error_panic_hook::set_once();
6683 console_log::init_with_level(Level::Trace).expect("should initialize logging OK");
6784
85+ // Get the document's `<body>`.
6886 let window = web_sys::window().unwrap();
6987 let document = window.document().unwrap();
7088 let body = document.body().unwrap();
examples/hello-world/README.md+12−20
@@ -1,29 +1,21 @@
1−# 🦀🕸 `rust-webpack-template`
1+# Hello World
22
3−> **Kickstart your Rust, WebAssembly, and Webpack project!**
3+The most basic example!
44
5−This template is designed for creating monorepo-style Web applications with
6−Rust-generated WebAssembly and Webpack without publishing your wasm to NPM.
5+## Source
76
8−* Want to create and publish NPM packages with Rust and WebAssembly? [Check out
9− `wasm-pack-template`.](https://github.com/rustwasm/wasm-pack-template)
7+See `src/lib.rs`.
108
11−## 🔋 Batteries Included
9+## Build
1210
13−This template comes pre-configured with all the boilerplate for compiling Rust
14−to WebAssembly and hooking into a Webpack build pipeline.
15−
16−* `npm run start` -- Serve the project locally for development at
17− `http://localhost:8080`.
18−
19−* `npm run build` -- Bundle the project (in production mode).
20−
21−## 🚴 Using This Template
11+```
12+wasm-pack build --target no-modules
13+```
2214
23−First, [install `wasm-pack`!](https://rustwasm.github.io/wasm-pack/installer/)
15+## Serve
2416
25−Then, use `npm init` to clone this template:
17+Use any HTTP server, for example:
2618
27−```sh
28−npm init rust-webpack my-app
19+```
20+python -m SimpleHTTPServer
2921```
examples/hello-world/src/lib.rs+11−7
@@ -2,16 +2,14 @@ use dodrio::bumpalo::Bump;
22use dodrio::{Node, Render, Vdom};
33use wasm_bindgen::prelude::*;
44
5+/// A rendering component that displays a greeting.
56struct Hello<'who> {
7+ /// Who to greet.
68 who: &'who str,
79}
810
9−impl<'who> Hello<'who> {
10− fn new(who: &str) -> Hello {
11− Hello { who }
12− }
13−}
14−
11+// The `Render` implementation describes how to render a `Hello` component into
12+// HTML.
1513impl<'who> Render for Hello<'who> {
1614 fn render<'a, 'bump>(&'a self, bump: &'bump Bump) -> Node<'bump>
1715 where
@@ -19,9 +17,13 @@ impl<'who> Render for Hello<'who> {
1917 {
2018 Node::element(
2119 bump,
20+ // The element's tag name. In this case a `<p>` element.
2221 "p",
22+ // Event listeners. Empty in this case.
2323 [],
24+ // Attributes. Again, empty in this case.
2425 [],
26+ // Child nodes.
2527 [Node::text("Hello, "), Node::text(self.who), Node::text("!")],
2628 )
2729 }
@@ -29,14 +31,16 @@ impl<'who> Render for Hello<'who> {
2931
3032#[wasm_bindgen(start)]
3133pub fn run() {
34+ // Set up the panic hook for debugging when things go wrong.
3235 console_error_panic_hook::set_once();
3336
37+ // Grab the document's `<body>`.
3438 let window = web_sys::window().unwrap_throw();
3539 let document = window.document().unwrap_throw();
3640 let body = document.body().unwrap_throw();
3741
3842 // Create a new `Hello` render component.
39− let component = Hello::new("World");
43+ let component = Hello { who: "World" };
4044
4145 // Create a virtual DOM and mount it and the `Hello` render component to the
4246 // `<body>`.
examples/input-form/README.md+13−20
@@ -1,29 +1,22 @@
1−# 🦀🕸 `rust-webpack-template`
1+# Input Forms
22
3−> **Kickstart your Rust, WebAssembly, and Webpack project!**
3+Renders a greeting to a user-supplied person via an `<input>` value. The
4+greeting is live-updated with new inputs.
45
5−This template is designed for creating monorepo-style Web applications with
6−Rust-generated WebAssembly and Webpack without publishing your wasm to NPM.
6+## Source
77
8−* Want to create and publish NPM packages with Rust and WebAssembly? [Check out
9− `wasm-pack-template`.](https://github.com/rustwasm/wasm-pack-template)
8+See `src/lib.rs`.
109
11−## 🔋 Batteries Included
10+## Build
1211
13−This template comes pre-configured with all the boilerplate for compiling Rust
14−to WebAssembly and hooking into a Webpack build pipeline.
15−
16−* `npm run start` -- Serve the project locally for development at
17− `http://localhost:8080`.
18−
19−* `npm run build` -- Bundle the project (in production mode).
20−
21−## 🚴 Using This Template
12+```
13+wasm-pack build --target no-modules
14+```
2215
23−First, [install `wasm-pack`!](https://rustwasm.github.io/wasm-pack/installer/)
16+## Serve
2417
25−Then, use `npm init` to clone this template:
18+Use any HTTP server, for example:
2619
27−```sh
28−npm init rust-webpack my-app
20+```
21+python -m SimpleHTTPServer
2922```
examples/input-form/src/lib.rs+17−2
@@ -3,21 +3,27 @@ use dodrio::{on, Attribute, Node, Render};
33use wasm_bindgen::prelude::*;
44use wasm_bindgen::JsCast;
55
6+/// Say hello to someone.
67struct SayHelloTo {
8+ /// Who to say hello to.
79 who: String,
810}
911
1012impl SayHelloTo {
13+ /// Construct a new `SayHelloTo` component.
1114 fn new<S: Into<String>>(who: S) -> SayHelloTo {
1215 let who = who.into();
1316 SayHelloTo { who }
1417 }
1518
19+ /// Update who to say hello to.
1620 fn set_who(&mut self, who: String) {
1721 self.who = who;
1822 }
1923}
2024
25+// The `Render` implementation has a text `<input>` and a `<div>` that shows a
26+// greeting to the `<input>`'s value.
2127impl Render for SayHelloTo {
2228 fn render<'a, 'bump>(&'a self, bump: &'bump Bump) -> dodrio::Node<'bump>
2329 where
@@ -27,15 +33,21 @@ impl Render for SayHelloTo {
2733 bump,
2834 "input",
2935 [on(bump, "input", |root, vdom, event| {
36+ // If the event's target is our input...
3037 let input = match event
3138 .target()
3239 .and_then(|t| t.dyn_into::<web_sys::HtmlInputElement>().ok())
3340 {
34− Some(input) => input,
3541 None => return,
42+ Some(input) => input,
3643 };
3744
38− root.unwrap_mut::<SayHelloTo>().set_who(input.value());
45+ // ...then get its value and update who we are greeting.
46+ let value = input.value();
47+ let hello = root.unwrap_mut::<SayHelloTo>();
48+ hello.set_who(value);
49+
50+ // Finally, re-render the component on the next animation frame.
3951 vdom.schedule_render();
4052 })],
4153 [
@@ -60,12 +72,15 @@ impl Render for SayHelloTo {
6072
6173#[wasm_bindgen(start)]
6274pub fn run() {
75+ // Initialize debugging for when/if something goes wrong.
6376 console_error_panic_hook::set_once();
6477
78+ // Get the document's `<body>`.
6579 let window = web_sys::window().unwrap();
6680 let document = window.document().unwrap();
6781 let body = document.body().unwrap();
6882
83+ // Construct a new `SayHelloTo` rendering component.
6984 let say_hello = SayHelloTo::new("World");
7085
7186 // Mount the component to the `<body>`.