Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix broken examples (#1289) - batch #1 #1340

Merged
merged 15 commits into from
Jun 26, 2020
Merged
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
jstarry marked this conversation as resolved.
Show resolved Hide resolved
```


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 <[email protected]>"]
edition = "2018"
description="A useful utility for handing markdown which is used by other examples – not an example in itself!"

jstarry marked this conversation as resolved.
Show resolved Hide resolved
[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 @@ -154,6 +153,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 @@ -163,10 +163,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 @@ -175,6 +182,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 @@ -186,7 +194,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 @@ -217,7 +225,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
10 changes: 7 additions & 3 deletions examples/inner_html/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@ 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>
const HTML: &str = r#"
jstarry marked this conversation as resolved.
Show resolved Hide resolved
<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.
Expand Down Expand Up @@ -42,7 +46,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