Skip to content

Commit

Permalink
Fix broken examples (yewstack#1289) - batch #1 (yewstack#1340)
Browse files Browse the repository at this point in the history
* Update run instructions

`python3 -m http.server --directory` flag was added in Python 3.7.
Change instructions to cd into static and skip the flag instead -
makes it work with earlier Pythons too.

* Add visual feedback for button click

The minimal example has a button, but clicking it does nothing. This
makes it hard to tell whether the example works or not.

This adds a label that is update when the button is clicked.

* Small improvements to crm example

* Add a heading to each scene to make it more obvious what the page is
for.

* Improve layout of input form by stack the inputs vertically.

* Add a little space between entries when displaying the list.

* Add a hint to the Description input that Markdown can be used.

* Add an explanation to the file_upload example

* Clarify purpose of var in fragments example

* Improve futures_wp example

* Add a second button that demonstrates an unsuccessful fetch.

* Render the markdown document (since we're fetching markdown after
all).

* Remove vague comment that's not really helping.

* Improve inner_html example

* Include a textual explanation of what the example is doing.

* Run cargo fmt

* Remove 'static lifetime for constant

* Improve suggestion in inner_html example

* move markdown.rs to a common crate

* add description to common Cargo.toml

* PR feedback

* PR feedback

* remove static lifetime annotation
  • Loading branch information
numerodix authored Jun 26, 2020
1 parent 09ffbb9 commit 7ce0bd8
Show file tree
Hide file tree
Showing 14 changed files with 93 additions and 37 deletions.
2 changes: 1 addition & 1 deletion examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Have a look at Yew's [starter templates](https://yew.rs/docs/getting-started/sta
git clone https://github.com/yewstack/yew.git
cd yew/examples
./build.sh minimal # example subfolder
python3 -m http.server --directory static # open localhost:8000 in browser
cd static && python3 -m http.server # open localhost:8000 in browser
```


Expand Down
10 changes: 10 additions & 0 deletions examples/common/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "common"
version = "0.1.0"
authors = ["Martin Matusiak <numerodix@gmail.com>"]
edition = "2018"
description="A useful utility for handing markdown which is used by other examples – not an example in itself!"

[dependencies]
yew = { path = "../../yew" }
pulldown-cmark = { version = "0.7.0", default-features = false }
1 change: 1 addition & 0 deletions examples/common/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod markdown;
File renamed without changes.
2 changes: 1 addition & 1 deletion examples/crm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ edition = "2018"
serde = "1"
serde_derive = "1"
yew = { path = "../../yew" }
pulldown-cmark = { version = "0.7.0", default-features = false }
common = { path = "../common" }
24 changes: 16 additions & 8 deletions examples/crm/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
#![recursion_limit = "128"]
#![recursion_limit = "256"]

#[macro_use]
extern crate serde_derive;

mod markdown;

use common::markdown;
use yew::format::Json;
use yew::services::storage::Area;
use yew::services::{DialogService, StorageService};
Expand Down Expand Up @@ -152,6 +151,7 @@ impl Component for Model {
match self.scene {
Scene::ClientsList => html! {
<div class="crm">
<h1>{"List of clients"}</h1>
<div class="clients">
{ for self.database.clients.iter().map(Renderable::render) }
</div>
Expand All @@ -161,10 +161,17 @@ impl Component for Model {
},
Scene::NewClientForm(ref client) => html! {
<div class="crm">
<h1>{"Add a new client"}</h1>
<div class="names">
{ client.view_first_name_input(&self.link) }
{ client.view_last_name_input(&self.link) }
{ client.view_description_textarea(&self.link) }
<div>
{ client.view_first_name_input(&self.link) }
</div>
<div>
{ client.view_last_name_input(&self.link) }
</div>
<div>
{ client.view_description_textarea(&self.link) }
</div>
</div>
<button disabled=client.first_name.is_empty() || client.last_name.is_empty()
onclick=self.link.callback(|_| Msg::AddNew)>{ "Add New" }</button>
Expand All @@ -173,6 +180,7 @@ impl Component for Model {
},
Scene::Settings => html! {
<div>
<h1>{"Settings"}</h1>
<button onclick=self.link.callback(|_| Msg::Clear)>{ "Clear Database" }</button>
<button onclick=self.link.callback(|_| Msg::SwitchTo(Scene::ClientsList))>{ "Go Back" }</button>
</div>
Expand All @@ -184,7 +192,7 @@ impl Component for Model {
impl Renderable for Client {
fn render(&self) -> Html {
html! {
<div class="client">
<div class="client" style="margin-bottom: 50px">
<p>{ format!("First Name: {}", self.first_name) }</p>
<p>{ format!("Last Name: {}", self.last_name) }</p>
<p>{ "Description:" }</p>
Expand Down Expand Up @@ -215,7 +223,7 @@ impl Client {
fn view_description_textarea(&self, link: &ComponentLink<Model>) -> Html {
html! {
<textarea class=("new-client", "description")
placeholder="Description"
placeholder="Description (can use Markdown)"
value=&self.description
oninput=link.callback(|e: InputData| Msg::UpdateDescription(e.value)) />
}
Expand Down
1 change: 1 addition & 0 deletions examples/file_upload/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ impl Component for Model {
html! {
<div>
<div>
<p>{"Choose a file to upload to see the uploaded bytes"}</p>
<input type="file" multiple=true onchange=self.link.callback(move |value| {
let mut result = Vec::new();
if let ChangeData::Files(files) = value {
Expand Down
6 changes: 3 additions & 3 deletions examples/fragments/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ impl Component for Model {
<nav class="menu">{ self.view_menu() }</nav>
<table>
<tr>
// Important! All columns have contain the same elements
// Important! All columns have to contain the same elements
{ self.view_cols() }
<td>{ "- - - >" }</td>
{ self.view_cols() }
Expand All @@ -59,13 +59,13 @@ impl Component for Model {

impl Model {
fn view_cols(&self) -> Html {
let render = |idx| {
let render_func = |idx| {
html! {
<td>{ idx }</td>
}
};
html! { // We use a fragment directly
{ for (0..self.counter).map(render) }
{ for (0..self.counter).map(render_func) }
}
}

Expand Down
1 change: 1 addition & 0 deletions examples/futures_wp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ crate-type = ["cdylib", "rlib"]
yew = { path = "../../yew" }
wasm-bindgen = "0.2.60"
wasm-bindgen-futures = "0.4.3"
common = { path = "../common" }

[dependencies.web-sys]
version = "0.3.35"
Expand Down
42 changes: 30 additions & 12 deletions examples/futures_wp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use wasm_bindgen_futures::JsFuture;
use web_sys::{Request, RequestInit, RequestMode, Response, Window};
use yew::{html, Component, ComponentLink, Html, ShouldRender};

use common::markdown;

/// This method processes a Future that returns a message and sends it back to the component's
/// loop.
///
Expand Down Expand Up @@ -52,15 +54,12 @@ pub enum FetchState<T> {
///
/// Consult the following for an example of the fetch api by the team behind web_sys:
/// https://rustwasm.github.io/wasm-bindgen/examples/fetch.html
async fn fetch_markdown() -> Result<String, FetchError> {
async fn fetch_markdown(url: &'static str) -> Result<String, FetchError> {
let mut opts = RequestInit::new();
opts.method("GET");
opts.mode(RequestMode::Cors);

let request = Request::new_with_str_and_init(
"https://raw.githubusercontent.com/yewstack/yew/master/README.md",
&opts,
)?;
let request = Request::new_with_str_and_init(url, &opts)?;

let window: Window = web_sys::window().unwrap();
let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;
Expand All @@ -80,11 +79,13 @@ struct Model {
enum Msg {
SetMarkdownFetchState(FetchState<String>),
GetMarkdown,
GetError,
}

impl Component for Model {
// Some details omitted. Explore the examples to see more.
const MARKDOWN_URL: &str = "https://raw.githubusercontent.com/yewstack/yew/master/README.md";
const INCORRECT_URL: &str = "https://raw.githubusercontent.com/yewstack/yew/master/README.md.404";

impl Component for Model {
type Message = Msg;
type Properties = ();

Expand All @@ -107,7 +108,19 @@ impl Component for Model {
}
Msg::GetMarkdown => {
let future = async {
match fetch_markdown().await {
match fetch_markdown(MARKDOWN_URL).await {
Ok(md) => Msg::SetMarkdownFetchState(FetchState::Success(md)),
Err(err) => Msg::SetMarkdownFetchState(FetchState::Failed(err)),
}
};
send_future(self.link.clone(), future);
self.link
.send_message(SetMarkdownFetchState(FetchState::Fetching));
false
}
Msg::GetError => {
let future = async {
match fetch_markdown(INCORRECT_URL).await {
Ok(md) => Msg::SetMarkdownFetchState(FetchState::Success(md)),
Err(err) => Msg::SetMarkdownFetchState(FetchState::Failed(err)),
}
Expand All @@ -123,12 +136,17 @@ impl Component for Model {
fn view(&self) -> Html {
match &self.markdown {
FetchState::NotFetching => html! {
<button onclick=self.link.callback(|_| Msg::GetMarkdown)>
{"Get Markdown"}
</button>
<>
<button onclick=self.link.callback(|_| Msg::GetMarkdown)>
{"Get Markdown"}
</button>
<button onclick=self.link.callback(|_| Msg::GetError)>
{"Get using incorrect URL"}
</button>
</>
},
FetchState::Fetching => html! {"Fetching"},
FetchState::Success(data) => html! {&data},
FetchState::Success(data) => html! { markdown::render_markdown(&data) },
FetchState::Failed(err) => html! {&err},
}
}
Expand Down
9 changes: 9 additions & 0 deletions examples/inner_html/src/document.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<h2>Inline HTML with SVG</h2>
<p>The whole contents of this page is stored as a constant HTML string in
the Rust source code. The code queries the DOM, creates a new element, and
applies this snippet of HTML to the element's innerHTML.</p>
<p>If you look at your browser's console you can see the DOM element (logged to the console).</p>
<svg height="250" width="500">
<polygon points="220,10 300,210 170,250 123,234" style="fill:lime;stroke:purple;stroke-width:1" />
Sorry, your browser does not support inline SVG.
</svg>
10 changes: 2 additions & 8 deletions examples/inner_html/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,7 @@ use web_sys::{console, Node};
use yew::virtual_dom::VNode;
use yew::{Component, ComponentLink, Html, ShouldRender};

const SVG: &str = r#"
<h2>Inline SVG or <i>any</i> HTML:</h2>
<svg height="250" width="500">
<polygon points="220,10 300,210 170,250 123,234" style="fill:lime;stroke:purple;stroke-width:1" />
Sorry, your browser does not support inline SVG.
</svg>
"#;
const HTML: &str = include_str!("document.html");

pub struct Model {
pub value: i64,
Expand Down Expand Up @@ -42,7 +36,7 @@ impl Component for Model {
.unwrap()
.create_element("div")
.unwrap();
div.set_inner_html(SVG);
div.set_inner_html(HTML);
console::log_1(&div);
div
};
Expand Down
11 changes: 9 additions & 2 deletions examples/minimal/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use yew::{html, Component, ComponentLink, Html, ShouldRender};

pub struct Model {
link: ComponentLink<Self>,
clicked: bool,
}

pub enum Msg {
Expand All @@ -13,7 +14,10 @@ impl Component for Model {
type Properties = ();

fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Model { link }
Model {
link,
clicked: false,
}
}

fn change(&mut self, _: Self::Properties) -> bool {
Expand All @@ -22,7 +26,9 @@ impl Component for Model {

fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::Click => {}
Msg::Click => {
self.clicked = true;
}
}
true
}
Expand All @@ -31,6 +37,7 @@ impl Component for Model {
html! {
<div>
<button onclick=self.link.callback(|_| Msg::Click)>{ "Click ( wasm-bindgen )" }</button>
<p>{format!("Has been clicked: {}", self.clicked)}</p>
</div>
}
}
Expand Down
11 changes: 9 additions & 2 deletions examples/minimal_wp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use yew::{html, Component, ComponentLink, Html, ShouldRender};

pub struct Model {
link: ComponentLink<Self>,
clicked: bool,
}

pub enum Msg {
Expand All @@ -14,7 +15,10 @@ impl Component for Model {
type Properties = ();

fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
Model { link }
Model {
link,
clicked: false,
}
}

fn change(&mut self, _: Self::Properties) -> bool {
Expand All @@ -23,7 +27,9 @@ impl Component for Model {

fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::Click => {}
Msg::Click => {
self.clicked = true;
}
}
true
}
Expand All @@ -32,6 +38,7 @@ impl Component for Model {
html! {
<div>
<button onclick=self.link.callback(|_| Msg::Click)>{ "Click ( wasm-pack )" }</button>
<p>{format!("Has been clicked: {}", self.clicked)}</p>
</div>
}
}
Expand Down

0 comments on commit 7ce0bd8

Please sign in to comment.