repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/web_worker_fib/src/bin/worker.rs | examples/web_worker_fib/src/bin/worker.rs | use yew_agent::Registrable;
use yew_worker_fib::agent::{FibonacciTask, Postcard};
fn main() {
FibonacciTask::registrar().encoding::<Postcard>().register();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/two_apps/src/main.rs | examples/two_apps/src/main.rs | use yew::html::Scope;
use yew::{html, AppHandle, Component, Context, Html};
pub enum Msg {
SetOpposite(Scope<App>),
SendToOpposite(String),
SetTitle(String),
}
pub struct App {
opposite: Option<Scope<App>>,
selector: &'static str,
title: String,
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
App {
opposite: None,
selector: "",
title: "Nothing".to_owned(),
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::SetOpposite(opposite) => {
self.opposite = Some(opposite);
false
}
Msg::SendToOpposite(title) => {
self.opposite
.as_mut()
.unwrap()
.send_message(Msg::SetTitle(title));
false
}
Msg::SetTitle(title) => {
let send_msg = match title.as_ref() {
"Ping" => Some(Msg::SetTitle("Pong".into())),
"Pong" => Some(Msg::SetTitle("Pong Done".into())),
"Pong Done" => Some(Msg::SetTitle("Ping Done".into())),
_ => None,
};
if let Some(send_msg) = send_msg {
self.opposite.as_mut().unwrap().send_message(send_msg);
}
self.title = title;
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<div>
<h3>{ format!("{} received <{}>", self.selector, self.title) }</h3>
<button onclick={ctx.link().callback(|_| Msg::SendToOpposite("One".into()))}>{ "One" }</button>
<button onclick={ctx.link().callback(|_| Msg::SendToOpposite("Two".into()))}>{ "Two" }</button>
<button onclick={ctx.link().callback(|_| Msg::SendToOpposite("Three".into()))}>{ "Three" }</button>
<button onclick={ctx.link().callback(|_| Msg::SendToOpposite("Ping".into()))}>{ "Ping" }</button>
</div>
}
}
}
fn mount_app(selector: &'static str) -> AppHandle<App> {
let document = gloo::utils::document();
let element = document.query_selector(selector).unwrap().unwrap();
yew::Renderer::<App>::with_root(element).render()
}
fn main() {
let first_app = mount_app(".first-app");
let second_app = mount_app(".second-app");
first_app.send_message(Msg::SetOpposite(second_app.clone()));
second_app.send_message(Msg::SetOpposite(first_app.clone()));
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/keyed_list/src/random.rs | examples/keyed_list/src/random.rs | use rand::distr::Bernoulli;
use rand::Rng;
/// `0 <= p <= 1`
pub fn chance(p: f64) -> bool {
let d = Bernoulli::new(p).unwrap();
rand::rng().sample(d)
}
/// half-open: [min, max)
pub fn range_exclusive(min: usize, max: usize) -> usize {
rand::rng().random_range(min..max)
}
pub fn choose_two_distinct_mut<T>(items: &mut [T]) -> Option<(&mut T, &mut T)> {
let (lo, hi) = {
// Choose two distinct indices `(a, b)` such that `a < b`.
match items.len() {
0 | 1 => return None,
_ => {
let indexes = rand::seq::index::sample(&mut rand::rng(), items.len(), 2);
let (a, b) = (indexes.index(0), indexes.index(1));
if a < b {
(a, b)
} else {
(b, a)
}
}
}
};
// a = `items[0..hi]` which contains `lo` because `lo < hi`
// b = `items[hi..]` where `items[hi] == b[0]`
let (a, b) = items.split_at_mut(hi);
Some((&mut a[lo], &mut b[0]))
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/keyed_list/src/person.rs | examples/keyed_list/src/person.rs | use std::rc::Rc;
use fake::faker::address::raw::*;
use fake::faker::name::raw::*;
use fake::locales::*;
use fake::Fake;
use yew::{html, Component, Context, Html, Properties};
use crate::random;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PersonInfo {
pub id: usize,
pub name: Rc<str>,
pub address: Rc<str>,
pub age: usize,
}
impl PersonInfo {
pub fn new_random(id: usize) -> Self {
let address = {
let no = random::range_exclusive(1, 300);
let state = StateAbbr(EN).fake::<String>();
let city = CityName(EN).fake::<String>();
let street = StreetName(EN).fake::<String>();
Rc::from(format!("{no} {street} St., {city}, {state}").as_str())
};
Self {
id,
name: Rc::from(Name(EN).fake::<String>().as_str()),
age: random::range_exclusive(7, 77),
address,
}
}
fn render(&self) -> Html {
html! {
<div class="card w-50 card_style">
<div class="card-body">
<h5 class="card-title">{ format!("{} - {}", &self.id, &self.name) }</h5>
<p class="card-text">{ format!("Age: {}", &self.age) }</p>
<p class="card-text">{ format!("Address: {}", &self.address) }</p>
</div>
</div>
}
}
}
#[derive(Debug, Eq, PartialEq, Properties)]
pub struct PersonProps {
info: PersonInfo,
}
pub struct PersonComponent;
impl Component for PersonComponent {
type Message = ();
type Properties = PersonProps;
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<div class="text-info" id={ctx.props().info.id.to_string()}>
{ ctx.props().info.render() }
</div>
}
}
}
pub enum PersonType {
Inline(PersonInfo),
Component(PersonInfo),
}
impl PersonType {
pub fn info(&self) -> &PersonInfo {
match self {
Self::Inline(info) => info,
Self::Component(info) => info,
}
}
pub fn new_random(id: usize, ratio: f64) -> Self {
let info = PersonInfo::new_random(id);
if random::chance(ratio) {
Self::Inline(info)
} else {
Self::Component(info)
}
}
pub fn render(&self, keyed: bool) -> Html {
match self {
Self::Inline(info) => {
if keyed {
html! {
<div key={info.id.to_string()} class="text-danger" id={info.id.to_string()}>
{ info.render() }
</div>
}
} else {
html! {
<div class="text-danger" id={info.id.to_string()}>
{ info.render() }
</div>
}
}
}
Self::Component(info) => {
if keyed {
html! { <PersonComponent key={info.id.to_string()} info={info.clone()} /> }
} else {
html! { <PersonComponent info={info.clone()} /> }
}
}
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/keyed_list/src/main.rs | examples/keyed_list/src/main.rs | use std::cell::RefCell;
use instant::Instant;
use person::PersonType;
use web_sys::{HtmlElement, HtmlInputElement};
use yew::html::Scope;
use yew::prelude::*;
mod person;
mod random;
pub enum Msg {
CreatePersons(usize),
CreatePersonsPrepend(usize),
ChangeRatio(f64),
DeletePersonById(usize),
DeleteEverybody,
SwapRandom,
ReverseList,
SortById,
SortByName,
SortByAge,
SortByAddress,
ToggleKeyed,
}
pub struct App {
persons: Vec<PersonType>,
last_id: usize,
keyed: bool,
build_component_ratio: f64,
delta_ref: NodeRef,
last_view: RefCell<Option<Instant>>,
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
persons: Vec::with_capacity(200),
last_id: 0,
keyed: true,
build_component_ratio: 0.5,
delta_ref: NodeRef::default(),
last_view: RefCell::default(),
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::CreatePersons(n) => {
for _ in 0..n {
self.last_id += 1;
self.persons.push(PersonType::new_random(
self.last_id,
self.build_component_ratio,
));
}
true
}
Msg::CreatePersonsPrepend(n) => {
for _ in 0..n {
self.last_id += 1;
self.persons.insert(
0,
PersonType::new_random(self.last_id, self.build_component_ratio),
);
}
true
}
Msg::ChangeRatio(ratio) => {
#[allow(clippy::float_cmp)] // it's fine here?
if self.build_component_ratio != ratio {
self.build_component_ratio = ratio;
log::info!("Ratio changed: {}", ratio);
true
} else {
false
}
}
Msg::DeletePersonById(id) => {
if let Some(idx) = self.persons.iter().position(|p| p.info().id == id) {
self.persons.remove(idx);
true
} else {
false
}
}
Msg::DeleteEverybody => {
self.persons.clear();
true
}
Msg::SwapRandom => {
if let Some((a, b)) = random::choose_two_distinct_mut(&mut self.persons) {
log::info!("Swapping {} and {}.", a.info().id, b.info().id);
std::mem::swap(a, b);
true
} else {
false
}
}
Msg::ReverseList => {
self.persons.reverse();
true
}
Msg::SortById => {
self.persons
.sort_unstable_by(|a, b| a.info().id.cmp(&b.info().id));
true
}
Msg::SortByName => {
self.persons
.sort_unstable_by(|a, b| a.info().name.cmp(&b.info().name));
true
}
Msg::SortByAge => {
self.persons.sort_by_key(|p| p.info().age);
true
}
Msg::SortByAddress => {
self.persons
.sort_unstable_by(|a, b| a.info().address.cmp(&b.info().address));
true
}
Msg::ToggleKeyed => {
self.keyed = !self.keyed;
true
}
}
}
fn rendered(&mut self, _ctx: &Context<Self>, _first_render: bool) {
let time_after = Instant::now();
let elapsed_max = time_after - self.last_view.get_mut().take().unwrap();
log::info!("Rendering started {} ms ago.", elapsed_max.as_millis());
let output = self.delta_ref.cast::<HtmlElement>().unwrap();
let delta_text = format!("The last rendering took {} ms", elapsed_max.as_millis());
output.set_inner_text(&delta_text);
}
fn view(&self, ctx: &Context<Self>) -> Html {
let mut last_view = self.last_view.borrow_mut();
if last_view.is_none() {
*last_view = Some(Instant::now());
}
html! {
<div class="container">
<div class="row">
<p class="h2" ref={self.delta_ref.clone()}/>
<hr />
</div>
{ self.action_view(ctx.link()) }
{ self.info_view() }
</div>
}
}
}
impl App {
fn action_view(&self, link: &Scope<Self>) -> Html {
html! {
<>
{ self.button_view(link) }
<div class="row">
<div class="col">
<p class="h5">
{ "Person type ratio (0=only tags <= ratio <= 1=only components): " }
{ self.build_component_ratio }
</p>
<input name="ratio" type="range" class="form-control-range" min="0.0" max="1.0" step="any"
oninput={link.callback(|e: InputEvent| {
let input: HtmlInputElement = e.target_unchecked_into();
Msg::ChangeRatio(input.value_as_number())
})}
/>
</div>
</div>
</>
}
}
fn button_view(&self, link: &Scope<Self>) -> Html {
html! {
<>
<div class="row">
<div class="col">
<button class="btn_size alert alert-danger" onclick={link.callback(|_| Msg::DeleteEverybody)}>
{ "Delete everybody" }
</button>
</div>
<div class="col">
<button class="btn_size alert alert-success" onclick={link.callback(|_| Msg::CreatePersons(1))}>
{ "Create 1" }
</button>
</div>
<div class="col">
<button class="btn_size alert alert-success" onclick={link.callback(|_| Msg::CreatePersons(5))}>
{ "Create 5" }
</button>
</div>
<div class="col">
<button class="btn_size alert alert-success" onclick={link.callback(|_| Msg::CreatePersons(100))}>
{ "Create 100" }
</button>
</div>
<div class="col">
<button class="btn_size alert alert-success" onclick={link.callback(|_| Msg::CreatePersons(500))}>
{ "Create 500" }
</button>
</div>
<div class="col">
<button class="btn_size alert alert-success" onclick={link.callback(|_| Msg::CreatePersonsPrepend(1))}>
{ "Prepend 1" }
</button>
</div>
<div class="col">
<button class="btn_size alert alert-success" onclick={link.callback(|_| Msg::CreatePersonsPrepend(5))}>
{ "Prepend 5" }
</button>
</div>
</div>
<div class="row">
<div class="col">
<button class="btn_size alert alert-warning" onclick={link.callback(|_| Msg::ToggleKeyed)}>
{ if self.keyed { "Disable keys" } else { "Enable keys" } }
</button>
</div>
<div class="col">
<button class="btn_size alert alert-info" onclick={link.callback(|_| Msg::SwapRandom)}>
{ "Swap random" }
</button>
</div>
<div class="col">
<button class="btn_size alert alert-info" onclick={link.callback(|_| Msg::ReverseList)}>
{ "Reverse list" }
</button>
</div>
<div class="col">
<button class="btn_size alert alert-info" onclick={link.callback(|_| Msg::SortById)}>
{ "Sort by id" }
</button>
</div>
<div class="col">
<button class="btn_size alert alert-info" onclick={link.callback(|_| Msg::SortByName)}>
{ "Sort by name" }
</button>
</div>
<div class="col">
<button class="btn_size alert alert-info" onclick={link.callback(|_| Msg::SortByAge)}>
{ "Sort by age" }
</button>
</div>
<div class="col">
<button class="btn_size alert alert-info" onclick={link.callback(|_| Msg::SortByAddress)}>
{ "Sort by address" }
</button>
</div>
</div>
</>
}
}
fn info_view(&self) -> Html {
let ids = if self.persons.len() < 20 {
self.persons
.iter()
.map(|p| p.info().id.to_string())
.collect::<Vec<_>>()
.join(" ")
} else {
String::from("<too many>")
};
html! {
<div>
<p class="h5">{ "Number of persons: " }{ self.persons.len() }</p>
<p class="h5">{ "Ids: " }{ ids }</p>
<hr />
<div class="persons">
{ for self.persons.iter().map(|p| p.render(self.keyed)) }
</div>
</div>
}
}
}
fn main() {
wasm_logger::init(wasm_logger::Config::new(log::Level::Trace));
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_todomvc/src/state.rs | examples/function_todomvc/src/state.rs | use std::rc::Rc;
use serde::{Deserialize, Serialize};
use strum_macros::{Display, EnumIter};
use yew::html::IntoPropValue;
use yew::prelude::*;
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct State {
pub entries: Vec<Entry>,
pub filter: Filter,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct Entry {
pub id: usize,
pub description: String,
pub completed: bool,
}
#[derive(Clone, Copy, Debug, EnumIter, Display, PartialEq, Eq, Serialize, Deserialize)]
pub enum Filter {
All,
Active,
Completed,
}
impl Filter {
pub fn fits(&self, entry: &Entry) -> bool {
match *self {
Filter::All => true,
Filter::Active => !entry.completed,
Filter::Completed => entry.completed,
}
}
pub fn as_href(&self) -> &'static str {
match self {
Filter::All => "#/",
Filter::Active => "#/active",
Filter::Completed => "#/completed",
}
}
}
impl IntoPropValue<Html> for Filter {
fn into_prop_value(self) -> Html {
html! {<>{self.to_string()}</>}
}
}
pub enum Action {
Add(String),
Edit((usize, String)),
Remove(usize),
SetFilter(Filter),
ToggleAll,
Toggle(usize),
ClearCompleted,
}
impl Reducible for State {
type Action = Action;
fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
match action {
Action::Add(description) => {
let mut entries = self.entries.clone();
entries.push(Entry {
id: entries.last().map(|entry| entry.id + 1).unwrap_or(1),
description,
completed: false,
});
State {
entries,
filter: self.filter,
}
.into()
}
Action::Remove(id) => {
let mut entries = self.entries.clone();
entries.retain(|entry| entry.id != id);
State {
entries,
filter: self.filter,
}
.into()
}
Action::Toggle(id) => {
let mut entries = self.entries.clone();
let entry = entries.iter_mut().find(|entry| entry.id == id);
if let Some(entry) = entry {
entry.completed = !entry.completed;
}
State {
entries,
filter: self.filter,
}
.into()
}
Action::Edit((id, description)) => {
let mut entries = self.entries.clone();
if description.is_empty() {
entries.retain(|entry| entry.id != id)
}
let entry = entries.iter_mut().find(|entry| entry.id == id);
if let Some(entry) = entry {
entry.description = description;
}
State {
entries,
filter: self.filter,
}
.into()
}
Action::ToggleAll => {
let mut entries = self.entries.clone();
for entry in &mut entries {
if self.filter.fits(entry) {
entry.completed = !entry.completed;
}
}
State {
entries,
filter: self.filter,
}
.into()
}
Action::ClearCompleted => {
let mut entries = self.entries.clone();
entries.retain(|e| Filter::Active.fits(e));
State {
entries,
filter: self.filter,
}
.into()
}
Action::SetFilter(filter) => State {
filter,
entries: self.entries.clone(),
}
.into(),
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_todomvc/src/hooks.rs | examples/function_todomvc/src/hooks.rs | pub mod use_bool_toggle;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_todomvc/src/main.rs | examples/function_todomvc/src/main.rs | use gloo::storage::{LocalStorage, Storage};
use state::{Action, Filter, State};
use strum::IntoEnumIterator;
use yew::prelude::*;
mod components;
mod hooks;
mod state;
use components::entry::Entry as EntryItem;
use components::filter::Filter as FilterItem;
use components::header_input::HeaderInput;
use components::info_footer::InfoFooter;
const KEY: &str = "yew.functiontodomvc.self";
#[function_component(App)]
fn app() -> Html {
let state = use_reducer(|| State {
entries: LocalStorage::get(KEY).unwrap_or_else(|_| vec![]),
filter: Filter::All, // TODO: get from uri
});
// Effect
use_effect_with(state.clone(), |state| {
LocalStorage::set(KEY, &state.clone().entries).expect("failed to set");
});
// Callbacks
fn make_callback<E, F>(state: &UseReducerHandle<State>, f: F) -> Callback<E>
where
F: Fn(E) -> Action + 'static,
{
let state = state.clone();
Callback::from(move |e: E| state.dispatch(f(e)))
}
let onremove = make_callback(&state, Action::Remove);
let ontoggle = make_callback(&state, Action::Toggle);
let ontoggle_all = make_callback(&state, |_| Action::ToggleAll);
let onclear_completed = make_callback(&state, |_| Action::ClearCompleted);
let onedit = make_callback(&state, Action::Edit);
let onadd = make_callback(&state, Action::Add);
let onset_filter = make_callback(&state, Action::SetFilter);
// Helpers
let completed = state
.entries
.iter()
.filter(|entry| Filter::Completed.fits(entry))
.count();
let is_all_completed = state
.entries
.iter()
.all(|e| state.filter.fits(e) & e.completed);
let total = state.entries.len();
let hidden_class = if state.entries.is_empty() {
"hidden"
} else {
""
};
html! {
<div class="todomvc-wrapper">
<section class="todoapp">
<header class="header">
<h1>{ "todos" }</h1>
<HeaderInput {onadd} />
</header>
<section class={classes!("main", hidden_class)}>
<input
type="checkbox"
class="toggle-all"
id="toggle-all"
checked={is_all_completed}
onclick={ontoggle_all}
/>
<label for="toggle-all" />
<ul class="todo-list">
{ for state.entries.iter().filter(|e| state.filter.fits(e)).cloned().map(|entry|
html! {
<EntryItem {entry}
ontoggle={&ontoggle}
onremove={&onremove}
onedit={&onedit}
/>
}) }
</ul>
</section>
<footer class={classes!("footer", hidden_class)}>
<span class="todo-count">
<strong>{ total }</strong>
{ " item(s) left" }
</span>
<ul class="filters">
{ for Filter::iter().map(|filter| {
html! {
<FilterItem {filter}
selected={state.filter == filter}
onset_filter={&onset_filter}
/>
}
}) }
</ul>
<button class="clear-completed" onclick={onclear_completed}>
{ format!("Clear completed ({completed})") }
</button>
</footer>
</section>
<InfoFooter />
</div>
}
}
fn main() {
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_todomvc/src/components.rs | examples/function_todomvc/src/components.rs | pub mod entry;
pub mod filter;
pub mod header_input;
pub mod info_footer;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_todomvc/src/hooks/use_bool_toggle.rs | examples/function_todomvc/src/hooks/use_bool_toggle.rs | use std::ops::Deref;
use std::rc::Rc;
use yew::prelude::*;
#[derive(Clone)]
pub struct UseBoolToggleHandle {
value: UseStateHandle<bool>,
toggle: Rc<dyn Fn()>,
}
impl UseBoolToggleHandle {
pub fn toggle(self) {
(self.toggle)()
}
}
impl Deref for UseBoolToggleHandle {
type Target = bool;
fn deref(&self) -> &Self::Target {
&self.value
}
}
/// This hook can be used to cause a re-render with the non-default value, which is
/// then reset to the default value after that render.
///
/// # Arguments
///
/// * `default` - The default value.
///
/// # Example
/// ```
/// use crate::hooks::use_bool_toggle::use_bool_toggle;
/// ...
/// let value = use_bool_toggle(false);
/// ...
/// let onclick = {
/// let value = value.clone();
/// move |_| {
/// value.toggle();
/// // This will toggle the value to true.
/// // Then render.
/// // Post render it will toggle back to false skipping the render.
/// }
/// }
/// <button {onclick}>{ "Click me" }</button>
/// ...
/// ```
#[hook]
pub fn use_bool_toggle(default: bool) -> UseBoolToggleHandle {
let state = use_state_eq(|| default);
let toggle = {
let state = state.clone();
Rc::new(move || state.set(!*state))
};
UseBoolToggleHandle {
value: state,
toggle,
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_todomvc/src/components/info_footer.rs | examples/function_todomvc/src/components/info_footer.rs | use yew::prelude::*;
#[function_component(InfoFooter)]
pub fn info_footer() -> Html {
html! {
<footer class="info">
<p>{ "Double-click to edit a todo" }</p>
<p>{ "Written by " }<a href="https://github.com/Yoroshikun/" target="_blank">{ "Drew Hutton <Yoroshi>" }</a></p>
<p>{ "Part of " }<a href="http://todomvc.com/" target="_blank">{ "TodoMVC" }</a></p>
</footer>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_todomvc/src/components/filter.rs | examples/function_todomvc/src/components/filter.rs | use yew::prelude::*;
use crate::state::Filter as FilterEnum;
#[derive(PartialEq, Properties)]
pub struct FilterProps {
pub filter: FilterEnum,
pub selected: bool,
pub onset_filter: Callback<FilterEnum>,
}
#[function_component]
pub fn Filter(props: &FilterProps) -> Html {
let filter = props.filter;
let cls = if props.selected {
"selected"
} else {
"not-selected"
};
let onset_filter = {
let onset_filter = props.onset_filter.clone();
move |_| onset_filter.emit(filter)
};
html! {
<li>
<a class={cls}
href={props.filter.as_href()}
onclick={onset_filter}
>
{ props.filter }
</a>
</li>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_todomvc/src/components/header_input.rs | examples/function_todomvc/src/components/header_input.rs | use web_sys::HtmlInputElement;
use yew::events::KeyboardEvent;
use yew::prelude::*;
#[derive(PartialEq, Properties, Clone)]
pub struct HeaderInputProps {
pub onadd: Callback<String>,
}
#[function_component(HeaderInput)]
pub fn header_input(props: &HeaderInputProps) -> Html {
let onkeypress = {
let onadd = props.onadd.clone();
move |e: KeyboardEvent| {
if e.key() == "Enter" {
let input: HtmlInputElement = e.target_unchecked_into();
let value = input.value();
input.set_value("");
onadd.emit(value);
}
}
};
html! {
<input
class="new-todo"
placeholder="What needs to be done?"
{onkeypress}
/>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_todomvc/src/components/entry.rs | examples/function_todomvc/src/components/entry.rs | use web_sys::{HtmlInputElement, MouseEvent};
use yew::events::{Event, FocusEvent, KeyboardEvent};
use yew::prelude::*;
use crate::hooks::use_bool_toggle::use_bool_toggle;
use crate::state::Entry as Item;
#[derive(PartialEq, Properties, Clone)]
pub struct EntryProps {
pub entry: Item,
pub ontoggle: Callback<usize>,
pub onremove: Callback<usize>,
pub onedit: Callback<(usize, String)>,
}
#[function_component(Entry)]
pub fn entry(props: &EntryProps) -> Html {
let id = props.entry.id;
let mut class = Classes::from("todo");
// We use the `use_bool_toggle` hook and set the default value to `false`
// as the default we are not editing the entry. When we want to edit the
// entry we can call the toggle method on the `UseBoolToggleHandle`
// which will trigger a re-render with the toggle value being `true` for that
// render and after that render the value of toggle will be flipped back to
// its default (`false`).
// We are relying on the behavior of `onblur` and `onkeypress` to cause
// another render so that this component will render again with the
// default value of toggle.
let edit_toggle = use_bool_toggle(false);
let is_editing = *edit_toggle;
if is_editing {
class.push("editing");
}
if props.entry.completed {
class.push("completed");
}
let ontoggle = {
let ontoggle = props.ontoggle.clone();
move |_| ontoggle.emit(id)
};
let onremove = {
let onremove = props.onremove.clone();
move |_| onremove.emit(id)
};
let onedit = {
let onedit = props.onedit.clone();
let edit_toggle = edit_toggle.clone();
move |value| {
edit_toggle.clone().toggle();
onedit.emit(value)
}
};
html! {
<li {class}>
<div class="view">
<input
type="checkbox"
class="toggle"
checked={props.entry.completed}
onclick={ontoggle}
/>
<label ondblclick={move |_| edit_toggle.clone().toggle()}>
{ &props.entry.description }
</label>
<button class="destroy" onclick={onremove} />
</div>
<EntryEdit entry={props.entry.clone()} onedit={onedit} editing={is_editing} />
</li>
}
}
#[derive(PartialEq, Properties, Clone)]
pub struct EntryEditProps {
pub entry: Item,
pub onedit: Callback<(usize, String)>,
pub editing: bool,
}
#[function_component(EntryEdit)]
pub fn entry_edit(props: &EntryEditProps) -> Html {
if props.editing {
let id = props.entry.id;
let target_input_value = |e: &Event| {
let input: HtmlInputElement = e.target_unchecked_into();
input.value()
};
let onblur = {
let edit = props.onedit.clone();
move |e: FocusEvent| {
let value = target_input_value(&e);
edit.emit((id, value))
}
};
let onkeypress = {
let edit = props.onedit.clone();
move |e: KeyboardEvent| {
if e.key() == "Enter" {
let value = target_input_value(&e);
edit.emit((id, value))
}
}
};
let onmouseover = |e: MouseEvent| {
e.target_unchecked_into::<HtmlInputElement>()
.focus()
.unwrap_or_default();
};
html! {
<input
class="edit"
type="text"
value={props.entry.description.clone()}
{onmouseover}
{onblur}
{onkeypress}
/>
}
} else {
html! { <input type="hidden" /> }
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_delayed_input/src/main.rs | examples/function_delayed_input/src/main.rs | use std::time::Duration;
use gloo_timers::callback::Timeout;
use web_sys::wasm_bindgen::JsCast;
use web_sys::HtmlInputElement;
use yew::*;
#[component]
fn App() -> Html {
#[derive(PartialEq, Default, Clone)]
enum Search {
#[default]
Idle,
Fetching(AttrValue),
Fetched(AttrValue),
}
let search = use_state(Search::default);
use_effect_with(search.clone(), {
move |search| {
// here you would typically do a REST call to send the search input to backend
// for simplicity sake here we just set back the original input
if let Search::Fetching(query) = &**search {
yew::platform::spawn_local({
let query = query.clone();
let search = search.setter();
async move {
// Simulate a network delay
gloo_timers::future::sleep(Duration::from_millis(500)).await;
search.set(Search::Fetched(
format!("Placeholder response for: {}", query).into(),
));
}
});
}
}
});
let oninput = {
let timeout_ref = use_mut_ref(|| None);
use_callback((), {
let search = search.clone();
move |e: InputEvent, _| {
if let Some(target) = e.target() {
let input = target.dyn_into::<HtmlInputElement>().ok();
if let Some(input) = input {
let value = input.value();
if !value.is_empty() {
let search = search.setter();
let timeout = Timeout::new(1_000, move || {
search.set(Search::Fetching(value.into()));
});
(*timeout_ref.borrow_mut()) = Some(timeout);
}
}
}
}
})
};
html! {
<div class="container p-2">
<div class="row">
<div class="p-2">
<form class="input-group bg-dark border border-white rounded">
<input id="search" autocomplete="off" type="search" class="form-control" placeholder="Type something here..." aria-label="Search" {oninput}/>
</form>
</div>
<div class="p-2 border border-black rounded">
<p>{
match &*search {
Search::Idle => "Type something to search...".into(),
Search::Fetching(query) => format!("Searching for: {}", query).into(),
Search::Fetched(response) => response.clone(),
}
}</p>
</div>
</div>
</div>
}
}
fn main() {
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/async_clock/src/services.rs | examples/async_clock/src/services.rs | use std::time::Duration;
use chrono::{DateTime, Local};
use futures::{Stream, StreamExt};
use gloo_net::http::Request;
use yew::platform::pinned::mpsc::UnboundedSender;
use yew::platform::spawn_local;
use yew::platform::time::{interval, sleep};
use yew::{AttrValue, Callback};
const ONE_SEC: Duration = Duration::from_secs(1);
const TEN_SECS: Duration = Duration::from_secs(10);
/// Demonstration code to show how to use async code in a yew component.
pub async fn initialize_atomic_clocks() {
// aligning with atomic clocks :-)
sleep(ONE_SEC).await;
}
/// Returns a stream of time updates.
pub fn stream_time() -> impl Stream<Item = DateTime<Local>> {
interval(ONE_SEC).map(|_| Local::now())
}
/// Emit entertaining jokes every 10 seconds.
pub fn emit_jokes(joke_cb: Callback<AttrValue>) {
// Spawn a background task that will fetch a joke and send it to the component.
spawn_local(async move {
loop {
// Fetch the online joke
let fun_fact =
Request::get("https://v2.jokeapi.dev/joke/Programming?format=txt&safe-mode")
.send()
.await
.unwrap()
.text()
.await
.unwrap();
// Emit it to the component
joke_cb.emit(AttrValue::from(fun_fact));
sleep(TEN_SECS).await;
}
});
}
/// Background task that computes the fun score from jokes that are delivered on the channel.
pub fn compute_fun_score(fun_score_cb: Callback<i16>) -> UnboundedSender<AttrValue> {
let (tx, mut rx) = yew::platform::pinned::mpsc::unbounded::<AttrValue>();
// Read endlessly from the UnboundedReceiver and compute the fun score.
spawn_local(async move {
while let Some(joke) = rx.next().await {
sleep(ONE_SEC).await;
let score = joke.len() as i16;
fun_score_cb.emit(score);
}
});
tx
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/async_clock/src/main.rs | examples/async_clock/src/main.rs | use chrono::{DateTime, Local};
use futures::{FutureExt, StreamExt};
use services::compute_fun_score;
use yew::platform::pinned::mpsc::UnboundedSender;
use yew::{html, AttrValue, Component, Context, Html};
use crate::services::{emit_jokes, initialize_atomic_clocks, stream_time};
mod services;
/// The AsyncComponent displays the current time and some silly jokes. Its main purpose is to
/// demonstrate the use of async code in a yew component. It uses the following async features:
/// - send_future
/// - send_stream
/// - spawn_local
/// - mpsc::unbounded channels
pub struct AsyncComponent {
clock: Option<AttrValue>,
joke: Option<AttrValue>,
fun_score: Option<i16>,
fun_score_channel: UnboundedSender<AttrValue>,
}
pub enum Msg {
ClockInitialized(()),
ClockTicked(DateTime<Local>),
Joke(AttrValue),
FunScore(i16),
}
impl Component for AsyncComponent {
type Message = Msg;
type Properties = ();
fn create(ctx: &Context<Self>) -> Self {
// Demonstrate how we can send a message to the component when a future completes.
// This is the most straightforward way to use async code in a yew component.
let is_initialized = initialize_atomic_clocks();
ctx.link()
.send_future(is_initialized.map(Msg::ClockInitialized));
// The compute_fun_score launches a background task that is ready to compute the fun score
// from jokes that are delivered on this channel. The outcome of the computation is
// sent back to the component via the Msg::FunScore callback.
let fun_score_cb = ctx.link().callback(Msg::FunScore);
let fun_score_channel = compute_fun_score(fun_score_cb);
Self {
clock: None,
joke: None,
fun_score: None,
fun_score_channel,
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::ClockTicked(current_time) => {
// Update the clock display
self.clock = Some(AttrValue::from(current_time.to_rfc2822()));
}
Msg::ClockInitialized(_) => {
// Now that the clock is initialized, we can start the time stream.
self.clock = Some(AttrValue::from("Initialized"));
// The stream_time method returns a stream of time updates. We use send_stream to
// update the component with a Msg::ClockTicked message every time
// the stream produces a new value.
let time_steam = stream_time();
ctx.link().send_stream(time_steam.map(Msg::ClockTicked));
// In parallel we launch a background task that produces jokes to make the clock
// more fun to watch. The jokes are emitted back to the component
// throught the Msg::Joke callback.
let joke_cb = ctx.link().callback(Msg::Joke);
emit_jokes(joke_cb);
}
Msg::Joke(joke) => {
// Update the joke
self.joke = Some(joke.clone());
// Reset the fun score
self.fun_score = None;
// Send the joke to the background task that computes the fun score.
self.fun_score_channel
.send_now(joke)
.expect("failed to send joke");
}
Msg::FunScore(score) => {
self.fun_score = Some(score);
}
}
true
}
fn view(&self, _ctx: &Context<Self>) -> Html {
let display = self.clock.as_deref().unwrap_or("Loading...");
let joke = self.joke.as_deref().unwrap_or("Loading...");
let fun_score = self
.fun_score
.map(|score| format!("Fun score: {score}"))
.unwrap_or_else(|| "Computing...".to_string());
html! {
<div class="app">
<div class="clock">
<h2>{ "Asynchronous Examples" }</h2>
<div class="time-display">
{ display }
</div>
<div class="joke-display">
{ joke }
</div>
<div class="fun-score-display">
{ fun_score }
</div>
</div>
</div>
}
}
}
fn main() {
yew::Renderer::<AsyncComponent>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/app.rs | examples/function_router/src/app.rs | use std::collections::HashMap;
use yew::prelude::*;
use yew_router::history::{AnyHistory, History, MemoryHistory};
use yew_router::prelude::*;
use crate::components::nav::Nav;
use crate::pages::author::Author;
use crate::pages::author_list::AuthorList;
use crate::pages::home::Home;
use crate::pages::page_not_found::PageNotFound;
use crate::pages::post::Post;
use crate::pages::post_list::PostList;
#[derive(Routable, PartialEq, Eq, Clone, Debug)]
pub enum Route {
#[at("/posts/:id")]
Post { id: u32 },
#[at("/posts")]
Posts,
#[at("/authors/:id")]
Author { id: u32 },
#[at("/authors")]
Authors,
#[at("/")]
Home,
#[not_found]
#[at("/404")]
NotFound,
}
#[function_component]
pub fn App() -> Html {
html! {
<BrowserRouter>
<Nav />
<main>
<Switch<Route> render={switch} />
</main>
<footer class="footer">
<div class="content has-text-centered">
{ "Powered by " }
<a href="https://yew.rs">{ "Yew" }</a>
{ " using " }
<a href="https://bulma.io">{ "Bulma" }</a>
{ " and images from " }
<a href="https://unsplash.com">{ "Unsplash" }</a>
</div>
</footer>
</BrowserRouter>
}
}
#[derive(Properties, PartialEq, Eq, Debug)]
pub struct ServerAppProps {
pub url: AttrValue,
pub queries: HashMap<String, String>,
}
#[function_component]
pub fn ServerApp(props: &ServerAppProps) -> Html {
let history = AnyHistory::from(MemoryHistory::new());
history
.push_with_query(&*props.url, &props.queries)
.unwrap();
html! {
<Router history={history}>
<Nav />
<main>
<Switch<Route> render={switch} />
</main>
<footer class="footer">
<div class="content has-text-centered">
{ "Powered by " }
<a href="https://yew.rs">{ "Yew" }</a>
{ " using " }
<a href="https://bulma.io">{ "Bulma" }</a>
{ " and images from " }
<a href="https://unsplash.com">{ "Unsplash" }</a>
</div>
</footer>
</Router>
}
}
fn switch(routes: Route) -> Html {
match routes {
Route::Post { id } => {
html! { <Post seed={id} /> }
}
Route::Posts => {
html! { <PostList /> }
}
Route::Author { id } => {
html! { <Author seed={id} /> }
}
Route::Authors => {
html! { <AuthorList /> }
}
Route::Home => {
html! { <Home /> }
}
Route::NotFound => {
html! { <PageNotFound /> }
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/lib.rs | examples/function_router/src/lib.rs | // # Implementation Note:
//
// This example is also used to demonstrate SSR hydration.
// It is important to follow the following rules when updating this example:
//
// - Do not use usize for randomised contents.
//
// usize differs in memory size in 32-bit and 64-bit targets (wasm32 is a 32-bit target family.)
// and would lead to a different value even if the Rng at the same state.
//
// - Do not swap StdRng for SmallRng.
//
// SmallRng uses different algorithms depending on the platform.
// Hence, it may not yield the same value on the client and server side.
mod app;
mod components;
mod content;
mod generator;
mod pages;
pub use app::*;
pub use content::*;
pub use generator::*;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/content.rs | examples/function_router/src/content.rs | use crate::generator::{Generated, Generator};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Author {
pub seed: u32,
pub name: String,
pub keywords: Vec<String>,
pub image_url: String,
}
impl Generated for Author {
fn generate(gen: &mut Generator) -> Self {
let name = gen.human_name();
let keywords = gen.keywords();
let image_url = gen.face_image_url((600, 600));
Self {
seed: gen.seed,
name,
keywords,
image_url,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PostMeta {
pub seed: u32,
pub title: String,
pub author: Author,
pub keywords: Vec<String>,
pub image_url: String,
}
impl Generated for PostMeta {
fn generate(gen: &mut Generator) -> Self {
let title = gen.title();
let author = Author::generate_from_seed(gen.new_seed());
let keywords = gen.keywords();
let image_url = gen.image_url((1000, 500), &keywords);
Self {
seed: gen.seed,
title,
author,
keywords,
image_url,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Post {
pub meta: PostMeta,
pub content: Vec<PostPart>,
}
impl Generated for Post {
fn generate(gen: &mut Generator) -> Self {
const PARTS_MIN: u32 = 1;
const PARTS_MAX: u32 = 10;
let meta = PostMeta::generate(gen);
let n_parts = gen.range(PARTS_MIN, PARTS_MAX);
let content = (0..n_parts).map(|_| PostPart::generate(gen)).collect();
Self { meta, content }
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PostPart {
Section(Section),
Quote(Quote),
}
impl Generated for PostPart {
fn generate(gen: &mut Generator) -> Self {
// Because we pass the same (already used) generator down,
// the resulting `Section` and `Quote` aren't be reproducible with just the seed.
// This doesn't matter here though, because we don't need it.
if gen.chance(1, 10) {
Self::Quote(Quote::generate(gen))
} else {
Self::Section(Section::generate(gen))
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Section {
pub title: String,
pub paragraphs: Vec<String>,
pub image_url: String,
}
impl Generated for Section {
fn generate(gen: &mut Generator) -> Self {
const PARAGRAPHS_MIN: u32 = 1;
const PARAGRAPHS_MAX: u32 = 8;
let title = gen.title();
let n_paragraphs = gen.range(PARAGRAPHS_MIN, PARAGRAPHS_MAX);
let paragraphs = (0..n_paragraphs).map(|_| gen.paragraph()).collect();
let image_url = gen.image_url((600, 300), &[]);
Self {
title,
paragraphs,
image_url,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Quote {
pub author: Author,
pub content: String,
}
impl Generated for Quote {
fn generate(gen: &mut Generator) -> Self {
// wouldn't it be funny if the author ended up quoting themselves?
let author = Author::generate_from_seed(gen.new_seed());
let content = gen.paragraph();
Self { author, content }
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/generator.rs | examples/function_router/src/generator.rs | use lipsum::MarkovChain;
use once_cell::sync::Lazy;
use rand::distr::Bernoulli;
use rand::rngs::StdRng;
use rand::seq::IteratorRandom;
use rand::{Rng, SeedableRng};
const KEYWORDS: &str = include_str!("../data/keywords.txt");
const SYLLABLES: &str = include_str!("../data/syllables.txt");
const YEW_CONTENT: &str = include_str!("../data/yew.txt");
static YEW_CHAIN: Lazy<MarkovChain<'static>> = Lazy::new(|| {
let mut chain = MarkovChain::new();
chain.learn(YEW_CONTENT);
chain
});
pub struct Generator {
pub seed: u32,
rng: StdRng,
}
impl Generator {
pub fn from_seed(seed: u32) -> Self {
let rng = StdRng::seed_from_u64(seed as u64);
Self { seed, rng }
}
}
impl Generator {
pub fn new_seed(&mut self) -> u32 {
self.rng.random()
}
/// [low, high)
pub fn range(&mut self, low: u32, high: u32) -> u32 {
self.rng.random_range(low..high)
}
/// `n / d` chance
pub fn chance(&mut self, n: u32, d: u32) -> bool {
self.rng.sample(Bernoulli::from_ratio(n, d).unwrap())
}
pub fn image_url(&mut self, dimension: (u32, u32), keywords: &[String]) -> String {
let cache_buster = self.rng.random::<u16>();
let (width, height) = dimension;
format!(
"https://source.unsplash.com/random/{}x{}?{}&sig={}",
width,
height,
keywords.join(","),
cache_buster
)
}
pub fn face_image_url(&mut self, dimension: (u32, u32)) -> String {
self.image_url(dimension, &["human".to_owned(), "face".to_owned()])
}
pub fn human_name(&mut self) -> String {
const SYLLABLES_MIN: u32 = 1;
const SYLLABLES_MAX: u32 = 5;
let n_syllables = self.rng.random_range(SYLLABLES_MIN..SYLLABLES_MAX);
let first_name = SYLLABLES
.split_whitespace()
.choose_multiple(&mut self.rng, n_syllables as usize)
.join("");
let n_syllables = self.rng.random_range(SYLLABLES_MIN..SYLLABLES_MAX);
let last_name = SYLLABLES
.split_whitespace()
.choose_multiple(&mut self.rng, n_syllables as usize)
.join("");
format!("{} {}", title_case(&first_name), title_case(&last_name))
}
pub fn keywords(&mut self) -> Vec<String> {
const KEYWORDS_MIN: u32 = 1;
const KEYWORDS_MAX: u32 = 4;
let n_keywords = self.rng.random_range(KEYWORDS_MIN..KEYWORDS_MAX);
KEYWORDS
.split_whitespace()
.map(ToOwned::to_owned)
.choose_multiple(&mut self.rng, n_keywords as usize)
}
pub fn title(&mut self) -> String {
const WORDS_MIN: u32 = 3;
const WORDS_MAX: u32 = 8;
const SMALL_WORD_LEN: u32 = 3;
let n_words = self.rng.random_range(WORDS_MIN..WORDS_MAX);
let mut title = String::new();
let words = YEW_CHAIN
.iter_with_rng(&mut self.rng)
.map(|word| word.trim_matches(|c: char| c.is_ascii_punctuation()))
.filter(|word| !word.is_empty())
.take(n_words as usize);
for (i, word) in words.enumerate() {
if i > 0 {
title.push(' ');
}
// Capitalize the first word and all long words.
if i == 0 || word.len() > SMALL_WORD_LEN as usize {
title.push_str(&title_case(word));
} else {
title.push_str(word);
}
}
title
}
pub fn sentence(&mut self) -> String {
const WORDS_MIN: u32 = 7;
const WORDS_MAX: u32 = 25;
let n_words = self.rng.random_range(WORDS_MIN..WORDS_MAX);
YEW_CHAIN.generate_with_rng(&mut self.rng, n_words as usize)
}
pub fn paragraph(&mut self) -> String {
const SENTENCES_MIN: u32 = 3;
const SENTENCES_MAX: u32 = 20;
let n_sentences = self.rng.random_range(SENTENCES_MIN..SENTENCES_MAX);
let mut paragraph = String::new();
for i in 0..n_sentences {
if i > 0 {
paragraph.push(' ');
}
paragraph.push_str(&self.sentence());
}
paragraph
}
}
fn title_case(word: &str) -> String {
let idx = match word.chars().next() {
Some(c) => c.len_utf8(),
None => 0,
};
let mut result = String::with_capacity(word.len());
result.push_str(&word[..idx].to_uppercase());
result.push_str(&word[idx..]);
result
}
pub trait Generated: Sized {
fn generate(gen: &mut Generator) -> Self;
fn generate_from_seed(seed: u32) -> Self {
Self::generate(&mut Generator::from_seed(seed))
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/pages/page_not_found.rs | examples/function_router/src/pages/page_not_found.rs | use yew::prelude::*;
#[function_component]
pub fn PageNotFound() -> Html {
html! {
<section class="hero is-danger is-bold is-large">
<div class="hero-body">
<div class="container">
<h1 class="title">
{ "Page not found" }
</h1>
<h2 class="subtitle">
{ "Page page does not seem to exist" }
</h2>
</div>
</div>
</section>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/pages/author.rs | examples/function_router/src/pages/author.rs | use yew::prelude::*;
use crate::components::author_card::AuthorState;
use crate::content;
use crate::generator::Generated;
#[derive(Clone, Debug, Eq, PartialEq, Properties)]
pub struct Props {
pub seed: u32,
}
#[function_component]
pub fn Author(props: &Props) -> Html {
let seed = props.seed;
let author = use_reducer_eq(|| AuthorState {
inner: content::Author::generate_from_seed(seed),
});
{
let author_dispatcher = author.dispatcher();
use_effect_with(seed, move |seed| {
author_dispatcher.dispatch(*seed);
|| {}
});
}
let author = &author.inner;
html! {
<div class="section container">
<div class="tile is-ancestor is-vertical">
<div class="tile is-parent">
<article class="tile is-child notification is-light">
<p class="title">{ &author.name }</p>
</article>
</div>
<div class="tile">
<div class="tile is-parent is-3">
<article class="tile is-child notification">
<p class="title">{ "Interests" }</p>
<div class="tags">
{ for author.keywords.iter().map(|tag| html! { <span class="tag is-info">{ tag }</span> }) }
</div>
</article>
</div>
<div class="tile is-parent">
<figure class="tile is-child image is-square">
<img alt="The author's profile picture." src={author.image_url.clone()} />
</figure>
</div>
<div class="tile is-parent">
<article class="tile is-child notification is-info">
<div class="content">
<p class="title">{ "About me" }</p>
<div class="content">
{ "This author has chosen not to reveal anything about themselves" }
</div>
</div>
</article>
</div>
</div>
</div>
</div>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/pages/home.rs | examples/function_router/src/pages/home.rs | use yew::prelude::*;
#[function_component]
fn InfoTiles() -> Html {
html! {
<>
<div class="tile is-parent">
<div class="tile is-child box">
<p class="title">{ "What are yews?" }</p>
<p class="subtitle">{ "Everything you need to know!" }</p>
<div class="content">
{r#"
A yew is a small to medium-sized evergreen tree, growing 10 to 20 metres tall, with a trunk up to 2 metres in diameter.
The bark is thin, scaly brown, coming off in small flakes aligned with the stem.
The leaves are flat, dark green, 1 to 4 centimetres long and 2 to 3 millimetres broad, arranged spirally on the stem,
but with the leaf bases twisted to align the leaves in two flat rows either side of the stem,
except on erect leading shoots where the spiral arrangement is more obvious.
The leaves are poisonous.
"#}
</div>
</div>
</div>
<div class="tile is-parent">
<div class="tile is-child box">
<p class="title">{ "Who are we?" }</p>
<div class="content">
{ "We're a small team of just 2" }
<sup>{ 64 }</sup>
{ " members working tirelessly to bring you the low-effort yew content we all desperately crave." }
<br />
{r#"
We put a ton of effort into fact-checking our posts.
Some say they read like a Wikipedia article - what a compliment!
"#}
</div>
</div>
</div>
</>
}
}
#[function_component]
pub fn Home() -> Html {
html! {
<div class="tile is-ancestor is-vertical">
<div class="tile is-child hero">
<div class="hero-body container pb-0">
<h1 class="title is-1">{ "Welcome..." }</h1>
<h2 class="subtitle">{ "...to the best yew content" }</h2>
</div>
</div>
<div class="tile is-child">
<figure class="image is-3by1">
<img alt="A random image for the input term 'yew'." src="https://source.unsplash.com/random/1200x400/?yew" />
</figure>
</div>
<div class="tile is-parent container">
<InfoTiles />
</div>
</div>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/pages/mod.rs | examples/function_router/src/pages/mod.rs | pub mod author;
pub mod author_list;
pub mod home;
pub mod page_not_found;
pub mod post;
pub mod post_list;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/pages/post.rs | examples/function_router/src/pages/post.rs | use std::rc::Rc;
use content::PostPart;
use yew::prelude::*;
use yew_router::prelude::*;
use crate::generator::Generated;
use crate::{content, Route};
#[derive(Clone, Debug, Eq, PartialEq, Properties)]
pub struct Props {
pub seed: u32,
}
#[derive(PartialEq, Eq, Debug)]
pub struct PostState {
pub inner: content::Post,
}
impl Reducible for PostState {
type Action = u32;
fn reduce(self: Rc<Self>, action: u32) -> Rc<Self> {
Self {
inner: content::Post::generate_from_seed(action),
}
.into()
}
}
#[function_component]
pub fn Post(props: &Props) -> Html {
let seed = props.seed;
let post = use_reducer(|| PostState {
inner: content::Post::generate_from_seed(seed),
});
{
let post_dispatcher = post.dispatcher();
use_effect_with(seed, move |seed| {
post_dispatcher.dispatch(*seed);
|| {}
});
}
let post = &post.inner;
let render_quote = |quote: &content::Quote| {
html! {
<article class="media block box my-6">
<figure class="media-left">
<p class="image is-64x64">
<img alt="The author's profile" src={quote.author.image_url.clone()} loading="lazy" />
</p>
</figure>
<div class="media-content">
<div class="content">
<Link<Route> classes={classes!("is-size-5")} to={Route::Author { id: quote.author.seed }}>
<strong>{ "e.author.name }</strong>
</Link<Route>>
<p class="is-family-secondary">
{ "e.content }
</p>
</div>
</div>
</article>
}
};
let render_section_hero = |section: &content::Section| {
html! {
<section class="hero is-dark has-background mt-6 mb-3">
<img alt="This section's image" class="hero-background is-transparent" src={section.image_url.clone()} loading="lazy" />
<div class="hero-body">
<div class="container">
<h2 class="subtitle">{ §ion.title }</h2>
</div>
</div>
</section>
}
};
let render_section = |section, show_hero| {
let hero = if show_hero {
render_section_hero(section)
} else {
html! {}
};
let paragraphs = section.paragraphs.iter().map(|paragraph| {
html! {
<p>{ paragraph }</p>
}
});
html! {
<section>
{ hero }
<div>{ for paragraphs }</div>
</section>
}
};
let view_content = {
// don't show hero for the first section
let mut show_hero = false;
let parts = post.content.iter().map(|part| match part {
PostPart::Section(section) => {
let html = render_section(section, show_hero);
// show hero between sections
show_hero = true;
html
}
PostPart::Quote(quote) => {
// don't show hero after a quote
show_hero = false;
render_quote(quote)
}
});
html! {{for parts}}
};
let keywords = post
.meta
.keywords
.iter()
.map(|keyword| html! { <span class="tag is-info">{ keyword }</span> });
html! {
<>
<section class="hero is-medium is-light has-background">
<img alt="The hero's background" class="hero-background is-transparent" src={post.meta.image_url.clone()} />
<div class="hero-body">
<div class="container">
<h1 class="title">
{ &post.meta.title }
</h1>
<h2 class="subtitle">
{ "by " }
<Link<Route> classes={classes!("has-text-weight-semibold")} to={Route::Author { id: post.meta.author.seed }}>
{ &post.meta.author.name }
</Link<Route>>
</h2>
<div class="tags">
{ for keywords }
</div>
</div>
</div>
</section>
<div class="section container">
{ view_content }
</div>
</>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/pages/post_list.rs | examples/function_router/src/pages/post_list.rs | use yew::prelude::*;
use yew_router::prelude::*;
use crate::components::pagination::{PageQuery, Pagination};
use crate::components::post_card::PostCard;
use crate::Route;
const ITEMS_PER_PAGE: u32 = 10;
const TOTAL_PAGES: u32 = u32::MAX / ITEMS_PER_PAGE;
#[function_component]
pub fn PostList() -> Html {
let location = use_location().unwrap();
let current_page = location.query::<PageQuery>().map(|it| it.page).unwrap_or(1);
let posts = {
let start_seed = (current_page - 1) * ITEMS_PER_PAGE;
let mut cards = (0..ITEMS_PER_PAGE).map(|seed_offset| {
html! {
<li class="list-item mb-5">
<PostCard seed={start_seed + seed_offset} />
</li>
}
});
html! {
<div class="columns">
<div class="column">
<ul class="list">
{ for cards.by_ref().take(ITEMS_PER_PAGE as usize / 2) }
</ul>
</div>
<div class="column">
<ul class="list">
{ for cards }
</ul>
</div>
</div>
}
};
html! {
<div class="section container">
<h1 class="title">{ "Posts" }</h1>
<h2 class="subtitle">{ "All of our quality writing in one place" }</h2>
{ posts }
<Pagination
page={current_page}
total_pages={TOTAL_PAGES}
route_to_page={Route::Posts}
/>
</div>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/pages/author_list.rs | examples/function_router/src/pages/author_list.rs | use rand::{distr, Rng};
use yew::prelude::*;
use crate::components::author_card::AuthorCard;
use crate::components::progress_delay::ProgressDelay;
/// Amount of milliseconds to wait before showing the next set of authors.
const CAROUSEL_DELAY_MS: u32 = 15000;
#[function_component]
pub fn AuthorList() -> Html {
let seeds = use_state(random_author_seeds);
let authors = seeds.iter().map(|&seed| {
html! {
<div class="tile is-parent">
<div class="tile is-child">
<AuthorCard {seed} />
</div>
</div>
}
});
let on_complete = {
let seeds = seeds.clone();
Callback::from(move |_| {
seeds.set(random_author_seeds());
})
};
html! {
<div class="container">
<section class="hero">
<div class="hero-body">
<div class="container">
<h1 class="title">{ "Authors" }</h1>
<h2 class="subtitle">
{ "Meet the definitely real people behind your favourite Yew content" }
</h2>
</div>
</div>
</section>
<p class="section py-0">
{ "It wouldn't be fair " }
<i>{ "(or possible :P)" }</i>
{" to list each and every author in alphabetical order."}
<br />
{ "So instead we chose to put more focus on the individuals by introducing you to two people at a time" }
</p>
<div class="section">
<div class="tile is-ancestor">
{ for authors }
</div>
<ProgressDelay duration_ms={CAROUSEL_DELAY_MS} on_complete={on_complete} />
</div>
</div>
}
}
fn random_author_seeds() -> Vec<u32> {
rand::rng()
.sample_iter(distr::StandardUniform)
.take(2)
.collect()
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/components/progress_delay.rs | examples/function_router/src/components/progress_delay.rs | use std::rc::Rc;
use gloo::timers::callback::Interval;
use instant::Instant;
use yew::prelude::*;
const RESOLUTION: u32 = 500;
const MIN_INTERVAL_MS: u32 = 50;
pub enum ValueAction {
Tick,
Props(Props),
}
#[derive(Clone, PartialEq, Debug)]
pub struct ValueState {
start: Instant,
value: f64,
props: Props,
}
impl Reducible for ValueState {
type Action = ValueAction;
fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
match action {
Self::Action::Props(props) => Self {
start: self.start,
value: self.value,
props,
}
.into(),
Self::Action::Tick => {
let elapsed = self.start.elapsed().as_millis() as u32;
let value = elapsed as f64 / self.props.duration_ms as f64;
let mut start = self.start;
if elapsed > self.props.duration_ms {
self.props.on_complete.emit(());
start = Instant::now();
} else {
self.props.on_progress.emit(self.value);
}
Self {
start,
value,
props: self.props.clone(),
}
.into()
}
}
}
}
#[derive(Clone, Debug, PartialEq, Properties)]
pub struct Props {
pub duration_ms: u32,
pub on_complete: Callback<()>,
#[prop_or_default]
pub on_progress: Callback<f64>,
}
#[function_component]
pub fn ProgressDelay(props: &Props) -> Html {
let Props { duration_ms, .. } = props.clone();
let value = {
let props = props.clone();
use_reducer(move || ValueState {
start: Instant::now(),
value: 0.0,
props,
})
};
{
let value = value.clone();
use_effect_with((), move |_| {
let interval = (duration_ms / RESOLUTION).min(MIN_INTERVAL_MS);
let interval = Interval::new(interval, move || value.dispatch(ValueAction::Tick));
|| {
let _interval = interval;
}
});
}
{
let value = value.clone();
use_effect_with(props.clone(), move |props| {
value.dispatch(ValueAction::Props(props.clone()));
|| {}
});
}
let value = &value.value;
html! {
<progress class="progress is-primary" value={value.to_string()} max=1.0>
{ format!("{:.0}%", 100.0 * value) }
</progress>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/components/post_card.rs | examples/function_router/src/components/post_card.rs | use std::rc::Rc;
use yew::prelude::*;
use yew_router::components::Link;
use crate::content::PostMeta;
use crate::generator::Generated;
use crate::Route;
#[derive(Clone, Debug, PartialEq, Eq, Properties)]
pub struct Props {
pub seed: u32,
}
#[derive(PartialEq, Eq, Debug)]
pub struct PostMetaState {
inner: PostMeta,
}
impl Reducible for PostMetaState {
type Action = u32;
fn reduce(self: Rc<Self>, action: u32) -> Rc<Self> {
Self {
inner: PostMeta::generate_from_seed(action),
}
.into()
}
}
#[function_component]
pub fn PostCard(props: &Props) -> Html {
let seed = props.seed;
let post = use_reducer_eq(|| PostMetaState {
inner: PostMeta::generate_from_seed(seed),
});
{
let post_dispatcher = post.dispatcher();
use_effect_with(seed, move |seed| {
post_dispatcher.dispatch(*seed);
|| {}
});
}
let post = &post.inner;
html! {
<div class="card">
<div class="card-image">
<figure class="image is-2by1">
<img alt="This post's image" src={post.image_url.clone()} loading="lazy" />
</figure>
</div>
<div class="card-content">
<Link<Route> classes={classes!("title", "is-block")} to={Route::Post { id: post.seed }}>
{ &post.title }
</Link<Route>>
<Link<Route> classes={classes!("subtitle", "is-block")} to={Route::Author { id: post.author.seed }}>
{ &post.author.name }
</Link<Route>>
</div>
</div>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/components/author_card.rs | examples/function_router/src/components/author_card.rs | use std::rc::Rc;
use yew::prelude::*;
use yew_router::prelude::*;
use crate::content::Author;
use crate::generator::Generated;
use crate::Route;
#[derive(Clone, Debug, PartialEq, Eq, Properties)]
pub struct Props {
pub seed: u32,
}
#[derive(PartialEq, Eq, Debug)]
pub struct AuthorState {
pub inner: Author,
}
impl Reducible for AuthorState {
type Action = u32;
fn reduce(self: Rc<Self>, action: u32) -> Rc<Self> {
Self {
inner: Author::generate_from_seed(action),
}
.into()
}
}
#[function_component]
pub fn AuthorCard(props: &Props) -> Html {
let seed = props.seed;
let author = use_reducer_eq(|| AuthorState {
inner: Author::generate_from_seed(seed),
});
{
let author_dispatcher = author.dispatcher();
use_effect_with(seed, move |seed| {
author_dispatcher.dispatch(*seed);
|| {}
});
}
let author = &author.inner;
html! {
<div class="card">
<div class="card-content">
<div class="media">
<div class="media-left">
<figure class="image is-128x128">
<img alt="Author's profile picture" src={author.image_url.clone()} />
</figure>
</div>
<div class="media-content">
<p class="title is-3">{ &author.name }</p>
<p>
{ "I like " }
<b>{ author.keywords.join(", ") }</b>
</p>
</div>
</div>
</div>
<footer class="card-footer">
<Link<Route> classes={classes!("card-footer-item")} to={Route::Author { id: author.seed }}>
{ "Profile" }
</Link<Route>>
</footer>
</div>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/components/mod.rs | examples/function_router/src/components/mod.rs | pub mod author_card;
pub mod nav;
pub mod pagination;
pub mod post_card;
pub mod progress_delay;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/components/nav.rs | examples/function_router/src/components/nav.rs | use yew::prelude::*;
use yew_router::prelude::*;
use crate::Route;
#[function_component]
pub fn Nav() -> Html {
let navbar_active = use_state_eq(|| false);
let toggle_navbar = {
let navbar_active = navbar_active.clone();
Callback::from(move |_| {
navbar_active.set(!*navbar_active);
})
};
let active_class = if !*navbar_active { "is-active" } else { "" };
html! {
<nav class="navbar is-primary" role="navigation" aria-label="main navigation">
<div class="navbar-brand">
<h1 class="navbar-item is-size-3">{ "Yew Blog" }</h1>
<button class={classes!("navbar-burger", "burger", active_class)}
aria-label="menu" aria-expanded="false"
onclick={toggle_navbar}
>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
</button>
</div>
<div class={classes!("navbar-menu", active_class)}>
<div class="navbar-start">
<Link<Route> classes={classes!("navbar-item")} to={Route::Home}>
{ "Home" }
</Link<Route>>
<Link<Route> classes={classes!("navbar-item")} to={Route::Posts}>
{ "Posts" }
</Link<Route>>
<div class="navbar-item has-dropdown is-hoverable">
<div class="navbar-link">
{ "More" }
</div>
<div class="navbar-dropdown">
<Link<Route> classes={classes!("navbar-item")} to={Route::Authors}>
{ "Meet the authors" }
</Link<Route>>
</div>
</div>
</div>
</div>
</nav>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/components/pagination.rs | examples/function_router/src/components/pagination.rs | use std::ops::Range;
use serde::{Deserialize, Serialize};
use yew::prelude::*;
use yew_router::prelude::*;
use crate::Route;
const ELLIPSIS: &str = "\u{02026}";
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
pub struct PageQuery {
pub page: u32,
}
#[derive(Clone, Debug, PartialEq, Eq, Properties)]
pub struct Props {
pub page: u32,
pub total_pages: u32,
pub route_to_page: Route,
}
#[function_component]
pub fn RelNavButtons(props: &Props) -> Html {
let Props {
page,
total_pages,
route_to_page: to,
} = props.clone();
html! {
<>
<Link<Route, PageQuery>
classes={classes!("pagination-previous")}
disabled={page==1}
query={Some(PageQuery{page: page - 1})}
to={to.clone()}
>
{ "Previous" }
</Link<Route, PageQuery>>
<Link<Route, PageQuery>
classes={classes!("pagination-next")}
disabled={page==total_pages}
query={Some(PageQuery{page: page + 1})}
{to}
>
{ "Next page" }
</Link<Route, PageQuery>>
</>
}
}
#[derive(Properties, Clone, Debug, PartialEq, Eq)]
pub struct RenderLinksProps {
range: Range<u32>,
len: usize,
max_links: usize,
props: Props,
}
#[function_component]
pub fn RenderLinks(props: &RenderLinksProps) -> Html {
let RenderLinksProps {
range,
len,
max_links,
props,
} = props.clone();
let mut range = range;
if len > max_links {
let last_link =
html! {<RenderLink to_page={range.next_back().unwrap()} props={props.clone()} />};
// remove 1 for the ellipsis and 1 for the last link
let links = range
.take(max_links - 2)
.map(|page| html! {<RenderLink to_page={page} props={props.clone()} />});
html! {
<>
{ for links }
<li><span class="pagination-ellipsis">{ ELLIPSIS }</span></li>
{ last_link }
</>
}
} else {
html! {
for page in range {
<RenderLink to_page={page} props={props.clone()} />
}
}
}
}
#[derive(Properties, Clone, Debug, PartialEq, Eq)]
pub struct RenderLinkProps {
to_page: u32,
props: Props,
}
#[function_component]
pub fn RenderLink(props: &RenderLinkProps) -> Html {
let RenderLinkProps { to_page, props } = props.clone();
let Props {
page,
route_to_page,
..
} = props;
let is_current_class = if to_page == page { "is-current" } else { "" };
html! {
<li>
<Link<Route, PageQuery>
classes={classes!("pagination-link", is_current_class)}
to={route_to_page}
query={Some(PageQuery{page: to_page})}
>
{ to_page }
</Link<Route, PageQuery>>
</li>
}
}
#[function_component]
pub fn Links(props: &Props) -> Html {
const LINKS_PER_SIDE: usize = 3;
let Props {
page, total_pages, ..
} = *props;
let pages_prev = page.checked_sub(1).unwrap_or_default() as usize;
let pages_next = (total_pages - page) as usize;
let links_left = LINKS_PER_SIDE.min(pages_prev)
// if there are less than `LINKS_PER_SIDE` to the right, we add some more on the left.
+ LINKS_PER_SIDE.checked_sub(pages_next).unwrap_or_default();
let links_right = 2 * LINKS_PER_SIDE - links_left;
html! {
<>
<RenderLinks range={ 1..page } len={pages_prev} max_links={links_left} props={props.clone()} />
<RenderLink to_page={page} props={props.clone()} />
<RenderLinks range={ page + 1..total_pages + 1 } len={pages_next} max_links={links_right} props={props.clone()} />
</>
}
}
#[function_component]
pub fn Pagination(props: &Props) -> Html {
html! {
<nav class="pagination is-right" role="navigation" aria-label="pagination">
<RelNavButtons ..{props.clone()} />
<ul class="pagination-list">
<Links ..{props.clone()} />
</ul>
</nav>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/function_router/src/bin/function_router.rs | examples/function_router/src/bin/function_router.rs | pub use function_router::*;
fn main() {
wasm_logger::init(wasm_logger::Config::new(log::Level::Trace));
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/todomvc/src/state.rs | examples/todomvc/src/state.rs | use serde_derive::{Deserialize, Serialize};
use strum_macros::{Display, EnumIter};
use yew::html::IntoPropValue;
use yew::prelude::*;
#[derive(Debug, Serialize, Deserialize)]
pub struct State {
pub entries: Vec<Entry>,
pub filter: Filter,
pub edit_value: String,
}
impl State {
pub fn new(entries: Vec<Entry>) -> Self {
Self {
entries,
filter: Filter::All,
edit_value: "".into(),
}
}
pub fn total(&self) -> usize {
self.entries.len()
}
pub fn total_completed(&self) -> usize {
self.entries
.iter()
.filter(|e| Filter::Completed.fits(e))
.count()
}
pub fn is_all_completed(&self) -> bool {
let mut filtered_iter = self
.entries
.iter()
.filter(|e| self.filter.fits(e))
.peekable();
if filtered_iter.peek().is_none() {
return false;
}
filtered_iter.all(|e| e.completed)
}
pub fn clear_completed(&mut self) {
self.entries.retain(|e| Filter::Active.fits(e));
}
pub fn toggle_completed(&mut self, idx: usize) {
let entry = self.entries.get_mut(idx).unwrap();
entry.completed = !entry.completed;
}
pub fn set_completed(&mut self, value: bool) {
for entry in &mut self.entries {
if self.filter.fits(entry) {
entry.completed = value;
}
}
}
pub fn toggle_edit(&mut self, idx: usize) {
let entry = self.entries.get_mut(idx).unwrap();
entry.editing = !entry.editing;
}
pub fn clear_all_edit(&mut self) {
for entry in &mut self.entries {
entry.editing = false;
}
}
pub fn complete_edit(&mut self, idx: usize, val: String) {
if val.is_empty() {
self.remove(idx);
} else {
let entry = self.entries.get_mut(idx).unwrap();
entry.description = val;
entry.editing = !entry.editing;
}
}
pub fn remove(&mut self, idx: usize) {
self.entries.remove(idx);
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Entry {
pub description: String,
pub completed: bool,
pub editing: bool,
}
#[derive(Clone, Copy, Debug, EnumIter, Display, PartialEq, Serialize, Deserialize, Eq)]
pub enum Filter {
All,
Active,
Completed,
}
impl Filter {
pub fn fits(&self, entry: &Entry) -> bool {
match *self {
Filter::All => true,
Filter::Active => !entry.completed,
Filter::Completed => entry.completed,
}
}
pub fn as_href(&self) -> &'static str {
match self {
Filter::All => "#/",
Filter::Active => "#/active",
Filter::Completed => "#/completed",
}
}
}
impl IntoPropValue<Html> for Filter {
fn into_prop_value(self) -> yew::Html {
html! { <>{self.to_string()}</> }
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/todomvc/src/main.rs | examples/todomvc/src/main.rs | use gloo::storage::{LocalStorage, Storage};
use state::{Entry, Filter, State};
use strum::IntoEnumIterator;
use web_sys::HtmlInputElement as InputElement;
use yew::events::{FocusEvent, KeyboardEvent};
use yew::html::Scope;
use yew::{classes, html, Classes, Component, Context, Html, NodeRef, TargetCast};
mod state;
const KEY: &str = "yew.todomvc.self";
pub enum Msg {
Add(String),
Edit((usize, String)),
Remove(usize),
SetFilter(Filter),
ToggleAll,
ToggleEdit(usize),
Toggle(usize),
ClearCompleted,
Focus,
}
pub struct App {
state: State,
focus_ref: NodeRef,
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
let entries = LocalStorage::get(KEY).unwrap_or_else(|_| Vec::new());
let state = State::new(entries);
let focus_ref = NodeRef::default();
Self { state, focus_ref }
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Add(description) => {
let description = description.trim();
if !description.is_empty() {
let entry = Entry {
description: description.to_string(),
completed: false,
editing: false,
};
self.state.entries.push(entry);
}
}
Msg::Edit((idx, edit_value)) => {
self.state.complete_edit(idx, edit_value.trim().to_string());
self.state.edit_value = "".to_string();
}
Msg::Remove(idx) => {
self.state.remove(idx);
}
Msg::SetFilter(filter) => {
self.state.filter = filter;
}
Msg::ToggleEdit(idx) => {
let entry = self
.state
.entries
.iter()
.filter(|e| self.state.filter.fits(e))
.nth(idx)
.unwrap();
self.state.edit_value.clone_from(&entry.description);
self.state.clear_all_edit();
self.state.toggle_edit(idx);
}
Msg::ToggleAll => {
let status = !self.state.is_all_completed();
self.state.set_completed(status);
}
Msg::Toggle(idx) => {
self.state.toggle_completed(idx);
}
Msg::ClearCompleted => {
self.state.clear_completed();
}
Msg::Focus => {
if let Some(input) = self.focus_ref.cast::<InputElement>() {
input.focus().unwrap();
}
}
}
LocalStorage::set(KEY, &self.state.entries).expect("failed to set");
true
}
fn view(&self, ctx: &Context<Self>) -> Html {
let hidden_class = if self.state.entries.is_empty() {
"hidden"
} else {
""
};
html! {
<div class="todomvc-wrapper">
<section class="todoapp">
<header class="header">
<h1>{ "todos" }</h1>
{ self.view_input(ctx.link()) }
</header>
<section class={classes!("main", hidden_class)}>
<input
type="checkbox"
class="toggle-all"
id="toggle-all"
checked={self.state.is_all_completed()}
onclick={ctx.link().callback(|_| Msg::ToggleAll)}
/>
<label for="toggle-all" />
<ul class="todo-list">
{ for self
.state
.entries
.iter()
.enumerate()
.filter(|(_, entry)| self.state.filter.fits(entry))
.map(|(i, e)| self.view_entry((i, e), ctx.link()))
}
</ul>
</section>
<footer class={classes!("footer", hidden_class)}>
<span class="todo-count">
<strong>{ self.state.total() }</strong>
{ " item(s) left" }
</span>
<ul class="filters">
{ for Filter::iter().map(|flt| self.view_filter(flt, ctx.link())) }
</ul>
<button class="clear-completed" onclick={ctx.link().callback(|_| Msg::ClearCompleted)}>
{ format!("Clear completed ({})", self.state.total_completed()) }
</button>
</footer>
</section>
<footer class="info">
<p>{ "Double-click to edit a todo" }</p>
<p>{ "Written by " }<a href="https://github.com/DenisKolodin/" target="_blank">{ "Denis Kolodin" }</a></p>
<p>{ "Part of " }<a href="http://todomvc.com/" target="_blank">{ "TodoMVC" }</a></p>
</footer>
</div>
}
}
}
impl App {
fn view_filter(&self, filter: Filter, link: &Scope<Self>) -> Html {
let cls = if self.state.filter == filter {
"selected"
} else {
"not-selected"
};
html! {
<li>
<a class={cls}
href={filter.as_href()}
onclick={link.callback(move |_| Msg::SetFilter(filter))}
>
{ filter }
</a>
</li>
}
}
fn view_input(&self, link: &Scope<Self>) -> Html {
let onkeypress = link.batch_callback(|e: KeyboardEvent| {
if e.key() == "Enter" {
let input: InputElement = e.target_unchecked_into();
let value = input.value();
input.set_value("");
Some(Msg::Add(value))
} else {
None
}
});
html! {
// You can use standard Rust comments. One line:
// <li></li>
<input
class="new-todo"
placeholder="What needs to be done?"
{onkeypress}
/>
/* Or multiline:
<ul>
<li></li>
</ul>
*/
}
}
fn view_entry(&self, (idx, entry): (usize, &Entry), link: &Scope<Self>) -> Html {
let mut class = Classes::from("todo");
if entry.editing {
class.push(" editing");
}
if entry.completed {
class.push(" completed");
}
html! {
<li {class}>
<div class="view">
<input
type="checkbox"
class="toggle"
checked={entry.completed}
onclick={link.callback(move |_| Msg::Toggle(idx))}
/>
<label ondblclick={link.callback(move |_| Msg::ToggleEdit(idx))}>{ &entry.description }</label>
<button class="destroy" onclick={link.callback(move |_| Msg::Remove(idx))} />
</div>
{ self.view_entry_edit_input((idx, entry), link) }
</li>
}
}
fn view_entry_edit_input(&self, (idx, entry): (usize, &Entry), link: &Scope<Self>) -> Html {
let edit = move |input: InputElement| {
let value = input.value();
input.set_value("");
Msg::Edit((idx, value))
};
let onblur = link.callback(move |e: FocusEvent| edit(e.target_unchecked_into()));
let onkeypress = link.batch_callback(move |e: KeyboardEvent| {
(e.key() == "Enter").then(|| edit(e.target_unchecked_into()))
});
if entry.editing {
html! {
<input
class="edit"
type="text"
ref={self.focus_ref.clone()}
value={self.state.edit_value.clone()}
onmouseover={link.callback(|_| Msg::Focus)}
{onblur}
{onkeypress}
/>
}
} else {
html! { <input type="hidden" /> }
}
}
}
fn main() {
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/communication_grandparent_to_grandchild/src/grandparent.rs | examples/communication_grandparent_to_grandchild/src/grandparent.rs | use super::*;
/// Our top-level (grandparent) component that holds a reference to the shared state.
pub struct GrandParent {
state: Rc<AppState>,
}
pub enum Msg {
ButtonClick,
}
impl Component for GrandParent {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
let state = Rc::new(AppState { total_clicks: 0 });
Self { state }
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::ButtonClick => {
Rc::make_mut(&mut self.state).total_clicks += 1;
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let onclick = ctx.link().callback(|_| Msg::ButtonClick);
let app_state = self.state.clone();
html! {
<ContextProvider<Rc<AppState>> context={app_state}>
<div class="grandparent">
<div>
<h2 class="title">{ "Grandparent-to-Grandchild Communication Example" }</h2>
<div class="grandparent-body">
<div class="grandparent-tag">
<span>{ "Grandparent" }</span>
</div>
<div class="grandparent-content">
<button {onclick}>{"Click"}</button>
<Parent />
</div>
</div>
</div>
</div>
</ContextProvider<Rc<AppState>>>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/communication_grandparent_to_grandchild/src/child.rs | examples/communication_grandparent_to_grandchild/src/child.rs | use super::*;
/// The `Child` component is the child of the `Parent` component, and will receive updates from the
/// grandparent using the context.
pub struct Child {
state: Rc<AppState>,
_listener: ContextHandle<Rc<AppState>>,
}
pub enum ChildMsg {
ContextChanged(Rc<AppState>),
}
impl Component for Child {
type Message = ChildMsg;
type Properties = ();
fn create(ctx: &Context<Self>) -> Self {
// Here we fetch the shared state from the context. For a demonstration on the use of
// context in a functional component, have a look at the `examples/contexts` code.
let (state, _listener) = ctx
.link()
.context::<Rc<AppState>>(ctx.link().callback(ChildMsg::ContextChanged))
.expect("context to be set");
Self { state, _listener }
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
ChildMsg::ContextChanged(state) => {
self.state = state;
true
}
}
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {
<div class="child-body">
<div class="child-tag">
<span>{ "Child" }</span>
</div>
<div class="child-content">
<span>{ "My grandparent has been clicked " }<span>{ self.state.total_clicks }</span>{ " times." }</span>
</div>
</div>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/communication_grandparent_to_grandchild/src/main.rs | examples/communication_grandparent_to_grandchild/src/main.rs | use std::rc::Rc;
use child::Child;
use grandparent::GrandParent;
use parent::Parent;
mod child;
mod grandparent;
mod parent;
use yew::{function_component, html, Component, Context, ContextHandle, ContextProvider, Html};
/// This is the shared state between the parent and child components.
#[derive(Clone, Eq, PartialEq)]
pub struct AppState {
/// The total number of clicks received.
total_clicks: u32,
}
fn main() {
yew::Renderer::<GrandParent>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/communication_grandparent_to_grandchild/src/parent.rs | examples/communication_grandparent_to_grandchild/src/parent.rs | use super::*;
/// The `Parent` component is the parent of the `Child` component. It has no logic, and is here to
/// show there is no direct relation between grandchild and grandparent.
#[function_component]
pub fn Parent() -> Html {
html! {
<div class="parent-body">
<div class="parent-tag">
<span>{ "Parent" }</span>
</div>
<div class="parent-content">
<Child />
</div>
</div>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/communication_parent_to_child/src/child.rs | examples/communication_parent_to_child/src/child.rs | use super::*;
/// The `Child` component is the child of the `Parent` component, and will receive updates from the
/// parent using properties.
pub struct Child;
#[derive(Clone, Eq, PartialEq, Properties)]
pub struct ChildProps {
pub clicks: u32,
}
impl Component for Child {
type Message = ();
type Properties = ChildProps;
fn create(_ctx: &Context<Self>) -> Self {
Self {}
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<div class="child-body">
<div class="child-tag">
<span>{ "Child" }</span>
</div>
<div class="child-content">
<span>{ "My parent has been clicked " }<span>{ ctx.props().clicks }</span>{ " times." }</span>
</div>
</div>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/communication_parent_to_child/src/main.rs | examples/communication_parent_to_child/src/main.rs | use child::Child;
use parent::Parent;
use yew::{html, Component, Context, Html, Properties};
mod child;
mod parent;
fn main() {
yew::Renderer::<Parent>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/communication_parent_to_child/src/parent.rs | examples/communication_parent_to_child/src/parent.rs | use super::*;
/// The `Parent` component holds some state that is passed down to the children.
pub struct Parent {
/// The total number of clicks received
nr_of_clicks: u32,
}
pub enum Msg {
ButtonClick,
}
impl Component for Parent {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self { nr_of_clicks: 0 }
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::ButtonClick => {
self.nr_of_clicks += 1;
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let onclick = ctx.link().callback(|_| Msg::ButtonClick);
// Here we pass down "our" nr_of_clicks to the child by setting the "clicks" property.
let clicks = self.nr_of_clicks;
html! {
<div class="parent">
<div>
<h2 class="title">{ "Parent-to-Child Communication Example" }</h2>
<div class="parent-body">
<div class="parent-tag">
<span>{ "Parent" }</span>
</div>
<div class="parent-content">
<button {onclick}>{"Click"}</button>
<Child {clicks} />
</div>
</div>
</div>
</div>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/immutable/src/array.rs | examples/immutable/src/array.rs | use implicit_clone::unsync::*;
use wasm_bindgen::{JsCast, UnwrapThrowExt};
use web_sys::{HtmlInputElement, KeyboardEvent};
use yew::prelude::*;
#[derive(Properties, PartialEq)]
struct FolksViewProps {
folks: IArray<IString>,
}
#[function_component(FolksView)]
fn folks_view(props: &FolksViewProps) -> Html {
html! {
<>
<p>{"Hello to:"}</p>
<ul>
{ for props.folks.iter().map(|s| html!(<li>{s}</li>)) }
</ul>
</>
}
}
#[function_component(ArrayExample)]
pub fn array_example() -> Html {
let folks = use_state(IArray::<IString>::default);
let onkeyup = {
let folks = folks.clone();
Callback::from(move |e: KeyboardEvent| {
if e.key() == "Enter" {
let event: Event = e.dyn_into().unwrap_throw();
let event_target = event.target().unwrap_throw();
let target: HtmlInputElement = event_target.dyn_into().unwrap_throw();
let name = target.value();
target.set_value("");
folks.set(
folks
.iter()
.cloned()
.chain(std::iter::once(IString::from(name)))
.collect(),
);
}
})
};
html! {
<>
<h2>{"Input"}</h2>
<input {onkeyup} />
<h2>{"Output"}</h2>
<FolksView folks={&*folks} />
</>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/immutable/src/string.rs | examples/immutable/src/string.rs | use implicit_clone::unsync::*;
use wasm_bindgen::{JsCast, UnwrapThrowExt};
use web_sys::{HtmlInputElement, InputEvent};
use yew::prelude::*;
#[derive(Properties, PartialEq)]
struct DisplayProps {
name: IString,
}
#[function_component]
fn Display(props: &DisplayProps) -> Html {
html! {
<p>{"Hello "}{&props.name}{"!"}</p>
}
}
pub struct StringExample {
name: IString,
}
pub enum StringExampleMessage {
UpdateName(String),
}
impl Component for StringExample {
type Message = StringExampleMessage;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
name: "World".into(),
}
}
fn update(&mut self, _: &Context<Self>, msg: Self::Message) -> bool {
match msg {
StringExampleMessage::UpdateName(name) => {
self.name = name.into();
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let link = ctx.link();
let oninput = link.callback(|e: InputEvent| {
let event: Event = e.dyn_into().unwrap_throw();
let event_target = event.target().unwrap_throw();
let target: HtmlInputElement = event_target.dyn_into().unwrap_throw();
StringExampleMessage::UpdateName(target.value())
});
html! {
<>
<h2>{"Input"}</h2>
<input value={&self.name} {oninput} />
<h2>{"Output"}</h2>
<Display name={&self.name} />
</>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/immutable/src/map.rs | examples/immutable/src/map.rs | use implicit_clone::unsync::*;
use wasm_bindgen::{JsCast, UnwrapThrowExt};
use web_sys::{HtmlInputElement, KeyboardEvent};
use yew::prelude::*;
#[derive(Properties, PartialEq)]
struct DisplayProps {
values: IMap<u32, IString>,
}
#[function_component]
fn Display(props: &DisplayProps) -> Html {
html! {
<>
<p>{"Hello to:"}</p>
<ul>
{ for props.values.iter().map(|(i, s)| html!(<li>{i}{" => "}{s}</li>)) }
</ul>
</>
}
}
pub struct MapExample {
values: IMap<u32, IString>,
}
pub enum MapExampleMessage {
AddName(String),
Noop,
}
impl Component for MapExample {
type Message = MapExampleMessage;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
values: Default::default(),
}
}
fn update(&mut self, _: &Context<Self>, msg: Self::Message) -> bool {
match msg {
MapExampleMessage::AddName(name) => {
self.values = self
.values
.iter()
.map(|(&k, v)| (k, v.clone()))
.chain(std::iter::once((
self.values.len() as u32,
IString::from(name),
)))
.collect();
true
}
MapExampleMessage::Noop => false,
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let link = ctx.link();
let onkeyup = link.callback(|e: KeyboardEvent| {
if e.key() == "Enter" {
let event: Event = e.dyn_into().unwrap_throw();
let event_target = event.target().unwrap_throw();
let target: HtmlInputElement = event_target.dyn_into().unwrap_throw();
let value = target.value();
target.set_value("");
MapExampleMessage::AddName(value)
} else {
MapExampleMessage::Noop
}
});
html! {
<>
<h2>{"Input"}</h2>
<input {onkeyup} />
<h2>{"Output"}</h2>
<Display values={&self.values} />
</>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/immutable/src/main.rs | examples/immutable/src/main.rs | mod array;
mod map;
mod string;
use yew::prelude::*;
use self::array::*;
use self::map::*;
use self::string::*;
#[function_component]
fn App() -> Html {
html! {
<>
<h1>{ "IString Example" }</h1>
<StringExample />
<hr/>
<h1>{ "IArray Example" }</h1>
<ArrayExample />
<hr/>
<h1>{ "IMap Example" }</h1>
<MapExample />
</>
}
}
fn main() {
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/web_worker_prime/src/lib.rs | examples/web_worker_prime/src/lib.rs | pub mod agent;
use agent::{ControlSignal, PrimeReactor};
use yew::prelude::*;
use yew_agent::reactor::{use_reactor_subscription, ReactorProvider};
#[function_component]
fn Main() -> Html {
let prime_sub = use_reactor_subscription::<PrimeReactor>();
let started = use_state_eq(|| false);
let skip_len = use_state_eq(|| 0);
let result_s = prime_sub
.iter()
// Skip results in previous runs.
.skip(*skip_len)
.fold("".to_string(), |mut output, item| {
if !output.is_empty() {
output.push_str(", ");
}
output.push_str(&item.to_string());
output
});
let start_prime_calc = use_callback(
(prime_sub.clone(), started.setter(), skip_len.setter()),
|_input, (prime_sub, started_setter, skip_len)| {
skip_len.set(prime_sub.len());
prime_sub.send(ControlSignal::Start);
started_setter.set(true);
},
);
let stop_prime_calc = use_callback(
(prime_sub, started.setter()),
|_input, (prime_sub, started_setter)| {
prime_sub.send(ControlSignal::Stop);
started_setter.set(false);
},
);
html! {
<>
<h1>{"Find Prime"}</h1>
<p>{"This page demonstrates how to calculate prime in a web worker."}</p>
if *started {
<button onclick={stop_prime_calc}>{"Stop"}</button>
} else {
<button onclick={start_prime_calc}>{"Start"}</button>
}
<div id="result">{result_s}</div>
</>
}
}
#[function_component]
pub fn App() -> Html {
html! {
<ReactorProvider<PrimeReactor> path="/worker.js">
<Main />
</ReactorProvider<PrimeReactor>>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/web_worker_prime/src/agent.rs | examples/web_worker_prime/src/agent.rs | use std::time::Duration;
use futures::sink::SinkExt;
use futures::{FutureExt, StreamExt};
use serde::{Deserialize, Serialize};
use yew::platform::time::sleep;
use yew_agent::prelude::*;
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ControlSignal {
Start,
Stop,
}
#[reactor]
pub async fn PrimeReactor(mut scope: ReactorScope<ControlSignal, u64>) {
while let Some(m) = scope.next().await {
if m == ControlSignal::Start {
'inner: for i in 1.. {
// This is not the most efficient way to calculate prime,
// but this example is here to demonstrate how primes can be
// sent to the application in an ascending order.
if primes::is_prime(i) {
scope.send(i).await.unwrap();
}
futures::select! {
m = scope.next() => {
if m == Some(ControlSignal::Stop) {
break 'inner;
}
},
_ = sleep(Duration::from_millis(100)).fuse() => {},
}
}
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/web_worker_prime/src/bin/app.rs | examples/web_worker_prime/src/bin/app.rs | fn main() {
yew::Renderer::<yew_worker_prime::App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/web_worker_prime/src/bin/worker.rs | examples/web_worker_prime/src/bin/worker.rs | use yew_agent::Registrable;
use yew_worker_prime::agent::PrimeReactor;
fn main() {
PrimeReactor::registrar().register();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/portals/src/main.rs | examples/portals/src/main.rs | use wasm_bindgen::JsCast;
use web_sys::{Element, ShadowRootInit, ShadowRootMode};
use yew::{create_portal, html, Component, Context, Html, NodeRef, Properties};
#[derive(Properties, PartialEq)]
pub struct ShadowDOMProps {
#[prop_or_default]
pub children: Html,
}
pub struct ShadowDOMHost {
host_ref: NodeRef,
inner_host: Option<Element>,
}
impl Component for ShadowDOMHost {
type Message = ();
type Properties = ShadowDOMProps;
fn create(_: &Context<Self>) -> Self {
Self {
host_ref: NodeRef::default(),
inner_host: None,
}
}
fn rendered(&mut self, ctx: &Context<Self>, first_render: bool) {
if first_render {
let shadow_root = self
.host_ref
.get()
.expect("rendered host")
.unchecked_into::<Element>()
.attach_shadow(&ShadowRootInit::new(ShadowRootMode::Open))
.expect("installing shadow root succeeds");
let inner_host = gloo::utils::document()
.create_element("div")
.expect("can create inner wrapper");
shadow_root
.append_child(&inner_host)
.expect("can attach inner host");
self.inner_host = Some(inner_host);
ctx.link().send_message(());
}
}
fn update(&mut self, _: &Context<Self>, _: Self::Message) -> bool {
true
}
fn view(&self, ctx: &Context<Self>) -> Html {
let contents = if let Some(ref inner_host) = self.inner_host {
create_portal(ctx.props().children.clone(), inner_host.clone())
} else {
html! { <></> }
};
html! {
<div ref={self.host_ref.clone()}>
{contents}
</div>
}
}
}
pub struct App {
style_html: Html,
title_element: Element,
counter: u32,
}
pub enum AppMessage {
IncreaseCounter,
}
impl Component for App {
type Message = AppMessage;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
let document_head = gloo::utils::document()
.head()
.expect("head element to be present");
let title_element = document_head
.query_selector("title")
.expect("to find a title element")
.expect("to find a title element");
title_element.set_text_content(None); // Clear the title element
let style_html = create_portal(
html! {
<style>{"p { color: red; }"}</style>
},
document_head.into(),
);
Self {
style_html,
title_element,
counter: 0,
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
AppMessage::IncreaseCounter => self.counter += 1,
}
true
}
fn view(&self, ctx: &Context<Self>) -> Html {
let onclick = ctx.link().callback(|_| AppMessage::IncreaseCounter);
let title = create_portal(
html! {
if self.counter > 0 {
{format!("Clicked {} times", self.counter)}
} else {
{"Yew • Portals"}
}
},
self.title_element.clone(),
);
html! {
<>
{self.style_html.clone()}
{title}
<p>{"This paragraph is colored red, and its style is mounted into "}<pre>{"document.head"}</pre>{" with a portal"}</p>
<div>
<ShadowDOMHost>
<p>{"This paragraph is rendered in a shadow dom and thus not affected by the surrounding styling context"}</p>
<span>{"Buttons clicked inside the shadow dom work fine."}</span>
<button {onclick}>{"Click me!"}</button>
</ShadowDOMHost>
<p>{format!("The button has been clicked {} times. This is also reflected in the title of the tab!", self.counter)}</p>
</div>
</>
}
}
}
fn main() {
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/ssr_router/src/lib.rs | examples/ssr_router/src/lib.rs | rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false | |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/ssr_router/src/bin/ssr_router_server.rs | examples/ssr_router/src/bin/ssr_router_server.rs | use std::collections::HashMap;
use std::convert::Infallible;
use std::future::Future;
use std::net::SocketAddr;
use std::path::PathBuf;
use axum::body::Body;
use axum::extract::{Query, Request, State};
use axum::handler::HandlerWithoutStateExt;
use axum::http::Uri;
use axum::response::IntoResponse;
use axum::routing::get;
use axum::Router;
use clap::Parser;
use function_router::{ServerApp, ServerAppProps};
use futures::stream::{self, StreamExt};
use hyper::body::Incoming;
use hyper_util::rt::TokioIo;
use hyper_util::server;
use tokio::net::TcpListener;
use tower::Service;
use tower_http::services::ServeDir;
use yew::platform::Runtime;
// We use jemalloc as it produces better performance.
#[cfg(unix)]
#[global_allocator]
static GLOBAL: jemallocator::Jemalloc = jemallocator::Jemalloc;
/// A basic example
#[derive(Parser, Debug)]
struct Opt {
/// the "dist" created by trunk directory to be served for hydration.
#[clap(short, long)]
dir: PathBuf,
}
async fn render(
url: Uri,
Query(queries): Query<HashMap<String, String>>,
State((index_html_before, index_html_after)): State<(String, String)>,
) -> impl IntoResponse {
let url = url.path().to_owned();
let renderer = yew::ServerRenderer::<ServerApp>::with_props(move || ServerAppProps {
url: url.into(),
queries,
});
Body::from_stream(
stream::once(async move { index_html_before })
.chain(renderer.render_stream())
.chain(stream::once(async move { index_html_after }))
.map(Result::<_, Infallible>::Ok),
)
}
// An executor to process requests on the Yew runtime.
//
// By spawning requests on the Yew runtime,
// it processes request on the same thread as the rendering task.
//
// This increases performance in some environments (e.g.: in VM).
#[derive(Clone, Default)]
struct Executor {
inner: Runtime,
}
impl<F> hyper::rt::Executor<F> for Executor
where
F: Future + Send + 'static,
{
fn execute(&self, fut: F) {
self.inner.spawn_pinned(move || async move {
fut.await;
});
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let exec = Executor::default();
env_logger::init();
let opts = Opt::parse();
let index_html_s = tokio::fs::read_to_string(opts.dir.join("index.html"))
.await
.expect("failed to read index.html");
let (index_html_before, index_html_after) = index_html_s.split_once("<body>").unwrap();
let mut index_html_before = index_html_before.to_owned();
index_html_before.push_str("<body>");
let index_html_after = index_html_after.to_owned();
let app = Router::new().fallback_service(
ServeDir::new(opts.dir)
.append_index_html_on_directories(false)
.fallback(
get(render)
.with_state((index_html_before.clone(), index_html_after.clone()))
.into_service(),
),
);
let addr: SocketAddr = ([127, 0, 0, 1], 8080).into();
println!("You can view the website at: http://localhost:8080/");
let listener = TcpListener::bind(addr).await?;
// Continuously accept new connections.
loop {
// In this example we discard the remote address. See `fn serve_with_connect_info` for how
// to expose that.
let (socket, _remote_addr) = listener.accept().await.unwrap();
// We don't need to call `poll_ready` because `Router` is always ready.
let tower_service = app.clone();
let exec = exec.clone();
// Spawn a task to handle the connection. That way we can handle multiple connections
// concurrently.
tokio::spawn(async move {
// Hyper has its own `AsyncRead` and `AsyncWrite` traits and doesn't use tokio.
// `TokioIo` converts between them.
let socket = TokioIo::new(socket);
// Hyper also has its own `Service` trait and doesn't use tower. We can use
// `hyper::service::service_fn` to create a hyper `Service` that calls our app through
// `tower::Service::call`.
let hyper_service = hyper::service::service_fn(move |request: Request<Incoming>| {
// We have to clone `tower_service` because hyper's `Service` uses `&self` whereas
// tower's `Service` requires `&mut self`.
//
// We don't need to call `poll_ready` since `Router` is always ready.
tower_service.clone().call(request)
});
// `server::conn::auto::Builder` supports both http1 and http2.
//
// `TokioExecutor` tells hyper to use `tokio::spawn` to spawn tasks.
if let Err(err) = server::conn::auto::Builder::new(exec)
// `serve_connection_with_upgrades` is required for websockets. If you don't need
// that you can use `serve_connection` instead.
.serve_connection_with_upgrades(socket, hyper_service)
.await
{
eprintln!("failed to serve connection: {err:#}");
}
});
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/ssr_router/src/bin/ssr_router_hydrate.rs | examples/ssr_router/src/bin/ssr_router_hydrate.rs | use function_router::App;
fn main() {
#[cfg(target_arch = "wasm32")]
wasm_logger::init(wasm_logger::Config::new(log::Level::Trace));
yew::Renderer::<App>::new().hydrate();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/timer/src/main.rs | examples/timer/src/main.rs | use gloo::console::{self, Timer};
use gloo::timers::callback::{Interval, Timeout};
use yew::prelude::*;
pub enum Msg {
StartTimeout,
StartInterval,
Cancel,
Done,
Tick,
UpdateTime,
}
pub struct App {
time: String,
messages: Vec<AttrValue>,
_standalone: (Interval, Interval),
interval: Option<Interval>,
timeout: Option<Timeout>,
console_timer: Option<Timer<'static>>,
}
impl App {
fn get_current_time() -> String {
let date = js_sys::Date::new_0();
String::from(date.to_locale_time_string("en-US"))
}
fn cancel(&mut self) {
self.timeout = None;
self.interval = None;
}
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(ctx: &Context<Self>) -> Self {
let standalone_handle =
Interval::new(10, || console::debug!("Example of a standalone callback."));
let clock_handle = {
let link = ctx.link().clone();
Interval::new(1, move || link.send_message(Msg::UpdateTime))
};
Self {
time: App::get_current_time(),
messages: Vec::new(),
_standalone: (standalone_handle, clock_handle),
interval: None,
timeout: None,
console_timer: None,
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::StartTimeout => {
let handle = {
let link = ctx.link().clone();
Timeout::new(3000, move || link.send_message(Msg::Done))
};
self.timeout = Some(handle);
self.messages.clear();
console::clear!();
self.log("Timer started!");
self.console_timer = Some(Timer::new("Timer"));
true
}
Msg::StartInterval => {
let handle = {
let link = ctx.link().clone();
Interval::new(1000, move || link.send_message(Msg::Tick))
};
self.interval = Some(handle);
self.messages.clear();
console::clear!();
self.log("Interval started!");
true
}
Msg::Cancel => {
self.cancel();
self.log("Canceled!");
console::warn!("Canceled!");
true
}
Msg::Done => {
self.cancel();
self.log("Done!");
// todo weblog
// ConsoleService::group();
console::info!("Done!");
if let Some(timer) = self.console_timer.take() {
drop(timer);
}
// todo weblog
// ConsoleService::group_end();
true
}
Msg::Tick => {
self.log("Tick...");
// todo weblog
// ConsoleService::count_named("Tick");
true
}
Msg::UpdateTime => {
self.time = App::get_current_time();
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let has_job = self.timeout.is_some() || self.interval.is_some();
html! {
<>
<div id="buttons">
<button disabled={has_job} onclick={ctx.link().callback(|_| Msg::StartTimeout)}>
{ "Start Timeout" }
</button>
<button disabled={has_job} onclick={ctx.link().callback(|_| Msg::StartInterval)}>
{ "Start Interval" }
</button>
<button disabled={!has_job} onclick={ctx.link().callback(|_| Msg::Cancel)}>
{ "Cancel!" }
</button>
</div>
<div id="wrapper">
<div id="time">
{ &self.time }
</div>
<div id="messages">
{ for self.messages.iter().map(|message| html! { <p>{ message }</p> }) }
</div>
</div>
</>
}
}
}
impl App {
fn log(&mut self, message: impl Into<AttrValue>) {
self.messages.push(message.into());
}
}
fn main() {
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/mount_point/src/main.rs | examples/mount_point/src/main.rs | use wasm_bindgen::JsValue;
use web_sys::{
CanvasRenderingContext2d, Document, HtmlCanvasElement, HtmlInputElement, InputEvent,
};
use yew::{html, Component, Context, Html, TargetCast};
pub enum Msg {
UpdateName(String),
}
pub struct App {
name: String,
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
name: "Reversed".to_owned(),
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::UpdateName(new_name) => {
self.name = new_name;
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<div>
<input
value={self.name.clone()}
oninput={ctx.link().callback(|e: InputEvent| {
let input = e.target_unchecked_into::<HtmlInputElement>();
Msg::UpdateName(input.value())
})}
/>
<p>{ self.name.chars().rev().collect::<String>() }</p>
</div>
}
}
}
fn create_canvas(document: &Document) -> HtmlCanvasElement {
let canvas = HtmlCanvasElement::from(JsValue::from(document.create_element("canvas").unwrap()));
canvas.set_width(100);
canvas.set_height(100);
let ctx =
CanvasRenderingContext2d::from(JsValue::from(canvas.get_context("2d").unwrap().unwrap()));
ctx.set_fill_style_str("green");
ctx.fill_rect(10., 10., 50., 50.);
canvas
}
fn main() {
let document = gloo::utils::document();
let body = document.query_selector("body").unwrap().unwrap();
let canvas = create_canvas(&document);
// This canvas won't be overwritten by yew!
body.append_child(&canvas).unwrap();
let mount_point = document.create_element("div").unwrap();
let class_list = mount_point.class_list();
class_list.add_1("mount-point").unwrap();
body.append_child(&mount_point).unwrap();
yew::Renderer::<App>::with_root(mount_point).render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/file_upload/src/main.rs | examples/file_upload/src/main.rs | extern crate base64;
use std::collections::HashMap;
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use gloo::file::callbacks::FileReader;
use web_sys::{DragEvent, Event, HtmlInputElement};
use yew::html::TargetCast;
use yew::{html, Callback, Component, Context, Html};
pub struct FileDetails {
name: String,
file_type: String,
data: Vec<u8>,
}
pub enum Msg {
Loaded(FileDetails),
Files(Option<web_sys::FileList>),
}
pub struct App {
readers: HashMap<String, FileReader>,
files: Vec<FileDetails>,
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
readers: HashMap::default(),
files: Vec::default(),
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Loaded(file) => {
self.readers.remove(&file.name);
self.files.push(file);
true
}
Msg::Files(files) => {
for file in gloo::file::FileList::from(files.expect("files")).iter() {
let link = ctx.link().clone();
let name = file.name().clone();
let file_type = file.raw_mime_type();
let task = {
gloo::file::callbacks::read_as_bytes(file, move |res| {
link.send_message(Msg::Loaded(FileDetails {
data: res.expect("failed to read file"),
file_type,
name,
}))
})
};
self.readers.insert(file.name(), task);
}
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let noop_drag = Callback::from(|e: DragEvent| {
e.prevent_default();
});
html! {
<div id="wrapper">
<p id="title">{ "Upload Your Files To The Cloud" }</p>
<label for="file-upload">
<div
id="drop-container"
ondrop={ctx.link().callback(|event: DragEvent| {
event.prevent_default();
Msg::Files(event.data_transfer().unwrap().files())
})}
ondragover={&noop_drag}
ondragenter={&noop_drag}
>
<i class="fa fa-cloud-upload"></i>
<p>{"Drop your images here or click to select"}</p>
</div>
</label>
<input
id="file-upload"
type="file"
accept="image/*,video/*"
multiple={true}
onchange={ctx.link().callback(move |e: Event| {
let input: HtmlInputElement = e.target_unchecked_into();
Msg::Files(input.files())
})}
/>
<div id="preview-area">
{ for self.files.iter().map(Self::view_file) }
</div>
</div>
}
}
}
impl App {
fn view_file(file: &FileDetails) -> Html {
let file_type = file.file_type.to_string();
let src = format!("data:{};base64,{}", file_type, STANDARD.encode(&file.data));
html! {
<div class="preview-tile">
<p class="preview-name">{ &file.name }</p>
<div class="preview-media">
if file.file_type.contains("image") {
<img src={src} />
} else if file.file_type.contains("video") {
<video controls={true}>
<source src={src} type={ file_type }/>
</video>
}
</div>
</div>
}
}
}
fn main() {
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/js_callback/trunk_post_build.rs | examples/js_callback/trunk_post_build.rs | use std::fs;
use std::io::{Read, Write};
fn read_env(env: &'static str) -> String {
std::env::var(env).unwrap_or_else(|e| panic!("can't read {} env var: {}", env, e))
}
fn main() {
let stage_dir = read_env("TRUNK_STAGING_DIR");
let mut res = fs::read_dir(format!("{stage_dir}/snippets")).expect("no snippets dir in stage");
let dir = res
.next()
.expect("there must be one snippets dir present")
.expect("can't read snippets dir");
let dir_name = dir.file_name().to_string_lossy().to_string();
let mut index_html =
fs::File::open(format!("{stage_dir}/index.html")).expect("can't open index.html");
let mut html = String::new();
index_html
.read_to_string(&mut html)
.expect("can't read index.html");
let mut split = html
.split("</head>")
.map(|it| it.to_string())
.collect::<Vec<String>>();
let public_url = read_env("TRUNK_PUBLIC_URL");
let public_url = public_url.strip_suffix("/").unwrap_or(&public_url);
let wasm_bindgen_snippets_path = format!("{public_url}/snippets/{dir_name}");
split.insert(1, format!("<script>window.wasmBindgenSnippetsPath = '{wasm_bindgen_snippets_path}';</script></head>"));
let joined = split.join("");
drop(index_html);
let mut index_html = fs::File::options()
.write(true)
.truncate(true)
.open(format!("{stage_dir}/index.html"))
.expect("can't open index.html");
index_html
.write_all(joined.as_ref())
.expect("can't write index.html")
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/js_callback/src/bindings.rs | examples/js_callback/src/bindings.rs | use wasm_bindgen::prelude::*;
// https://github.com/rustwasm/wasm-bindgen/issues/3208
#[wasm_bindgen(inline_js = "export function import2(path) { return import(path); }")]
extern "C" {
// this should be in js-sys but is not. see https://github.com/rustwasm/wasm-bindgen/issues/2865
// pub fn import(s: &str) -> js_sys::Promise;
#[wasm_bindgen(js_name = "import2")]
pub fn import(name: &str) -> js_sys::Promise;
pub type Window;
#[wasm_bindgen(method, getter, js_name = "wasmBindgenSnippetsPath")]
pub fn wasm_bindgen_snippets_path(this: &Window) -> String;
}
#[wasm_bindgen(module = "/js/imp.js")]
extern "C" {
#[wasm_bindgen]
pub fn hello() -> String;
}
#[wasm_bindgen]
extern "C" {
pub type UnimpModule;
#[wasm_bindgen(method)]
pub fn bye(this: &UnimpModule) -> String;
}
#[wasm_bindgen(module = "/js/unimp.js")]
extern "C" {
/// This exists so that wasm bindgen copies js/unimp.js to
/// dist/snippets/<bin-name>-<hash>/js/uninp.js
#[wasm_bindgen]
fn _dummy_fn_so_wasm_bindgen_copies_over_the_file();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/js_callback/src/main.rs | examples/js_callback/src/main.rs | use once_cell::sync::OnceCell;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use yew::prelude::*;
use yew::suspense::{use_future, SuspensionResult};
mod bindings;
static WASM_BINDGEN_SNIPPETS_PATH: OnceCell<String> = OnceCell::new();
#[function_component]
fn Important() -> Html {
let msg = use_memo((), |_| bindings::hello());
html! {
<>
<h2>{"Important"}</h2>
<p>{msg}</p>
</>
}
}
#[hook]
fn use_do_bye() -> SuspensionResult<String> {
let path = WASM_BINDGEN_SNIPPETS_PATH
.get()
.map(|path| format!("{path}/js/unimp.js"))
.unwrap();
let s = use_future(|| async move {
let promise = bindings::import(&path);
let module = JsFuture::from(promise).await.unwrap_throw();
let module = module.unchecked_into::<bindings::UnimpModule>();
module.bye()
})?;
Ok((*s).clone())
}
#[function_component]
fn UnImportant() -> HtmlResult {
let msg = use_do_bye()?;
Ok(html! {
<>
<h2>{"Unimportant"}</h2>
<p>{msg}</p>
</>
})
}
#[function_component]
fn App() -> Html {
let showing_unimportant = use_state(|| false);
let show_unimportant = {
let showing_unimportant = showing_unimportant.clone();
move |_| showing_unimportant.set(true)
};
let fallback = html! {"fallback"};
html! {
<main>
<Important />
<button onclick={show_unimportant}>{"load unimportant data"}</button>
<Suspense {fallback}>
if *showing_unimportant {
<UnImportant />
}
</Suspense>
</main>
}
}
fn main() {
let wasm_bindgen_snippets_path = js_sys::global()
.unchecked_into::<bindings::Window>()
.wasm_bindgen_snippets_path();
WASM_BINDGEN_SNIPPETS_PATH
.set(wasm_bindgen_snippets_path)
.expect("unreachable");
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/counter/src/main.rs | examples/counter/src/main.rs | use gloo::console;
use js_sys::Date;
use yew::{html, Component, Context, Html};
// Define the possible messages which can be sent to the component
pub enum Msg {
Increment,
Decrement,
}
pub struct App {
value: i64, // This will store the counter value
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self { value: 0 }
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Increment => {
self.value += 1;
console::log!("plus one"); // Will output a string to the browser console
true // Return true to cause the displayed change to update
}
Msg::Decrement => {
self.value -= 1;
console::log!("minus one");
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<div>
<div class="panel">
// A button to send the Increment message
<button class="button" onclick={ctx.link().callback(|_| Msg::Increment)}>
{ "+1" }
</button>
// A button to send the Decrement message
<button onclick={ctx.link().callback(|_| Msg::Decrement)}>
{ "-1" }
</button>
// A button to send two Increment messages
<button onclick={ctx.link().batch_callback(|_| vec![Msg::Increment, Msg::Increment])}>
{ "+1, +1" }
</button>
</div>
// Display the current value of the counter
<p class="counter">
{ self.value }
</p>
// Display the current date and time the page was rendered
<p class="footer">
{ "Rendered: " }
{ String::from(Date::new_0().to_string()) }
</p>
</div>
}
}
}
fn main() {
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/webgl/src/main.rs | examples/webgl/src/main.rs | use std::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::{window, HtmlCanvasElement, WebGlRenderingContext as GL, WebGlRenderingContext};
use yew::{html, Component, Context, Html, NodeRef};
// Wrap gl in Rc (Arc for multi-threaded) so it can be injected into the render-loop closure.
pub struct App {
node_ref: NodeRef,
}
impl Component for App {
type Message = ();
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
node_ref: NodeRef::default(),
}
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {
<canvas ref={self.node_ref.clone()} />
}
}
fn rendered(&mut self, _ctx: &Context<Self>, first_render: bool) {
// Only start the render loop if it's the first render
// There's no loop cancellation taking place, so if multiple renders happen,
// there would be multiple loops running. That doesn't *really* matter here because
// there's no props update and no SSR is taking place, but it is something to keep in
// consideration
if !first_render {
return;
}
// Once rendered, store references for the canvas and GL context. These can be used for
// resizing the rendering area when the window or canvas element are resized, as well as
// for making GL calls.
let canvas = self.node_ref.cast::<HtmlCanvasElement>().unwrap();
let gl: GL = canvas
.get_context("webgl")
.unwrap()
.unwrap()
.dyn_into()
.unwrap();
Self::render_gl(gl);
}
}
impl App {
fn request_animation_frame(f: &Closure<dyn FnMut()>) {
window()
.unwrap()
.request_animation_frame(f.as_ref().unchecked_ref())
.expect("should register `requestAnimationFrame` OK");
}
fn render_gl(gl: WebGlRenderingContext) {
// This should log only once -- not once per frame
let mut timestamp = 0.0;
let vert_code = include_str!("./basic.vert");
let frag_code = include_str!("./basic.frag");
// This list of vertices will draw two triangles to cover the entire canvas.
let vertices: Vec<f32> = vec![
-1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0,
];
let vertex_buffer = gl.create_buffer().unwrap();
let verts = js_sys::Float32Array::from(vertices.as_slice());
gl.bind_buffer(GL::ARRAY_BUFFER, Some(&vertex_buffer));
gl.buffer_data_with_array_buffer_view(GL::ARRAY_BUFFER, &verts, GL::STATIC_DRAW);
let vert_shader = gl.create_shader(GL::VERTEX_SHADER).unwrap();
gl.shader_source(&vert_shader, vert_code);
gl.compile_shader(&vert_shader);
let frag_shader = gl.create_shader(GL::FRAGMENT_SHADER).unwrap();
gl.shader_source(&frag_shader, frag_code);
gl.compile_shader(&frag_shader);
let shader_program = gl.create_program().unwrap();
gl.attach_shader(&shader_program, &vert_shader);
gl.attach_shader(&shader_program, &frag_shader);
gl.link_program(&shader_program);
gl.use_program(Some(&shader_program));
// Attach the position vector as an attribute for the GL context.
let position = gl.get_attrib_location(&shader_program, "a_position") as u32;
gl.vertex_attrib_pointer_with_i32(position, 2, GL::FLOAT, false, 0, 0);
gl.enable_vertex_attrib_array(position);
// Attach the time as a uniform for the GL context.
let time = gl.get_uniform_location(&shader_program, "u_time");
gl.uniform1f(time.as_ref(), timestamp as f32);
gl.draw_arrays(GL::TRIANGLES, 0, 6);
// Gloo-render's request_animation_frame has this extra closure
// wrapping logic running every frame, unnecessary cost.
// Here constructing the wrapped closure just once.
let cb = Rc::new(RefCell::new(None));
*cb.borrow_mut() = Some(Closure::wrap(Box::new({
let cb = cb.clone();
move || {
// This should repeat every frame
timestamp += 20.0;
gl.uniform1f(time.as_ref(), timestamp as f32);
gl.draw_arrays(GL::TRIANGLES, 0, 6);
App::request_animation_frame(cb.borrow().as_ref().unwrap());
}
}) as Box<dyn FnMut()>));
App::request_animation_frame(cb.borrow().as_ref().unwrap());
}
}
fn main() {
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/timer_functional/src/main.rs | examples/timer_functional/src/main.rs | use std::rc::Rc;
use gloo::timers::callback::{Interval, Timeout};
use yew::prelude::*;
fn get_current_time() -> String {
let date = js_sys::Date::new_0();
String::from(date.to_locale_time_string("en-US"))
}
enum TimerAction {
Add(&'static str),
Cancel,
SetInterval(Interval),
SetTimeout(Timeout),
TimeoutDone,
}
#[derive(Clone, Debug)]
struct TimerState {
messages: Messages,
interval_handle: Option<Rc<Interval>>,
timeout_handle: Option<Rc<Timeout>>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Messages(Vec<AttrValue>);
impl Messages {
fn log(&mut self, message: impl Into<AttrValue>) {
self.0.push(message.into());
}
}
impl std::ops::Deref for Messages {
type Target = Vec<AttrValue>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl FromIterator<&'static str> for Messages {
fn from_iter<T: IntoIterator<Item = &'static str>>(it: T) -> Self {
Messages(it.into_iter().map(Into::into).collect())
}
}
impl PartialEq for TimerState {
fn eq(&self, other: &Self) -> bool {
self.messages == other.messages
&& self.interval_handle.is_some() == other.interval_handle.is_some()
}
}
impl Reducible for TimerState {
type Action = TimerAction;
fn reduce(self: Rc<Self>, action: TimerAction) -> Rc<Self> {
match action {
TimerAction::Add(message) => {
let mut messages = self.messages.clone();
messages.log(message);
Rc::new(TimerState {
messages,
interval_handle: self.interval_handle.clone(),
timeout_handle: self.timeout_handle.clone(),
})
}
TimerAction::SetInterval(t) => Rc::new(TimerState {
messages: ["Interval started!"].into_iter().collect(),
interval_handle: Some(Rc::from(t)),
timeout_handle: self.timeout_handle.clone(),
}),
TimerAction::SetTimeout(t) => Rc::new(TimerState {
messages: ["Timer started!!"].into_iter().collect(),
interval_handle: self.interval_handle.clone(),
timeout_handle: Some(Rc::from(t)),
}),
TimerAction::TimeoutDone => {
let mut messages = self.messages.clone();
messages.log("Done!");
Rc::new(TimerState {
messages,
interval_handle: self.interval_handle.clone(),
timeout_handle: None,
})
}
TimerAction::Cancel => {
let mut messages = self.messages.clone();
messages.log("Canceled!");
Rc::new(TimerState {
messages,
interval_handle: None,
timeout_handle: None,
})
}
}
}
}
#[function_component(Clock)]
fn clock() -> Html {
let time = use_state(get_current_time);
{
let time = time.clone();
use_effect_with((), |_| {
Interval::new(1000, move || time.set(get_current_time())).forget();
});
}
html!(
<div id="time">{ time.as_str() }</div>
)
}
#[function_component]
fn App() -> Html {
let state = use_reducer(|| TimerState {
messages: Default::default(),
interval_handle: None,
timeout_handle: None,
});
let mut key = 0;
let messages: Html = state
.messages
.iter()
.map(|message| {
key += 1;
html! { <p {key}>{ message }</p> }
})
.collect();
let has_job = state.interval_handle.is_some() || state.timeout_handle.is_some();
let on_add_timeout = {
let state = state.clone();
Callback::from(move |_: MouseEvent| {
let timeout_state = state.clone();
let message_state = state.clone();
let t = Timeout::new(3000, move || {
message_state.dispatch(TimerAction::TimeoutDone);
});
timeout_state.dispatch(TimerAction::SetTimeout(t));
})
};
let on_add_interval = {
let state = state.clone();
Callback::from(move |_: MouseEvent| {
let interval_state = state.clone();
let message_state = state.clone();
let i = Interval::new(1000, move || {
message_state.dispatch(TimerAction::Add("Tick.."));
});
interval_state.dispatch(TimerAction::SetInterval(i));
})
};
let on_cancel = {
Callback::from(move |_: MouseEvent| {
state.dispatch(TimerAction::Cancel);
})
};
html!(
<>
<div id="buttons">
<button disabled={has_job} onclick={on_add_timeout}>{ "Start Timeout" }</button>
<button disabled={has_job} onclick={on_add_interval}>{ "Start Interval" }</button>
<button disabled={!has_job} onclick={on_cancel}>{ "Cancel"}</button>
</div>
<div id="wrapper">
<Clock />
<div id="messages">
{ messages }
</div>
</div>
</>
)
}
fn main() {
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/boids/src/simulation.rs | examples/boids/src/simulation.rs | use gloo::timers::callback::Interval;
use yew::{html, Component, Context, Html, Properties};
use crate::boid::Boid;
use crate::math::Vector2D;
use crate::settings::Settings;
pub const SIZE: Vector2D = Vector2D::new(1600.0, 1000.0);
#[derive(Debug)]
pub enum Msg {
Tick,
}
#[derive(Clone, Debug, PartialEq, Properties)]
pub struct Props {
pub settings: Settings,
#[prop_or_default]
pub generation: usize,
#[prop_or_default]
pub paused: bool,
}
#[derive(Debug)]
pub struct Simulation {
boids: Vec<Boid>,
interval: Interval,
generation: usize,
}
impl Component for Simulation {
type Message = Msg;
type Properties = Props;
fn create(ctx: &Context<Self>) -> Self {
let settings = ctx.props().settings.clone();
let boids = (0..settings.boids)
.map(|_| Boid::new_random(&settings))
.collect();
let interval = {
let link = ctx.link().clone();
Interval::new(settings.tick_interval_ms as u32, move || {
link.send_message(Msg::Tick)
})
};
let generation = ctx.props().generation;
Self {
boids,
interval,
generation,
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Tick => {
let Props {
ref settings,
paused,
..
} = *ctx.props();
if paused {
false
} else {
Boid::update_all(settings, &mut self.boids);
true
}
}
}
}
fn changed(&mut self, ctx: &Context<Self>, old_props: &Self::Properties) -> bool {
let props = ctx.props();
let should_reset =
old_props.settings != props.settings || self.generation != props.generation;
self.generation = props.generation;
if should_reset {
self.boids.clear();
let settings = &props.settings;
self.boids
.resize_with(settings.boids, || Boid::new_random(settings));
// as soon as the previous task is dropped it is cancelled.
// We don't need to worry about manually stopping it.
self.interval = {
let link = ctx.link().clone();
Interval::new(settings.tick_interval_ms as u32, move || {
link.send_message(Msg::Tick)
})
};
true
} else {
false
}
}
fn view(&self, _ctx: &Context<Self>) -> Html {
let view_box = format!("0 0 {} {}", SIZE.x, SIZE.y);
html! {
<svg class="simulation-window" viewBox={view_box}>
{ for self.boids.iter().map(Boid::render) }
</svg>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/boids/src/settings.rs | examples/boids/src/settings.rs | use gloo::storage::{LocalStorage, Storage};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct Settings {
/// amount of boids
pub boids: usize,
// time between each simulation tick
pub tick_interval_ms: u64,
/// view distance of a boid
pub visible_range: f64,
/// distance boids try to keep between each other
pub min_distance: f64,
/// max speed
pub max_speed: f64,
/// force multiplier for pulling boids together
pub cohesion_factor: f64,
/// force multiplier for separating boids
pub separation_factor: f64,
/// force multiplier for matching velocity of other boids
pub alignment_factor: f64,
/// controls turn speed to avoid leaving boundary
pub turn_speed_ratio: f64,
/// percentage of the size to the boundary at which a boid starts turning away
pub border_margin: f64,
/// factor for adapting the average color of the swarm
pub color_adapt_factor: f64,
}
impl Settings {
const KEY: &'static str = "yew.boids.settings";
pub fn load() -> Self {
LocalStorage::get(Self::KEY).unwrap_or_default()
}
pub fn remove() {
LocalStorage::delete(Self::KEY);
}
pub fn store(&self) {
let _ = LocalStorage::set(Self::KEY, self);
}
}
impl Default for Settings {
fn default() -> Self {
Self {
boids: 300,
tick_interval_ms: 50,
visible_range: 80.0,
min_distance: 15.0,
max_speed: 20.0,
alignment_factor: 0.15,
cohesion_factor: 0.05,
separation_factor: 0.6,
turn_speed_ratio: 0.25,
border_margin: 0.1,
color_adapt_factor: 0.05,
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/boids/src/math.rs | examples/boids/src/math.rs | use std::f64::consts::{FRAC_PI_3, PI};
use std::iter::Sum;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
// at the time of writing the TAU constant is still unstable
pub const TAU: f64 = 2.0 * PI;
pub const FRAC_TAU_3: f64 = 2.0 * FRAC_PI_3;
/// Get the smaller signed angle from `source` to `target`.
/// The result is in the range `[-PI, PI)`.
pub fn smallest_angle_between(source: f64, target: f64) -> f64 {
let d = target - source;
(d + PI).rem_euclid(TAU) - PI
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Vector2D {
pub x: f64,
pub y: f64,
}
impl Vector2D {
pub const fn new(x: f64, y: f64) -> Self {
Self { x, y }
}
pub fn from_polar(angle: f64, radius: f64) -> Self {
let (sin, cos) = angle.sin_cos();
Self::new(radius * cos, radius * sin)
}
pub fn magnitude_squared(self) -> f64 {
self.x * self.x + self.y * self.y
}
pub fn magnitude(self) -> f64 {
self.magnitude_squared().sqrt()
}
pub fn clamp_magnitude(self, max: f64) -> Self {
let mag = self.magnitude();
if mag > max {
self / mag * max
} else {
self
}
}
/// Positive angles measured counter-clockwise from positive x axis.
pub fn angle(self) -> f64 {
self.y.atan2(self.x)
}
}
impl Neg for Vector2D {
type Output = Self;
fn neg(self) -> Self::Output {
Self::new(-self.x, -self.y)
}
}
impl AddAssign for Vector2D {
fn add_assign(&mut self, other: Self) {
self.x += other.x;
self.y += other.y;
}
}
impl Add for Vector2D {
type Output = Self;
fn add(mut self, rhs: Self) -> Self::Output {
self += rhs;
self
}
}
impl SubAssign for Vector2D {
fn sub_assign(&mut self, other: Self) {
self.x -= other.x;
self.y -= other.y;
}
}
impl Sub for Vector2D {
type Output = Self;
fn sub(mut self, rhs: Self) -> Self::Output {
self -= rhs;
self
}
}
impl MulAssign<f64> for Vector2D {
fn mul_assign(&mut self, scalar: f64) {
self.x *= scalar;
self.y *= scalar;
}
}
impl Mul<f64> for Vector2D {
type Output = Self;
fn mul(mut self, rhs: f64) -> Self::Output {
self *= rhs;
self
}
}
impl DivAssign<f64> for Vector2D {
fn div_assign(&mut self, scalar: f64) {
self.x /= scalar;
self.y /= scalar;
}
}
impl Div<f64> for Vector2D {
type Output = Self;
fn div(mut self, rhs: f64) -> Self::Output {
self /= rhs;
self
}
}
impl Sum for Vector2D {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(Self::default(), |sum, v| sum + v)
}
}
pub trait WeightedMean<T = Self>: Sized {
fn weighted_mean(it: impl Iterator<Item = (T, f64)>) -> Option<Self>;
}
impl<T> WeightedMean for T
where
T: AddAssign + Mul<f64, Output = T> + Div<f64, Output = T> + Copy + Default,
{
fn weighted_mean(it: impl Iterator<Item = (T, f64)>) -> Option<T> {
let (sum, total_weight) = it.fold(
(T::default(), 0.0),
|(mut sum, total_weight), (value, weight)| {
sum += value * weight;
(sum, total_weight + weight)
},
);
if total_weight.is_normal() {
Some(sum / total_weight)
} else {
None
}
}
}
pub trait Mean<T = Self>: Sized {
fn mean(it: impl Iterator<Item = T>) -> Option<Self>;
}
impl<T> Mean for T
where
T: AddAssign + Sub<Output = T> + Div<f64, Output = T> + Copy + Default,
{
fn mean(it: impl Iterator<Item = T>) -> Option<T> {
let (avg, count) = it.fold((T::default(), 0.0), |(mut avg, mut count), value| {
count += 1.0;
avg += (value - avg) / count;
(avg, count)
});
if count.is_normal() {
Some(avg)
} else {
None
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/boids/src/slider.rs | examples/boids/src/slider.rs | use std::cell::Cell;
use web_sys::HtmlInputElement;
use yew::events::InputEvent;
use yew::{html, Callback, Component, Context, Html, Properties, TargetCast};
thread_local! {
static SLIDER_ID: Cell<usize> = Cell::default();
}
fn next_slider_id() -> usize {
SLIDER_ID.with(|cell| cell.replace(cell.get() + 1))
}
#[derive(Clone, Debug, PartialEq, Properties)]
pub struct Props {
pub label: &'static str,
pub value: f64,
pub onchange: Callback<f64>,
#[prop_or_default]
pub precision: Option<usize>,
#[prop_or_default]
pub percentage: bool,
#[prop_or_default]
pub min: f64,
pub max: f64,
#[prop_or_default]
pub step: Option<f64>,
}
pub struct Slider {
id: usize,
}
impl Component for Slider {
type Message = ();
type Properties = Props;
fn create(_ctx: &Context<Self>) -> Self {
Self {
id: next_slider_id(),
}
}
fn update(&mut self, _ctx: &Context<Self>, _msg: Self::Message) -> bool {
unimplemented!()
}
fn view(&self, ctx: &Context<Self>) -> Html {
let Props {
label,
value,
ref onchange,
precision,
percentage,
min,
max,
step,
} = *ctx.props();
let precision = precision.unwrap_or_else(|| usize::from(percentage));
let display_value = if percentage {
format!("{:.p$}%", 100.0 * value, p = precision)
} else {
format!("{value:.precision$}")
};
let id = format!("slider-{}", self.id);
let step = step.unwrap_or_else(|| {
let p = if percentage { precision + 2 } else { precision };
10f64.powi(-(p as i32))
});
let oninput = onchange.reform(|e: InputEvent| {
let input: HtmlInputElement = e.target_unchecked_into();
input.value_as_number()
});
html! {
<div class="slider">
<label for={id.clone()} class="slider__label">{ label }</label>
<input type="range"
value={value.to_string()}
{id}
class="slider__input"
min={min.to_string()} max={max.to_string()} step={step.to_string()}
{oninput}
/>
<span class="slider__value">{ display_value }</span>
</div>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/boids/src/boid.rs | examples/boids/src/boid.rs | use std::fmt::Write;
use std::iter;
use rand::Rng;
use yew::{html, Html};
use crate::math::{self, Mean, Vector2D, WeightedMean};
use crate::settings::Settings;
use crate::simulation::SIZE;
#[derive(Clone, Debug, PartialEq)]
pub struct Boid {
position: Vector2D,
velocity: Vector2D,
radius: f64,
hue: f64,
}
impl Boid {
pub fn new_random(settings: &Settings) -> Self {
let mut rng = rand::rng();
let max_radius = settings.min_distance / 2.0;
let min_radius = max_radius / 6.0;
// by using the third power large boids become rarer
let radius = min_radius + rng.random::<f64>().powi(3) * (max_radius - min_radius);
Self {
position: Vector2D::new(rng.random::<f64>() * SIZE.x, rng.random::<f64>() * SIZE.y),
velocity: Vector2D::from_polar(rng.random::<f64>() * math::TAU, settings.max_speed),
radius,
hue: rng.random::<f64>() * math::TAU,
}
}
fn coherence(&self, boids: VisibleBoidIter, factor: f64) -> Vector2D {
Vector2D::weighted_mean(
boids.map(|other| (other.boid.position, other.boid.radius * other.boid.radius)),
)
.map(|mean| (mean - self.position) * factor)
.unwrap_or_default()
}
fn separation(&self, boids: VisibleBoidIter, settings: &Settings) -> Vector2D {
let accel = boids
.filter_map(|other| {
if other.distance > settings.min_distance {
None
} else {
Some(-other.offset)
}
})
.sum::<Vector2D>();
accel * settings.separation_factor
}
fn alignment(&self, boids: VisibleBoidIter, factor: f64) -> Vector2D {
Vector2D::mean(boids.map(|other| other.boid.velocity))
.map(|mean| (mean - self.velocity) * factor)
.unwrap_or_default()
}
fn adapt_color(&mut self, boids: VisibleBoidIter, factor: f64) {
let mean = f64::mean(boids.filter_map(|other| {
if other.boid.radius > self.radius {
Some(math::smallest_angle_between(self.hue, other.boid.hue))
} else {
None
}
}));
if let Some(avg_hue_offset) = mean {
self.hue += avg_hue_offset * factor;
}
}
fn keep_in_bounds(&mut self, settings: &Settings) {
let min = SIZE * settings.border_margin;
let max = SIZE - min;
let mut v = Vector2D::default();
let turn_speed = self.velocity.magnitude() * settings.turn_speed_ratio;
let pos = self.position;
if pos.x < min.x {
v.x += turn_speed;
}
if pos.x > max.x {
v.x -= turn_speed
}
if pos.y < min.y {
v.y += turn_speed;
}
if pos.y > max.y {
v.y -= turn_speed;
}
self.velocity += v;
}
fn update_velocity(&mut self, settings: &Settings, boids: VisibleBoidIter) {
let v = self.velocity
+ self.coherence(boids.clone(), settings.cohesion_factor)
+ self.separation(boids.clone(), settings)
+ self.alignment(boids, settings.alignment_factor);
self.velocity = v.clamp_magnitude(settings.max_speed);
}
fn update(&mut self, settings: &Settings, boids: VisibleBoidIter) {
self.adapt_color(boids.clone(), settings.color_adapt_factor);
self.update_velocity(settings, boids);
self.keep_in_bounds(settings);
self.position += self.velocity;
}
pub fn update_all(settings: &Settings, boids: &mut [Self]) {
for i in 0..boids.len() {
let (before, after) = boids.split_at_mut(i);
let (boid, after) = after.split_first_mut().unwrap();
let visible_boids =
VisibleBoidIter::new(before, after, boid.position, settings.visible_range);
boid.update(settings, visible_boids);
}
}
pub fn render(&self) -> Html {
let color = format!("hsl({:.3}rad, 100%, 50%)", self.hue);
let mut points = String::new();
for offset in iter_shape_points(self.radius, self.velocity.angle()) {
let Vector2D { x, y } = self.position + offset;
// Write to string will never fail.
let _ = write!(points, "{x:.2},{y:.2} ");
}
html! { <polygon {points} fill={color} /> }
}
}
fn iter_shape_points(radius: f64, rotation: f64) -> impl Iterator<Item = Vector2D> {
const SHAPE: [(f64, f64); 3] = [
(0. * math::FRAC_TAU_3, 2.0),
(1. * math::FRAC_TAU_3, 1.0),
(2. * math::FRAC_TAU_3, 1.0),
];
SHAPE
.iter()
.copied()
.map(move |(angle, radius_mul)| Vector2D::from_polar(angle + rotation, radius_mul * radius))
}
#[derive(Debug)]
struct VisibleBoid<'a> {
boid: &'a Boid,
offset: Vector2D,
distance: f64,
}
#[derive(Clone, Debug)]
struct VisibleBoidIter<'boid> {
// Pay no mind to this mess of a type.
// It's just `before` and `after` joined together.
it: iter::Chain<std::slice::Iter<'boid, Boid>, std::slice::Iter<'boid, Boid>>,
position: Vector2D,
visible_range: f64,
}
impl<'boid> VisibleBoidIter<'boid> {
fn new(
before: &'boid [Boid],
after: &'boid [Boid],
position: Vector2D,
visible_range: f64,
) -> Self {
Self {
it: before.iter().chain(after),
position,
visible_range,
}
}
}
impl<'boid> Iterator for VisibleBoidIter<'boid> {
type Item = VisibleBoid<'boid>;
fn next(&mut self) -> Option<Self::Item> {
let Self {
ref mut it,
position,
visible_range,
} = *self;
it.find_map(move |other| {
let offset = other.position - position;
let distance = offset.magnitude();
if distance > visible_range {
None
} else {
Some(VisibleBoid {
boid: other,
offset,
distance,
})
}
})
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/boids/src/main.rs | examples/boids/src/main.rs | use settings::Settings;
use simulation::Simulation;
use slider::Slider;
use yew::html::Scope;
use yew::{html, Component, Context, Html};
mod boid;
mod math;
mod settings;
mod simulation;
mod slider;
pub enum Msg {
ChangeSettings(Settings),
ResetSettings,
RestartSimulation,
TogglePause,
}
pub struct App {
settings: Settings,
generation: usize,
paused: bool,
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
settings: Settings::load(),
generation: 0,
paused: false,
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Msg) -> bool {
match msg {
Msg::ChangeSettings(settings) => {
self.settings = settings;
self.settings.store();
true
}
Msg::ResetSettings => {
self.settings = Settings::default();
Settings::remove();
true
}
Msg::RestartSimulation => {
self.generation = self.generation.wrapping_add(1);
true
}
Msg::TogglePause => {
self.paused = !self.paused;
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let Self {
ref settings,
generation,
paused,
..
} = *self;
html! {
<>
<h1 class="title">{ "Boids" }</h1>
<Simulation settings={settings.clone()} {generation} {paused} />
{ self.view_panel(ctx.link()) }
</>
}
}
}
impl App {
fn view_panel(&self, link: &Scope<Self>) -> Html {
let pause_text = if self.paused { "Resume" } else { "Pause" };
html! {
<div class="panel">
{ self.view_settings(link) }
<div class="panel__buttons">
<button onclick={link.callback(|_| Msg::TogglePause)}>{ pause_text }</button>
<button onclick={link.callback(|_| Msg::ResetSettings)}>{ "Use Defaults" }</button>
<button onclick={link.callback(|_| Msg::RestartSimulation)}>{ "Restart" }</button>
</div>
</div>
}
}
fn view_settings(&self, link: &Scope<Self>) -> Html {
let Self { settings, .. } = self;
// This helper macro creates a callback which applies the new value to the current settings
// and sends `Msg::ChangeSettings`. Thanks to this, we don't need to have
// "ChangeBoids", "ChangeCohesion", etc. messages, but it comes at the cost of
// cloning the `Settings` struct each time.
macro_rules! settings_callback {
($link:expr, $settings:ident; $key:ident as $ty:ty) => {{
let settings = $settings.clone();
$link.callback(move |value| {
let mut settings = settings.clone();
settings.$key = value as $ty;
Msg::ChangeSettings(settings)
})
}};
($link:expr, $settings:ident; $key:ident) => {
settings_callback!($link, $settings; $key as f64)
}
}
html! {
<div class="settings">
<Slider label="Number of Boids"
min=1.0 max=600.0
onchange={settings_callback!(link, settings; boids as usize)}
value={settings.boids as f64}
/>
<Slider label="View Distance"
max=500.0 step=10.0
onchange={settings_callback!(link, settings; visible_range)}
value={settings.visible_range}
/>
<Slider label="Spacing"
max=100.0
onchange={settings_callback!(link, settings; min_distance)}
value={settings.min_distance}
/>
<Slider label="Max Speed"
max=50.0
onchange={settings_callback!(link, settings; max_speed)}
value={settings.max_speed}
/>
<Slider label="Cohesion"
max=0.5 percentage=true
onchange={settings_callback!(link, settings; cohesion_factor)}
value={settings.cohesion_factor}
/>
<Slider label="Separation"
max=1.0 percentage=true
onchange={settings_callback!(link, settings; separation_factor)}
value={settings.separation_factor}
/>
<Slider label="Alignment"
max=0.5 percentage=true
onchange={settings_callback!(link, settings; alignment_factor)}
value={settings.alignment_factor}
/>
<Slider label="Turn Speed"
max=1.5 percentage=true
onchange={settings_callback!(link, settings; turn_speed_ratio)}
value={settings.turn_speed_ratio}
/>
<Slider label="Color Adaption"
max=1.5 percentage=true
onchange={settings_callback!(link, settings; color_adapt_factor)}
value={settings.color_adapt_factor}
/>
</div>
}
}
}
fn main() {
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/simple_ssr/src/lib.rs | examples/simple_ssr/src/lib.rs | use serde::{Deserialize, Serialize};
use uuid::Uuid;
use yew::prelude::*;
#[derive(Serialize, Deserialize)]
struct UuidResponse {
uuid: Uuid,
}
#[cfg(feature = "ssr")]
async fn fetch_uuid() -> Uuid {
// reqwest works for both non-wasm and wasm targets.
let resp = reqwest::get("https://httpbin.org/uuid").await.unwrap();
let uuid_resp = resp.json::<UuidResponse>().await.unwrap();
uuid_resp.uuid
}
#[function_component]
fn Content() -> HtmlResult {
let uuid = use_prepared_state!((), async move |_| -> Uuid { fetch_uuid().await })?.unwrap();
Ok(html! {
<div>{"Random UUID: "}{uuid}</div>
})
}
#[function_component]
pub fn App() -> Html {
let fallback = html! {<div>{"Loading..."}</div>};
html! {
<Suspense {fallback}>
<Content />
</Suspense>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/simple_ssr/src/bin/simple_ssr_server.rs | examples/simple_ssr/src/bin/simple_ssr_server.rs | use std::error::Error;
use std::path::PathBuf;
use bytes::Bytes;
use clap::Parser;
use futures::stream::{self, Stream, StreamExt};
use simple_ssr::App;
use warp::Filter;
type BoxedError = Box<dyn Error + Send + Sync + 'static>;
/// A basic example
#[derive(Parser, Debug)]
struct Opt {
/// the "dist" created by trunk directory to be served for hydration.
#[structopt(short, long)]
dir: PathBuf,
}
async fn render(
index_html_before: String,
index_html_after: String,
) -> Box<dyn Stream<Item = Result<Bytes, BoxedError>> + Send> {
let renderer = yew::ServerRenderer::<App>::new();
Box::new(
stream::once(async move { index_html_before })
.chain(renderer.render_stream())
.chain(stream::once(async move { index_html_after }))
.map(|m| Result::<_, BoxedError>::Ok(m.into())),
)
}
#[tokio::main]
async fn main() {
let opts = Opt::parse();
let index_html_s = tokio::fs::read_to_string(opts.dir.join("index.html"))
.await
.expect("failed to read index.html");
let (index_html_before, index_html_after) = index_html_s.split_once("<body>").unwrap();
let mut index_html_before = index_html_before.to_owned();
index_html_before.push_str("<body>");
let index_html_after = index_html_after.to_owned();
let html = warp::path::end().then(move || {
let index_html_before = index_html_before.clone();
let index_html_after = index_html_after.clone();
async move { warp::reply::html(render(index_html_before, index_html_after).await) }
});
let routes = html.or(warp::fs::dir(opts.dir));
println!("You can view the website at: http://localhost:8080/");
warp::serve(routes).run(([127, 0, 0, 1], 8080)).await;
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/simple_ssr/src/bin/simple_ssr_hydrate.rs | examples/simple_ssr/src/bin/simple_ssr_hydrate.rs | use simple_ssr::App;
fn main() {
#[cfg(target_arch = "wasm32")]
wasm_logger::init(wasm_logger::Config::new(log::Level::Trace));
yew::Renderer::<App>::new().hydrate();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/futures/src/markdown.rs | examples/futures/src/markdown.rs | /// Original author of this code is [Nathan Ringo](https://github.com/remexre)
/// Source: https://github.com/acmumn/mentoring/blob/master/web-client/src/view/markdown.rs
use pulldown_cmark::{Alignment, CodeBlockKind, Event, Options, Parser, Tag, TagEnd};
use yew::virtual_dom::{VNode, VTag, VText};
use yew::Html;
struct TableContext {
next_cell_index: usize,
in_head: bool,
has_body: bool,
alignment: Vec<Alignment>,
}
struct TagWriter {
root_children: Vec<VNode>,
spine: Vec<VTag>,
table_ctx: Option<TableContext>,
}
impl TagWriter {
fn new() -> Self {
Self {
root_children: vec![],
spine: vec![],
table_ctx: None,
}
}
fn finish(mut self) -> VNode {
assert!(
self.spine.is_empty(),
"expected all nested elements to be closed"
);
if self.root_children.len() == 1 {
self.root_children.pop().unwrap()
} else {
self.root_children.into_iter().collect()
}
}
fn add_child(&mut self, child: VNode) {
if let Some(host) = self.spine.last_mut() {
host.add_child(child);
} else {
self.root_children.push(child);
}
}
fn pop_spine(&mut self) {
let top = self.spine.pop().expect("an element to close");
self.add_child(top.into());
}
fn get_table_ctx(&mut self) -> &mut TableContext {
self.table_ctx.as_mut().expect("a table context")
}
fn open_table_ctx(&mut self, alignment: Vec<Alignment>) {
assert!(self.table_ctx.is_none(), "nested tables not supported");
self.table_ctx = Some(TableContext {
next_cell_index: 0,
in_head: false,
has_body: false,
alignment,
});
}
fn close_table_ctx(&mut self) -> TableContext {
self.table_ctx.take().expect("expected to be in a table")
}
fn start_tag(&mut self, tag: Tag) {
let wrapper = match tag {
Tag::Paragraph => VTag::new("p"),
Tag::Heading { level, .. } => VTag::new(level.to_string()),
Tag::BlockQuote(_) => {
let mut el = VTag::new("blockquote");
el.add_attribute("class", "blockquote");
el
}
Tag::CodeBlock(code_block_kind) => {
self.spine.push(VTag::new("pre"));
let mut el = VTag::new("code");
if let CodeBlockKind::Fenced(lang) = code_block_kind {
// Different color schemes may be used for different code blocks,
// but a different library (likely js based at the moment) would be necessary to
// actually provide the highlighting support by locating the
// language classes and applying dom transforms on their contents.
match lang.as_ref() {
"html" => el.add_attribute("class", "html-language"),
"rust" => el.add_attribute("class", "rust-language"),
"java" => el.add_attribute("class", "java-language"),
"c" => el.add_attribute("class", "c-language"),
_ => {} // Add your own language highlighting support
};
}
el
}
Tag::List(None) => VTag::new("ul"),
Tag::List(Some(1)) => VTag::new("ol"),
Tag::List(Some(ref start)) => {
let mut el = VTag::new("ol");
el.add_attribute("start", start.to_string());
el
}
Tag::Item => VTag::new("li"),
Tag::Table(alignment) => {
self.open_table_ctx(alignment);
let mut el = VTag::new("table");
el.add_attribute("class", "table");
el
}
Tag::TableHead => {
let ctx = self.get_table_ctx();
ctx.next_cell_index = 0;
ctx.in_head = true;
self.spine.push(VTag::new("thead"));
VTag::new("tr")
}
Tag::TableRow => {
let ctx = self.get_table_ctx();
ctx.next_cell_index = 0;
if !ctx.has_body {
ctx.has_body = true;
self.spine.push(VTag::new("tbody"));
}
VTag::new("tr")
}
Tag::TableCell => {
let ctx = self.get_table_ctx();
let idx = ctx.next_cell_index;
ctx.next_cell_index += 1;
let mut tag = if ctx.in_head {
let mut th = VTag::new("th");
th.add_attribute("scope", "col");
th
} else {
VTag::new("td")
};
match &ctx.alignment[idx] {
Alignment::None => {}
Alignment::Left => {
tag.add_attribute("class", "text-left");
}
Alignment::Center => {
tag.add_attribute("class", "text-center");
}
Alignment::Right => {
tag.add_attribute("class", "text-right");
}
}
tag
}
Tag::Emphasis => {
let mut el = VTag::new("span");
el.add_attribute("class", "font-italic");
el
}
Tag::Strong => {
let mut el = VTag::new("span");
el.add_attribute("class", "font-weight-bold");
el
}
Tag::Link {
ref dest_url,
ref title,
link_type: _,
id: _,
} => {
let mut el = VTag::new("a");
el.add_attribute("href", dest_url.to_string());
let title = title.clone().into_string();
if !title.is_empty() {
el.add_attribute("title", title);
}
el
}
Tag::Image {
ref dest_url,
ref title,
link_type: _,
id: _,
} => {
let mut el = VTag::new("img");
el.add_attribute("src", dest_url.to_string());
let title = title.clone().into_string();
if !title.is_empty() {
el.add_attribute("title", title);
}
el
}
Tag::FootnoteDefinition(ref _footnote_id) => VTag::new("span"), // Footnotes are not
// rendered as anything
// special
Tag::Strikethrough => {
let mut el = VTag::new("span");
el.add_attribute("class", "text-decoration-strikethrough");
el
}
Tag::HtmlBlock => VTag::new("div"),
_ => {
gloo::console::log!(format!("Unhandled tag: {tag:#?}"));
VTag::new("div")
}
};
self.spine.push(wrapper);
}
fn end_tag(&mut self, tag: TagEnd) {
self.pop_spine();
match tag {
TagEnd::CodeBlock => {
self.pop_spine(); // Close <pre>
}
TagEnd::TableHead => {
self.pop_spine(); // Close <thead>
self.get_table_ctx().in_head = false;
}
TagEnd::Table => {
let ctx = self.close_table_ctx();
if ctx.has_body {
self.pop_spine(); // Close <tbody>
}
}
_ => {}
}
}
fn write_event(&mut self, ev: Event) {
match ev {
Event::Start(tag) => self.start_tag(tag),
Event::End(tag) => self.end_tag(tag),
Event::Text(text) => self.add_child(VText::new(text.to_string()).into()),
Event::Rule => self.add_child(VTag::new("hr").into()),
Event::SoftBreak => self.add_child(VText::new("\n").into()),
Event::HardBreak => self.add_child(VTag::new("br").into()),
_ => gloo::console::log!(format!("Unhandled event: {ev:#?}")),
};
}
}
/// Renders a string of Markdown to HTML with the default options (footnotes
/// disabled, tables enabled).
pub fn render_markdown(src: &str) -> Html {
let mut writer = TagWriter::new();
let mut options = Options::empty();
options.insert(Options::ENABLE_TABLES);
for ev in Parser::new_ext(src, options) {
writer.write_event(ev);
}
writer.finish()
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/futures/src/main.rs | examples/futures/src/main.rs | use std::error::Error;
use std::fmt::{self, Debug, Display, Formatter};
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use web_sys::{Request, RequestInit, RequestMode, Response};
use yew::{html, Component, Context, Html};
mod markdown;
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";
/// Something wrong has occurred while fetching an external resource.
#[derive(Debug, Clone, PartialEq)]
pub struct FetchError {
err: JsValue,
}
impl Display for FetchError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Debug::fmt(&self.err, f)
}
}
impl Error for FetchError {}
impl From<JsValue> for FetchError {
fn from(value: JsValue) -> Self {
Self { err: value }
}
}
/// The possible states a fetch request can be in.
pub enum FetchState<T> {
NotFetching,
Fetching,
Success(T),
Failed(FetchError),
}
/// Fetches markdown from Yew's README.md.
///
/// Consult the following for an example of the fetch api by the team behind web_sys:
/// https://wasm-bindgen.github.io/wasm-bindgen/examples/fetch.html
async fn fetch_markdown(url: &'static str) -> Result<String, FetchError> {
let opts = RequestInit::new();
opts.set_method("GET");
opts.set_mode(RequestMode::Cors);
let request = Request::new_with_str_and_init(url, &opts)?;
let window = gloo::utils::window();
let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;
let resp: Response = resp_value.dyn_into().unwrap();
let text = JsFuture::from(resp.text()?).await?;
Ok(text.as_string().unwrap())
}
enum Msg {
SetMarkdownFetchState(FetchState<String>),
GetMarkdown,
GetError,
}
struct App {
markdown: FetchState<String>,
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
markdown: FetchState::NotFetching,
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::SetMarkdownFetchState(fetch_state) => {
self.markdown = fetch_state;
true
}
Msg::GetMarkdown => {
ctx.link().send_future(async {
match fetch_markdown(MARKDOWN_URL).await {
Ok(md) => Msg::SetMarkdownFetchState(FetchState::Success(md)),
Err(err) => Msg::SetMarkdownFetchState(FetchState::Failed(err)),
}
});
ctx.link()
.send_message(Msg::SetMarkdownFetchState(FetchState::Fetching));
false
}
Msg::GetError => {
ctx.link().send_future(async {
match fetch_markdown(INCORRECT_URL).await {
Ok(md) => Msg::SetMarkdownFetchState(FetchState::Success(md)),
Err(err) => Msg::SetMarkdownFetchState(FetchState::Failed(err)),
}
});
ctx.link()
.send_message(Msg::SetMarkdownFetchState(FetchState::Fetching));
false
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
match &self.markdown {
FetchState::NotFetching => html! {
<>
<button onclick={ctx.link().callback(|_| Msg::GetMarkdown)}>
{ "Get Markdown" }
</button>
<button onclick={ctx.link().callback(|_| Msg::GetError)}>
{ "Get using incorrect URL" }
</button>
</>
},
FetchState::Fetching => html! { "Fetching" },
FetchState::Success(data) => html! { markdown::render_markdown(data) },
FetchState::Failed(err) => html! { err },
}
}
}
fn main() {
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/nested_list/src/app.rs | examples/nested_list/src/app.rs | use std::iter;
use yew::prelude::*;
use super::header::ListHeader;
use super::item::ListItem;
use super::list::List;
use super::{Hovered, WeakComponentLink};
pub enum Msg {
Hover(Hovered),
}
pub struct App {
hovered: Hovered,
list_link: WeakComponentLink<List>,
sub_list_link: WeakComponentLink<List>,
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
hovered: Hovered::None,
list_link: WeakComponentLink::default(),
sub_list_link: WeakComponentLink::default(),
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Hover(hovered) => {
self.hovered = hovered;
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let on_hover = &ctx.link().callback(Msg::Hover);
let onmouseover = &ctx.link().callback(|_| Msg::Hover(Hovered::None));
let onmouseoversublist = &ctx.link().callback(|e: MouseEvent| {
e.stop_propagation();
Msg::Hover(Hovered::List)
});
let list_link = &self.list_link;
let sub_list_link = &self.sub_list_link;
// note the use of `html_nested!` instead of `html!`.
let letters = ('A'..='C')
.map(|letter| html_nested! { <ListItem key={format!("letter-{}", letter)} name={letter.to_string()} {on_hover} /> });
html! {
<div class="main" {onmouseover}>
<h1>{ "Nested List Demo" }</h1>
<List
{on_hover}
weak_link={list_link}
header={
vec![
html_nested! {
<ListHeader text="Calling all Rusties!" {on_hover} {list_link} key="header" />
}
]
}
>
{vec![
html_nested! { <ListItem key="rustin" name="Rustin" {on_hover} /> },
html_nested! { <ListItem key="rustaroo" hide=true name="Rustaroo" {on_hover} /> },
html_nested! {
<ListItem key="rustifer" name="Rustifer" {on_hover}>
<div class="sublist" onmouseover={onmouseoversublist}>{ "Sublist!" }</div>
<List
{on_hover}
weak_link={sub_list_link}
header={
vec![html_nested! {
<ListHeader key="sub-rusties" text="Sub Rusties!" {on_hover} list_link={sub_list_link}/>
}]
}
>
{
iter::once(html_nested! { <ListItem key="hidden-sub" hide=true name="Hidden Sub" {on_hover} /> })
.chain(letters)
.collect::<Vec<_>>()
}
</List>
</ListItem>
},
]}
</List>
{ self.view_last_hovered() }
</div>
}
}
}
impl App {
fn view_last_hovered(&self) -> Html {
html! {
<div class="last-hovered">
{ "Last hovered:"}
<span class="last-hovered-text">
{ &self.hovered }
</span>
</div>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/nested_list/src/list.rs | examples/nested_list/src/list.rs | use implicit_clone::unsync::IArray;
use yew::prelude::*;
use yew::virtual_dom::VChild;
use crate::header::ListHeader;
use crate::item::ListItem;
use crate::{Hovered, WeakComponentLink};
pub enum Msg {
HeaderClick,
}
#[derive(Clone, PartialEq, Properties)]
pub struct Props {
#[prop_or_default]
pub header: IArray<VChild<ListHeader>>,
#[prop_or_default]
pub children: IArray<VChild<ListItem>>,
pub on_hover: Callback<Hovered>,
pub weak_link: WeakComponentLink<List>,
}
pub struct List {
inactive: bool,
}
impl Component for List {
type Message = Msg;
type Properties = Props;
fn create(ctx: &Context<Self>) -> Self {
ctx.props()
.weak_link
.borrow_mut()
.replace(ctx.link().clone());
Self { inactive: false }
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::HeaderClick => {
self.inactive = !self.inactive;
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let inactive = if self.inactive { "inactive" } else { "" };
let onmouseover = ctx.props().on_hover.reform(|e: MouseEvent| {
e.stop_propagation();
Hovered::List
});
html! {
<div class="list-container" {onmouseover}>
<div class={classes!("list", inactive)}>
{ &ctx.props().header }
<div class="items">
{ Self::view_items(&ctx.props().children) }
</div>
</div>
</div>
}
}
}
impl List {
fn view_items(children: &IArray<VChild<ListItem>>) -> Html {
children
.iter()
.filter(|c| !c.props.hide)
.cloned()
.enumerate()
.map(|(i, mut c)| {
let props = c.get_mut();
props.name = format!("#{} - {}", i + 1, props.name).into();
c
})
.collect::<Html>()
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/nested_list/src/header.rs | examples/nested_list/src/header.rs | use yew::prelude::*;
use super::list::{List, Msg as ListMsg};
use super::{Hovered, WeakComponentLink};
#[derive(Clone, PartialEq, Properties)]
pub struct Props {
pub on_hover: Callback<Hovered>,
pub text: String,
pub list_link: WeakComponentLink<List>,
}
pub struct ListHeader;
impl Component for ListHeader {
type Message = ();
type Properties = Props;
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, ctx: &Context<Self>) -> Html {
let list_link = ctx.props().list_link.borrow().clone().unwrap();
let onmouseover = ctx.props().on_hover.reform(|e: MouseEvent| {
e.stop_propagation();
Hovered::Header
});
html! {
<div
class="list-header"
{onmouseover}
onclick={list_link.callback(|_| ListMsg::HeaderClick)}
>
{ &ctx.props().text }
</div>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/nested_list/src/main.rs | examples/nested_list/src/main.rs | mod app;
mod header;
mod item;
mod list;
use std::cell::RefCell;
use std::fmt;
use std::ops::Deref;
use std::rc::Rc;
use yew::html::{ImplicitClone, IntoPropValue, Scope};
use yew::prelude::*;
pub struct WeakComponentLink<COMP: Component>(Rc<RefCell<Option<Scope<COMP>>>>);
impl<COMP: Component> Clone for WeakComponentLink<COMP> {
fn clone(&self) -> Self {
Self(Rc::clone(&self.0))
}
}
impl<COMP: Component> ImplicitClone for WeakComponentLink<COMP> {}
impl<COMP: Component> Default for WeakComponentLink<COMP> {
fn default() -> Self {
Self(Rc::default())
}
}
impl<COMP: Component> Deref for WeakComponentLink<COMP> {
type Target = Rc<RefCell<Option<Scope<COMP>>>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<COMP: Component> PartialEq for WeakComponentLink<COMP> {
fn eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
#[derive(Debug, Clone, ImplicitClone, PartialEq, Eq, Hash)]
pub enum Hovered {
Header,
Item(AttrValue),
List,
None,
}
impl fmt::Display for Hovered {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
Hovered::Header => "Header",
Hovered::Item(name) => name,
Hovered::List => "List container",
Hovered::None => "Nothing",
}
)
}
}
impl IntoPropValue<Html> for &Hovered {
fn into_prop_value(self) -> Html {
html! {<>{self.to_string()}</>}
}
}
fn main() {
wasm_logger::init(wasm_logger::Config::default());
yew::Renderer::<app::App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/nested_list/src/item.rs | examples/nested_list/src/item.rs | use yew::prelude::*;
use crate::Hovered;
#[derive(PartialEq, Clone, Properties)]
pub struct Props {
#[prop_or_default]
pub hide: bool,
pub on_hover: Callback<Hovered>,
pub name: AttrValue,
#[prop_or_default]
pub children: Children,
}
pub struct ListItem;
impl Component for ListItem {
type Message = ();
type Properties = Props;
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, ctx: &Context<Self>) -> Html {
let onmouseover = {
let name = ctx.props().name.clone();
ctx.props().on_hover.reform(move |e: MouseEvent| {
e.stop_propagation();
Hovered::Item(name.clone())
})
};
html! {
<div class="list-item" {onmouseover}>
{ &ctx.props().name }
{ Self::view_details(&ctx.props().children) }
</div>
}
}
}
impl ListItem {
fn view_details(children: &Children) -> Html {
if children.is_empty() {
html! {}
} else {
html! {
<div class="list-item-details">
{ children.clone() }
</div>
}
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/node_refs/src/main.rs | examples/node_refs/src/main.rs | mod input;
use input::InputComponent;
use web_sys::HtmlInputElement;
use yew::prelude::*;
pub enum Msg {
HoverIndex(usize),
Submit,
}
pub struct App {
refs: Vec<NodeRef>,
focus_index: usize,
email_error: String,
password_error: String,
}
impl App {
fn apply_focus(&self) {
if let Some(input) = self.refs[self.focus_index].cast::<HtmlInputElement>() {
input.focus().unwrap();
}
}
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
focus_index: 0,
refs: vec![NodeRef::default(), NodeRef::default()],
email_error: "".to_string(),
password_error: "".to_string(),
}
}
fn rendered(&mut self, _ctx: &Context<Self>, first_render: bool) {
if first_render {
self.apply_focus();
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::HoverIndex(index) => {
self.focus_index = index;
self.apply_focus();
false
}
Msg::Submit => {
let email = &self.refs[0];
let password = &self.refs[1];
let email_value = email.cast::<HtmlInputElement>().unwrap().value();
let password_value = password.cast::<HtmlInputElement>().unwrap().value();
self.email_error.clear();
self.password_error.clear();
if !(email_value.contains('@') && email_value.contains('.')) {
self.email_error.push_str("Invalid email.")
}
if password_value.len() < 8 {
self.password_error
.push_str("Password must be at least 8 characters long.")
}
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<div class="main">
<div id="left-pane">
<div>
<h1>{"Create your account"}</h1>
<div class="input-container">
<label>{ "Email" }</label>
<input
type="text"
ref={&self.refs[0]}
class="input-element"
onmouseover={ctx.link().callback(|_| Msg::HoverIndex(0))}
placeholder="abcd@xyz.com"
/>
<div class="error">{self.email_error.clone()}</div>
</div>
<div class="input-container">
<label>{ "Password" }</label>
<InputComponent
input_ref={&self.refs[1]}
on_hover={ctx.link().callback(|_| Msg::HoverIndex(1))}
placeholder="password"
/>
<div class="error">{self.password_error.clone()}</div>
</div>
<button onclick={ctx.link().callback(|_| Msg::Submit)}>{"Create"}</button>
</div>
</div>
<div id="right-pane">
<div>
<div id="graphic"></div>
<h1>{ "Node Refs Example" }</h1>
<p>{ "Refs can be used to access and manipulate DOM elements directly" }</p>
<ul>
<li>{ "First input will focus on mount" }</li>
<li>{ "Each input will focus on hover" }</li>
</ul>
</div>
</div>
</div>
}
}
}
fn main() {
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/node_refs/src/input.rs | examples/node_refs/src/input.rs | use yew::prelude::*;
pub enum Msg {
Hover,
}
#[derive(Properties, PartialEq)]
pub struct Props {
pub on_hover: Callback<()>,
pub placeholder: AttrValue,
pub input_ref: NodeRef,
}
pub struct InputComponent;
impl Component for InputComponent {
type Message = Msg;
type Properties = Props;
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Hover => {
ctx.props().on_hover.emit(());
false
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let placeholder = ctx.props().placeholder.clone();
html! {
<input
ref={&ctx.props().input_ref}
type="text"
class="input-component"
placeholder={placeholder}
onmouseover={ctx.link().callback(|_| Msg::Hover)}
/>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/dyn_create_destroy_apps/src/counter.rs | examples/dyn_create_destroy_apps/src/counter.rs | use gloo::console;
use gloo::timers::callback::Interval;
use yew::prelude::*;
pub struct CounterModel {
counter: usize,
_interval: Interval,
}
#[derive(Clone, Properties, PartialEq)]
pub struct CounterProps {
pub destroy_callback: Callback<()>,
}
pub enum CounterMessage {
Tick,
}
impl Component for CounterModel {
type Message = CounterMessage;
type Properties = CounterProps;
fn create(ctx: &Context<Self>) -> Self {
// Create a Tick message every second
let link = ctx.link().clone();
let interval = Interval::new(1, move || link.send_message(Self::Message::Tick));
Self {
counter: 0,
_interval: interval,
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
// Count our internal state up by one
Self::Message::Tick => {
self.counter += 1;
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let destroy_callback = ctx.props().destroy_callback.clone();
html! {
<>
// Display the current value of the counter
<p class="counter">
{ "App has lived for " }
{ self.counter }
{ " ticks" }
</p>
// Add button to send a destroy command to the parent app
<button class="destroy" onclick={Callback::from(move |_| destroy_callback.emit(()))}>
{ "Destroy this app" }
</button>
</>
}
}
fn destroy(&mut self, _ctx: &Context<Self>) {
console::log!("CounterModel app destroyed");
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/dyn_create_destroy_apps/src/main.rs | examples/dyn_create_destroy_apps/src/main.rs | use gloo::utils::document;
use slab::Slab;
use web_sys::Element;
use yew::prelude::*;
mod counter;
use counter::{CounterModel, CounterProps};
// Define the possible messages which can be sent to the component
pub enum Msg {
// Spawns a new instance of the CounterModel app
SpawnCounterAppInstance,
// Destroys an instance of a CounterModel app
DestroyCounterApp(usize),
}
pub struct App {
apps: Slab<(Element, AppHandle<CounterModel>)>, /* Contains the spawned apps and their
* parent div elements */
apps_container_ref: NodeRef,
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
apps: Slab::new(),
apps_container_ref: NodeRef::default(),
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
let app_container = self
.apps_container_ref
.cast::<Element>()
.expect("Failed to cast app container div to HTMLElement");
match msg {
Msg::SpawnCounterAppInstance => {
// Create a new <div> HtmlElement where the new app will live
let app_div = document()
.create_element("div")
.expect("Failed to create <div> element");
// Append the div to the document body
let _ = app_container
.append_child(&app_div)
.expect("Failed to append app div app container div");
// Reserve an entry for the new app
let app_entry = self.apps.vacant_entry();
// Get the key for the entry and create and mount a new CounterModel app
// with a callback that destroys the app when emitted
let app_key = app_entry.key();
let new_counter_app = yew::Renderer::<CounterModel>::with_root_and_props(
app_div.clone(),
CounterProps {
destroy_callback: ctx
.link()
.callback(move |_| Msg::DestroyCounterApp(app_key)),
},
)
.render();
// Insert the app and the app div to our app collection
app_entry.insert((app_div, new_counter_app));
}
Msg::DestroyCounterApp(app_id) => {
// Get the app from the app slabmap
let (app_div, app) = self.apps.remove(app_id);
// Destroy the app
app.destroy();
// Remove the app div from the DOM
app_div.remove()
}
}
// Never render
false
}
fn view(&self, ctx: &Context<Self>) -> Html {
// We will only render once, and then do the rest of the DOM changes
// by mounting/destroying appinstances of CounterModel
html! {
<>
<div class="panel">
// Create button to create a new app
<button
class="create"
onclick={ctx.link().callback(|_| Msg::SpawnCounterAppInstance)}
>
{ "Spawn new CounterModel app" }
</button>
</div>
// Create a container for all the app instances
<div ref={self.apps_container_ref.clone()}>
</div>
</>
}
}
}
fn main() {
// Start main app
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/wasi_ssr_module/src/router.rs | examples/wasi_ssr_module/src/router.rs | use yew::prelude::*;
use yew_router::prelude::*;
#[derive(Routable, PartialEq, Eq, Clone, Debug)]
pub enum Route {
#[at("/")]
Portal,
#[at("/t/:id")]
Thread { id: String },
#[not_found]
#[at("/404")]
NotFound,
}
pub fn switch(routes: Route) -> Html {
match routes {
Route::Portal => {
html! { <h1>{"Hello"}</h1> }
}
Route::Thread { id } => {
html! { <h1>{format!("Thread id {}", id)}</h1> }
}
Route::NotFound => {
html! { <h1>{"Not found"}</h1> }
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/wasi_ssr_module/src/main.rs | examples/wasi_ssr_module/src/main.rs | #![allow(unused_imports)]
#![allow(non_snake_case)]
mod router;
use anyhow::Result;
use router::{switch, Route};
use yew::prelude::*;
use yew::LocalServerRenderer;
#[function_component]
fn Content() -> Html {
use yew_router::prelude::*;
html! {
<>
<h1>{"Yew WASI SSR demo"}</h1>
<Switch<Route> render={switch} />
</>
}
}
#[function_component]
fn App() -> Html {
use yew_router::history::{AnyHistory, History, MemoryHistory};
use yew_router::prelude::*;
let history = AnyHistory::from(MemoryHistory::new());
history.push("/");
html! {
<div>
<Router history={history}>
<Content />
</Router>
</div>
}
}
pub async fn render() -> Result<String> {
let renderer = LocalServerRenderer::<App>::new();
let html_raw = renderer.render().await;
let mut body = String::new();
body.push_str("<body>");
body.push_str("<div id='app' style='width: 100vw; height: 100vh; position: fixed;'>");
body.push_str(&html_raw);
body.push_str("</div>");
body.push_str("</body>");
Ok(body)
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
let ret = render().await?;
println!("{ret}");
Ok(())
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/router/src/content.rs | examples/router/src/content.rs | use crate::generator::{Generated, Generator};
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Author {
pub seed: u64,
pub name: String,
pub keywords: Vec<String>,
pub image_url: String,
}
impl Generated for Author {
fn generate(gen: &mut Generator) -> Self {
let name = gen.human_name();
let keywords = gen.keywords();
let image_url = gen.face_image_url((600, 600));
Self {
seed: gen.seed,
name,
keywords,
image_url,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PostMeta {
pub seed: u64,
pub title: String,
pub author: Author,
pub keywords: Vec<String>,
pub image_url: String,
}
impl Generated for PostMeta {
fn generate(gen: &mut Generator) -> Self {
let title = gen.title();
let author = Author::generate_from_seed(gen.new_seed());
let keywords = gen.keywords();
let image_url = gen.image_url((1000, 500), &keywords);
Self {
seed: gen.seed,
title,
author,
keywords,
image_url,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Post {
pub meta: PostMeta,
pub content: Vec<PostPart>,
}
impl Generated for Post {
fn generate(gen: &mut Generator) -> Self {
const PARTS_MIN: usize = 1;
const PARTS_MAX: usize = 10;
let meta = PostMeta::generate(gen);
let n_parts = gen.range(PARTS_MIN, PARTS_MAX);
let content = (0..n_parts).map(|_| PostPart::generate(gen)).collect();
Self { meta, content }
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PostPart {
Section(Section),
Quote(Quote),
}
impl Generated for PostPart {
fn generate(gen: &mut Generator) -> Self {
// Because we pass the same (already used) generator down,
// the resulting `Section` and `Quote` aren't be reproducible with just the seed.
// This doesn't matter here though, because we don't need it.
if gen.chance(1, 10) {
Self::Quote(Quote::generate(gen))
} else {
Self::Section(Section::generate(gen))
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Section {
pub title: String,
pub paragraphs: Vec<String>,
pub image_url: String,
}
impl Generated for Section {
fn generate(gen: &mut Generator) -> Self {
const PARAGRAPHS_MIN: usize = 1;
const PARAGRAPHS_MAX: usize = 8;
let title = gen.title();
let n_paragraphs = gen.range(PARAGRAPHS_MIN, PARAGRAPHS_MAX);
let paragraphs = (0..n_paragraphs).map(|_| gen.paragraph()).collect();
let image_url = gen.image_url((600, 300), &[]);
Self {
title,
paragraphs,
image_url,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Quote {
pub author: Author,
pub content: String,
}
impl Generated for Quote {
fn generate(gen: &mut Generator) -> Self {
// wouldn't it be funny if the author ended up quoting themselves?
let author = Author::generate_from_seed(gen.new_seed());
let content = gen.paragraph();
Self { author, content }
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/router/src/generator.rs | examples/router/src/generator.rs | use lipsum::MarkovChain;
use once_cell::sync::Lazy;
use rand::distr::Bernoulli;
use rand::rngs::SmallRng;
use rand::seq::IteratorRandom;
use rand::{Rng, SeedableRng};
const KEYWORDS: &str = include_str!("../data/keywords.txt");
const SYLLABLES: &str = include_str!("../data/syllables.txt");
const YEW_CONTENT: &str = include_str!("../data/yew.txt");
static YEW_CHAIN: Lazy<MarkovChain<'static>> = Lazy::new(|| {
let mut chain = MarkovChain::new();
chain.learn(YEW_CONTENT);
chain
});
pub struct Generator {
pub seed: u64,
rng: SmallRng,
}
impl Generator {
pub fn from_seed(seed: u64) -> Self {
let rng = SmallRng::seed_from_u64(seed);
Self { seed, rng }
}
}
impl Generator {
pub fn new_seed(&mut self) -> u64 {
self.rng.random()
}
/// [low, high)
pub fn range(&mut self, low: usize, high: usize) -> usize {
self.rng.random_range(low..high)
}
/// `n / d` chance
pub fn chance(&mut self, n: u32, d: u32) -> bool {
self.rng.sample(Bernoulli::from_ratio(n, d).unwrap())
}
pub fn image_url(&mut self, dimension: (usize, usize), keywords: &[String]) -> String {
let cache_buster = self.rng.random::<u16>();
let (width, height) = dimension;
format!(
"https://source.unsplash.com/random/{}x{}?{}&sig={}",
width,
height,
keywords.join(","),
cache_buster
)
}
pub fn face_image_url(&mut self, dimension: (usize, usize)) -> String {
self.image_url(dimension, &["human".to_owned(), "face".to_owned()])
}
pub fn human_name(&mut self) -> String {
const SYLLABLES_MIN: usize = 1;
const SYLLABLES_MAX: usize = 5;
let n_syllables = self.rng.random_range(SYLLABLES_MIN..SYLLABLES_MAX);
let first_name = SYLLABLES
.split_whitespace()
.choose_multiple(&mut self.rng, n_syllables)
.join("");
let n_syllables = self.rng.random_range(SYLLABLES_MIN..SYLLABLES_MAX);
let last_name = SYLLABLES
.split_whitespace()
.choose_multiple(&mut self.rng, n_syllables)
.join("");
format!("{} {}", title_case(&first_name), title_case(&last_name))
}
pub fn keywords(&mut self) -> Vec<String> {
const KEYWORDS_MIN: usize = 1;
const KEYWORDS_MAX: usize = 4;
let n_keywords = self.rng.random_range(KEYWORDS_MIN..KEYWORDS_MAX);
KEYWORDS
.split_whitespace()
.map(ToOwned::to_owned)
.choose_multiple(&mut self.rng, n_keywords)
}
pub fn title(&mut self) -> String {
const WORDS_MIN: usize = 3;
const WORDS_MAX: usize = 8;
const SMALL_WORD_LEN: usize = 3;
let n_words = self.rng.random_range(WORDS_MIN..WORDS_MAX);
let mut title = String::new();
let words = YEW_CHAIN
.iter_with_rng(&mut self.rng)
.map(|word| word.trim_matches(|c: char| c.is_ascii_punctuation()))
.filter(|word| !word.is_empty())
.take(n_words);
for (i, word) in words.enumerate() {
if i > 0 {
title.push(' ');
}
// Capitalize the first word and all long words.
if i == 0 || word.len() > SMALL_WORD_LEN {
title.push_str(&title_case(word));
} else {
title.push_str(word);
}
}
title
}
pub fn sentence(&mut self) -> String {
const WORDS_MIN: usize = 7;
const WORDS_MAX: usize = 25;
let n_words = self.rng.random_range(WORDS_MIN..WORDS_MAX);
YEW_CHAIN.generate_with_rng(&mut self.rng, n_words)
}
pub fn paragraph(&mut self) -> String {
const SENTENCES_MIN: usize = 3;
const SENTENCES_MAX: usize = 20;
let n_sentences = self.rng.random_range(SENTENCES_MIN..SENTENCES_MAX);
let mut paragraph = String::new();
for i in 0..n_sentences {
if i > 0 {
paragraph.push(' ');
}
paragraph.push_str(&self.sentence());
}
paragraph
}
}
fn title_case(word: &str) -> String {
let idx = match word.chars().next() {
Some(c) => c.len_utf8(),
None => 0,
};
let mut result = String::with_capacity(word.len());
result.push_str(&word[..idx].to_uppercase());
result.push_str(&word[idx..]);
result
}
pub trait Generated: Sized {
fn generate(gen: &mut Generator) -> Self;
fn generate_from_seed(seed: u64) -> Self {
Self::generate(&mut Generator::from_seed(seed))
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/router/src/main.rs | examples/router/src/main.rs | use yew::prelude::*;
use yew_router::prelude::*;
mod components;
mod content;
mod generator;
mod pages;
use pages::author::Author;
use pages::author_list::AuthorList;
use pages::home::Home;
use pages::page_not_found::PageNotFound;
use pages::post::Post;
use pages::post_list::PostList;
use yew::html::Scope;
#[derive(Routable, PartialEq, Eq, Clone, Debug)]
pub enum Route {
#[at("/posts/:id")]
Post { id: u64 },
#[at("/posts")]
Posts,
#[at("/authors/:id")]
Author { id: u64 },
#[at("/authors")]
Authors,
#[at("/")]
Home,
#[not_found]
#[at("/404")]
NotFound,
}
pub enum Msg {
ToggleNavbar,
}
pub struct App {
navbar_active: bool,
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
navbar_active: false,
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::ToggleNavbar => {
self.navbar_active = !self.navbar_active;
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<BrowserRouter>
{ self.view_nav(ctx.link()) }
<main>
<Switch<Route> render={switch} />
</main>
<footer class="footer">
<div class="content has-text-centered">
{ "Powered by " }
<a href="https://yew.rs">{ "Yew" }</a>
{ " using " }
<a href="https://bulma.io">{ "Bulma" }</a>
{ " and images from " }
<a href="https://unsplash.com">{ "Unsplash" }</a>
</div>
</footer>
</BrowserRouter>
}
}
}
impl App {
fn view_nav(&self, link: &Scope<Self>) -> Html {
let Self { navbar_active, .. } = *self;
let active_class = if !navbar_active { "is-active" } else { "" };
html! {
<nav class="navbar is-primary" role="navigation" aria-label="main navigation">
<div class="navbar-brand">
<h1 class="navbar-item is-size-3">{ "Yew Blog" }</h1>
<button class={classes!("navbar-burger", "burger", active_class)}
aria-label="menu" aria-expanded="false"
onclick={link.callback(|_| Msg::ToggleNavbar)}
>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
</button>
</div>
<div class={classes!("navbar-menu", active_class)}>
<div class="navbar-start">
<Link<Route> classes={classes!("navbar-item")} to={Route::Home}>
{ "Home" }
</Link<Route>>
<Link<Route> classes={classes!("navbar-item")} to={Route::Posts}>
{ "Posts" }
</Link<Route>>
<div class="navbar-item has-dropdown is-hoverable">
<div class="navbar-link">
{ "More" }
</div>
<div class="navbar-dropdown">
<Link<Route> classes={classes!("navbar-item")} to={Route::Authors}>
{ "Meet the authors" }
</Link<Route>>
</div>
</div>
</div>
</div>
</nav>
}
}
}
fn switch(routes: Route) -> Html {
match routes {
Route::Post { id } => {
html! { <Post seed={id} /> }
}
Route::Posts => {
html! { <PostList /> }
}
Route::Author { id } => {
html! { <Author seed={id} /> }
}
Route::Authors => {
html! { <AuthorList /> }
}
Route::Home => {
html! { <Home /> }
}
Route::NotFound => {
html! { <PageNotFound /> }
}
}
}
fn main() {
wasm_logger::init(wasm_logger::Config::new(log::Level::Trace));
yew::Renderer::<App>::new().render();
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/router/src/pages/page_not_found.rs | examples/router/src/pages/page_not_found.rs | use yew::prelude::*;
pub struct PageNotFound;
impl Component for PageNotFound {
type Message = ();
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {
<section class="hero is-danger is-bold is-large">
<div class="hero-body">
<div class="container">
<h1 class="title">
{ "Page not found" }
</h1>
<h2 class="subtitle">
{ "Page page does not seem to exist" }
</h2>
</div>
</div>
</section>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/router/src/pages/author.rs | examples/router/src/pages/author.rs | use yew::prelude::*;
use crate::content;
use crate::generator::Generated;
#[derive(Clone, Debug, Eq, PartialEq, Properties)]
pub struct Props {
pub seed: u64,
}
pub struct Author {
author: content::Author,
}
impl Component for Author {
type Message = ();
type Properties = Props;
fn create(ctx: &Context<Self>) -> Self {
Self {
author: content::Author::generate_from_seed(ctx.props().seed),
}
}
fn changed(&mut self, ctx: &Context<Self>, _old_props: &Self::Properties) -> bool {
self.author = content::Author::generate_from_seed(ctx.props().seed);
true
}
fn view(&self, _ctx: &Context<Self>) -> Html {
let Self { author } = self;
html! {
<div class="section container">
<div class="tile is-ancestor is-vertical">
<div class="tile is-parent">
<article class="tile is-child notification is-light">
<p class="title">{ &author.name }</p>
</article>
</div>
<div class="tile">
<div class="tile is-parent is-3">
<article class="tile is-child notification">
<p class="title">{ "Interests" }</p>
<div class="tags">
{ for author.keywords.iter().map(|tag| html! { <span class="tag is-info">{ tag }</span> }) }
</div>
</article>
</div>
<div class="tile is-parent">
<figure class="tile is-child image is-square">
<img alt="The author's profile picture." src={author.image_url.clone()} />
</figure>
</div>
<div class="tile is-parent">
<article class="tile is-child notification is-info">
<div class="content">
<p class="title">{ "About me" }</p>
<div class="content">
{ "This author has chosen not to reveal anything about themselves" }
</div>
</div>
</article>
</div>
</div>
</div>
</div>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/router/src/pages/home.rs | examples/router/src/pages/home.rs | use yew::prelude::*;
pub struct Home;
impl Component for Home {
type Message = ();
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {
<div class="tile is-ancestor is-vertical">
<div class="tile is-child hero">
<div class="hero-body container pb-0">
<h1 class="title is-1">{ "Welcome..." }</h1>
<h2 class="subtitle">{ "...to the best yew content" }</h2>
</div>
</div>
<div class="tile is-child">
<figure class="image is-3by1">
<img alt="A random image for the input term 'yew'." src="https://source.unsplash.com/random/1200x400/?yew" />
</figure>
</div>
<div class="tile is-parent container">
{ self.view_info_tiles() }
</div>
</div>
}
}
}
impl Home {
fn view_info_tiles(&self) -> Html {
html! {
<>
<div class="tile is-parent">
<div class="tile is-child box">
<p class="title">{ "What are yews?" }</p>
<p class="subtitle">{ "Everything you need to know!" }</p>
<div class="content">
{r#"
A yew is a small to medium-sized evergreen tree, growing 10 to 20 metres tall, with a trunk up to 2 metres in diameter.
The bark is thin, scaly brown, coming off in small flakes aligned with the stem.
The leaves are flat, dark green, 1 to 4 centimetres long and 2 to 3 millimetres broad, arranged spirally on the stem,
but with the leaf bases twisted to align the leaves in two flat rows either side of the stem,
except on erect leading shoots where the spiral arrangement is more obvious.
The leaves are poisonous.
"#}
</div>
</div>
</div>
<div class="tile is-parent">
<div class="tile is-child box">
<p class="title">{ "Who are we?" }</p>
<div class="content">
{ "We're a small team of just 2" }
<sup>{ 64 }</sup>
{ " members working tirelessly to bring you the low-effort yew content we all desperately crave." }
<br />
{r#"
We put a ton of effort into fact-checking our posts.
Some say they read like a Wikipedia article - what a compliment!
"#}
</div>
</div>
</div>
</>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/router/src/pages/mod.rs | examples/router/src/pages/mod.rs | pub mod author;
pub mod author_list;
pub mod home;
pub mod page_not_found;
pub mod post;
pub mod post_list;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/router/src/pages/post.rs | examples/router/src/pages/post.rs | use content::PostPart;
use yew::prelude::*;
use yew_router::prelude::*;
use crate::generator::Generated;
use crate::{content, Route};
#[derive(Clone, Debug, Eq, PartialEq, Properties)]
pub struct Props {
pub seed: u64,
}
pub struct Post {
post: content::Post,
}
impl Component for Post {
type Message = ();
type Properties = Props;
fn create(ctx: &Context<Self>) -> Self {
Self {
post: content::Post::generate_from_seed(ctx.props().seed),
}
}
fn changed(&mut self, ctx: &Context<Self>, _old_props: &Self::Properties) -> bool {
self.post = content::Post::generate_from_seed(ctx.props().seed);
true
}
fn view(&self, _ctx: &Context<Self>) -> Html {
let Self { post } = self;
let keywords = post
.meta
.keywords
.iter()
.map(|keyword| html! { <span class="tag is-info">{ keyword }</span> });
html! {
<>
<section class="hero is-medium is-light has-background">
<img alt="The hero's background" class="hero-background is-transparent" src={post.meta.image_url.clone()} />
<div class="hero-body">
<div class="container">
<h1 class="title">
{ &post.meta.title }
</h1>
<h2 class="subtitle">
{ "by " }
<Link<Route> classes={classes!("has-text-weight-semibold")} to={Route::Author { id: post.meta.author.seed }}>
{ &post.meta.author.name }
</Link<Route>>
</h2>
<div class="tags">
{ for keywords }
</div>
</div>
</div>
</section>
<div class="section container">
{ self.view_content() }
</div>
</>
}
}
}
impl Post {
fn render_quote(&self, quote: &content::Quote) -> Html {
html! {
<article class="media block box my-6">
<figure class="media-left">
<p class="image is-64x64">
<img alt="The author's profile" src={quote.author.image_url.clone()} loading="lazy" />
</p>
</figure>
<div class="media-content">
<div class="content">
<Link<Route> classes={classes!("is-size-5")} to={Route::Author { id: quote.author.seed }}>
<strong>{ "e.author.name }</strong>
</Link<Route>>
<p class="is-family-secondary">
{ "e.content }
</p>
</div>
</div>
</article>
}
}
fn render_section_hero(&self, section: &content::Section) -> Html {
html! {
<section class="hero is-dark has-background mt-6 mb-3">
<img alt="This section's image" class="hero-background is-transparent" src={section.image_url.clone()} loading="lazy" />
<div class="hero-body">
<div class="container">
<h2 class="subtitle">{ §ion.title }</h2>
</div>
</div>
</section>
}
}
fn render_section(&self, section: &content::Section, show_hero: bool) -> Html {
let hero = if show_hero {
self.render_section_hero(section)
} else {
html! {}
};
let paragraphs = section.paragraphs.iter().map(|paragraph| {
html! {
<p>{ paragraph }</p>
}
});
html! {
<section>
{ hero }
<div>{ for paragraphs }</div>
</section>
}
}
fn view_content(&self) -> Html {
// don't show hero for the first section
let mut show_hero = false;
let parts = self.post.content.iter().map(|part| match part {
PostPart::Section(section) => {
let html = self.render_section(section, show_hero);
// show hero between sections
show_hero = true;
html
}
PostPart::Quote(quote) => {
// don't show hero after a quote
show_hero = false;
self.render_quote(quote)
}
});
html! {{for parts}}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/router/src/pages/post_list.rs | examples/router/src/pages/post_list.rs | use yew::prelude::*;
use yew_router::prelude::*;
use crate::components::pagination::{PageQuery, Pagination};
use crate::components::post_card::PostCard;
use crate::Route;
const ITEMS_PER_PAGE: u64 = 10;
const TOTAL_PAGES: u64 = u64::MAX / ITEMS_PER_PAGE;
pub enum Msg {
PageUpdated,
}
pub struct PostList {
page: u64,
_listener: LocationHandle,
}
fn current_page(ctx: &Context<PostList>) -> u64 {
let location = ctx.link().location().unwrap();
location.query::<PageQuery>().map(|it| it.page).unwrap_or(1)
}
impl Component for PostList {
type Message = Msg;
type Properties = ();
fn create(ctx: &Context<Self>) -> Self {
let link = ctx.link().clone();
let listener = ctx
.link()
.add_location_listener(link.callback(move |_| Msg::PageUpdated))
.unwrap();
Self {
page: current_page(ctx),
_listener: listener,
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::PageUpdated => self.page = current_page(ctx),
}
true
}
fn view(&self, ctx: &Context<Self>) -> Html {
let page = self.page;
html! {
<div class="section container">
<h1 class="title">{ "Posts" }</h1>
<h2 class="subtitle">{ "All of our quality writing in one place" }</h2>
{ self.view_posts(ctx) }
<Pagination
{page}
total_pages={TOTAL_PAGES}
route_to_page={Route::Posts}
/>
</div>
}
}
}
impl PostList {
fn view_posts(&self, _ctx: &Context<Self>) -> Html {
let start_seed = (self.page - 1) * ITEMS_PER_PAGE;
let mut cards = (0..ITEMS_PER_PAGE).map(|seed_offset| {
html! {
<li class="list-item mb-5">
<PostCard seed={start_seed + seed_offset} />
</li>
}
});
html! {
<div class="columns">
<div class="column">
<ul class="list">
{ for cards.by_ref().take(ITEMS_PER_PAGE as usize / 2) }
</ul>
</div>
<div class="column">
<ul class="list">
{ for cards }
</ul>
</div>
</div>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/router/src/pages/author_list.rs | examples/router/src/pages/author_list.rs | use rand::{distr, Rng};
use yew::prelude::*;
use crate::components::author_card::AuthorCard;
use crate::components::progress_delay::ProgressDelay;
/// Amount of milliseconds to wait before showing the next set of authors.
const CAROUSEL_DELAY_MS: u64 = 15000;
pub enum Msg {
NextAuthors,
}
pub struct AuthorList {
seeds: Vec<u64>,
}
impl Component for AuthorList {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
seeds: random_author_seeds(),
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::NextAuthors => {
self.seeds = random_author_seeds();
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let authors = self.seeds.iter().map(|&seed| {
html! {
<div class="tile is-parent">
<div class="tile is-child">
<AuthorCard {seed} />
</div>
</div>
}
});
html! {
<div class="container">
<section class="hero">
<div class="hero-body">
<div class="container">
<h1 class="title">{ "Authors" }</h1>
<h2 class="subtitle">
{ "Meet the definitely real people behind your favourite Yew content" }
</h2>
</div>
</div>
</section>
<p class="section py-0">
{ "It wouldn't be fair " }
<i>{ "(or possible :P)" }</i>
{" to list each and every author in alphabetical order."}
<br />
{ "So instead we chose to put more focus on the individuals by introducing you to two people at a time" }
</p>
<div class="section">
<div class="tile is-ancestor">
{ for authors }
</div>
<ProgressDelay duration_ms={CAROUSEL_DELAY_MS} on_complete={ctx.link().callback(|_| Msg::NextAuthors)} />
</div>
</div>
}
}
}
fn random_author_seeds() -> Vec<u64> {
rand::rng()
.sample_iter(distr::StandardUniform)
.take(2)
.collect()
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/router/src/components/progress_delay.rs | examples/router/src/components/progress_delay.rs | use gloo::timers::callback::Interval;
use instant::Instant;
use yew::prelude::*;
const RESOLUTION: u64 = 500;
const MIN_INTERVAL_MS: u64 = 50;
pub enum Msg {
Tick,
}
#[derive(Clone, Debug, PartialEq, Properties)]
pub struct Props {
pub duration_ms: u64,
pub on_complete: Callback<()>,
#[prop_or_default]
pub on_progress: Callback<f64>,
}
pub struct ProgressDelay {
_interval: Interval,
start: Instant,
value: f64,
}
impl Component for ProgressDelay {
type Message = Msg;
type Properties = Props;
fn create(ctx: &Context<Self>) -> Self {
let interval = (ctx.props().duration_ms / RESOLUTION).min(MIN_INTERVAL_MS);
let link = ctx.link().clone();
let interval = Interval::new(interval as u32, move || link.send_message(Msg::Tick));
Self {
_interval: interval,
start: Instant::now(),
value: 0.0,
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Tick => {
let duration = ctx.props().duration_ms;
let elapsed = self.start.elapsed().as_millis() as u64;
self.value = elapsed as f64 / duration as f64;
if elapsed > duration {
ctx.props().on_complete.emit(());
self.start = Instant::now();
} else {
ctx.props().on_progress.emit(self.value);
}
true
}
}
}
fn view(&self, _ctx: &Context<Self>) -> Html {
let value = self.value;
html! {
<progress class="progress is-primary" value={value.to_string()} max=1.0>
{ format!("{:.0}%", 100.0 * value) }
</progress>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/router/src/components/post_card.rs | examples/router/src/components/post_card.rs | use yew::prelude::*;
use yew_router::components::Link;
use crate::content::PostMeta;
use crate::generator::Generated;
use crate::Route;
#[derive(Clone, Debug, PartialEq, Eq, Properties)]
pub struct Props {
pub seed: u64,
}
pub struct PostCard {
post: PostMeta,
}
impl Component for PostCard {
type Message = ();
type Properties = Props;
fn create(ctx: &Context<Self>) -> Self {
Self {
post: PostMeta::generate_from_seed(ctx.props().seed),
}
}
fn changed(&mut self, ctx: &Context<Self>, _old_props: &Self::Properties) -> bool {
self.post = PostMeta::generate_from_seed(ctx.props().seed);
true
}
fn view(&self, _ctx: &Context<Self>) -> Html {
let Self { post } = self;
html! {
<div class="card">
<div class="card-image">
<figure class="image is-2by1">
<img alt="This post's image" src={post.image_url.clone()} loading="lazy" />
</figure>
</div>
<div class="card-content">
<Link<Route> classes={classes!("title", "is-block")} to={Route::Post { id: post.seed }}>
{ &post.title }
</Link<Route>>
<Link<Route> classes={classes!("subtitle", "is-block")} to={Route::Author { id: post.author.seed }}>
{ &post.author.name }
</Link<Route>>
</div>
</div>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/router/src/components/author_card.rs | examples/router/src/components/author_card.rs | use yew::prelude::*;
use yew_router::prelude::*;
use crate::content::Author;
use crate::generator::Generated;
use crate::Route;
#[derive(Clone, Debug, PartialEq, Eq, Properties)]
pub struct Props {
pub seed: u64,
}
pub struct AuthorCard {
author: Author,
}
impl Component for AuthorCard {
type Message = ();
type Properties = Props;
fn create(ctx: &Context<Self>) -> Self {
Self {
author: Author::generate_from_seed(ctx.props().seed),
}
}
fn changed(&mut self, ctx: &Context<Self>, _old_props: &Self::Properties) -> bool {
self.author = Author::generate_from_seed(ctx.props().seed);
true
}
fn view(&self, _ctx: &Context<Self>) -> Html {
let Self { author } = self;
html! {
<div class="card">
<div class="card-content">
<div class="media">
<div class="media-left">
<figure class="image is-128x128">
<img alt="Author's profile picture" src={author.image_url.clone()} />
</figure>
</div>
<div class="media-content">
<p class="title is-3">{ &author.name }</p>
<p>
{ "I like " }
<b>{ author.keywords.join(", ") }</b>
</p>
</div>
</div>
</div>
<footer class="card-footer">
<Link<Route> classes={classes!("card-footer-item")} to={Route::Author { id: author.seed }}>
{ "Profile" }
</Link<Route>>
</footer>
</div>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.