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/router/src/components/mod.rs | examples/router/src/components/mod.rs | pub mod author_card;
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/router/src/components/pagination.rs | examples/router/src/components/pagination.rs | 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: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Properties)]
pub struct Props {
pub page: u64,
pub total_pages: u64,
pub route_to_page: Route,
}
pub struct Pagination;
impl Component for Pagination {
type Message = ();
type Properties = Props;
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<nav class="pagination is-right" role="navigation" aria-label="pagination">
{ self.view_relnav_buttons(ctx.props()) }
<ul class="pagination-list">
{ self.view_links(ctx.props()) }
</ul>
</nav>
}
}
}
impl Pagination {
fn render_link(&self, to_page: u64, props: &Props) -> Html {
let Props {
page,
route_to_page,
..
} = props.clone();
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>
}
}
fn render_links<P>(&self, mut pages: P, len: usize, max_links: usize, props: &Props) -> Html
where
P: Iterator<Item = u64> + DoubleEndedIterator,
{
if len > max_links {
let last_link = self.render_link(pages.next_back().unwrap(), props);
// remove 1 for the ellipsis and 1 for the last link
let links = pages
.take(max_links - 2)
.map(|page| self.render_link(page, props));
html! {
<>
{ for links }
<li><span class="pagination-ellipsis">{ ELLIPSIS }</span></li>
{ last_link }
</>
}
} else {
html! {
for page in pages {
{self.render_link(page, props)}
}
}
}
}
fn view_links(&self, 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! {
<>
{ self.render_links(1..page, pages_prev, links_left, props) }
<li>{ self.render_link(page, props) }</li>
{ self.render_links(page + 1..=total_pages, pages_next, links_right, props) }
</>
}
}
fn view_relnav_buttons(&self, 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>>
</>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/game_of_life/src/conway.rs | examples/game_of_life/src/conway.rs | use rand::Rng;
pub struct Conway {
pub cellules: Vec<bool>,
pub width: usize,
pub height: usize,
}
impl Conway {
pub fn new(width: usize, height: usize) -> Self {
Self {
cellules: vec![false; width * height],
width,
height,
}
}
pub fn alive(&self, row: usize, col: usize) -> bool {
self.cellules[row * self.width + col]
}
pub fn toggle(&mut self, row: usize, col: usize) {
let i = row * self.width + col;
self.cellules[i] = !self.cellules[i];
}
pub fn random_mutate(&mut self) {
let mut rng = rand::rng();
self.cellules.iter_mut().for_each(|c| *c = rng.random());
}
pub fn reset(&mut self) {
self.cellules.iter_mut().for_each(|c| *c = false);
}
pub fn step(&mut self) {
let mut to_toggle = Vec::new();
for row in 0..self.height {
for col in 0..self.width {
let n = self.live_neighbours(row as isize, col as isize);
if (self.alive(row, col) && (n <= 1 || n > 3)) || (!self.alive(row, col) && n == 3)
{
to_toggle.push((row, col));
}
}
}
to_toggle
.iter()
.for_each(|(row, col)| self.toggle(*row, *col));
}
fn live_neighbours(&self, row: isize, col: isize) -> usize {
(-1..=1)
.flat_map(|r| (-1..=1).map(move |c| (r, c)))
.filter(|&(r, c)| (r, c) != (0, 0))
.filter(|&(r, c)| self.cellules[self.row_col_as_idx(row + r, col + c)])
.count()
}
fn row_col_as_idx(&self, row: isize, col: isize) -> usize {
let row = wrap(row, self.height as isize);
let col = wrap(col, self.width as isize);
row * self.width + col
}
}
fn wrap(idx: isize, range: isize) -> usize {
((idx % range + range) % range) as usize // because % has sign of dividend
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/game_of_life/src/main.rs | examples/game_of_life/src/main.rs | use gloo::timers::callback::Interval;
use yew::html::Scope;
use yew::{classes, html, Component, Context, Html};
mod conway;
pub enum Msg {
Random,
Start,
Step,
Reset,
Stop,
ToggleCellule((usize, usize)),
Tick,
}
pub struct App {
active: bool,
conway: conway::Conway,
_interval: Interval,
}
impl App {
fn view_cellule(&self, row: usize, col: usize, link: &Scope<Self>) -> Html {
let status = if self.conway.alive(row, col) {
"cellule-live"
} else {
"cellule-dead"
};
html! {
<div class={classes!("game-cellule", status)}
onclick={link.callback(move |_| Msg::ToggleCellule((row,col)))}>
</div>
}
}
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(ctx: &Context<Self>) -> Self {
let callback = ctx.link().callback(|_| Msg::Tick);
Self {
active: false,
conway: conway::Conway::new(53, 40),
_interval: Interval::new(200, move || callback.emit(())),
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
let mut render = true;
match msg {
Msg::Random => {
self.conway.random_mutate();
log::info!("Random");
}
Msg::Start => {
self.active = true;
log::info!("Start");
render = false;
}
Msg::Step => {
self.conway.step();
}
Msg::Reset => {
self.conway.reset();
log::info!("Reset");
}
Msg::Stop => {
self.active = false;
log::info!("Stop");
render = false;
}
Msg::ToggleCellule((row, col)) => self.conway.toggle(row, col),
Msg::Tick => {
if self.active {
self.conway.step();
} else {
render = false;
}
}
}
render
}
fn view(&self, ctx: &Context<Self>) -> Html {
let cell_rows = self
.conway
.cellules
.chunks(self.conway.width)
.enumerate()
.map(|(row, cellules)| {
let cells = cellules
.iter()
.enumerate()
.map(|(col, _)| self.view_cellule(row, col, ctx.link()));
html! {
<div class="game-row">
{ for cells }
</div>
}
});
html! {
<div>
<section class="game-container">
<header class="app-header">
<img alt="The app logo" src="favicon.ico" class="app-logo"/>
<h1 class="app-title">{ "Game of Life" }</h1>
</header>
<section class="game-area">
<div class="game-of-life">
{ for cell_rows }
</div>
<div class="game-buttons">
<button class="game-button" onclick={ctx.link().callback(|_| Msg::Random)}>{ "Random" }</button>
<button class="game-button" onclick={ctx.link().callback(|_| Msg::Step)}>{ "Step" }</button>
<button class="game-button" onclick={ctx.link().callback(|_| Msg::Start)}>{ "Start" }</button>
<button class="game-button" onclick={ctx.link().callback(|_| Msg::Stop)}>{ "Stop" }</button>
<button class="game-button" onclick={ctx.link().callback(|_| Msg::Reset)}>{ "Reset" }</button>
</div>
</section>
</section>
<footer class="app-footer">
<strong class="footer-text">
{ "Game of Life - a yew experiment " }
</strong>
<a href="https://github.com/yewstack/yew" target="_blank">{ "source" }</a>
</footer>
</div>
}
}
}
fn main() {
wasm_logger::init(wasm_logger::Config::default());
log::trace!("Initializing yew...");
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/suspense/src/use_sleep.rs | examples/suspense/src/use_sleep.rs | use std::rc::Rc;
use std::time::Duration;
use gloo::timers::future::sleep;
use yew::prelude::*;
use yew::suspense::{Suspension, SuspensionResult};
#[derive(PartialEq)]
pub struct SleepState {
s: Suspension,
}
impl SleepState {
fn new() -> Self {
let s = Suspension::from_future(async {
sleep(Duration::from_secs(5)).await;
});
Self { s }
}
}
impl Reducible for SleepState {
type Action = ();
fn reduce(self: Rc<Self>, _action: Self::Action) -> Rc<Self> {
Self::new().into()
}
}
#[hook]
pub fn use_sleep() -> SuspensionResult<Rc<dyn Fn()>> {
let sleep_state = use_reducer(SleepState::new);
if sleep_state.s.resumed() {
Ok(Rc::new(move || sleep_state.dispatch(())))
} else {
Err(sleep_state.s.clone())
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/suspense/src/struct_consumer.rs | examples/suspense/src/struct_consumer.rs | use web_sys::HtmlTextAreaElement;
use yew::prelude::*;
use crate::use_sleep;
#[function_component]
pub fn WithSleep<Comp>() -> HtmlResult
where
Comp: BaseComponent<Properties = AppContentProps>,
{
let sleep = use_sleep()?;
let sleep = Callback::from(move |_| sleep());
Ok(yew::virtual_dom::VChild::<Comp>::new(AppContentProps { resleep: sleep }, None).into())
}
#[derive(Debug, PartialEq, Properties)]
pub struct AppContentProps {
pub resleep: Callback<()>,
}
pub type AppContent = WithSleep<BaseAppContent>;
pub enum Msg {
ValueUpdate(String),
TakeABreak,
}
pub struct BaseAppContent {
value: String,
}
impl Component for BaseAppContent {
type Message = Msg;
type Properties = AppContentProps;
fn create(_ctx: &Context<Self>) -> Self {
Self {
value: "I am writing a long story...".to_string(),
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::ValueUpdate(v) => {
self.value = v;
}
Msg::TakeABreak => {
ctx.props().resleep.emit(());
}
};
true
}
fn view(&self, ctx: &Context<Self>) -> Html {
let oninput = ctx.link().callback(|e: InputEvent| {
let input: HtmlTextAreaElement = e.target_unchecked_into::<HtmlTextAreaElement>();
Msg::ValueUpdate(input.value())
});
let on_take_a_break = ctx.link().callback(|_| Msg::TakeABreak);
html! {
<div class="content-area">
<textarea value={self.value.clone()} {oninput} />
<div class="action-area">
<button onclick={on_take_a_break}>{"Take a break!"}</button>
<div class="hint">{"You can take a break at anytime"}<br />{"and your work will be preserved."}</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/suspense/src/main.rs | examples/suspense/src/main.rs | use web_sys::HtmlTextAreaElement;
use yew::prelude::*;
mod struct_consumer;
mod use_sleep;
pub use use_sleep::use_sleep;
#[derive(Debug, PartialEq, Properties)]
struct PleaseWaitProps {
from: &'static str,
}
#[function_component(PleaseWait)]
fn please_wait(props: &PleaseWaitProps) -> Html {
html! {<div class="content-area">{"Please wait 5 Seconds for "}{props.from}{" component to load..."}</div>}
}
#[function_component(AppContent)]
fn app_content() -> HtmlResult {
let resleep = use_sleep()?;
let value = use_state(|| "I am writing a long story...".to_string());
let on_text_input = {
let value = value.clone();
Callback::from(move |e: InputEvent| {
let input: HtmlTextAreaElement = e.target_unchecked_into::<HtmlTextAreaElement>();
value.set(input.value());
})
};
let on_take_a_break = Callback::from(move |_| resleep());
Ok(html! {
<div class="content-area">
<textarea value={value.to_string()} oninput={on_text_input} />
<div class="action-area">
<button onclick={on_take_a_break}>{"Take a break!"}</button>
<div class="hint">{"You can take a break at anytime"}<br />{"and your work will be preserved."}</div>
</div>
</div>
})
}
#[function_component(App)]
fn app() -> Html {
let fallback_fn = html! {<PleaseWait from="function" />};
let fallback_struct = html! {<PleaseWait from="struct" />};
html! {
<div class="layout">
<div class="content">
<h2>{" Yew Suspense Demo -- function component consumer"}</h2>
<Suspense fallback={fallback_fn}>
<AppContent />
</Suspense>
</div>
<div class="content">
<h2>{"Yew Suspense Demo -- struct component consumer"}</h2>
<Suspense fallback={fallback_struct}>
<struct_consumer::AppContent />
</Suspense>
</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/contexts/src/producer.rs | examples/contexts/src/producer.rs | use yew::prelude::*;
use super::msg_ctx::MessageContext;
#[function_component]
pub fn Producer() -> Html {
let msg_ctx = use_context::<MessageContext>().unwrap();
html! {
<button onclick={move |_| msg_ctx.dispatch("Message Received.".to_string())}>
{"PRESS ME"}
</button>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/contexts/src/struct_component_producer.rs | examples/contexts/src/struct_component_producer.rs | use yew::prelude::*;
use super::msg_ctx::MessageContext;
pub struct StructComponentProducer;
impl Component for StructComponentProducer {
type Message = ();
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, ctx: &Context<Self>) -> Html {
let (msg_ctx, _) = ctx
.link()
.context::<MessageContext>(Callback::noop())
.expect("No Message Context Provided");
html! {
<button onclick={move |_| msg_ctx.dispatch("Other message received.".to_owned())}>
{"OR ME"}
</button>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/contexts/src/msg_ctx.rs | examples/contexts/src/msg_ctx.rs | use std::rc::Rc;
use yew::prelude::*;
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Message {
pub inner: String,
}
impl Reducible for Message {
type Action = String;
fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
Message { inner: action }.into()
}
}
pub type MessageContext = UseReducerHandle<Message>;
#[derive(Properties, Debug, PartialEq)]
pub struct MessageProviderProps {
#[prop_or_default]
pub children: Html,
}
#[function_component]
pub fn MessageProvider(props: &MessageProviderProps) -> Html {
let msg = use_reducer(|| Message {
inner: "No message yet.".to_string(),
});
html! {
<ContextProvider<MessageContext> context={msg}>
{props.children.clone()}
</ContextProvider<MessageContext>>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/contexts/src/struct_component_subscriber.rs | examples/contexts/src/struct_component_subscriber.rs | use yew::prelude::*;
use super::msg_ctx::MessageContext;
pub enum Msg {
MessageContextUpdated(MessageContext),
}
pub struct StructComponentSubscriber {
message: MessageContext,
_context_listener: ContextHandle<MessageContext>,
}
impl Component for StructComponentSubscriber {
type Message = Msg;
type Properties = ();
fn create(ctx: &Context<Self>) -> Self {
let (message, context_listener) = ctx
.link()
.context(ctx.link().callback(Msg::MessageContextUpdated))
.expect("No Message Context Provided");
Self {
message,
_context_listener: context_listener,
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::MessageContextUpdated(message) => {
self.message = message;
true
}
}
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {
<h1>{ self.message.inner.to_string() }</h1>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/contexts/src/main.rs | examples/contexts/src/main.rs | mod msg_ctx;
mod producer;
mod struct_component_producer;
mod struct_component_subscriber;
mod subscriber;
use msg_ctx::MessageProvider;
use producer::Producer;
use struct_component_producer::StructComponentProducer;
use struct_component_subscriber::StructComponentSubscriber;
use subscriber::Subscriber;
use yew::prelude::*;
#[function_component]
pub fn App() -> Html {
html! {
<MessageProvider>
<Producer />
<StructComponentProducer />
<Subscriber />
<StructComponentSubscriber />
</MessageProvider>
}
}
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/contexts/src/subscriber.rs | examples/contexts/src/subscriber.rs | use yew::prelude::*;
use super::msg_ctx::MessageContext;
#[function_component]
pub fn Subscriber() -> Html {
let msg_ctx = use_context::<MessageContext>().unwrap();
let message = msg_ctx.inner.to_owned();
html! {
<h1>{ message }</h1>
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/counter_functional/src/main.rs | examples/counter_functional/src/main.rs | use yew::prelude::*;
#[function_component]
fn App() -> Html {
let state = use_state(|| 0);
let incr_counter = {
let state = state.clone();
Callback::from(move |_| state.set(*state + 1))
};
let decr_counter = {
let state = state.clone();
Callback::from(move |_| state.set(*state - 1))
};
html! {
<>
<p> {"current count: "} {*state} </p>
<button onclick={incr_counter}> {"+"} </button>
<button onclick={decr_counter}> {"-"} </button>
</>
}
}
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/password_strength/src/app.rs | examples/password_strength/src/app.rs | extern crate zxcvbn;
use yew::prelude::*;
use zxcvbn::zxcvbn;
use crate::password::generate_password;
use crate::text_input::TextInput;
pub enum Msg {
SetPassword(String),
RegeneratePassword,
}
#[derive(Debug, Default)]
pub struct App {
password: String,
}
impl App {
fn get_estimate(&self) -> u8 {
let score = zxcvbn(&self.password, &[]).score();
score.into()
}
fn redout_top_row_text(&self) -> String {
if self.password.is_empty() {
return "Provide a password".to_string();
}
let estimate_text = match self.get_estimate() {
0 => "That's a password?",
1 => "You can do a lot better.",
2 => "Meh",
3 => "Good",
_ => "Great!",
};
format!("Complexity = {estimate_text}")
}
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self::default()
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::SetPassword(next_password) => self.password = next_password,
Msg::RegeneratePassword => self.password = generate_password(),
};
true
}
fn view(&self, ctx: &Context<Self>) -> Html {
let on_change = ctx.link().callback(Msg::SetPassword);
let onclick = ctx.link().callback(|_| Msg::RegeneratePassword);
html! {
<main>
<div class="entry">
<div>
{"Enter a password below:"}
<div class="footnote">
{"(Will show in clear text)"}
</div>
</div>
<div>
<TextInput {on_change} value={self.password.clone()} />
</div>
</div>
<div class="readout">
<div>
{self.redout_top_row_text()}
</div>
<button {onclick}>
{"Generate new password *"}
</button>
<div class="footnote">
{"* Note: generated passwords are not actually cryptographically secure"}
</div>
</div>
</main>
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/password_strength/src/password.rs | examples/password_strength/src/password.rs | const PASSWORD_LEN: i32 = 17;
pub fn generate_password() -> String {
let mut space: Vec<char> = vec![];
for c in 'a'..='z' {
space.push(c);
}
for c in 'A'..='Z' {
space.push(c);
}
for c in '0'..='9' {
space.push(c);
}
space.extend(
[
'_', ']', '[', '.', '-', '+', '=', ':', ';', '/', '?', '<', '>', '\\', '*', '&', '^',
'%', '$', '#', '@', '!', '`', '~', ',',
]
.iter(),
);
let mut result = "".to_string();
for _ in 0..PASSWORD_LEN {
let i = (js_sys::Math::random() * space.len() as f64).floor() as usize;
result.push(space[i]);
}
result
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/password_strength/src/text_input.rs | examples/password_strength/src/text_input.rs | use wasm_bindgen::{JsCast, UnwrapThrowExt};
use web_sys::{Event, HtmlInputElement, InputEvent};
use yew::prelude::*;
#[derive(Clone, PartialEq, Properties)]
pub struct Props {
pub value: String,
pub on_change: Callback<String>,
}
fn get_value_from_input_event(e: InputEvent) -> String {
let event: Event = e.dyn_into().unwrap_throw();
let event_target = event.target().unwrap_throw();
let target: HtmlInputElement = event_target.dyn_into().unwrap_throw();
web_sys::console::log_1(&target.value().into());
target.value()
}
/// Controlled Text Input Component
#[function_component(TextInput)]
pub fn text_input(props: &Props) -> Html {
let Props { value, on_change } = props.clone();
let oninput = Callback::from(move |input_event: InputEvent| {
on_change.emit(get_value_from_input_event(input_event));
});
html! {
<input type="text" {value} {oninput} />
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/examples/password_strength/src/main.rs | examples/password_strength/src/main.rs | #![recursion_limit = "256"]
mod text_input;
mod app;
mod password;
use app::App;
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/packages/yew/src/lib.rs | packages/yew/src/lib.rs | #![allow(clippy::needless_doctest_main)]
#![doc(html_logo_url = "https://yew.rs/img/logo.png")]
#![cfg_attr(documenting, feature(doc_cfg))]
#![cfg_attr(nightly_yew, feature(fn_traits, unboxed_closures))]
//! # Yew Framework - API Documentation
//!
//! Yew is a modern Rust framework for creating multi-threaded front-end web apps using WebAssembly
//!
//! - Features a macro for declaring interactive HTML with Rust expressions. Developers who have
//! experience using JSX in React should feel quite at home when using Yew.
//! - Achieves high performance by minimizing DOM API calls for each page render and by making it
//! easy to offload processing to background web workers.
//! - Supports JavaScript interoperability, allowing developers to leverage NPM packages and
//! integrate with existing JavaScript applications.
//!
//! ### Supported Targets (Client-Side Rendering)
//! - `wasm32-unknown-unknown`
//!
//! ### Note
//!
//! Server-Side Rendering should work on all targets when feature `ssr` is enabled.
//!
//! ### Supported Features:
//! - `csr`: Enables Client-side Rendering support and [`Renderer`]. Only enable this feature if you
//! are making a Yew application (not a library).
//! - `ssr`: Enables Server-side Rendering support and [`ServerRenderer`].
//! - `hydration`: Enables Hydration support.
//!
//! ## Example
//!
//! ```rust,no_run
//! use yew::prelude::*;
//!
//! enum Msg {
//! AddOne,
//! }
//!
//! struct App {
//! value: i64,
//! }
//!
//! 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::AddOne => {
//! self.value += 1;
//! true
//! }
//! }
//! }
//!
//! fn view(&self, ctx: &Context<Self>) -> Html {
//! html! {
//! <div>
//! <button onclick={ctx.link().callback(|_| Msg::AddOne)}>{ "+1" }</button>
//! <p>{ self.value }</p>
//! </div>
//! }
//! }
//! }
//!
//! fn main() {
//! yew::Renderer::<App>::new().render();
//! }
//! ```
#![deny(
missing_docs,
missing_debug_implementations,
bare_trait_objects,
anonymous_parameters,
elided_lifetimes_in_paths
)]
#![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]
#![recursion_limit = "512"]
extern crate self as yew;
/// This macro provides a convenient way to create [`Classes`].
///
/// The macro takes a list of items similar to the [`vec!`] macro and returns a [`Classes`]
/// instance. Each item can be of any type that implements `Into<Classes>` (See the
/// implementations on [`Classes`] to learn what types can be used).
///
/// # Example
///
/// ```
/// # use yew::prelude::*;
/// # fn test() {
/// let conditional_class = Some("my-other-class");
/// let vec_of_classes = vec![
/// "one-bean",
/// "two-beans",
/// "three-beans",
/// "a-very-small-casserole",
/// ];
///
/// html! {
/// <div class={classes!("my-container-class", conditional_class, vec_of_classes)}>
/// // ...
/// </div>
/// };
/// # }
/// ```
pub use yew_macro::classes;
/// This macro implements JSX-like templates.
///
/// This macro always returns [`Html`].
/// If you need to preserve the type of a component, use the [`html_nested!`] macro instead.
///
/// More information about using the `html!` macro can be found in the [Yew Docs]
///
/// [`Html`]: ./html/type.Html.html
/// [`html_nested!`]: ./macro.html_nested.html
/// [Yew Docs]: https://yew.rs/docs/next/concepts/html
pub use yew_macro::html;
/// This macro is similar to [`html!`], but preserves the component type instead
/// of wrapping it in [`Html`].
///
/// That macro is useful when, for example, in a typical implementation of a list
/// component (let's assume it's called `List`).
/// In a typical implementation you might find two component types -- `List` and `ListItem`.
/// Only `ListItem` components are allowed to be children of List`.
///
/// You can find an example implementation of this in the [`nested_list`] example.
/// That example shows, how to create static lists with their children.
///
/// ```
/// # use yew::prelude::*;
/// use yew::html::ChildrenRenderer;
/// use yew::virtual_dom::VChild;
///
/// #[derive(Clone, Properties, PartialEq)]
/// struct ListProps {
/// children: ChildrenRenderer<ListItem>,
/// }
///
/// struct List;
/// impl Component for List {
/// # type Message = ();
/// type Properties = ListProps;
/// // ...
/// # fn create(ctx: &Context<Self>) -> Self { Self }
/// # fn view(&self, ctx: &Context<Self>) -> Html { unimplemented!() }
/// }
///
/// #[derive(Clone, PartialEq)]
/// struct ListItem;
/// impl Component for ListItem {
/// # type Message = ();
/// # type Properties = ();
/// // ...
/// # fn create(ctx: &Context<Self>) -> Self { Self }
/// # fn view(&self, ctx: &Context<Self>) -> Html { unimplemented!() }
/// }
///
/// // Required for ChildrenRenderer
/// impl From<VChild<ListItem>> for ListItem {
/// fn from(child: VChild<ListItem>) -> Self {
/// Self
/// }
/// }
///
/// impl Into<Html> for ListItem {
/// fn into(self) -> Html {
/// html! { <self /> }
/// }
/// }
/// // You can use `List` with nested `ListItem` components.
/// // Using any other kind of element would result in a compile error.
/// # fn test() -> Html {
/// html! {
/// <List>
/// <ListItem/>
/// <ListItem/>
/// <ListItem/>
/// </List>
/// }
/// # }
/// # fn test_iter() -> Html {
/// # let some_iter = (0..10);
/// // In many cases you might want to create the content dynamically.
/// // To do this, you can use the following code:
/// html! {
/// <List>
/// { for some_iter.map(|_| html_nested!{ <ListItem/> }) }
/// </List>
/// }
/// # }
/// ```
///
/// If you used the [`html!`] macro instead of `html_nested!`, the code would
/// not compile because we explicitly indicated to the compiler that `List`
/// can only contain elements of type `ListItem` using [`ChildrenRenderer<ListItem>`],
/// while [`html!`] creates items of type [`Html`].
///
///
/// [`html!`]: ./macro.html.html
/// [`Html`]: ./html/type.Html.html
/// [`nested_list`]: https://github.com/yewstack/yew/tree/master/examples/nested_list
/// [`ChildrenRenderer<ListItem>`]: ./html/struct.ChildrenRenderer.html
pub use yew_macro::html_nested;
/// Build [`Properties`] outside of the [`html!`] macro.
///
/// It's already possible to create properties like normal Rust structs
/// but if there are lots of optional props the end result is often needlessly verbose.
/// This macro allows you to build properties the same way the [`html!`] macro does.
///
/// The macro doesn't support special props like `ref` and `key`, they need to be set in the
/// [`html!`] macro.
///
/// You can read more about `Properties` in the [Yew Docs].
///
/// # Example
///
/// ```
/// # use yew::prelude::*;
/// use std::borrow::Cow;
///
/// #[derive(Clone, Properties, PartialEq)]
/// struct Props {
/// #[prop_or_default]
/// id: usize,
/// name: Cow<'static, str>,
/// }
///
/// struct MyComponent(Props);
/// impl Component for MyComponent {
/// # type Message = ();
/// type Properties = Props;
/// // ...
/// # fn create(ctx: &Context<Self>) -> Self { unimplemented!() }
/// # fn view(&self, ctx: &Context<Self>) -> Html { unimplemented!() }
/// }
///
/// # fn foo() -> Html {
/// // You can build props directly ...
/// let props = yew::props!(Props {
/// name: Cow::from("Minka")
/// });
/// # assert_eq!(props.name, "Minka");
/// // ... or build the associated properties of a component
/// let props = yew::props!(MyComponent::Properties {
/// id: 2,
/// name: Cow::from("Lemmy")
/// });
/// # assert_eq!(props.id, 2);
///
/// // Use the Rust-like struct update syntax to create a component with the props.
/// html! {
/// <MyComponent key=1 ..props />
/// }
/// # }
/// ```
///
/// [`html!`]: ./macro.html.html
/// [`Properties`]: ./html/trait.Properties.html
/// [Yew Docs]: https://yew.rs/concepts/components/properties
pub use yew_macro::props;
/// This module contains macros which implements html! macro and JSX-like templates
pub mod macros {
pub use crate::{classes, html, html_nested, props};
}
pub mod callback;
pub mod context;
#[cfg(feature = "csr")]
mod dom_bundle;
pub mod functional;
pub mod html;
pub mod platform;
pub mod scheduler;
mod sealed;
#[cfg(feature = "ssr")]
mod server_renderer;
pub mod suspense;
pub mod utils;
pub mod virtual_dom;
#[cfg(feature = "ssr")]
pub use server_renderer::*;
#[cfg(feature = "csr")]
mod app_handle;
#[cfg(feature = "csr")]
mod renderer;
#[cfg(all(feature = "csr", any(test, feature = "test")))]
#[allow(missing_docs)]
pub mod tests;
/// The module that contains all events available in the framework.
pub mod events {
#[doc(no_inline)]
pub use web_sys::{
AnimationEvent, DragEvent, ErrorEvent, Event, FocusEvent, InputEvent, KeyboardEvent,
MouseEvent, PointerEvent, ProgressEvent, SubmitEvent, TouchEvent, TransitionEvent, UiEvent,
WheelEvent,
};
#[cfg(feature = "csr")]
pub use crate::dom_bundle::set_event_bubbling;
pub use crate::html::TargetCast;
}
#[cfg(feature = "csr")]
pub use crate::app_handle::AppHandle;
#[cfg(feature = "csr")]
pub use crate::renderer::{set_custom_panic_hook, Renderer};
pub mod prelude {
//! The Yew Prelude
//!
//! The purpose of this module is to alleviate imports of many common types:
//!
//! ```
//! # #![allow(unused_imports)]
//! use yew::prelude::*;
//! ```
#[cfg(feature = "csr")]
pub use crate::app_handle::AppHandle;
pub use crate::callback::{Callback, CallbackRef, CallbackRefMut};
pub use crate::context::{ContextHandle, ContextProvider};
pub use crate::events::*;
pub use crate::functional::*;
pub use crate::html::{
create_portal, BaseComponent, Children, ChildrenWithProps, Classes, Component, Context,
Html, HtmlResult, NodeRef, Properties,
};
pub use crate::macros::{classes, html, html_nested};
pub use crate::suspense::Suspense;
pub use crate::virtual_dom::AttrValue;
}
pub use self::prelude::*;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/renderer.rs | packages/yew/src/renderer.rs | use std::cell::Cell;
use std::panic::PanicHookInfo as PanicInfo;
use std::rc::Rc;
use web_sys::Element;
use crate::app_handle::AppHandle;
use crate::html::BaseComponent;
thread_local! {
static PANIC_HOOK_IS_SET: Cell<bool> = const { Cell::new(false) };
}
/// Set a custom panic hook.
/// Unless a panic hook is set through this function, Yew will
/// overwrite any existing panic hook when an application is rendered with [Renderer].
#[cfg(feature = "csr")]
#[allow(clippy::incompatible_msrv)]
pub fn set_custom_panic_hook(hook: Box<dyn Fn(&PanicInfo<'_>) + Sync + Send + 'static>) {
std::panic::set_hook(hook);
PANIC_HOOK_IS_SET.with(|hook_is_set| hook_is_set.set(true));
}
fn set_default_panic_hook() {
if std::thread::panicking() {
// very unlikely, but avoid hitting this when running parallel tests.
return;
}
if !PANIC_HOOK_IS_SET.with(|hook_is_set| hook_is_set.replace(true)) {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
}
}
/// The Yew Renderer.
///
/// This is the main entry point of a Yew application.
#[cfg(feature = "csr")]
#[derive(Debug)]
#[must_use = "Renderer does nothing unless render() is called."]
pub struct Renderer<COMP>
where
COMP: BaseComponent + 'static,
{
root: Element,
props: COMP::Properties,
}
impl<COMP> Default for Renderer<COMP>
where
COMP: BaseComponent + 'static,
COMP::Properties: Default,
{
fn default() -> Self {
Self::with_props(Default::default())
}
}
impl<COMP> Renderer<COMP>
where
COMP: BaseComponent + 'static,
COMP::Properties: Default,
{
/// Creates a [Renderer] that renders into the document body with default properties.
pub fn new() -> Self {
Self::default()
}
/// Creates a [Renderer] that renders into a custom root with default properties.
pub fn with_root(root: Element) -> Self {
Self::with_root_and_props(root, Default::default())
}
}
impl<COMP> Renderer<COMP>
where
COMP: BaseComponent + 'static,
{
/// Creates a [Renderer] that renders into the document body with custom properties.
pub fn with_props(props: COMP::Properties) -> Self {
Self::with_root_and_props(
gloo::utils::document()
.body()
.expect("no body node found")
.into(),
props,
)
}
/// Creates a [Renderer] that renders into a custom root with custom properties.
pub fn with_root_and_props(root: Element, props: COMP::Properties) -> Self {
Self { root, props }
}
/// Renders the application.
pub fn render(self) -> AppHandle<COMP> {
set_default_panic_hook();
AppHandle::<COMP>::mount_with_props(self.root, Rc::new(self.props))
}
}
#[cfg(feature = "hydration")]
mod feat_hydration {
use super::*;
impl<COMP> Renderer<COMP>
where
COMP: BaseComponent + 'static,
{
/// Hydrates the application.
pub fn hydrate(self) -> AppHandle<COMP> {
set_default_panic_hook();
AppHandle::<COMP>::hydrate_with_props(self.root, Rc::new(self.props))
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/server_renderer.rs | packages/yew/src/server_renderer.rs | use std::fmt;
use std::future::Future;
use futures::pin_mut;
use futures::stream::{Stream, StreamExt};
use tracing::Instrument;
use crate::html::{BaseComponent, Scope};
use crate::platform::fmt::BufStream;
use crate::platform::{LocalHandle, Runtime};
#[cfg(feature = "ssr")]
pub(crate) mod feat_ssr {
/// Passed top-down as context for `render_into_stream` functions to know the current innermost
/// `VTag` kind to apply appropriate text escaping.
/// Right now this is used to make `VText` nodes aware of their environment and correctly
/// escape their contents when rendering them during SSR.
#[derive(Default, Clone, Copy)]
pub(crate) enum VTagKind {
/// <style> tag
Style,
/// <script> tag
Script,
#[default]
/// any other tag
Other,
}
impl<T: AsRef<str>> From<T> for VTagKind {
fn from(value: T) -> Self {
let value = value.as_ref();
if value.eq_ignore_ascii_case("style") {
Self::Style
} else if value.eq_ignore_ascii_case("script") {
Self::Script
} else {
Self::Other
}
}
}
}
/// A Yew Server-side Renderer that renders on the current thread.
///
/// # Note
///
/// This renderer does not spawn its own runtime and can only be used when:
///
/// - `wasm-bindgen-futures` is selected as the backend of Yew runtime.
/// - running within a [`Runtime`](crate::platform::Runtime).
/// - running within a tokio [`LocalSet`](struct@tokio::task::LocalSet).
#[cfg(feature = "ssr")]
#[derive(Debug)]
pub struct LocalServerRenderer<COMP>
where
COMP: BaseComponent,
{
props: COMP::Properties,
hydratable: bool,
}
impl<COMP> Default for LocalServerRenderer<COMP>
where
COMP: BaseComponent,
COMP::Properties: Default,
{
fn default() -> Self {
Self::with_props(COMP::Properties::default())
}
}
impl<COMP> LocalServerRenderer<COMP>
where
COMP: BaseComponent,
COMP::Properties: Default,
{
/// Creates a [LocalServerRenderer] with default properties.
pub fn new() -> Self {
Self::default()
}
}
impl<COMP> LocalServerRenderer<COMP>
where
COMP: BaseComponent,
{
/// Creates a [LocalServerRenderer] with custom properties.
pub fn with_props(props: COMP::Properties) -> Self {
Self {
props,
hydratable: true,
}
}
/// Sets whether an the rendered result is hydratable.
///
/// Defaults to `true`.
///
/// When this is sets to `true`, the rendered artifact will include additional information
/// to assist with the hydration process.
pub fn hydratable(mut self, val: bool) -> Self {
self.hydratable = val;
self
}
/// Renders Yew Application.
pub async fn render(self) -> String {
let s = self.render_stream();
futures::pin_mut!(s);
s.collect().await
}
/// Renders Yew Application to a String.
pub async fn render_to_string(self, w: &mut String) {
let s = self.render_stream();
futures::pin_mut!(s);
while let Some(m) = s.next().await {
w.push_str(&m);
}
}
fn render_stream_inner(self) -> impl Stream<Item = String> {
let scope = Scope::<COMP>::new(None);
let outer_span = tracing::Span::current();
BufStream::new(move |mut w| async move {
let render_span = tracing::debug_span!("render_stream_item");
render_span.follows_from(outer_span);
scope
.render_into_stream(
&mut w,
self.props.into(),
self.hydratable,
Default::default(),
)
.instrument(render_span)
.await;
})
}
// The duplicate implementation below is to selectively suppress clippy lints.
// These implementations should be merged once https://github.com/tokio-rs/tracing/issues/2503 is resolved.
/// Renders Yew Application into a string Stream
#[allow(clippy::let_with_type_underscore)]
#[tracing::instrument(
level = tracing::Level::DEBUG,
name = "render_stream",
skip(self),
fields(hydratable = self.hydratable),
)]
#[inline(always)]
pub fn render_stream(self) -> impl Stream<Item = String> {
self.render_stream_inner()
}
}
/// A Yew Server-side Renderer.
///
/// This renderer spawns the rendering task to a Yew [`Runtime`]. and receives result when
/// the rendering process has finished.
///
/// See [`yew::platform`] for more information.
#[cfg(feature = "ssr")]
pub struct ServerRenderer<COMP>
where
COMP: BaseComponent,
{
create_props: Box<dyn Send + FnOnce() -> COMP::Properties>,
hydratable: bool,
rt: Option<Runtime>,
}
impl<COMP> fmt::Debug for ServerRenderer<COMP>
where
COMP: BaseComponent,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ServerRenderer<_>")
}
}
impl<COMP> Default for ServerRenderer<COMP>
where
COMP: BaseComponent,
COMP::Properties: Default,
{
fn default() -> Self {
Self::with_props(Default::default)
}
}
impl<COMP> ServerRenderer<COMP>
where
COMP: BaseComponent,
COMP::Properties: Default,
{
/// Creates a [ServerRenderer] with default properties.
pub fn new() -> Self {
Self::default()
}
}
impl<COMP> ServerRenderer<COMP>
where
COMP: BaseComponent,
{
/// Creates a [ServerRenderer] with custom properties.
///
/// # Note
///
/// The properties does not have to implement `Send`.
/// However, the function to create properties needs to be `Send`.
pub fn with_props<F>(create_props: F) -> Self
where
F: 'static + Send + FnOnce() -> COMP::Properties,
{
Self {
create_props: Box::new(create_props),
hydratable: true,
rt: None,
}
}
/// Sets the runtime the ServerRenderer will run the rendering task with.
pub fn with_runtime(mut self, rt: Runtime) -> Self {
self.rt = Some(rt);
self
}
/// Sets whether an the rendered result is hydratable.
///
/// Defaults to `true`.
///
/// When this is sets to `true`, the rendered artifact will include additional information
/// to assist with the hydration process.
pub fn hydratable(mut self, val: bool) -> Self {
self.hydratable = val;
self
}
/// Renders Yew Application.
pub async fn render(self) -> String {
let Self {
create_props,
hydratable,
rt,
} = self;
let (tx, rx) = futures::channel::oneshot::channel();
let create_task = move || async move {
let props = create_props();
let s = LocalServerRenderer::<COMP>::with_props(props)
.hydratable(hydratable)
.render()
.await;
let _ = tx.send(s);
};
Self::spawn_rendering_task(rt, create_task);
rx.await.expect("failed to render application")
}
/// Renders Yew Application to a String.
pub async fn render_to_string(self, w: &mut String) {
let mut s = self.render_stream();
while let Some(m) = s.next().await {
w.push_str(&m);
}
}
#[inline]
fn spawn_rendering_task<F, Fut>(rt: Option<Runtime>, create_task: F)
where
F: 'static + Send + FnOnce() -> Fut,
Fut: Future<Output = ()> + 'static,
{
match rt {
// If a runtime is specified, spawn to the specified runtime.
Some(m) => m.spawn_pinned(create_task),
None => match LocalHandle::try_current() {
// If within a Yew Runtime, spawn to the current runtime.
Some(m) => m.spawn_local(create_task()),
// Outside of Yew Runtime, spawn to the default runtime.
None => Runtime::default().spawn_pinned(create_task),
},
}
}
/// Renders Yew Application into a string Stream.
pub fn render_stream(self) -> impl Send + Stream<Item = String> {
let Self {
create_props,
hydratable,
rt,
} = self;
let (tx, rx) = futures::channel::mpsc::unbounded();
let create_task = move || async move {
let props = create_props();
let s = LocalServerRenderer::<COMP>::with_props(props)
.hydratable(hydratable)
.render_stream();
pin_mut!(s);
while let Some(m) = s.next().await {
let _ = tx.unbounded_send(m);
}
};
Self::spawn_rendering_task(rt, create_task);
rx
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/callback.rs | packages/yew/src/callback.rs | //! This module contains data types for interacting with `Scope`s.
//!
//! ## Relevant examples
//! - [Counter](https://github.com/yewstack/yew/tree/master/examples/counter)
//! - [Timer](https://github.com/yewstack/yew/tree/master/examples/timer)
use std::fmt;
use std::rc::Rc;
use crate::html::ImplicitClone;
macro_rules! generate_callback_impls {
($callback:ident, $in_ty:ty, $out_var:ident => $out_val:expr) => {
impl<IN, OUT, F: Fn($in_ty) -> OUT + 'static> From<F> for $callback<IN, OUT> {
fn from(func: F) -> Self {
$callback { cb: Rc::new(func) }
}
}
impl<IN, OUT> Clone for $callback<IN, OUT> {
fn clone(&self) -> Self {
Self {
cb: self.cb.clone(),
}
}
}
// We are okay with comparisons from different compilation units to result in false
// not-equal results. This should only lead in the worst-case to some unneeded re-renders.
#[allow(ambiguous_wide_pointer_comparisons)]
impl<IN, OUT> PartialEq for $callback<IN, OUT> {
fn eq(&self, other: &$callback<IN, OUT>) -> bool {
let ($callback { cb }, $callback { cb: rhs_cb }) = (self, other);
Rc::ptr_eq(cb, rhs_cb)
}
}
impl<IN, OUT> fmt::Debug for $callback<IN, OUT> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "$callback<_>")
}
}
impl<IN, OUT> $callback<IN, OUT> {
/// This method calls the callback's function.
pub fn emit(&self, value: $in_ty) -> OUT {
(*self.cb)(value)
}
}
impl<IN> $callback<IN> {
/// Creates a "no-op" callback which can be used when it is not suitable to use an
/// `Option<$callback>`.
pub fn noop() -> Self {
Self::from(|_: $in_ty| ())
}
}
impl<IN> Default for $callback<IN> {
fn default() -> Self {
Self::noop()
}
}
impl<IN: 'static, OUT: 'static> $callback<IN, OUT> {
/// Creates a new [`Callback`] from another callback and a function.
///
/// That when emitted will call that function and will emit the original callback
pub fn reform<F, T>(&self, func: F) -> Callback<T, OUT>
where
F: Fn(T) -> IN + 'static,
{
let this = self.clone();
let func = move |input: T| {
#[allow(unused_mut)]
let mut $out_var = func(input);
this.emit($out_val)
};
func.into()
}
/// Creates a new [`CallbackRef`] from another callback and a function.
///
/// That when emitted will call that function and will emit the original callback
pub fn reform_ref<F, T>(&self, func: F) -> CallbackRef<T, OUT>
where
F: Fn(&T) -> $in_ty + 'static,
{
let this = self.clone();
let func = move |input: &T| {
#[allow(unused_mut)]
let mut $out_var = func(input);
this.emit($out_val)
};
func.into()
}
/// Creates a new [`CallbackRefMut`] from another callback and a function.
///
/// That when emitted will call that function and will emit the original callback
pub fn reform_ref_mut<F, T>(&self, func: F) -> CallbackRefMut<T, OUT>
where
F: Fn(&mut T) -> $in_ty + 'static,
{
let this = self.clone();
let func = move |input: &mut T| {
#[allow(unused_mut)]
let mut $out_var = func(input);
this.emit($out_val)
};
func.into()
}
/// Creates a new [`Callback`] from another callback and a function.
///
/// When emitted will call the function and, only if it returns `Some(value)`, will emit
/// `value` to the original callback.
pub fn filter_reform<F, T>(&self, func: F) -> Callback<T, Option<OUT>>
where
F: Fn(T) -> Option<IN> + 'static,
{
let this = self.clone();
let func = move |input: T| {
func(input).map(
#[allow(unused_mut)]
|mut $out_var| this.emit($out_val),
)
};
func.into()
}
/// Creates a new [`CallbackRef`] from another callback and a function.
///
/// When emitted will call the function and, only if it returns `Some(value)`, will emit
/// `value` to the original callback.
pub fn filter_reform_ref<F, T>(&self, func: F) -> CallbackRef<T, Option<OUT>>
where
F: Fn(&T) -> Option<$in_ty> + 'static,
{
let this = self.clone();
let func = move |input: &T| {
func(input).map(
#[allow(unused_mut)]
|mut $out_var| this.emit($out_val),
)
};
func.into()
}
/// Creates a new [`CallbackRefMut`] from another callback and a function.
///
/// When emitted will call the function and, only if it returns `Some(value)`, will emit
/// `value` to the original callback.
pub fn filter_reform_ref_mut<F, T>(&self, func: F) -> CallbackRefMut<T, Option<OUT>>
where
F: Fn(&mut T) -> Option<$in_ty> + 'static,
{
let this = self.clone();
let func = move |input: &mut T| {
func(input).map(
#[allow(unused_mut)]
|mut $out_var| this.emit($out_val),
)
};
func.into()
}
}
impl<IN, OUT> ImplicitClone for $callback<IN, OUT> {}
};
}
/// Universal callback wrapper.
///
/// An `Rc` wrapper is used to make it cloneable.
pub struct Callback<IN, OUT = ()> {
/// A callback which can be called multiple times
pub(crate) cb: Rc<dyn Fn(IN) -> OUT>,
}
generate_callback_impls!(Callback, IN, output => output);
/// Universal callback wrapper with reference in argument.
///
/// An `Rc` wrapper is used to make it cloneable.
pub struct CallbackRef<IN, OUT = ()> {
/// A callback which can be called multiple times
pub(crate) cb: Rc<dyn Fn(&IN) -> OUT>,
}
generate_callback_impls!(CallbackRef, &IN, output => #[allow(clippy::needless_borrow)] &output);
/// Universal callback wrapper with mutable reference in argument.
///
/// An `Rc` wrapper is used to make it cloneable.
pub struct CallbackRefMut<IN, OUT = ()> {
/// A callback which can be called multiple times
pub(crate) cb: Rc<dyn Fn(&mut IN) -> OUT>,
}
generate_callback_impls!(CallbackRefMut, &mut IN, output => &mut output);
#[cfg(test)]
mod test {
use std::sync::Mutex;
use super::*;
/// emit the callback with the provided value
fn emit<T, I, R: 'static + Clone, F, OUT>(values: I, f: F) -> Vec<R>
where
I: IntoIterator<Item = T>,
F: FnOnce(Callback<R, ()>) -> Callback<T, OUT>,
{
let result = Rc::new(Mutex::new(Vec::new()));
let cb_result = result.clone();
let cb = f(Callback::<R, ()>::from(move |v| {
cb_result.lock().unwrap().push(v);
}));
for value in values {
cb.emit(value);
}
let x = result.lock().unwrap().clone();
x
}
#[test]
fn test_callback() {
assert_eq!(*emit([true, false], |cb| cb), vec![true, false]);
}
#[test]
fn test_reform() {
assert_eq!(
*emit([true, false], |cb| cb.reform(|v: bool| !v)),
vec![false, true]
);
}
#[test]
fn test_filter_reform() {
assert_eq!(
*emit([1, 2, 3], |cb| cb.filter_reform(|v| match v {
1 => Some(true),
2 => Some(false),
_ => None,
})),
vec![true, false]
);
}
#[test]
fn test_ref() {
let callback: CallbackRef<usize, usize> = CallbackRef::from(|x: &usize| *x);
assert_eq!(callback.emit(&42), 42);
}
#[test]
fn test_ref_mut() {
let callback: CallbackRefMut<usize, ()> = CallbackRefMut::from(|x: &mut usize| *x = 42);
let mut value: usize = 0;
callback.emit(&mut value);
assert_eq!(value, 42);
}
#[test]
fn test_reform_ref() {
let callback: Callback<usize, usize> = Callback::from(|x: usize| x + 1);
let reformed: CallbackRef<usize, usize> = callback.reform_ref(|x: &usize| *x + 2);
assert_eq!(reformed.emit(&42), 45);
}
#[test]
fn test_reform_ref_mut() {
let callback: CallbackRefMut<usize, ()> = CallbackRefMut::from(|x: &mut usize| *x += 1);
let reformed: CallbackRefMut<usize, ()> = callback.reform_ref_mut(|x: &mut usize| {
*x += 2;
x
});
let mut value: usize = 42;
reformed.emit(&mut value);
assert_eq!(value, 45);
}
#[test]
fn test_filter_reform_ref() {
let callback: Callback<usize, usize> = Callback::from(|x: usize| x + 1);
let reformed: CallbackRef<usize, Option<usize>> =
callback.filter_reform_ref(|x: &usize| Some(*x + 2));
assert_eq!(reformed.emit(&42), Some(45));
}
#[test]
fn test_filter_reform_ref_mut() {
let callback: CallbackRefMut<usize, ()> = CallbackRefMut::from(|x: &mut usize| *x += 1);
let reformed: CallbackRefMut<usize, Option<()>> =
callback.filter_reform_ref_mut(|x: &mut usize| {
*x += 2;
Some(x)
});
let mut value: usize = 42;
reformed.emit(&mut value).expect("is some");
assert_eq!(value, 45);
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/platform.rs | packages/yew/src/platform.rs | //! Yew's compatibility between JavaScript Runtime and Native Runtimes.
//!
//! This module is also published under the name [tokise] on crates.io.
//!
//! # Rationale
//!
//! When designing components and libraries that works on both WebAssembly targets backed by
//! JavaScript Runtime and non-WebAssembly targets with Native Runtimes. Developers usually face
//! challenges that requires applying multiple feature flags throughout their application:
//!
//! 1. Select I/O and timers that works with the target runtime.
//! 2. Native Runtimes usually require `Send` futures and WebAssembly types are usually `!Send`.
//!
//! # Implementation
//!
//! To alleviate these issues, Yew implements a single-threaded runtime that executes `?Send`
//! (`Send` or `!Send`) futures.
//!
//! On platforms with multi-threading support, Yew spawns multiple independent runtimes
//! proportional to the CPU core number. When tasks are spawned with a runtime handle, it will
//! randomly select a worker thread from the internal pool. All tasks spawned with `spawn_local`
//! will run on the same thread as the thread the task was running. When the runtime runs in a
//! WebAssembly target, all tasks will be scheduled on the main thread.
//!
//! This runtime is designed in favour of IO-bounded workload with similar runtime cost.
//! When running I/O workloads, it would produce a slightly better performance as tasks are
//! never moved to another thread. However, If a worker thread is busy,
//! other threads will not be able to steal tasks scheduled on the busy thread.
//! When you have a CPU-bounded task where CPU time is significantly
//! more expensive, it should be spawned with a dedicated thread (or Web Worker) and communicates
//! with the application using channels.
//!
//! Yew platform provides the following components:
//!
//! 1. A Task Scheduler that is capable of running non-Send tasks.
//! 2. A Timer that is compatible with the scheduler backend.
//! 3. Task Synchronisation Mechanisms.
//!
//! # Runtime Backend
//!
//! The Yew runtime is implemented with different runtimes depending on the target platform and can
//! use all features (timers / IO / task synchronisation) from the selected native runtime:
//!
//! - `wasm-bindgen-futures` (WebAssembly targets)
//! - `tokio` (non-WebAssembly targets)
#[doc(inline)]
pub use tokise::*;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/app_handle.rs | packages/yew/src/app_handle.rs | //! [AppHandle] contains the state Yew keeps to bootstrap a component in an isolated scope.
use std::ops::Deref;
use std::rc::Rc;
use web_sys::Element;
use crate::dom_bundle::{BSubtree, DomSlot};
use crate::html::{BaseComponent, Scope, Scoped};
/// An instance of an application.
#[derive(Debug)]
pub struct AppHandle<COMP: BaseComponent> {
/// `Scope` holder
pub(crate) scope: Scope<COMP>,
}
impl<COMP> AppHandle<COMP>
where
COMP: BaseComponent,
{
/// The main entry point of a Yew program which also allows passing properties. It works
/// similarly to the `program` function in Elm. You should provide an initial model, `update`
/// function which will update the state of the model and a `view` function which
/// will render the model to a virtual DOM tree.
#[tracing::instrument(
level = tracing::Level::DEBUG,
name = "mount",
skip(props),
)]
pub(crate) fn mount_with_props(host: Element, props: Rc<COMP::Properties>) -> Self {
clear_element(&host);
let app = Self {
scope: Scope::new(None),
};
let hosting_root = BSubtree::create_root(&host);
let _ = app
.scope
.mount_in_place(hosting_root, host, DomSlot::at_end(), props);
app
}
/// Update the properties of the app's root component.
///
/// This can be an alternative to sending and handling messages. The existing component will be
/// reused and have its properties updates. This will presumably trigger a re-render, refer to
/// the [`changed`] lifecycle for details.
///
/// [`changed`]: crate::Component::changed
#[tracing::instrument(
level = tracing::Level::DEBUG,
skip_all,
)]
pub fn update(&mut self, new_props: COMP::Properties) {
self.scope.reuse(Rc::new(new_props), DomSlot::at_end())
}
/// Schedule the app for destruction
#[tracing::instrument(
level = tracing::Level::DEBUG,
skip_all,
)]
pub fn destroy(self) {
self.scope.destroy(false)
}
}
impl<COMP> Deref for AppHandle<COMP>
where
COMP: BaseComponent,
{
type Target = Scope<COMP>;
fn deref(&self) -> &Self::Target {
&self.scope
}
}
/// Removes anything from the given element.
fn clear_element(host: &Element) {
while let Some(child) = host.last_child() {
host.remove_child(&child).expect("can't remove a child");
}
}
#[cfg(feature = "hydration")]
mod feat_hydration {
use super::*;
use crate::dom_bundle::Fragment;
impl<COMP> AppHandle<COMP>
where
COMP: BaseComponent,
{
#[tracing::instrument(
level = tracing::Level::DEBUG,
name = "hydrate",
skip(props),
)]
pub(crate) fn hydrate_with_props(host: Element, props: Rc<COMP::Properties>) -> Self {
let app = Self {
scope: Scope::new(None),
};
let mut fragment = Fragment::collect_children(&host);
let hosting_root = BSubtree::create_root(&host);
let mut previous_next_sibling = None;
app.scope.hydrate_in_place(
hosting_root,
host.clone(),
&mut fragment,
Rc::clone(&props),
&mut previous_next_sibling,
);
if let Some(previous_next_sibling) = previous_next_sibling {
previous_next_sibling.reassign(DomSlot::at_end());
}
// We remove all remaining nodes, this mimics the clear_element behaviour in
// mount_with_props.
for node in fragment.iter() {
host.remove_child(node).unwrap();
}
app
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/context.rs | packages/yew/src/context.rs | //! This module defines the `ContextProvider` component.
use std::cell::RefCell;
use slab::Slab;
use crate::html::Scope;
use crate::{Callback, Component, Context, Html, Properties};
/// Props for [`ContextProvider`]
#[derive(Debug, Clone, PartialEq, Properties)]
pub struct ContextProviderProps<T: Clone + PartialEq> {
/// Context value to be passed down
pub context: T,
/// Children
pub children: Html,
}
/// The context provider component.
///
/// Every child (direct or indirect) of this component may access the context value.
/// In order to consume contexts, [`Scope::context`][Scope::context] method is used,
/// In function components the `use_context` hook is used.
#[derive(Debug)]
pub struct ContextProvider<T: Clone + PartialEq + 'static> {
context: T,
consumers: RefCell<Slab<Callback<T>>>,
}
/// Owns the connection to a context provider. When dropped, the component will
/// no longer receive updates from the provider.
#[derive(Debug)]
pub struct ContextHandle<T: Clone + PartialEq + 'static> {
provider: Scope<ContextProvider<T>>,
key: usize,
}
impl<T: Clone + PartialEq + 'static> Drop for ContextHandle<T> {
fn drop(&mut self) {
if let Some(component) = self.provider.get_component() {
component.consumers.borrow_mut().remove(self.key);
}
}
}
impl<T: Clone + PartialEq> ContextProvider<T> {
/// Add the callback to the subscriber list to be called whenever the context changes.
/// The consumer is unsubscribed as soon as the callback is dropped.
pub(crate) fn subscribe_consumer(
&self,
callback: Callback<T>,
scope: Scope<Self>,
) -> (T, ContextHandle<T>) {
let ctx = self.context.clone();
let key = self.consumers.borrow_mut().insert(callback);
(
ctx,
ContextHandle {
provider: scope,
key,
},
)
}
/// Notify all subscribed consumers and remove dropped consumers from the list.
fn notify_consumers(&mut self) {
let consumers: Vec<Callback<T>> = self
.consumers
.borrow()
.iter()
.map(|(_, v)| v.clone())
.collect();
for consumer in consumers {
consumer.emit(self.context.clone());
}
}
}
impl<T: Clone + PartialEq + 'static> Component for ContextProvider<T> {
type Message = ();
type Properties = ContextProviderProps<T>;
fn create(ctx: &Context<Self>) -> Self {
let props = ctx.props();
Self {
context: props.context.clone(),
consumers: RefCell::new(Slab::new()),
}
}
fn changed(&mut self, ctx: &Context<Self>, old_props: &Self::Properties) -> bool {
let props = ctx.props();
let should_render = old_props.children != props.children;
if self.context != props.context {
self.context = props.context.clone();
self.notify_consumers();
}
should_render
}
fn view(&self, ctx: &Context<Self>) -> Html {
ctx.props().children.clone()
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/sealed.rs | packages/yew/src/sealed.rs | /// Base traits for sealed traits.
pub trait Sealed {}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/scheduler.rs | packages/yew/src/scheduler.rs | //! This module contains a scheduler.
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;
/// Alias for `Rc<RefCell<T>>`
pub type Shared<T> = Rc<RefCell<T>>;
/// A routine which could be run.
pub trait Runnable {
/// Runs a routine with a context instance.
fn run(self: Box<Self>);
}
struct QueueEntry {
task: Box<dyn Runnable>,
}
#[derive(Default)]
struct FifoQueue {
inner: Vec<QueueEntry>,
}
impl FifoQueue {
fn push(&mut self, task: Box<dyn Runnable>) {
self.inner.push(QueueEntry { task });
}
fn drain_into(&mut self, queue: &mut Vec<QueueEntry>) {
queue.append(&mut self.inner);
}
}
#[derive(Default)]
struct TopologicalQueue {
/// The Binary Tree Map guarantees components with lower id (parent) is rendered first
inner: BTreeMap<usize, QueueEntry>,
}
impl TopologicalQueue {
#[cfg(any(feature = "ssr", feature = "csr"))]
fn push(&mut self, component_id: usize, task: Box<dyn Runnable>) {
self.inner.insert(component_id, QueueEntry { task });
}
/// Take a single entry, preferring parents over children
#[inline]
fn pop_topmost(&mut self) -> Option<QueueEntry> {
self.inner.pop_first().map(|(_, v)| v)
}
/// Drain all entries, such that children are queued before parents
fn drain_post_order_into(&mut self, queue: &mut Vec<QueueEntry>) {
if self.inner.is_empty() {
return;
}
let rendered = std::mem::take(&mut self.inner);
// Children rendered lifecycle happen before parents.
queue.extend(rendered.into_values().rev());
}
}
/// This is a global scheduler suitable to schedule and run any tasks.
#[derive(Default)]
#[allow(missing_debug_implementations)] // todo
struct Scheduler {
// Main queue
main: FifoQueue,
// Component queues
destroy: FifoQueue,
create: FifoQueue,
props_update: FifoQueue,
update: FifoQueue,
render: TopologicalQueue,
render_first: TopologicalQueue,
render_priority: TopologicalQueue,
rendered_first: TopologicalQueue,
rendered: TopologicalQueue,
}
/// Execute closure with a mutable reference to the scheduler
#[inline]
fn with<R>(f: impl FnOnce(&mut Scheduler) -> R) -> R {
thread_local! {
/// This is a global scheduler suitable to schedule and run any tasks.
///
/// Exclusivity of mutable access is controlled by only accessing it through a set of public
/// functions.
static SCHEDULER: RefCell<Scheduler> = Default::default();
}
SCHEDULER.with(|s| f(&mut s.borrow_mut()))
}
/// Push a generic [Runnable] to be executed
pub fn push(runnable: Box<dyn Runnable>) {
with(|s| s.main.push(runnable));
// Execute pending immediately. Necessary for runnables added outside the component lifecycle,
// which would otherwise be delayed.
start();
}
#[cfg(any(feature = "ssr", feature = "csr"))]
mod feat_csr_ssr {
use super::*;
/// Push a component creation, first render and first rendered [Runnable]s to be executed
pub(crate) fn push_component_create(
component_id: usize,
create: Box<dyn Runnable>,
first_render: Box<dyn Runnable>,
) {
with(|s| {
s.create.push(create);
s.render_first.push(component_id, first_render);
});
}
/// Push a component destruction [Runnable] to be executed
pub(crate) fn push_component_destroy(runnable: Box<dyn Runnable>) {
with(|s| s.destroy.push(runnable));
}
/// Push a component render [Runnable]s to be executed
pub(crate) fn push_component_render(component_id: usize, render: Box<dyn Runnable>) {
with(|s| {
s.render.push(component_id, render);
});
}
/// Push a component update [Runnable] to be executed
pub(crate) fn push_component_update(runnable: Box<dyn Runnable>) {
with(|s| s.update.push(runnable));
}
}
#[cfg(any(feature = "ssr", feature = "csr"))]
pub(crate) use feat_csr_ssr::*;
#[cfg(feature = "csr")]
mod feat_csr {
use super::*;
pub(crate) fn push_component_rendered(
component_id: usize,
rendered: Box<dyn Runnable>,
first_render: bool,
) {
with(|s| {
if first_render {
s.rendered_first.push(component_id, rendered);
} else {
s.rendered.push(component_id, rendered);
}
});
}
pub(crate) fn push_component_props_update(props_update: Box<dyn Runnable>) {
with(|s| s.props_update.push(props_update));
}
}
#[cfg(feature = "csr")]
pub(crate) use feat_csr::*;
#[cfg(feature = "hydration")]
mod feat_hydration {
use super::*;
pub(crate) fn push_component_priority_render(component_id: usize, render: Box<dyn Runnable>) {
with(|s| {
s.render_priority.push(component_id, render);
});
}
}
#[cfg(feature = "hydration")]
pub(crate) use feat_hydration::*;
/// Execute any pending [Runnable]s
pub(crate) fn start_now() {
#[tracing::instrument(level = tracing::Level::DEBUG)]
fn scheduler_loop() {
let mut queue = vec![];
loop {
with(|s| s.fill_queue(&mut queue));
if queue.is_empty() {
break;
}
for r in queue.drain(..) {
r.task.run();
}
}
}
thread_local! {
// The lock is used to prevent recursion. If the lock cannot be acquired, it is because the
// `start()` method is being called recursively as part of a `runnable.run()`.
static LOCK: RefCell<()> = Default::default();
}
LOCK.with(|l| {
if let Ok(_lock) = l.try_borrow_mut() {
scheduler_loop();
}
});
}
#[cfg(all(
target_arch = "wasm32",
not(target_os = "wasi"),
not(feature = "not_browser_env")
))]
mod arch {
use std::sync::atomic::{AtomicBool, Ordering};
use crate::platform::spawn_local;
// Really only used as a `Cell<bool>` that is also `Sync`
static IS_SCHEDULED: AtomicBool = AtomicBool::new(false);
fn check_scheduled() -> bool {
// Since we can tolerate starting too many times, and we don't need to "see" any stores
// done in the scheduler, Relaxed ordering is fine
IS_SCHEDULED.load(Ordering::Relaxed)
}
fn set_scheduled(is: bool) {
// See comment in check_scheduled why Relaxed ordering is fine
IS_SCHEDULED.store(is, Ordering::Relaxed)
}
/// We delay the start of the scheduler to the end of the micro task queue.
/// So any messages that needs to be queued can be queued.
pub(crate) fn start() {
if check_scheduled() {
return;
}
set_scheduled(true);
spawn_local(async {
set_scheduled(false);
super::start_now();
});
}
}
#[cfg(any(
not(target_arch = "wasm32"),
target_os = "wasi",
feature = "not_browser_env"
))]
mod arch {
// Delayed rendering is not very useful in the context of server-side rendering.
// There are no event listeners or other high priority events that need to be
// processed and we risk of having a future un-finished.
// Until scheduler is future-capable which means we can join inside a future,
// it can remain synchronous.
pub(crate) fn start() {
super::start_now();
}
}
pub(crate) use arch::*;
impl Scheduler {
/// Fill vector with tasks to be executed according to Runnable type execution priority
///
/// This method is optimized for typical usage, where possible, but does not break on
/// non-typical usage (like scheduling renders in [crate::Component::create()] or
/// [crate::Component::rendered()] calls).
fn fill_queue(&mut self, to_run: &mut Vec<QueueEntry>) {
// Placed first to avoid as much needless work as possible, handling all the other events.
// Drained completely, because they are the highest priority events anyway.
self.destroy.drain_into(to_run);
// Create events can be batched, as they are typically just for object creation
self.create.drain_into(to_run);
// These typically do nothing and don't spawn any other events - can be batched.
// Should be run only after all first renders have finished.
if !to_run.is_empty() {
return;
}
// First render must never be skipped and takes priority over main, because it may need
// to init `NodeRef`s
//
// Should be processed one at time, because they can spawn more create and rendered events
// for their children.
if let Some(r) = self.render_first.pop_topmost() {
to_run.push(r);
return;
}
self.props_update.drain_into(to_run);
// Priority rendering
//
// This is needed for hydration subsequent render to fix node refs.
if let Some(r) = self.render_priority.pop_topmost() {
to_run.push(r);
return;
}
// Children rendered lifecycle happen before parents.
self.rendered_first.drain_post_order_into(to_run);
// Updates are after the first render to ensure we always have the entire child tree
// rendered, once an update is processed.
//
// Can be batched, as they can cause only non-first renders.
self.update.drain_into(to_run);
// Likely to cause duplicate renders via component updates, so placed before them
self.main.drain_into(to_run);
// Run after all possible updates to avoid duplicate renders.
//
// Should be processed one at time, because they can spawn more create and first render
// events for their children.
if !to_run.is_empty() {
return;
}
// Should be processed one at time, because they can spawn more create and rendered events
// for their children.
if let Some(r) = self.render.pop_topmost() {
to_run.push(r);
return;
}
// These typically do nothing and don't spawn any other events - can be batched.
// Should be run only after all renders have finished.
// Children rendered lifecycle happen before parents.
self.rendered.drain_post_order_into(to_run);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn push_executes_runnables_immediately() {
use std::cell::Cell;
thread_local! {
static FLAG: Cell<bool> = Default::default();
}
struct Test;
impl Runnable for Test {
fn run(self: Box<Self>) {
FLAG.with(|v| v.set(true));
}
}
push(Box::new(Test));
FLAG.with(|v| assert!(v.get()));
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/virtual_dom/key.rs | packages/yew/src/virtual_dom/key.rs | //! This module contains the implementation yew's virtual nodes' keys.
use std::fmt::{self, Display, Formatter};
use std::ops::Deref;
use std::rc::Rc;
use crate::html::ImplicitClone;
/// Represents the (optional) key of Yew's virtual nodes.
///
/// Keys are cheap to clone.
#[derive(Clone, ImplicitClone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct Key {
key: Rc<str>,
}
impl Display for Key {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.key.fmt(f)
}
}
impl Deref for Key {
type Target = str;
fn deref(&self) -> &str {
self.key.as_ref()
}
}
impl From<Rc<str>> for Key {
fn from(key: Rc<str>) -> Self {
Self { key }
}
}
impl From<&'_ str> for Key {
fn from(key: &'_ str) -> Self {
let key: Rc<str> = Rc::from(key);
Self::from(key)
}
}
impl From<String> for Key {
fn from(key: String) -> Self {
Self::from(key.as_str())
}
}
macro_rules! key_impl_from_to_string {
($type:ty) => {
impl From<$type> for Key {
fn from(key: $type) -> Self {
Self::from(key.to_string().as_str())
}
}
};
}
key_impl_from_to_string!(char);
key_impl_from_to_string!(u8);
key_impl_from_to_string!(u16);
key_impl_from_to_string!(u32);
key_impl_from_to_string!(u64);
key_impl_from_to_string!(u128);
key_impl_from_to_string!(usize);
key_impl_from_to_string!(i8);
key_impl_from_to_string!(i16);
key_impl_from_to_string!(i32);
key_impl_from_to_string!(i64);
key_impl_from_to_string!(i128);
key_impl_from_to_string!(isize);
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
mod test {
use std::rc::Rc;
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use crate::html;
wasm_bindgen_test_configure!(run_in_browser);
#[test]
fn all_key_conversions() {
let _ = html! {
<key="string literal">
<img key={"String".to_owned()} />
<p key={Rc::<str>::from("rc")}></p>
<key='a'>
<p key=11_usize></p>
<p key=12_u8></p>
<p key=13_u16></p>
<p key=14_u32></p>
<p key=15_u64></p>
<p key=16_u128></p>
<p key=21_isize></p>
<p key=22_i8></p>
<p key=23_i16></p>
<p key=24_i32></p>
<p key=25_i128></p>
</>
</>
};
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/virtual_dom/vlist.rs | packages/yew/src/virtual_dom/vlist.rs | //! This module contains fragments implementation.
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use super::{Key, VNode};
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FullyKeyedState {
KnownFullyKeyed,
KnownMissingKeys,
Unknown,
}
/// This struct represents a fragment of the Virtual DOM tree.
#[derive(Clone, Debug)]
pub struct VList {
/// The list of child [VNode]s
pub(crate) children: Option<Rc<Vec<VNode>>>,
/// All [VNode]s in the VList have keys
fully_keyed: FullyKeyedState,
pub key: Option<Key>,
}
impl PartialEq for VList {
fn eq(&self, other: &Self) -> bool {
if self.key != other.key {
return false;
}
match (self.children.as_ref(), other.children.as_ref()) {
(Some(a), Some(b)) => a == b,
(Some(a), None) => a.is_empty(),
(None, Some(b)) => b.is_empty(),
(None, None) => true,
}
}
}
impl Default for VList {
fn default() -> Self {
Self::new()
}
}
impl Deref for VList {
type Target = Vec<VNode>;
fn deref(&self) -> &Self::Target {
match self.children {
Some(ref m) => m,
None => {
// This can be replaced with `const { &Vec::new() }` in Rust 1.79.
const EMPTY: &Vec<VNode> = &Vec::new();
EMPTY
}
}
}
}
impl DerefMut for VList {
fn deref_mut(&mut self) -> &mut Self::Target {
self.fully_keyed = FullyKeyedState::Unknown;
self.children_mut()
}
}
impl<A: Into<VNode>> FromIterator<A> for VList {
fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
let children = iter.into_iter().map(|n| n.into()).collect::<Vec<_>>();
if children.is_empty() {
VList::new()
} else {
VList {
children: Some(Rc::new(children)),
fully_keyed: FullyKeyedState::Unknown,
key: None,
}
}
}
}
impl From<Option<Rc<Vec<VNode>>>> for VList {
fn from(children: Option<Rc<Vec<VNode>>>) -> Self {
if children.as_ref().map(|x| x.is_empty()).unwrap_or(true) {
VList::new()
} else {
let mut vlist = VList {
children,
fully_keyed: FullyKeyedState::Unknown,
key: None,
};
vlist.recheck_fully_keyed();
vlist
}
}
}
impl From<Vec<VNode>> for VList {
fn from(children: Vec<VNode>) -> Self {
if children.is_empty() {
VList::new()
} else {
let mut vlist = VList {
children: Some(Rc::new(children)),
fully_keyed: FullyKeyedState::Unknown,
key: None,
};
vlist.recheck_fully_keyed();
vlist
}
}
}
impl From<VNode> for VList {
fn from(child: VNode) -> Self {
let mut vlist = VList {
children: Some(Rc::new(vec![child])),
fully_keyed: FullyKeyedState::Unknown,
key: None,
};
vlist.recheck_fully_keyed();
vlist
}
}
impl VList {
/// Creates a new empty [VList] instance.
pub const fn new() -> Self {
Self {
children: None,
key: None,
fully_keyed: FullyKeyedState::KnownFullyKeyed,
}
}
/// Creates a new [VList] instance with children.
pub fn with_children(children: Vec<VNode>, key: Option<Key>) -> Self {
let mut vlist = VList::from(children);
vlist.key = key;
vlist
}
#[doc(hidden)]
/// Used by `html!` to avoid calling `.recheck_fully_keyed()` when possible.
pub fn __macro_new(
children: Vec<VNode>,
key: Option<Key>,
fully_keyed: FullyKeyedState,
) -> Self {
VList {
children: Some(Rc::new(children)),
fully_keyed,
key,
}
}
// Returns a mutable reference to children, allocates the children if it hasn't been done.
//
// This method does not reassign key state. So it should only be used internally.
fn children_mut(&mut self) -> &mut Vec<VNode> {
loop {
match self.children {
Some(ref mut m) => return Rc::make_mut(m),
None => {
self.children = Some(Rc::new(Vec::new()));
}
}
}
}
/// Add [VNode] child.
pub fn add_child(&mut self, child: VNode) {
if self.fully_keyed == FullyKeyedState::KnownFullyKeyed && !child.has_key() {
self.fully_keyed = FullyKeyedState::KnownMissingKeys;
}
self.children_mut().push(child);
}
/// Add multiple [VNode] children.
pub fn add_children(&mut self, children: impl IntoIterator<Item = VNode>) {
let it = children.into_iter();
let bound = it.size_hint();
self.children_mut().reserve(bound.1.unwrap_or(bound.0));
for ch in it {
self.add_child(ch);
}
}
/// Recheck, if the all the children have keys.
///
/// You can run this, after modifying the child list through the [DerefMut] implementation of
/// [VList], to precompute an internally kept flag, which speeds up reconciliation later.
pub fn recheck_fully_keyed(&mut self) {
self.fully_keyed = if self.fully_keyed() {
FullyKeyedState::KnownFullyKeyed
} else {
FullyKeyedState::KnownMissingKeys
};
}
pub(crate) fn fully_keyed(&self) -> bool {
match self.fully_keyed {
FullyKeyedState::KnownFullyKeyed => true,
FullyKeyedState::KnownMissingKeys => false,
FullyKeyedState::Unknown => self.iter().all(|c| c.has_key()),
}
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::virtual_dom::{VTag, VText};
#[test]
fn mutably_change_children() {
let mut vlist = VList::new();
assert_eq!(
vlist.fully_keyed,
FullyKeyedState::KnownFullyKeyed,
"should start fully keyed"
);
// add a child that is keyed
vlist.add_child(VNode::VTag({
let mut tag = VTag::new("a");
tag.key = Some(42u32.into());
tag.into()
}));
assert_eq!(
vlist.fully_keyed,
FullyKeyedState::KnownFullyKeyed,
"should still be fully keyed"
);
assert_eq!(vlist.len(), 1, "should contain 1 child");
// now add a child that is not keyed
vlist.add_child(VNode::VText(VText::new("lorem ipsum")));
assert_eq!(
vlist.fully_keyed,
FullyKeyedState::KnownMissingKeys,
"should not be fully keyed, text tags have no key"
);
let _: &mut [VNode] = &mut vlist; // Use deref mut
assert_eq!(
vlist.fully_keyed,
FullyKeyedState::Unknown,
"key state should be unknown, since it was potentially modified through children"
);
}
}
#[cfg(feature = "ssr")]
mod feat_ssr {
use std::fmt::Write;
use std::task::Poll;
use futures::stream::StreamExt;
use futures::{join, pin_mut, poll, FutureExt};
use super::*;
use crate::feat_ssr::VTagKind;
use crate::html::AnyScope;
use crate::platform::fmt::{self, BufWriter};
impl VList {
pub(crate) async fn render_into_stream(
&self,
w: &mut BufWriter,
parent_scope: &AnyScope,
hydratable: bool,
parent_vtag_kind: VTagKind,
) {
match &self[..] {
[] => {}
[child] => {
child
.render_into_stream(w, parent_scope, hydratable, parent_vtag_kind)
.await;
}
_ => {
async fn render_child_iter<'a, I>(
mut children: I,
w: &mut BufWriter,
parent_scope: &AnyScope,
hydratable: bool,
parent_vtag_kind: VTagKind,
) where
I: Iterator<Item = &'a VNode>,
{
let mut w = w;
while let Some(m) = children.next() {
let child_fur = async move {
// Rust's Compiler does not release the mutable reference to
// BufWriter until the end of the loop, regardless of whether an
// await statement has dropped the child_fur.
//
// We capture and return the mutable reference to avoid this.
m.render_into_stream(w, parent_scope, hydratable, parent_vtag_kind)
.await;
w
};
pin_mut!(child_fur);
match poll!(child_fur.as_mut()) {
Poll::Pending => {
let (mut next_w, next_r) = fmt::buffer();
// Move buf writer into an async block for it to be dropped at
// the end of the future.
let rest_render_fur = async move {
render_child_iter(
children,
&mut next_w,
parent_scope,
hydratable,
parent_vtag_kind,
)
.await;
}
// boxing to avoid recursion
.boxed_local();
let transfer_fur = async move {
let w = child_fur.await;
pin_mut!(next_r);
while let Some(m) = next_r.next().await {
let _ = w.write_str(m.as_str());
}
};
join!(rest_render_fur, transfer_fur);
break;
}
Poll::Ready(w_) => {
w = w_;
}
}
}
}
let children = self.iter();
render_child_iter(children, w, parent_scope, hydratable, parent_vtag_kind)
.await;
}
}
}
}
}
#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
#[cfg(feature = "ssr")]
#[cfg(test)]
mod ssr_tests {
use tokio::test;
use crate::prelude::*;
use crate::LocalServerRenderer as ServerRenderer;
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_text_back_to_back() {
#[component]
fn Comp() -> Html {
let s = "world";
html! { <div>{"Hello "}{s}{"!"}</div> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, "<div>Hello world!</div>");
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_fragment() {
#[derive(PartialEq, Properties, Debug)]
struct ChildProps {
name: String,
}
#[component]
fn Child(props: &ChildProps) -> Html {
html! { <div>{"Hello, "}{&props.name}{"!"}</div> }
}
#[component]
fn Comp() -> Html {
html! {
<>
<Child name="Jane" />
<Child name="John" />
<Child name="Josh" />
</>
}
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(
s,
"<div>Hello, Jane!</div><div>Hello, John!</div><div>Hello, Josh!</div>"
);
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/virtual_dom/vportal.rs | packages/yew/src/virtual_dom/vportal.rs | //! This module contains the implementation of a portal `VPortal`.
use web_sys::{Element, Node};
use super::VNode;
#[derive(Debug, Clone, PartialEq)]
pub struct VPortal {
/// The element under which the content is inserted.
pub host: Element,
/// The next sibling after the inserted content. Must be a child of `host`.
pub inner_sibling: Option<Node>,
/// The inserted node
pub node: VNode,
}
impl VPortal {
/// Creates a [VPortal] rendering `content` in the DOM hierarchy under `host`.
pub fn new(content: VNode, host: Element) -> Self {
Self {
host,
inner_sibling: None,
node: content,
}
}
/// Creates a [VPortal] rendering `content` in the DOM hierarchy under `host`.
/// If `inner_sibling` is given, the content is inserted before that [Node].
/// The parent of `inner_sibling`, if given, must be `host`.
pub fn new_before(content: VNode, host: Element, inner_sibling: Option<Node>) -> Self {
Self {
host,
inner_sibling,
node: content,
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/virtual_dom/listeners.rs | packages/yew/src/virtual_dom/listeners.rs | use std::rc::Rc;
use crate::html::ImplicitClone;
/// The [Listener] trait is an universal implementation of an event listener
/// which is used to bind Rust-listener to JS-listener (DOM).
pub trait Listener {
/// Returns the name of the event
fn kind(&self) -> ListenerKind;
/// Handles an event firing
fn handle(&self, event: web_sys::Event);
/// Makes the event listener passive. See
/// [addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener).
fn passive(&self) -> bool;
}
impl std::fmt::Debug for dyn Listener {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Listener {{ kind: {}, passive: {:?} }}",
self.kind().as_ref(),
self.passive(),
)
}
}
macro_rules! gen_listener_kinds {
($($kind:ident)*) => {
/// Supported kinds of DOM event listeners
// Using instead of strings to optimise registry collection performance by simplifying
// hashmap hash calculation.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
#[allow(non_camel_case_types)]
#[allow(missing_docs)]
pub enum ListenerKind {
$( $kind, )*
other(std::borrow::Cow<'static, str>),
}
impl ListenerKind {
pub fn type_name(&self) -> std::borrow::Cow<'static, str> {
match self {
Self::other(type_name) => type_name.clone(),
$( Self::$kind => stringify!($kind)[2..].into(), )*
}
}
}
impl AsRef<str> for ListenerKind {
fn as_ref(&self) -> &str {
match self {
$( Self::$kind => stringify!($kind), )*
Self::other(type_name) => type_name.as_ref(),
}
}
}
};
}
gen_listener_kinds! {
onabort
onauxclick
onblur
oncancel
oncanplay
oncanplaythrough
onchange
onclick
onclose
oncontextmenu
oncuechange
ondblclick
ondrag
ondragend
ondragenter
ondragexit
ondragleave
ondragover
ondragstart
ondrop
ondurationchange
onemptied
onended
onerror
onfocus
onfocusin
onfocusout
onformdata
oninput
oninvalid
onkeydown
onkeypress
onkeyup
onload
onloadeddata
onloadedmetadata
onloadstart
onmousedown
onmouseenter
onmouseleave
onmousemove
onmouseout
onmouseover
onmouseup
onpause
onplay
onplaying
onprogress
onratechange
onreset
onresize
onscroll
onsecuritypolicyviolation
onseeked
onseeking
onselect
onslotchange
onstalled
onsubmit
onsuspend
ontimeupdate
ontoggle
onvolumechange
onwaiting
onwheel
oncopy
oncut
onpaste
onanimationcancel
onanimationend
onanimationiteration
onanimationstart
ongotpointercapture
onloadend
onlostpointercapture
onpointercancel
onpointerdown
onpointerenter
onpointerleave
onpointerlockchange
onpointerlockerror
onpointermove
onpointerout
onpointerover
onpointerup
onselectionchange
onselectstart
onshow
ontouchcancel
ontouchend
ontouchmove
ontouchstart
ontransitioncancel
ontransitionend
ontransitionrun
ontransitionstart
}
/// A list of event listeners
#[derive(Debug, Clone, ImplicitClone, Default)]
pub enum Listeners {
/// No listeners registered or pending.
/// Distinct from `Pending` with an empty slice to avoid an allocation.
#[default]
None,
/// Not yet added to the element or registry
Pending(Box<[Option<Rc<dyn Listener>>]>),
}
impl PartialEq for Listeners {
fn eq(&self, rhs: &Self) -> bool {
use Listeners::*;
match (self, rhs) {
(None, None) => true,
(Pending(lhs), Pending(rhs)) => {
if lhs.len() != rhs.len() {
false
} else {
use std::option::Option::None;
lhs.iter()
.zip(rhs.iter())
.all(|(lhs, rhs)| match (lhs, rhs) {
(Some(lhs), Some(rhs)) => {
// We are okay with comparisons from different compilation units to
// result in false not-equal results. This should only lead in the
// worst-case to some unneeded re-renders.
#[allow(ambiguous_wide_pointer_comparisons)]
Rc::ptr_eq(lhs, rhs)
}
(None, None) => true,
_ => false,
})
}
}
(None, Pending(pending)) | (Pending(pending), None) => pending.is_empty(),
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/virtual_dom/vcomp.rs | packages/yew/src/virtual_dom/vcomp.rs | //! This module contains the implementation of a virtual component (`VComp`).
use std::any::{Any, TypeId};
use std::fmt;
use std::rc::Rc;
#[cfg(feature = "ssr")]
use futures::future::{FutureExt, LocalBoxFuture};
#[cfg(feature = "csr")]
use web_sys::Element;
use super::Key;
#[cfg(feature = "hydration")]
use crate::dom_bundle::Fragment;
#[cfg(feature = "csr")]
use crate::dom_bundle::{BSubtree, DomSlot, DynamicDomSlot};
use crate::html::BaseComponent;
#[cfg(feature = "csr")]
use crate::html::Scoped;
#[cfg(any(feature = "ssr", feature = "csr"))]
use crate::html::{AnyScope, Scope};
#[cfg(feature = "ssr")]
use crate::{feat_ssr::VTagKind, platform::fmt::BufWriter};
/// A virtual component.
pub struct VComp {
pub(crate) type_id: TypeId,
pub(crate) mountable: Box<dyn Mountable>,
pub(crate) key: Option<Key>,
// for some reason, this reduces the bundle size by ~2-3 KBs
_marker: u32,
}
impl fmt::Debug for VComp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("VComp")
.field("type_id", &self.type_id)
.field("mountable", &"..")
.field("key", &self.key)
.finish()
}
}
impl Clone for VComp {
fn clone(&self) -> Self {
Self {
type_id: self.type_id,
mountable: self.mountable.copy(),
key: self.key.clone(),
_marker: 0,
}
}
}
pub(crate) trait Mountable {
fn copy(&self) -> Box<dyn Mountable>;
fn mountable_eq(&self, rhs: &dyn Mountable) -> bool;
fn as_any(&self) -> &dyn Any;
#[cfg(feature = "csr")]
fn mount(
self: Box<Self>,
root: &BSubtree,
parent_scope: &AnyScope,
parent: Element,
slot: DomSlot,
) -> (Box<dyn Scoped>, DynamicDomSlot);
#[cfg(feature = "csr")]
fn reuse(self: Box<Self>, scope: &dyn Scoped, slot: DomSlot);
#[cfg(feature = "ssr")]
fn render_into_stream<'a>(
&'a self,
w: &'a mut BufWriter,
parent_scope: &'a AnyScope,
hydratable: bool,
parent_vtag_kind: VTagKind,
) -> LocalBoxFuture<'a, ()>;
#[cfg(feature = "hydration")]
fn hydrate(
self: Box<Self>,
root: BSubtree,
parent_scope: &AnyScope,
parent: Element,
fragment: &mut Fragment,
prev_next_sibling: &mut Option<DynamicDomSlot>,
) -> (Box<dyn Scoped>, DynamicDomSlot);
}
pub(crate) struct PropsWrapper<COMP: BaseComponent> {
props: Rc<COMP::Properties>,
}
impl<COMP: BaseComponent> PropsWrapper<COMP> {
pub fn new(props: Rc<COMP::Properties>) -> Self {
Self { props }
}
}
impl<COMP: BaseComponent> Mountable for PropsWrapper<COMP> {
fn copy(&self) -> Box<dyn Mountable> {
let wrapper: PropsWrapper<COMP> = PropsWrapper {
props: Rc::clone(&self.props),
};
Box::new(wrapper)
}
fn as_any(&self) -> &dyn Any {
self
}
fn mountable_eq(&self, rhs: &dyn Mountable) -> bool {
rhs.as_any()
.downcast_ref::<Self>()
.map(|rhs| self.props == rhs.props)
.unwrap_or(false)
}
#[cfg(feature = "csr")]
fn mount(
self: Box<Self>,
root: &BSubtree,
parent_scope: &AnyScope,
parent: Element,
slot: DomSlot,
) -> (Box<dyn Scoped>, DynamicDomSlot) {
let scope: Scope<COMP> = Scope::new(Some(parent_scope.clone()));
let own_slot = scope.mount_in_place(root.clone(), parent, slot, self.props);
(Box::new(scope), own_slot)
}
#[cfg(feature = "csr")]
fn reuse(self: Box<Self>, scope: &dyn Scoped, slot: DomSlot) {
let scope: Scope<COMP> = scope.to_any().downcast::<COMP>();
scope.reuse(self.props, slot);
}
#[cfg(feature = "ssr")]
fn render_into_stream<'a>(
&'a self,
w: &'a mut BufWriter,
parent_scope: &'a AnyScope,
hydratable: bool,
parent_vtag_kind: VTagKind,
) -> LocalBoxFuture<'a, ()> {
let scope: Scope<COMP> = Scope::new(Some(parent_scope.clone()));
async move {
scope
.render_into_stream(w, self.props.clone(), hydratable, parent_vtag_kind)
.await;
}
.boxed_local()
}
#[cfg(feature = "hydration")]
fn hydrate(
self: Box<Self>,
root: BSubtree,
parent_scope: &AnyScope,
parent: Element,
fragment: &mut Fragment,
prev_next_sibling: &mut Option<DynamicDomSlot>,
) -> (Box<dyn Scoped>, DynamicDomSlot) {
let scope: Scope<COMP> = Scope::new(Some(parent_scope.clone()));
let own_slot =
scope.hydrate_in_place(root, parent, fragment, self.props, prev_next_sibling);
(Box::new(scope), own_slot)
}
}
/// A virtual child component.
pub struct VChild<COMP: BaseComponent> {
/// The component properties
pub props: Rc<COMP::Properties>,
/// Reference to the mounted node
key: Option<Key>,
}
impl<COMP: BaseComponent> implicit_clone::ImplicitClone for VChild<COMP> {}
impl<COMP: BaseComponent> Clone for VChild<COMP> {
fn clone(&self) -> Self {
VChild {
props: Rc::clone(&self.props),
key: self.key.clone(),
}
}
}
impl<COMP: BaseComponent> PartialEq for VChild<COMP>
where
COMP::Properties: PartialEq,
{
fn eq(&self, other: &VChild<COMP>) -> bool {
self.props == other.props
}
}
impl<COMP> VChild<COMP>
where
COMP: BaseComponent,
{
/// Creates a child component that can be accessed and modified by its parent.
pub fn new(props: COMP::Properties, key: Option<Key>) -> Self {
Self {
props: Rc::new(props),
key,
}
}
}
impl<COMP> VChild<COMP>
where
COMP: BaseComponent,
COMP::Properties: Clone,
{
/// Get a mutable reference to the underlying properties.
pub fn get_mut(&mut self) -> &mut COMP::Properties {
Rc::make_mut(&mut self.props)
}
}
impl<COMP> From<VChild<COMP>> for VComp
where
COMP: BaseComponent,
{
fn from(vchild: VChild<COMP>) -> Self {
VComp::new::<COMP>(vchild.props, vchild.key)
}
}
impl VComp {
/// Creates a new `VComp` instance.
pub fn new<COMP>(props: Rc<COMP::Properties>, key: Option<Key>) -> Self
where
COMP: BaseComponent,
{
VComp {
type_id: TypeId::of::<COMP>(),
mountable: Box::new(PropsWrapper::<COMP>::new(props)),
key,
_marker: 0,
}
}
}
impl PartialEq for VComp {
fn eq(&self, other: &VComp) -> bool {
self.key == other.key
&& self.type_id == other.type_id
&& self.mountable.mountable_eq(other.mountable.as_ref())
}
}
impl<COMP: BaseComponent> fmt::Debug for VChild<COMP> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("VChild<_>")
}
}
#[cfg(feature = "ssr")]
mod feat_ssr {
use super::*;
use crate::html::AnyScope;
impl VComp {
#[inline]
pub(crate) async fn render_into_stream(
&self,
w: &mut BufWriter,
parent_scope: &AnyScope,
hydratable: bool,
parent_vtag_kind: VTagKind,
) {
self.mountable
.as_ref()
.render_into_stream(w, parent_scope, hydratable, parent_vtag_kind)
.await;
}
}
}
#[cfg(all(test, not(target_arch = "wasm32"), feature = "ssr"))]
mod ssr_tests {
use tokio::test;
use crate::prelude::*;
use crate::ServerRenderer;
#[test]
async fn test_props() {
#[derive(PartialEq, Properties, Debug)]
struct ChildProps {
name: String,
}
#[component]
fn Child(props: &ChildProps) -> Html {
html! { <div>{"Hello, "}{&props.name}{"!"}</div> }
}
#[component]
fn Comp() -> Html {
html! {
<div>
<Child name="Jane" />
<Child name="John" />
<Child name="Josh" />
</div>
}
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(
s,
"<div><div>Hello, Jane!</div><div>Hello, John!</div><div>Hello, Josh!</div></div>"
);
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/virtual_dom/vnode.rs | packages/yew/src/virtual_dom/vnode.rs | //! This module contains the implementation of abstract virtual node.
use std::cmp::PartialEq;
use std::iter::FromIterator;
use std::rc::Rc;
use std::{fmt, mem};
use web_sys::Node;
use super::{Key, VChild, VComp, VList, VPortal, VSuspense, VTag, VText};
use crate::html::{BaseComponent, ImplicitClone};
use crate::virtual_dom::VRaw;
use crate::AttrValue;
/// Bind virtual element to a DOM reference.
#[derive(Clone, ImplicitClone, PartialEq)]
#[must_use = "html does not do anything unless returned to Yew for rendering."]
pub enum VNode {
/// A bind between `VTag` and `Element`.
VTag(Rc<VTag>),
/// A bind between `VText` and `TextNode`.
VText(VText),
/// A bind between `VComp` and `Element`.
VComp(Rc<VComp>),
/// A holder for a list of other nodes.
VList(Rc<VList>),
/// A portal to another part of the document
VPortal(Rc<VPortal>),
/// A holder for any `Node` (necessary for replacing node).
VRef(Node),
/// A suspendible document fragment.
VSuspense(Rc<VSuspense>),
/// A raw HTML string, represented by [`AttrValue`](crate::AttrValue).
///
/// Also see: [`VNode::from_html_unchecked`]
VRaw(VRaw),
}
impl VNode {
pub fn key(&self) -> Option<&Key> {
match self {
VNode::VComp(vcomp) => vcomp.key.as_ref(),
VNode::VList(vlist) => vlist.key.as_ref(),
VNode::VRef(_) => None,
VNode::VTag(vtag) => vtag.key.as_ref(),
VNode::VText(_) => None,
VNode::VPortal(vportal) => vportal.node.key(),
VNode::VSuspense(vsuspense) => vsuspense.key.as_ref(),
VNode::VRaw(_) => None,
}
}
/// Returns true if the [VNode] has a key.
pub fn has_key(&self) -> bool {
self.key().is_some()
}
/// Acquires a mutable reference of current VNode as a VList.
///
/// Creates a VList with the current node as the first child if current VNode is not a VList.
pub fn to_vlist_mut(&mut self) -> &mut VList {
loop {
match *self {
Self::VList(ref mut m) => return Rc::make_mut(m),
_ => {
*self = VNode::VList(Rc::new(VList::from(mem::take(self))));
}
}
}
}
/// Create a [`VNode`] from a string of HTML
///
/// # Behavior in browser
///
/// In the browser, this function creates an element with the same XML namespace as the parent,
/// sets the passed HTML to its `innerHTML` and inserts the contents of it into the DOM.
///
/// # Behavior on server
///
/// When rendering on the server, the contents of HTML are directly injected into the HTML
/// stream.
///
/// ## Warning
///
/// The contents are **not** sanitized or validated. You, as the developer, are responsible to
/// ensure the HTML string passed to this method are _valid_ and _not malicious_
///
/// # Example
///
/// ```rust
/// use yew::{html, AttrValue, Html};
/// # fn _main() {
/// let parsed = Html::from_html_unchecked(AttrValue::from("<div>content</div>"));
/// let _: Html = html! {
/// <div>
/// {parsed}
/// </div>
/// };
/// # }
/// ```
pub fn from_html_unchecked(html: AttrValue) -> Self {
VNode::VRaw(VRaw { html })
}
}
impl Default for VNode {
fn default() -> Self {
VNode::VList(Rc::new(VList::default()))
}
}
impl From<VText> for VNode {
#[inline]
fn from(vtext: VText) -> Self {
VNode::VText(vtext)
}
}
impl From<VList> for VNode {
#[inline]
fn from(vlist: VList) -> Self {
VNode::VList(Rc::new(vlist))
}
}
impl From<VTag> for VNode {
#[inline]
fn from(vtag: VTag) -> Self {
VNode::VTag(Rc::new(vtag))
}
}
impl From<VComp> for VNode {
#[inline]
fn from(vcomp: VComp) -> Self {
VNode::VComp(Rc::new(vcomp))
}
}
impl From<VSuspense> for VNode {
#[inline]
fn from(vsuspense: VSuspense) -> Self {
VNode::VSuspense(Rc::new(vsuspense))
}
}
impl From<VPortal> for VNode {
#[inline]
fn from(vportal: VPortal) -> Self {
VNode::VPortal(Rc::new(vportal))
}
}
impl<COMP> From<VChild<COMP>> for VNode
where
COMP: BaseComponent,
{
fn from(vchild: VChild<COMP>) -> Self {
VNode::VComp(Rc::new(VComp::from(vchild)))
}
}
impl<T: ToString> From<T> for VNode {
fn from(value: T) -> Self {
VNode::VText(VText::new(value.to_string()))
}
}
impl<A: Into<VNode>> FromIterator<A> for VNode {
fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
VNode::VList(Rc::new(VList::from_iter(
iter.into_iter().map(|n| n.into()),
)))
}
}
impl fmt::Debug for VNode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
VNode::VTag(ref vtag) => vtag.fmt(f),
VNode::VText(ref vtext) => vtext.fmt(f),
VNode::VComp(ref vcomp) => vcomp.fmt(f),
VNode::VList(ref vlist) => vlist.fmt(f),
VNode::VRef(ref vref) => write!(f, "VRef ( \"{}\" )", crate::utils::print_node(vref)),
VNode::VPortal(ref vportal) => vportal.fmt(f),
VNode::VSuspense(ref vsuspense) => vsuspense.fmt(f),
VNode::VRaw(ref vraw) => write!(f, "VRaw {{ {} }}", vraw.html),
}
}
}
#[cfg(feature = "ssr")]
mod feat_ssr {
use futures::future::{FutureExt, LocalBoxFuture};
use super::*;
use crate::feat_ssr::VTagKind;
use crate::html::AnyScope;
use crate::platform::fmt::BufWriter;
impl VNode {
pub(crate) fn render_into_stream<'a>(
&'a self,
w: &'a mut BufWriter,
parent_scope: &'a AnyScope,
hydratable: bool,
parent_vtag_kind: VTagKind,
) -> LocalBoxFuture<'a, ()> {
async fn render_into_stream_(
this: &VNode,
w: &mut BufWriter,
parent_scope: &AnyScope,
hydratable: bool,
parent_vtag_kind: VTagKind,
) {
match this {
VNode::VTag(vtag) => vtag.render_into_stream(w, parent_scope, hydratable).await,
VNode::VText(vtext) => {
vtext
.render_into_stream(w, parent_scope, hydratable, parent_vtag_kind)
.await
}
VNode::VComp(vcomp) => {
vcomp
.render_into_stream(w, parent_scope, hydratable, parent_vtag_kind)
.await
}
VNode::VList(vlist) => {
vlist
.render_into_stream(w, parent_scope, hydratable, parent_vtag_kind)
.await
}
// We are pretty safe here as it's not possible to get a web_sys::Node without
// DOM support in the first place.
//
// The only exception would be to use `ServerRenderer` in a browser or wasm32
// environment with jsdom present.
VNode::VRef(_) => {
panic!("VRef is not possible to be rendered in to a string.")
}
// Portals are not rendered.
VNode::VPortal(_) => {}
VNode::VSuspense(vsuspense) => {
vsuspense
.render_into_stream(w, parent_scope, hydratable, parent_vtag_kind)
.await
}
VNode::VRaw(vraw) => vraw.render_into_stream(w, parent_scope, hydratable).await,
}
}
async move {
render_into_stream_(self, w, parent_scope, hydratable, parent_vtag_kind).await
}.boxed_local()
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/virtual_dom/mod.rs | packages/yew/src/virtual_dom/mod.rs | //! This module contains Yew's implementation of a reactive virtual DOM.
#[doc(hidden)]
pub mod key;
#[doc(hidden)]
pub mod listeners;
#[doc(hidden)]
pub mod vcomp;
#[doc(hidden)]
pub mod vlist;
#[doc(hidden)]
pub mod vnode;
#[doc(hidden)]
pub mod vportal;
#[doc(hidden)]
pub mod vraw;
#[doc(hidden)]
pub mod vsuspense;
#[doc(hidden)]
pub mod vtag;
#[doc(hidden)]
pub mod vtext;
use std::hint::unreachable_unchecked;
use std::rc::Rc;
use indexmap::IndexMap;
use wasm_bindgen::JsValue;
#[doc(inline)]
pub use self::key::Key;
#[doc(inline)]
pub use self::listeners::*;
#[doc(inline)]
pub use self::vcomp::{VChild, VComp};
#[doc(hidden)]
pub use self::vlist::FullyKeyedState;
#[doc(inline)]
pub use self::vlist::VList;
#[doc(inline)]
pub use self::vnode::VNode;
#[doc(inline)]
pub use self::vportal::VPortal;
#[doc(inline)]
pub use self::vraw::VRaw;
#[doc(inline)]
pub use self::vsuspense::VSuspense;
#[doc(inline)]
pub use self::vtag::VTag;
#[doc(inline)]
pub use self::vtext::VText;
/// Attribute value
pub type AttrValue = implicit_clone::unsync::IString;
#[cfg(any(feature = "ssr", feature = "hydration"))]
mod feat_ssr_hydration {
#[cfg(debug_assertions)]
type ComponentName = &'static str;
#[cfg(not(debug_assertions))]
type ComponentName = std::marker::PhantomData<()>;
#[cfg(feature = "hydration")]
use std::borrow::Cow;
/// A collectable.
///
/// This indicates a kind that can be collected from fragment to be processed at a later time
pub enum Collectable {
Component(ComponentName),
Raw,
Suspense,
}
impl Collectable {
#[cfg(not(debug_assertions))]
#[inline(always)]
pub fn for_component<T: 'static>() -> Self {
use std::marker::PhantomData;
// This suppresses the clippy lint about unused generic.
// We inline this function
// so the function body is copied to its caller and generics get optimised away.
let _comp_type: PhantomData<T> = PhantomData;
Self::Component(PhantomData)
}
#[cfg(debug_assertions)]
pub fn for_component<T: 'static>() -> Self {
let comp_name = std::any::type_name::<T>();
Self::Component(comp_name)
}
pub fn open_start_mark(&self) -> &'static str {
match self {
Self::Component(_) => "<[",
Self::Raw => "<#",
Self::Suspense => "<?",
}
}
pub fn close_start_mark(&self) -> &'static str {
match self {
Self::Component(_) => "</[",
Self::Raw => "</#",
Self::Suspense => "</?",
}
}
pub fn end_mark(&self) -> &'static str {
match self {
Self::Component(_) => "]>",
Self::Raw => ">",
Self::Suspense => ">",
}
}
#[cfg(feature = "hydration")]
pub fn name(&self) -> Cow<'static, str> {
match self {
#[cfg(debug_assertions)]
Self::Component(m) => format!("Component({m})").into(),
#[cfg(not(debug_assertions))]
Self::Component(_) => "Component".into(),
Self::Raw => "Raw".into(),
Self::Suspense => "Suspense".into(),
}
}
}
}
#[cfg(any(feature = "ssr", feature = "hydration"))]
pub(crate) use feat_ssr_hydration::*;
#[cfg(feature = "ssr")]
mod feat_ssr {
use std::fmt::Write;
use super::*;
use crate::platform::fmt::BufWriter;
impl Collectable {
pub(crate) fn write_open_tag(&self, w: &mut BufWriter) {
let _ = w.write_str("<!--");
let _ = w.write_str(self.open_start_mark());
#[cfg(debug_assertions)]
match self {
Self::Component(type_name) => {
let _ = w.write_str(type_name);
}
Self::Raw => {}
Self::Suspense => {}
}
let _ = w.write_str(self.end_mark());
let _ = w.write_str("-->");
}
pub(crate) fn write_close_tag(&self, w: &mut BufWriter) {
let _ = w.write_str("<!--");
let _ = w.write_str(self.close_start_mark());
#[cfg(debug_assertions)]
match self {
Self::Component(type_name) => {
let _ = w.write_str(type_name);
}
Self::Raw => {}
Self::Suspense => {}
}
let _ = w.write_str(self.end_mark());
let _ = w.write_str("-->");
}
}
}
/// Defines if the [`Attributes`] is set as element's attribute or property and its value.
#[allow(missing_docs)]
#[derive(PartialEq, Clone, Debug)]
pub enum AttributeOrProperty {
// This exists as a workaround to support Rust <1.72
// Previous versions of Rust did not See
// `AttributeOrProperty::Attribute(AttrValue::Static(_))` as `'static` that html! macro
// used, and thus failed with "temporary value dropped while borrowed"
//
// See: https://github.com/yewstack/yew/pull/3458#discussion_r1350362215
Static(&'static str),
Attribute(AttrValue),
Property(JsValue),
}
/// A collection of attributes for an element
#[derive(PartialEq, Clone, Debug)]
pub enum Attributes {
/// Static list of attributes.
///
/// Allows optimizing comparison to a simple pointer equality check and reducing allocations,
/// if the attributes do not change on a node.
Static(&'static [(&'static str, AttributeOrProperty)]),
/// Static list of attribute keys with possibility to exclude attributes and dynamic attribute
/// values.
///
/// Allows optimizing comparison to a simple pointer equality check and reducing allocations,
/// if the attributes keys do not change on a node.
Dynamic {
/// Attribute keys. Includes both always set and optional attribute keys.
keys: &'static [&'static str],
/// Attribute values. Matches [keys](Attributes::Dynamic::keys). Optional attributes are
/// designated by setting [None].
values: Box<[Option<AttributeOrProperty>]>,
},
/// IndexMap is used to provide runtime attribute deduplication in cases where the html! macro
/// was not used to guarantee it.
IndexMap(Rc<IndexMap<AttrValue, AttributeOrProperty>>),
}
impl Attributes {
/// Construct a default Attributes instance
pub fn new() -> Self {
Self::default()
}
/// Return iterator over attribute key-value pairs.
/// This function is suboptimal and does not inline well. Avoid on hot paths.
///
/// This function only returns attributes
pub fn iter<'a>(&'a self) -> Box<dyn Iterator<Item = (&'a str, &'a str)> + 'a> {
match self {
Self::Static(arr) => Box::new(arr.iter().filter_map(|(k, v)| match v {
AttributeOrProperty::Attribute(v) => Some((*k, v.as_ref())),
AttributeOrProperty::Property(_) => None,
AttributeOrProperty::Static(v) => Some((*k, v)),
})),
Self::Dynamic { keys, values } => {
Box::new(keys.iter().zip(values.iter()).filter_map(|(k, v)| match v {
Some(AttributeOrProperty::Attribute(v)) => Some((*k, v.as_ref())),
_ => None,
}))
}
Self::IndexMap(m) => Box::new(m.iter().filter_map(|(k, v)| match v {
AttributeOrProperty::Attribute(v) => Some((k.as_ref(), v.as_ref())),
_ => None,
})),
}
}
/// Get a mutable reference to the underlying `IndexMap`.
/// If the attributes are stored in the `Vec` variant, it will be converted.
pub fn get_mut_index_map(&mut self) -> &mut IndexMap<AttrValue, AttributeOrProperty> {
macro_rules! unpack {
() => {
match self {
Self::IndexMap(m) => Rc::make_mut(m),
// SAFETY: unreachable because we set self to the `IndexMap` variant above.
_ => unsafe { unreachable_unchecked() },
}
};
}
match self {
Self::IndexMap(m) => Rc::make_mut(m),
Self::Static(arr) => {
*self = Self::IndexMap(Rc::new(
arr.iter().map(|(k, v)| ((*k).into(), v.clone())).collect(),
));
unpack!()
}
Self::Dynamic { keys, values } => {
*self = Self::IndexMap(Rc::new(
std::mem::take(values)
.iter_mut()
.zip(keys.iter())
.filter_map(|(v, k)| v.take().map(|v| (AttrValue::from(*k), v)))
.collect(),
));
unpack!()
}
}
}
}
impl From<IndexMap<AttrValue, AttrValue>> for Attributes {
fn from(map: IndexMap<AttrValue, AttrValue>) -> Self {
let v = map
.into_iter()
.map(|(k, v)| (k, AttributeOrProperty::Attribute(v)))
.collect();
Self::IndexMap(Rc::new(v))
}
}
impl From<IndexMap<&'static str, AttrValue>> for Attributes {
fn from(v: IndexMap<&'static str, AttrValue>) -> Self {
let v = v
.into_iter()
.map(|(k, v)| (AttrValue::Static(k), (AttributeOrProperty::Attribute(v))))
.collect();
Self::IndexMap(Rc::new(v))
}
}
impl From<IndexMap<&'static str, JsValue>> for Attributes {
fn from(v: IndexMap<&'static str, JsValue>) -> Self {
let v = v
.into_iter()
.map(|(k, v)| (AttrValue::Static(k), (AttributeOrProperty::Property(v))))
.collect();
Self::IndexMap(Rc::new(v))
}
}
impl Default for Attributes {
fn default() -> Self {
Self::Static(&[])
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/virtual_dom/vsuspense.rs | packages/yew/src/virtual_dom/vsuspense.rs | use super::{Key, VNode};
use crate::html::ImplicitClone;
/// This struct represents a suspendable DOM fragment.
#[derive(Clone, ImplicitClone, Debug, PartialEq)]
pub struct VSuspense {
/// Child nodes.
pub(crate) children: VNode,
/// Fallback nodes when suspended.
pub(crate) fallback: VNode,
/// Whether the current status is suspended.
pub(crate) suspended: bool,
/// The Key.
pub(crate) key: Option<Key>,
}
impl VSuspense {
pub fn new(children: VNode, fallback: VNode, suspended: bool, key: Option<Key>) -> Self {
Self {
children,
fallback,
suspended,
key,
}
}
}
#[cfg(feature = "ssr")]
mod feat_ssr {
use super::*;
use crate::feat_ssr::VTagKind;
use crate::html::AnyScope;
use crate::platform::fmt::BufWriter;
use crate::virtual_dom::Collectable;
impl VSuspense {
pub(crate) async fn render_into_stream(
&self,
w: &mut BufWriter,
parent_scope: &AnyScope,
hydratable: bool,
parent_vtag_kind: VTagKind,
) {
let collectable = Collectable::Suspense;
if hydratable {
collectable.write_open_tag(w);
}
// always render children on the server side.
self.children
.render_into_stream(w, parent_scope, hydratable, parent_vtag_kind)
.await;
if hydratable {
collectable.write_close_tag(w);
}
}
}
}
#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
#[cfg(feature = "ssr")]
#[cfg(test)]
mod ssr_tests {
use std::rc::Rc;
use std::time::Duration;
use tokio::task::{spawn_local, LocalSet};
use tokio::test;
use crate::platform::time::sleep;
use crate::prelude::*;
use crate::suspense::{Suspension, SuspensionResult};
use crate::ServerRenderer;
#[cfg(not(target_os = "wasi"))]
#[test(flavor = "multi_thread", worker_threads = 2)]
async fn test_suspense() {
#[derive(PartialEq)]
pub struct SleepState {
s: Suspension,
}
impl SleepState {
fn new() -> Self {
let (s, handle) = Suspension::new();
// we use tokio spawn local here.
spawn_local(async move {
// we use tokio sleep here.
sleep(Duration::from_millis(50)).await;
handle.resume();
});
Self { s }
}
}
impl Reducible for SleepState {
type Action = ();
fn reduce(self: Rc<Self>, _action: Self::Action) -> Rc<Self> {
Self::new().into()
}
}
#[hook]
pub fn use_sleep() -> SuspensionResult<Rc<dyn Fn()>> {
let sleep_state = use_reducer(SleepState::new);
if sleep_state.s.resumed() {
Ok(Rc::new(move || sleep_state.dispatch(())))
} else {
Err(sleep_state.s.clone())
}
}
#[derive(PartialEq, Properties, Debug)]
struct ChildProps {
name: String,
}
#[component]
fn Child(props: &ChildProps) -> HtmlResult {
use_sleep()?;
Ok(html! { <div>{"Hello, "}{&props.name}{"!"}</div> })
}
#[component]
fn Comp() -> Html {
let fallback = html! {"loading..."};
html! {
<Suspense {fallback}>
<Child name="Jane" />
<Child name="John" />
<Child name="Josh" />
</Suspense>
}
}
let local = LocalSet::new();
let s = local
.run_until(async move {
ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await
})
.await;
assert_eq!(
s,
"<div>Hello, Jane!</div><div>Hello, John!</div><div>Hello, Josh!</div>"
);
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/virtual_dom/vraw.rs | packages/yew/src/virtual_dom/vraw.rs | use crate::html::ImplicitClone;
use crate::AttrValue;
/// A raw HTML string to be used in VDOM.
#[derive(Clone, ImplicitClone, Debug, PartialEq, Eq)]
pub struct VRaw {
pub html: AttrValue,
}
impl From<AttrValue> for VRaw {
fn from(html: AttrValue) -> Self {
Self { html }
}
}
#[cfg(feature = "ssr")]
mod feat_ssr {
use std::fmt::Write;
use super::*;
use crate::html::AnyScope;
use crate::platform::fmt::BufWriter;
use crate::virtual_dom::Collectable;
impl VRaw {
pub(crate) async fn render_into_stream(
&self,
w: &mut BufWriter,
_parent_scope: &AnyScope,
hydratable: bool,
) {
let collectable = Collectable::Raw;
if hydratable {
collectable.write_open_tag(w);
}
let _ = w.write_str(self.html.as_ref());
if hydratable {
collectable.write_close_tag(w);
}
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/virtual_dom/vtext.rs | packages/yew/src/virtual_dom/vtext.rs | //! This module contains the implementation of a virtual text node `VText`.
use std::cmp::PartialEq;
use super::AttrValue;
use crate::html::ImplicitClone;
/// A type for a virtual
/// [`TextNode`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode)
/// representation.
#[derive(Clone, ImplicitClone)]
pub struct VText {
/// Contains a text of the node.
pub text: AttrValue,
}
impl VText {
/// Creates new virtual text node with a content.
pub fn new(text: impl Into<AttrValue>) -> Self {
VText { text: text.into() }
}
}
impl std::fmt::Debug for VText {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "VText {{ text: \"{}\" }}", self.text)
}
}
impl PartialEq for VText {
fn eq(&self, other: &VText) -> bool {
self.text == other.text
}
}
impl<T: ToString> From<T> for VText {
fn from(value: T) -> Self {
VText::new(value.to_string())
}
}
#[cfg(feature = "ssr")]
mod feat_ssr {
use std::fmt::Write;
use super::*;
use crate::feat_ssr::VTagKind;
use crate::html::AnyScope;
use crate::platform::fmt::BufWriter;
impl VText {
pub(crate) async fn render_into_stream(
&self,
w: &mut BufWriter,
_parent_scope: &AnyScope,
_hydratable: bool,
parent_vtag_kind: VTagKind,
) {
_ = w.write_str(&match parent_vtag_kind {
VTagKind::Style => html_escape::encode_style(&self.text),
VTagKind::Script => html_escape::encode_script(&self.text),
VTagKind::Other => html_escape::encode_text(&self.text),
})
}
}
}
#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
#[cfg(feature = "ssr")]
#[cfg(test)]
mod ssr_tests {
use tokio::test;
use crate::prelude::*;
use crate::LocalServerRenderer as ServerRenderer;
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_simple_str() {
#[component]
fn Comp() -> Html {
html! { "abc" }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, r#"abc"#);
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/virtual_dom/vtag.rs | packages/yew/src/virtual_dom/vtag.rs | //! This module contains the implementation of a virtual element node [VTag].
use std::cmp::PartialEq;
use std::marker::PhantomData;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use wasm_bindgen::JsValue;
use web_sys::{HtmlInputElement as InputElement, HtmlTextAreaElement as TextAreaElement};
use super::{AttrValue, AttributeOrProperty, Attributes, Key, Listener, Listeners, VNode};
use crate::html::{ImplicitClone, IntoPropValue, NodeRef};
/// SVG namespace string used for creating svg elements
pub const SVG_NAMESPACE: &str = "http://www.w3.org/2000/svg";
/// MathML namespace string used for creating MathML elements
pub const MATHML_NAMESPACE: &str = "http://www.w3.org/1998/Math/MathML";
/// Default namespace for html elements
pub const HTML_NAMESPACE: &str = "http://www.w3.org/1999/xhtml";
/// Value field corresponding to an [Element]'s `value` property
#[derive(Debug, Eq, PartialEq)]
pub(crate) struct Value<T>(Option<AttrValue>, PhantomData<T>);
impl<T> Clone for Value<T> {
fn clone(&self) -> Self {
Self::new(self.0.clone())
}
}
impl<T> ImplicitClone for Value<T> {}
impl<T> Default for Value<T> {
fn default() -> Self {
Self::new(None)
}
}
impl<T> Value<T> {
/// Create a new value. The caller should take care that the value is valid for the element's
/// `value` property
fn new(value: Option<AttrValue>) -> Self {
Value(value, PhantomData)
}
/// Set a new value. The caller should take care that the value is valid for the element's
/// `value` property
pub(crate) fn set(&mut self, value: Option<AttrValue>) {
self.0 = value;
}
}
impl<T> Deref for Value<T> {
type Target = Option<AttrValue>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// Fields specific to
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) [VTag](crate::virtual_dom::VTag)s
#[derive(Debug, Clone, ImplicitClone, Default, Eq, PartialEq)]
pub(crate) struct InputFields {
/// Contains a value of an
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
pub(crate) value: Value<InputElement>,
/// Represents `checked` attribute of
/// [input](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-checked).
/// It exists to override standard behavior of `checked` attribute, because
/// in original HTML it sets `defaultChecked` value of `InputElement`, but for reactive
/// frameworks it's more useful to control `checked` value of an `InputElement`.
pub(crate) checked: Option<bool>,
}
impl Deref for InputFields {
type Target = Value<InputElement>;
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl DerefMut for InputFields {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.value
}
}
impl InputFields {
/// Create new attributes for an [InputElement] element
fn new(value: Option<AttrValue>, checked: Option<bool>) -> Self {
Self {
value: Value::new(value),
checked,
}
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct TextareaFields {
/// Contains the value of an
/// [TextAreaElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea).
pub(crate) value: Value<TextAreaElement>,
/// Contains the default value of
/// [TextAreaElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea).
#[allow(unused)] // unused only if both "csr" and "ssr" features are off
pub(crate) defaultvalue: Option<AttrValue>,
}
/// [VTag] fields that are specific to different [VTag] kinds.
/// Decreases the memory footprint of [VTag] by avoiding impossible field and value combinations.
#[derive(Debug, Clone, ImplicitClone)]
pub(crate) enum VTagInner {
/// Fields specific to
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input)
/// [VTag]s
Input(InputFields),
/// Fields specific to
/// [TextArea](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea)
/// [VTag]s
Textarea(TextareaFields),
/// Fields for all other kinds of [VTag]s
Other {
/// A tag of the element.
tag: AttrValue,
/// children of the element.
children: VNode,
},
}
/// A type for a virtual
/// [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element)
/// representation.
#[derive(Debug, Clone, ImplicitClone)]
pub struct VTag {
/// [VTag] fields that are specific to different [VTag] kinds.
pub(crate) inner: VTagInner,
/// List of attached listeners.
pub(crate) listeners: Listeners,
/// A node reference used for DOM access in Component lifecycle methods
pub node_ref: NodeRef,
/// List of attributes.
pub attributes: Attributes,
pub key: Option<Key>,
}
impl VTag {
/// Creates a new [VTag] instance with `tag` name (cannot be changed later in DOM).
pub fn new(tag: impl Into<AttrValue>) -> Self {
let tag = tag.into();
let lowercase_tag = tag.to_ascii_lowercase();
Self::new_base(
match &*lowercase_tag {
"input" => VTagInner::Input(Default::default()),
"textarea" => VTagInner::Textarea(Default::default()),
_ => VTagInner::Other {
tag,
children: Default::default(),
},
},
Default::default(),
Default::default(),
Default::default(),
Default::default(),
)
}
/// Creates a new
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) [VTag]
/// instance.
///
/// Unlike [VTag::new()], this sets all the public fields of [VTag] in one call. This allows the
/// compiler to inline property and child list construction in the `html!` macro. This enables
/// higher instruction parallelism by reducing data dependency and avoids `memcpy` of Vtag
/// fields.
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub fn __new_input(
value: Option<AttrValue>,
checked: Option<bool>,
node_ref: NodeRef,
key: Option<Key>,
// at the bottom for more readable macro-expanded code
attributes: Attributes,
listeners: Listeners,
) -> Self {
VTag::new_base(
VTagInner::Input(InputFields::new(
value,
// In HTML node `checked` attribute sets `defaultChecked` parameter,
// but we use own field to control real `checked` parameter
checked,
)),
node_ref,
key,
attributes,
listeners,
)
}
/// Creates a new
/// [TextArea](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea) [VTag]
/// instance.
///
/// Unlike [VTag::new()], this sets all the public fields of [VTag] in one call. This allows the
/// compiler to inline property and child list construction in the `html!` macro. This enables
/// higher instruction parallelism by reducing data dependency and avoids `memcpy` of Vtag
/// fields.
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub fn __new_textarea(
value: Option<AttrValue>,
defaultvalue: Option<AttrValue>,
node_ref: NodeRef,
key: Option<Key>,
// at the bottom for more readable macro-expanded code
attributes: Attributes,
listeners: Listeners,
) -> Self {
VTag::new_base(
VTagInner::Textarea(TextareaFields {
value: Value::new(value),
defaultvalue,
}),
node_ref,
key,
attributes,
listeners,
)
}
/// Creates a new [VTag] instance with `tag` name (cannot be changed later in DOM).
///
/// Unlike [VTag::new()], this sets all the public fields of [VTag] in one call. This allows the
/// compiler to inline property and child list construction in the `html!` macro. This enables
/// higher instruction parallelism by reducing data dependency and avoids `memcpy` of Vtag
/// fields.
#[doc(hidden)]
#[allow(clippy::too_many_arguments)]
pub fn __new_other(
tag: AttrValue,
node_ref: NodeRef,
key: Option<Key>,
// at the bottom for more readable macro-expanded code
attributes: Attributes,
listeners: Listeners,
children: VNode,
) -> Self {
VTag::new_base(
VTagInner::Other { tag, children },
node_ref,
key,
attributes,
listeners,
)
}
/// Constructs a [VTag] from [VTagInner] and fields common to all [VTag] kinds
#[inline]
#[allow(clippy::too_many_arguments)]
fn new_base(
inner: VTagInner,
node_ref: NodeRef,
key: Option<Key>,
attributes: Attributes,
listeners: Listeners,
) -> Self {
VTag {
inner,
attributes,
listeners,
node_ref,
key,
}
}
/// Returns tag of an [Element](web_sys::Element). In HTML tags are always uppercase.
pub fn tag(&self) -> &str {
match &self.inner {
VTagInner::Input { .. } => "input",
VTagInner::Textarea { .. } => "textarea",
VTagInner::Other { tag, .. } => tag.as_ref(),
}
}
/// Add [VNode] child.
pub fn add_child(&mut self, child: VNode) {
if let VTagInner::Other { children, .. } = &mut self.inner {
children.to_vlist_mut().add_child(child)
}
}
/// Add multiple [VNode] children.
pub fn add_children(&mut self, children: impl IntoIterator<Item = VNode>) {
if let VTagInner::Other { children: dst, .. } = &mut self.inner {
dst.to_vlist_mut().add_children(children)
}
}
/// Returns a reference to the children of this [VTag], if the node can have
/// children
pub fn children(&self) -> Option<&VNode> {
match &self.inner {
VTagInner::Other { children, .. } => Some(children),
_ => None,
}
}
/// Returns a mutable reference to the children of this [VTag], if the node can have
/// children
pub fn children_mut(&mut self) -> Option<&mut VNode> {
match &mut self.inner {
VTagInner::Other { children, .. } => Some(children),
_ => None,
}
}
/// Returns the children of this [VTag], if the node can have
/// children
pub fn into_children(self) -> Option<VNode> {
match self.inner {
VTagInner::Other { children, .. } => Some(children),
_ => None,
}
}
/// Returns the `value` of an
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) or
/// [TextArea](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea)
pub fn value(&self) -> Option<&AttrValue> {
match &self.inner {
VTagInner::Input(f) => f.as_ref(),
VTagInner::Textarea(TextareaFields { value, .. }) => value.as_ref(),
VTagInner::Other { .. } => None,
}
}
/// Sets `value` for an
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) or
/// [TextArea](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea)
pub fn set_value(&mut self, value: impl IntoPropValue<Option<AttrValue>>) {
match &mut self.inner {
VTagInner::Input(f) => {
f.set(value.into_prop_value());
}
VTagInner::Textarea(TextareaFields { value: dst, .. }) => {
dst.set(value.into_prop_value());
}
VTagInner::Other { .. } => (),
}
}
/// Returns `checked` property of an
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
/// (Does not affect the value of the node's attribute).
pub fn checked(&self) -> Option<bool> {
match &self.inner {
VTagInner::Input(f) => f.checked,
_ => None,
}
}
/// Sets `checked` property of an
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
/// (Does not affect the value of the node's attribute).
pub fn set_checked(&mut self, value: bool) {
if let VTagInner::Input(f) = &mut self.inner {
f.checked = Some(value);
}
}
/// Keeps the current value of the `checked` property of an
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).
/// (Does not affect the value of the node's attribute).
pub fn preserve_checked(&mut self) {
if let VTagInner::Input(f) = &mut self.inner {
f.checked = None;
}
}
/// Adds a key-value pair to attributes
///
/// Not every attribute works when it set as an attribute. We use workarounds for:
/// `value` and `checked`.
pub fn add_attribute(&mut self, key: &'static str, value: impl Into<AttrValue>) {
self.attributes.get_mut_index_map().insert(
AttrValue::Static(key),
AttributeOrProperty::Attribute(value.into()),
);
}
/// Set the given key as property on the element
///
/// [`js_sys::Reflect`] is used for setting properties.
pub fn add_property(&mut self, key: &'static str, value: impl Into<JsValue>) {
self.attributes.get_mut_index_map().insert(
AttrValue::Static(key),
AttributeOrProperty::Property(value.into()),
);
}
/// Sets attributes to a virtual node.
///
/// Not every attribute works when it set as an attribute. We use workarounds for:
/// `value` and `checked`.
pub fn set_attributes(&mut self, attrs: impl Into<Attributes>) {
self.attributes = attrs.into();
}
#[doc(hidden)]
pub fn __macro_push_attr(&mut self, key: &'static str, value: impl IntoPropValue<AttrValue>) {
self.attributes.get_mut_index_map().insert(
AttrValue::from(key),
AttributeOrProperty::Attribute(value.into_prop_value()),
);
}
/// Add event listener on the [VTag]'s [Element](web_sys::Element).
/// Returns `true` if the listener has been added, `false` otherwise.
pub fn add_listener(&mut self, listener: Rc<dyn Listener>) -> bool {
match &mut self.listeners {
Listeners::None => {
self.set_listeners([Some(listener)].into());
true
}
Listeners::Pending(listeners) => {
let mut listeners = mem::take(listeners).into_vec();
listeners.push(Some(listener));
self.set_listeners(listeners.into());
true
}
}
}
/// Set event listeners on the [VTag]'s [Element](web_sys::Element)
pub fn set_listeners(&mut self, listeners: Box<[Option<Rc<dyn Listener>>]>) {
self.listeners = Listeners::Pending(listeners);
}
}
impl PartialEq for VTag {
fn eq(&self, other: &VTag) -> bool {
use VTagInner::*;
(match (&self.inner, &other.inner) {
(Input(l), Input(r)) => l == r,
(Textarea (TextareaFields{ value: value_l, .. }), Textarea (TextareaFields{ value: value_r, .. })) => value_l == value_r,
(Other { tag: tag_l, .. }, Other { tag: tag_r, .. }) => tag_l == tag_r,
_ => false,
}) && self.listeners.eq(&other.listeners)
&& self.attributes == other.attributes
// Diff children last, as recursion is the most expensive
&& match (&self.inner, &other.inner) {
(Other { children: ch_l, .. }, Other { children: ch_r, .. }) => ch_l == ch_r,
_ => true,
}
}
}
#[cfg(feature = "ssr")]
mod feat_ssr {
use std::fmt::Write;
use super::*;
use crate::feat_ssr::VTagKind;
use crate::html::AnyScope;
use crate::platform::fmt::BufWriter;
use crate::virtual_dom::VText;
// Elements that cannot have any child elements.
static VOID_ELEMENTS: &[&str; 15] = &[
"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param",
"source", "track", "wbr", "textarea",
];
impl VTag {
pub(crate) async fn render_into_stream(
&self,
w: &mut BufWriter,
parent_scope: &AnyScope,
hydratable: bool,
) {
let _ = w.write_str("<");
let _ = w.write_str(self.tag());
let write_attr = |w: &mut BufWriter, name: &str, val: Option<&str>| {
let _ = w.write_str(" ");
let _ = w.write_str(name);
if let Some(m) = val {
let _ = w.write_str("=\"");
let _ = w.write_str(&html_escape::encode_double_quoted_attribute(m));
let _ = w.write_str("\"");
}
};
if let VTagInner::Input(InputFields { value, checked }) = &self.inner {
if let Some(value) = value.as_deref() {
write_attr(w, "value", Some(value));
}
// Setting is as an attribute sets the `defaultChecked` property. Only emit this
// if it's explicitly set to checked.
if *checked == Some(true) {
write_attr(w, "checked", None);
}
}
for (k, v) in self.attributes.iter() {
write_attr(w, k, Some(v));
}
let _ = w.write_str(">");
match &self.inner {
VTagInner::Input(_) => {}
VTagInner::Textarea(TextareaFields {
value,
defaultvalue,
}) => {
if let Some(def) = value.as_ref().or(defaultvalue.as_ref()) {
VText::new(def.clone())
.render_into_stream(w, parent_scope, hydratable, VTagKind::Other)
.await;
}
let _ = w.write_str("</textarea>");
}
VTagInner::Other { tag, children } => {
let lowercase_tag = tag.to_ascii_lowercase();
if !VOID_ELEMENTS.contains(&lowercase_tag.as_ref()) {
children
.render_into_stream(w, parent_scope, hydratable, tag.into())
.await;
let _ = w.write_str("</");
let _ = w.write_str(tag);
let _ = w.write_str(">");
} else {
// We don't write children of void elements nor closing tags.
debug_assert!(
match children {
VNode::VList(m) => m.is_empty(),
_ => false,
},
"{tag} cannot have any children!"
);
}
}
}
}
}
}
#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
#[cfg(feature = "ssr")]
#[cfg(test)]
mod ssr_tests {
use tokio::test;
use crate::prelude::*;
use crate::LocalServerRenderer as ServerRenderer;
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_simple_tag() {
#[component]
fn Comp() -> Html {
html! { <div></div> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, "<div></div>");
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_simple_tag_with_attr() {
#[component]
fn Comp() -> Html {
html! { <div class="abc"></div> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, r#"<div class="abc"></div>"#);
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_simple_tag_with_content() {
#[component]
fn Comp() -> Html {
html! { <div>{"Hello!"}</div> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, r#"<div>Hello!</div>"#);
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_simple_tag_with_nested_tag_and_input() {
#[component]
fn Comp() -> Html {
html! { <div>{"Hello!"}<input value="abc" type="text" /></div> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, r#"<div>Hello!<input value="abc" type="text"></div>"#);
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_textarea() {
#[component]
fn Comp() -> Html {
html! { <textarea value="teststring" /> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, r#"<textarea>teststring</textarea>"#);
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_textarea_w_defaultvalue() {
#[component]
fn Comp() -> Html {
html! { <textarea defaultvalue="teststring" /> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, r#"<textarea>teststring</textarea>"#);
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_value_precedence_over_defaultvalue() {
#[component]
fn Comp() -> Html {
html! { <textarea defaultvalue="defaultvalue" value="value" /> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, r#"<textarea>value</textarea>"#);
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_escaping_in_style_tag() {
#[component]
fn Comp() -> Html {
html! { <style>{"body > a {color: #cc0;}"}</style> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, r#"<style>body > a {color: #cc0;}</style>"#);
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_escaping_in_script_tag() {
#[component]
fn Comp() -> Html {
html! { <script>{"foo.bar = x < y;"}</script> }
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(s, r#"<script>foo.bar = x < y;</script>"#);
}
#[cfg_attr(not(target_os = "wasi"), test)]
#[cfg_attr(target_os = "wasi", test(flavor = "current_thread"))]
async fn test_multiple_vtext_in_style_tag() {
#[component]
fn Comp() -> Html {
let one = "html { background: black } ";
let two = "body > a { color: white } ";
html! {
<style>
{one}
{two}
</style>
}
}
let s = ServerRenderer::<Comp>::new()
.hydratable(false)
.render()
.await;
assert_eq!(
s,
r#"<style>html { background: black } body > a { color: white } </style>"#
);
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/tests/mod.rs | packages/yew/src/tests/mod.rs | //! Internal module for unit tests
pub mod layout_tests;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/tests/layout_tests.rs | packages/yew/src/tests/layout_tests.rs | //! Snapshot testing of Yew components
//!
//! This tests must be run in browser and thus require the `csr` feature to be enabled
use gloo::console::log;
use crate::dom_bundle::{BSubtree, Bundle, DomSlot};
use crate::html::AnyScope;
use crate::virtual_dom::VNode;
use crate::{scheduler, Component, Context, Html};
#[allow(dead_code)]
struct Comp;
impl Component for Comp {
type Message = ();
type Properties = ();
fn create(_: &Context<Self>) -> Self {
unimplemented!()
}
fn update(&mut self, _ctx: &Context<Self>, _: Self::Message) -> bool {
unimplemented!();
}
fn changed(&mut self, _ctx: &Context<Self>, _: &Self::Properties) -> bool {
unimplemented!()
}
fn view(&self, _ctx: &Context<Self>) -> Html {
unimplemented!()
}
}
#[derive(Debug)]
#[allow(missing_docs)]
pub struct TestLayout<'a> {
pub name: &'a str,
pub node: VNode,
pub expected: &'a str,
}
#[allow(missing_docs)]
pub fn diff_layouts(layouts: Vec<TestLayout<'_>>) {
let document = gloo::utils::document();
let scope: AnyScope = AnyScope::test();
let parent_element = document.create_element("div").unwrap();
let root = BSubtree::create_root(&parent_element);
let end_node = document.create_text_node("END");
parent_element.append_child(&end_node).unwrap();
// Tests each layout independently
let slot = DomSlot::at(end_node.into());
for layout in layouts.iter() {
// Apply the layout
let vnode = layout.node.clone();
log!("Independently apply layout '{}'", layout.name);
let mut bundle = Bundle::new();
bundle.reconcile(&root, &scope, &parent_element, slot.clone(), vnode);
scheduler::start_now();
assert_eq!(
parent_element.inner_html(),
format!("{}END", layout.expected),
"Independent apply failed for layout '{}'",
layout.name,
);
// Diff with no changes
let vnode = layout.node.clone();
log!("Independently reapply layout '{}'", layout.name);
bundle.reconcile(&root, &scope, &parent_element, slot.clone(), vnode);
scheduler::start_now();
assert_eq!(
parent_element.inner_html(),
format!("{}END", layout.expected),
"Independent reapply failed for layout '{}'",
layout.name,
);
// Detach
bundle.detach(&root, &parent_element, false);
scheduler::start_now();
assert_eq!(
parent_element.inner_html(),
"END",
"Independent detach failed for layout '{}'",
layout.name,
);
}
// Sequentially apply each layout
let mut bundle = Bundle::new();
for layout in layouts.iter() {
let next_vnode = layout.node.clone();
log!("Sequentially apply layout '{}'", layout.name);
bundle.reconcile(&root, &scope, &parent_element, slot.clone(), next_vnode);
scheduler::start_now();
assert_eq!(
parent_element.inner_html(),
format!("{}END", layout.expected),
"Sequential apply failed for layout '{}'",
layout.name,
);
}
// Sequentially detach each layout
for layout in layouts.into_iter().rev() {
let next_vnode = layout.node.clone();
log!("Sequentially detach layout '{}'", layout.name);
bundle.reconcile(&root, &scope, &parent_element, slot.clone(), next_vnode);
scheduler::start_now();
assert_eq!(
parent_element.inner_html(),
format!("{}END", layout.expected),
"Sequential detach failed for layout '{}'",
layout.name,
);
}
// Detach last layout
bundle.detach(&root, &parent_element, false);
scheduler::start_now();
assert_eq!(
parent_element.inner_html(),
"END",
"Failed to detach last layout"
);
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/utils/mod.rs | packages/yew/src/utils/mod.rs | //! This module contains useful utilities to get information about the current document.
use std::marker::PhantomData;
use std::rc::Rc;
use implicit_clone::unsync::IArray;
use implicit_clone::ImplicitClone;
use yew::html::ChildrenRenderer;
/// Map `IntoIterator<Item = Into<T>>` to `Iterator<Item = T>`
pub fn into_node_iter<IT, T, R>(it: IT) -> impl Iterator<Item = R>
where
IT: IntoIterator<Item = T>,
T: Into<R>,
{
it.into_iter().map(|n| n.into())
}
fn array_single<T: ImplicitClone + 'static>(singl: T) -> IArray<T> {
IArray::Rc(Rc::new([singl]))
}
/// A special type necessary for flattening components returned from nested html macros.
#[derive(Debug)]
pub struct NodeSeq<IN, OUT: ImplicitClone + 'static>(IArray<OUT>, PhantomData<IN>);
impl<IN: Into<OUT>, OUT: ImplicitClone + 'static> From<IN> for NodeSeq<IN, OUT> {
fn from(val: IN) -> Self {
Self(array_single(val.into()), PhantomData)
}
}
impl<IN: Into<OUT>, OUT: ImplicitClone + 'static> From<Option<IN>> for NodeSeq<IN, OUT> {
fn from(val: Option<IN>) -> Self {
Self(
val.map(|s| array_single(s.into())).unwrap_or_default(),
PhantomData,
)
}
}
impl<IN: Into<OUT>, OUT: ImplicitClone + 'static> From<Vec<IN>> for NodeSeq<IN, OUT> {
fn from(mut val: Vec<IN>) -> Self {
if val.len() == 1 {
let item = val.pop().unwrap();
Self(array_single(item.into()), PhantomData)
} else {
Self(val.into_iter().map(|x| x.into()).collect(), PhantomData)
}
}
}
impl<IN: Into<OUT> + ImplicitClone, OUT: ImplicitClone + 'static> From<IArray<IN>>
for NodeSeq<IN, OUT>
{
fn from(val: IArray<IN>) -> Self {
Self(val.into_iter().map(|x| x.into()).collect(), PhantomData)
}
}
impl<IN: Into<OUT> + ImplicitClone, OUT: ImplicitClone + 'static> From<&IArray<IN>>
for NodeSeq<IN, OUT>
{
fn from(val: &IArray<IN>) -> Self {
Self(
val.clone().into_iter().map(|x| x.into()).collect(),
PhantomData,
)
}
}
impl<IN: Into<OUT> + Clone, OUT: ImplicitClone + 'static> From<&ChildrenRenderer<IN>>
for NodeSeq<IN, OUT>
{
fn from(val: &ChildrenRenderer<IN>) -> Self {
Self(val.iter().map(|x| x.into()).collect(), PhantomData)
}
}
impl<IN, OUT: ImplicitClone + 'static> IntoIterator for NodeSeq<IN, OUT> {
type IntoIter = implicit_clone::unsync::IArrayIntoIter<Self::Item>;
type Item = OUT;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
/// Hack to force type mismatch compile errors in yew-macro.
// TODO: replace with `compile_error!`, when `type_name_of_val` is stabilised (https://github.com/rust-lang/rust/issues/66359).
#[doc(hidden)]
pub fn __ensure_type<T>(_: T) {}
/// Print the [web_sys::Node]'s contents as a string for debugging purposes
pub fn print_node(n: &web_sys::Node) -> String {
use wasm_bindgen::JsCast;
match n.dyn_ref::<web_sys::Element>() {
Some(el) => el.outer_html(),
None => n.text_content().unwrap_or_default(),
}
}
// NOTE: replace this by Rc::unwrap_or_clone() when it becomes stable
pub(crate) trait RcExt<T: Clone> {
fn unwrap_or_clone(this: Self) -> T;
}
impl<T: Clone> RcExt<T> for std::rc::Rc<T> {
fn unwrap_or_clone(this: Self) -> T {
std::rc::Rc::try_unwrap(this).unwrap_or_else(|rc| (*rc).clone())
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/html/classes.rs | packages/yew/src/html/classes.rs | use std::borrow::Cow;
use std::iter::FromIterator;
use std::rc::Rc;
use indexmap::IndexSet;
use super::IntoPropValue;
use crate::html::ImplicitClone;
use crate::utils::RcExt;
use crate::virtual_dom::AttrValue;
/// A set of classes, cheap to clone.
///
/// The preferred way of creating this is using the [`classes!`][yew::classes!] macro.
#[derive(Debug, Clone, ImplicitClone, Default)]
pub struct Classes {
set: Rc<IndexSet<AttrValue>>,
}
/// helper method to efficiently turn a set of classes into a space-separated
/// string. Abstracts differences between ToString and IntoPropValue. The
/// `rest` iterator is cloned to pre-compute the length of the String; it
/// should be cheap to clone.
fn build_attr_value(first: AttrValue, rest: impl Iterator<Item = AttrValue> + Clone) -> AttrValue {
// The length of the string is known to be the length of all the
// components, plus one space for each element in `rest`.
let mut s = String::with_capacity(
rest.clone()
.map(|class| class.len())
.chain([first.len(), rest.size_hint().0])
.sum(),
);
s.push_str(first.as_str());
// NOTE: this can be improved once Iterator::intersperse() becomes stable
for class in rest {
s.push(' ');
s.push_str(class.as_str());
}
s.into()
}
impl Classes {
/// Creates an empty set of classes. (Does not allocate.)
#[inline]
pub fn new() -> Self {
Self {
set: Rc::new(IndexSet::new()),
}
}
/// Creates an empty set of classes with capacity for n elements. (Does not allocate if n is
/// zero.)
#[inline]
pub fn with_capacity(n: usize) -> Self {
Self {
set: Rc::new(IndexSet::with_capacity(n)),
}
}
/// Adds a class to a set.
///
/// If the provided class has already been added, this method will ignore it.
pub fn push<T: Into<Self>>(&mut self, class: T) {
let classes_to_add: Self = class.into();
if self.is_empty() {
*self = classes_to_add
} else {
Rc::make_mut(&mut self.set).extend(classes_to_add.set.iter().cloned())
}
}
/// Adds a class to a set.
///
/// If the provided class has already been added, this method will ignore it.
///
/// This method won't check if there are multiple classes in the input string.
///
/// # Safety
///
/// This function will not split the string into multiple classes. Please do not use it unless
/// you are absolutely certain that the string does not contain any whitespace and it is not
/// empty. Using `push()` is preferred.
pub unsafe fn unchecked_push<T: Into<AttrValue>>(&mut self, class: T) {
Rc::make_mut(&mut self.set).insert(class.into());
}
/// Check the set contains a class.
#[inline]
pub fn contains<T: AsRef<str>>(&self, class: T) -> bool {
self.set.contains(class.as_ref())
}
/// Check the set is empty.
#[inline]
pub fn is_empty(&self) -> bool {
self.set.is_empty()
}
}
impl IntoPropValue<AttrValue> for Classes {
#[inline]
fn into_prop_value(self) -> AttrValue {
let mut classes = self.set.iter().cloned();
match classes.next() {
None => AttrValue::Static(""),
Some(class) if classes.len() == 0 => class,
Some(first) => build_attr_value(first, classes),
}
}
}
impl IntoPropValue<Option<AttrValue>> for Classes {
#[inline]
fn into_prop_value(self) -> Option<AttrValue> {
if self.is_empty() {
None
} else {
Some(self.into_prop_value())
}
}
}
impl IntoPropValue<Classes> for &'static str {
#[inline]
fn into_prop_value(self) -> Classes {
self.into()
}
}
impl<T: Into<Classes>> Extend<T> for Classes {
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
iter.into_iter().for_each(|classes| self.push(classes))
}
}
impl<T: Into<Classes>> FromIterator<T> for Classes {
fn from_iter<IT: IntoIterator<Item = T>>(iter: IT) -> Self {
let mut classes = Self::new();
classes.extend(iter);
classes
}
}
impl IntoIterator for Classes {
type IntoIter = indexmap::set::IntoIter<AttrValue>;
type Item = AttrValue;
#[inline]
fn into_iter(self) -> Self::IntoIter {
RcExt::unwrap_or_clone(self.set).into_iter()
}
}
impl IntoIterator for &Classes {
type IntoIter = indexmap::set::IntoIter<AttrValue>;
type Item = AttrValue;
#[inline]
fn into_iter(self) -> Self::IntoIter {
(*self.set).clone().into_iter()
}
}
#[allow(clippy::to_string_trait_impl)]
impl ToString for Classes {
fn to_string(&self) -> String {
let mut iter = self.set.iter().cloned();
iter.next()
.map(|first| build_attr_value(first, iter))
.unwrap_or_default()
.to_string()
}
}
impl From<Cow<'static, str>> for Classes {
fn from(t: Cow<'static, str>) -> Self {
match t {
Cow::Borrowed(x) => Self::from(x),
Cow::Owned(x) => Self::from(x),
}
}
}
impl From<&'static str> for Classes {
fn from(t: &'static str) -> Self {
let set = t.split_whitespace().map(AttrValue::Static).collect();
Self { set: Rc::new(set) }
}
}
impl From<String> for Classes {
fn from(t: String) -> Self {
match t.contains(|c: char| c.is_whitespace()) {
// If the string only contains a single class, we can just use it
// directly (rather than cloning it into a new string). Need to make
// sure it's not empty, though.
false => match t.is_empty() {
true => Self::new(),
false => Self {
set: Rc::new(IndexSet::from_iter([AttrValue::from(t)])),
},
},
true => Self::from(&t),
}
}
}
impl From<&String> for Classes {
fn from(t: &String) -> Self {
let set = t
.split_whitespace()
.map(ToOwned::to_owned)
.map(AttrValue::from)
.collect();
Self { set: Rc::new(set) }
}
}
impl From<&AttrValue> for Classes {
fn from(t: &AttrValue) -> Self {
let set = t
.split_whitespace()
.map(ToOwned::to_owned)
.map(AttrValue::from)
.collect();
Self { set: Rc::new(set) }
}
}
impl From<AttrValue> for Classes {
fn from(t: AttrValue) -> Self {
match t.contains(|c: char| c.is_whitespace()) {
// If the string only contains a single class, we can just use it
// directly (rather than cloning it into a new string). Need to make
// sure it's not empty, though.
false => match t.is_empty() {
true => Self::new(),
false => Self {
set: Rc::new(IndexSet::from_iter([t])),
},
},
true => Self::from(&t),
}
}
}
impl<T: Into<Classes>> From<Option<T>> for Classes {
fn from(t: Option<T>) -> Self {
t.map(|x| x.into()).unwrap_or_default()
}
}
impl<T: Into<Classes> + Clone> From<&Option<T>> for Classes {
fn from(t: &Option<T>) -> Self {
Self::from(t.clone())
}
}
impl<T: Into<Classes>> From<Vec<T>> for Classes {
fn from(t: Vec<T>) -> Self {
Self::from_iter(t)
}
}
impl<T: Into<Classes> + Clone> From<&[T]> for Classes {
fn from(t: &[T]) -> Self {
t.iter().cloned().collect()
}
}
impl<T: Into<Classes>, const SIZE: usize> From<[T; SIZE]> for Classes {
fn from(t: [T; SIZE]) -> Self {
t.into_iter().collect()
}
}
impl From<&Classes> for Classes {
fn from(c: &Classes) -> Self {
c.clone()
}
}
impl From<&Classes> for AttrValue {
fn from(c: &Classes) -> Self {
c.clone().into_prop_value()
}
}
impl PartialEq for Classes {
fn eq(&self, other: &Self) -> bool {
self.set.len() == other.set.len() && self.set.iter().eq(other.set.iter())
}
}
impl Eq for Classes {}
#[cfg(test)]
mod tests {
use super::*;
struct TestClass;
impl TestClass {
fn as_class(&self) -> &'static str {
"test-class"
}
}
impl From<TestClass> for Classes {
fn from(x: TestClass) -> Self {
Classes::from(x.as_class())
}
}
#[test]
fn it_is_initially_empty() {
let subject = Classes::new();
assert!(subject.is_empty());
}
#[test]
fn it_pushes_value() {
let mut subject = Classes::new();
subject.push("foo");
assert!(!subject.is_empty());
assert!(subject.contains("foo"));
}
#[test]
fn it_adds_values_via_extend() {
let mut other = Classes::new();
other.push("bar");
let mut subject = Classes::new();
subject.extend(other);
assert!(subject.contains("bar"));
}
#[test]
fn it_contains_both_values() {
let mut other = Classes::new();
other.push("bar");
let mut subject = Classes::new();
subject.extend(other);
subject.push("foo");
assert!(subject.contains("foo"));
assert!(subject.contains("bar"));
}
#[test]
fn it_splits_class_with_spaces() {
let mut subject = Classes::new();
subject.push("foo bar");
assert!(subject.contains("foo"));
assert!(subject.contains("bar"));
}
#[test]
fn push_and_contains_can_be_used_with_other_objects() {
let mut subject = Classes::new();
subject.push(TestClass);
let other_class: Option<TestClass> = None;
subject.push(other_class);
assert!(subject.contains(TestClass.as_class()));
}
#[test]
fn can_be_extended_with_another_class() {
let mut other = Classes::new();
other.push("foo");
other.push("bar");
let mut subject = Classes::new();
subject.extend(&other);
subject.extend(other);
assert!(subject.contains("foo"));
assert!(subject.contains("bar"));
}
#[test]
fn can_be_collected() {
let classes = vec!["foo", "bar"];
let subject = classes.into_iter().collect::<Classes>();
assert!(subject.contains("foo"));
assert!(subject.contains("bar"));
}
#[test]
fn ignores_empty_string() {
let classes = String::from("");
let subject = Classes::from(classes);
assert!(subject.is_empty())
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/html/error.rs | packages/yew/src/html/error.rs | use thiserror::Error;
use crate::suspense::Suspension;
/// Render Error.
#[derive(Error, Debug, Clone, PartialEq)]
pub enum RenderError {
/// Component Rendering Suspended
#[error("component rendering is suspended.")]
Suspended(#[from] Suspension),
}
/// Render Result.
pub type RenderResult<T> = std::result::Result<T, RenderError>;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/html/mod.rs | packages/yew/src/html/mod.rs | //! The main html module which defines components, listeners, and class helpers.
mod classes;
mod component;
mod conversion;
mod error;
mod listener;
use std::cell::RefCell;
use std::rc::Rc;
pub use classes::*;
pub use component::*;
pub use conversion::*;
pub use error::*;
pub use listener::*;
use wasm_bindgen::JsValue;
use web_sys::{Element, Node};
use crate::sealed::Sealed;
use crate::virtual_dom::{VNode, VPortal};
/// A type which expected as a result of `view` function implementation.
pub type Html = VNode;
/// An enhanced type of `Html` returned in suspendible function components.
pub type HtmlResult = RenderResult<Html>;
impl Sealed for HtmlResult {}
impl Sealed for Html {}
/// A trait to translate into a [`HtmlResult`].
pub trait IntoHtmlResult: Sealed {
/// Performs the conversion.
fn into_html_result(self) -> HtmlResult;
}
impl IntoHtmlResult for HtmlResult {
#[inline(always)]
fn into_html_result(self) -> HtmlResult {
self
}
}
impl IntoHtmlResult for Html {
#[inline(always)]
fn into_html_result(self) -> HtmlResult {
Ok(self)
}
}
/// Wrapped Node reference for later use in Component lifecycle methods.
///
/// # Example
/// Focus an `<input>` element on mount.
/// ```
/// use web_sys::HtmlInputElement;
/// # use yew::prelude::*;
///
/// pub struct Input {
/// node_ref: NodeRef,
/// }
///
/// impl Component for Input {
/// type Message = ();
/// type Properties = ();
///
/// fn create(_ctx: &Context<Self>) -> Self {
/// Input {
/// node_ref: NodeRef::default(),
/// }
/// }
///
/// fn rendered(&mut self, _ctx: &Context<Self>, first_render: bool) {
/// if first_render {
/// if let Some(input) = self.node_ref.cast::<HtmlInputElement>() {
/// input.focus();
/// }
/// }
/// }
///
/// fn view(&self, _ctx: &Context<Self>) -> Html {
/// html! {
/// <input ref={self.node_ref.clone()} type="text" />
/// }
/// }
/// }
/// ```
/// ## Relevant examples
/// - [Node Refs](https://github.com/yewstack/yew/tree/master/examples/node_refs)
#[derive(Default, Clone, ImplicitClone)]
pub struct NodeRef(Rc<RefCell<NodeRefInner>>);
impl PartialEq for NodeRef {
fn eq(&self, other: &Self) -> bool {
std::ptr::eq(self.0.as_ptr(), other.0.as_ptr())
}
}
impl std::fmt::Debug for NodeRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"NodeRef {{ references: {:?} }}",
self.get().map(|n| crate::utils::print_node(&n))
)
}
}
#[derive(PartialEq, Debug, Default, Clone)]
struct NodeRefInner {
node: Option<Node>,
}
impl NodeRef {
/// Get the wrapped Node reference if it exists
pub fn get(&self) -> Option<Node> {
let inner = self.0.borrow();
inner.node.clone()
}
/// Try converting the node reference into another form
pub fn cast<INTO: AsRef<Node> + From<JsValue>>(&self) -> Option<INTO> {
let node = self.get();
node.map(Into::into).map(INTO::from)
}
}
#[cfg(feature = "csr")]
mod feat_csr {
use super::*;
impl NodeRef {
pub(crate) fn set(&self, new_ref: Option<Node>) {
let mut inner = self.0.borrow_mut();
inner.node = new_ref;
}
}
}
/// Render children into a DOM node that exists outside the hierarchy of the parent
/// component.
/// ## Relevant examples
/// - [Portals](https://github.com/yewstack/yew/tree/master/examples/portals)
pub fn create_portal(child: Html, host: Element) -> Html {
VNode::VPortal(Rc::new(VPortal::new(child, host)))
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/html/conversion/into_prop_value.rs | packages/yew/src/html/conversion/into_prop_value.rs | use std::borrow::Cow;
use std::rc::Rc;
use std::sync::Arc;
use implicit_clone::unsync::{IArray, IMap};
pub use implicit_clone::ImplicitClone;
use crate::callback::Callback;
use crate::html::{BaseComponent, ChildrenRenderer, Component, Scope};
use crate::virtual_dom::{AttrValue, VChild, VList, VNode, VText};
impl<Comp: Component> ImplicitClone for Scope<Comp> {}
// TODO there are still a few missing
/// A trait similar to `Into<T>` which allows conversion to a value of a `Properties` struct.
pub trait IntoPropValue<T> {
/// Convert `self` to a value of a `Properties` struct.
fn into_prop_value(self) -> T;
}
impl<T> IntoPropValue<T> for T {
#[inline]
fn into_prop_value(self) -> T {
self
}
}
impl<T> IntoPropValue<T> for &T
where
T: ImplicitClone,
{
#[inline]
fn into_prop_value(self) -> T {
self.clone()
}
}
impl<T> IntoPropValue<Option<T>> for T {
#[inline]
fn into_prop_value(self) -> Option<T> {
Some(self)
}
}
impl<T> IntoPropValue<Option<T>> for &T
where
T: ImplicitClone,
{
#[inline]
fn into_prop_value(self) -> Option<T> {
Some(self.clone())
}
}
impl<I, O, F> IntoPropValue<Callback<I, O>> for F
where
F: 'static + Fn(I) -> O,
{
#[inline]
fn into_prop_value(self) -> Callback<I, O> {
Callback::from(self)
}
}
impl<I, O, F> IntoPropValue<Option<Callback<I, O>>> for F
where
F: 'static + Fn(I) -> O,
{
#[inline]
fn into_prop_value(self) -> Option<Callback<I, O>> {
Some(Callback::from(self))
}
}
impl<I, O, F> IntoPropValue<Option<Callback<I, O>>> for Option<F>
where
F: 'static + Fn(I) -> O,
{
#[inline]
fn into_prop_value(self) -> Option<Callback<I, O>> {
self.map(Callback::from)
}
}
impl<T, C> IntoPropValue<ChildrenRenderer<C>> for VChild<T>
where
T: BaseComponent,
C: Clone + Into<VNode>,
VChild<T>: Into<C>,
{
#[inline]
fn into_prop_value(self) -> ChildrenRenderer<C> {
ChildrenRenderer::new(vec![self.into()])
}
}
impl<T, C> IntoPropValue<Option<ChildrenRenderer<C>>> for VChild<T>
where
T: BaseComponent,
C: Clone + Into<VNode>,
VChild<T>: Into<C>,
{
#[inline]
fn into_prop_value(self) -> Option<ChildrenRenderer<C>> {
Some(ChildrenRenderer::new(vec![self.into()]))
}
}
impl<T, C> IntoPropValue<Option<ChildrenRenderer<C>>> for Option<VChild<T>>
where
T: BaseComponent,
C: Clone + Into<VNode>,
VChild<T>: Into<C>,
{
#[inline]
fn into_prop_value(self) -> Option<ChildrenRenderer<C>> {
self.map(|m| ChildrenRenderer::new(vec![m.into()]))
}
}
impl<T, R> IntoPropValue<ChildrenRenderer<R>> for Vec<T>
where
T: Into<R>,
R: Clone + Into<VNode>,
{
#[inline]
fn into_prop_value(self) -> ChildrenRenderer<R> {
ChildrenRenderer::new(self.into_iter().map(|m| m.into()).collect::<Vec<_>>())
}
}
impl<T> IntoPropValue<VNode> for VChild<T>
where
T: BaseComponent,
{
#[inline]
fn into_prop_value(self) -> VNode {
VNode::from(self)
}
}
impl IntoPropValue<VNode> for VList {
#[inline]
fn into_prop_value(self) -> VNode {
VNode::VList(Rc::new(self))
}
}
impl IntoPropValue<VNode> for VText {
#[inline]
fn into_prop_value(self) -> VNode {
VNode::VText(self)
}
}
impl IntoPropValue<VNode> for () {
#[inline]
fn into_prop_value(self) -> VNode {
VNode::default()
}
}
impl IntoPropValue<VNode> for ChildrenRenderer<VNode> {
#[inline]
fn into_prop_value(self) -> VNode {
VNode::VList(Rc::new(self.into()))
}
}
impl IntoPropValue<VNode> for &ChildrenRenderer<VNode> {
#[inline]
fn into_prop_value(self) -> VNode {
VNode::VList(Rc::new(VList::from(self.children.clone())))
}
}
impl IntoPropValue<ChildrenRenderer<VNode>> for VNode {
#[inline]
fn into_prop_value(self) -> ChildrenRenderer<VNode> {
ChildrenRenderer::new(vec![self])
}
}
impl IntoPropValue<ChildrenRenderer<VNode>> for VText {
#[inline]
fn into_prop_value(self) -> ChildrenRenderer<VNode> {
ChildrenRenderer::new(vec![self.into()])
}
}
impl IntoPropValue<VList> for ChildrenRenderer<VNode> {
#[inline]
fn into_prop_value(self) -> VList {
VList::from(self.children)
}
}
impl<C: BaseComponent> IntoPropValue<VList> for VChild<C> {
#[inline]
fn into_prop_value(self) -> VList {
VList::from(VNode::from(self))
}
}
impl IntoPropValue<ChildrenRenderer<VNode>> for AttrValue {
fn into_prop_value(self) -> ChildrenRenderer<VNode> {
ChildrenRenderer::new(vec![VNode::VText(VText::new(self))])
}
}
impl IntoPropValue<VNode> for Vec<VNode> {
#[inline]
fn into_prop_value(self) -> VNode {
VNode::VList(Rc::new(VList::from(self)))
}
}
impl IntoPropValue<VNode> for Option<VNode> {
#[inline]
fn into_prop_value(self) -> VNode {
self.unwrap_or_default()
}
}
macro_rules! impl_into_prop {
(|$value:ident: $from_ty:ty| -> $to_ty:ty { $conversion:expr }) => {
// implement V -> T
impl IntoPropValue<$to_ty> for $from_ty {
#[inline]
fn into_prop_value(self) -> $to_ty {
let $value = self;
$conversion
}
}
// implement V -> Option<T>
impl IntoPropValue<Option<$to_ty>> for $from_ty {
#[inline]
fn into_prop_value(self) -> Option<$to_ty> {
let $value = self;
Some({ $conversion })
}
}
// implement Option<V> -> Option<T>
impl IntoPropValue<Option<$to_ty>> for Option<$from_ty> {
#[inline]
fn into_prop_value(self) -> Option<$to_ty> {
self.map(IntoPropValue::into_prop_value)
}
}
};
}
// implemented with literals in mind
impl_into_prop!(|value: &'static str| -> String { value.to_owned() });
impl_into_prop!(|value: &'static str| -> AttrValue { AttrValue::Static(value) });
impl_into_prop!(|value: String| -> AttrValue { AttrValue::Rc(Rc::from(value)) });
impl_into_prop!(|value: Rc<str>| -> AttrValue { AttrValue::Rc(value) });
impl_into_prop!(|value: Cow<'static, str>| -> AttrValue { AttrValue::from(value) });
impl<T: ImplicitClone + 'static> IntoPropValue<IArray<T>> for &'static [T] {
fn into_prop_value(self) -> IArray<T> {
IArray::from(self)
}
}
impl<T: ImplicitClone + 'static> IntoPropValue<IArray<T>> for Vec<T> {
fn into_prop_value(self) -> IArray<T> {
IArray::from(self)
}
}
impl<K: Eq + std::hash::Hash + ImplicitClone + 'static, V: PartialEq + ImplicitClone + 'static>
IntoPropValue<IMap<K, V>> for &'static [(K, V)]
{
fn into_prop_value(self) -> IMap<K, V> {
IMap::from(self)
}
}
impl<K: Eq + std::hash::Hash + ImplicitClone + 'static, V: PartialEq + ImplicitClone + 'static>
IntoPropValue<IMap<K, V>> for indexmap::IndexMap<K, V>
{
fn into_prop_value(self) -> IMap<K, V> {
IMap::from(self)
}
}
macro_rules! impl_into_prop_value_via_display {
($from_ty: ty) => {
impl IntoPropValue<VNode> for $from_ty {
#[inline(always)]
fn into_prop_value(self) -> VNode {
VText::from(self).into()
}
}
};
}
// go through AttrValue::from where possible
macro_rules! impl_into_prop_value_via_attr_value {
($from_ty: ty) => {
impl IntoPropValue<VNode> for $from_ty {
#[inline(always)]
fn into_prop_value(self) -> VNode {
VText::new(self).into()
}
}
};
}
// These are a selection of types implemented via display.
impl_into_prop_value_via_display!(bool);
impl_into_prop_value_via_display!(char);
impl_into_prop_value_via_display!(&String);
impl_into_prop_value_via_display!(&str);
impl_into_prop_value_via_display!(Arc<str>);
impl_into_prop_value_via_display!(Arc<String>);
impl_into_prop_value_via_display!(Rc<String>);
impl_into_prop_value_via_display!(u8);
impl_into_prop_value_via_display!(u16);
impl_into_prop_value_via_display!(u32);
impl_into_prop_value_via_display!(u64);
impl_into_prop_value_via_display!(u128);
impl_into_prop_value_via_display!(usize);
impl_into_prop_value_via_display!(i8);
impl_into_prop_value_via_display!(i16);
impl_into_prop_value_via_display!(i32);
impl_into_prop_value_via_display!(i64);
impl_into_prop_value_via_display!(i128);
impl_into_prop_value_via_display!(isize);
impl_into_prop_value_via_display!(f32);
impl_into_prop_value_via_display!(f64);
impl_into_prop_value_via_attr_value!(String);
impl_into_prop_value_via_attr_value!(AttrValue);
impl_into_prop_value_via_attr_value!(&AttrValue);
impl_into_prop_value_via_attr_value!(Rc<str>);
impl_into_prop_value_via_attr_value!(Cow<'static, str>);
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_str() {
let _: String = "foo".into_prop_value();
let _: Option<String> = "foo".into_prop_value();
let _: AttrValue = "foo".into_prop_value();
let _: Option<AttrValue> = "foo".into_prop_value();
let _: Option<AttrValue> = Rc::<str>::from("foo").into_prop_value();
let _: Option<AttrValue> = Cow::Borrowed("foo").into_prop_value();
}
#[test]
fn test_callback() {
let _: Callback<String> = (|_: String| ()).into_prop_value();
let _: Option<Callback<String>> = (|_: String| ()).into_prop_value();
let _: Option<Callback<String>> = Some(|_: String| ()).into_prop_value();
let _: Callback<String, String> = (|s: String| s).into_prop_value();
let _: Option<Callback<String, String>> = (|s: String| s).into_prop_value();
let _: Option<Callback<String, String>> = Some(|s: String| s).into_prop_value();
}
#[test]
fn test_html_to_children_compiles() {
use crate::prelude::*;
#[derive(Clone, Debug, PartialEq, Properties)]
pub struct Props {
#[prop_or_default]
pub header: Children,
#[prop_or_default]
pub children: Children,
#[prop_or_default]
pub footer: Children,
}
#[component]
pub fn App(props: &Props) -> Html {
let Props {
header,
children,
footer,
} = props.clone();
html! {
<div>
<header>
{header}
</header>
<main>
{children}
</main>
<footer>
{footer}
</footer>
</div>
}
}
let header = html! { <div>{"header"}</div> };
let footer = html! { <div>{"footer"}</div> };
let children = html! { <div>{"main"}</div> };
let _ = html! {
<App {header} {footer}>
{children}
</App>
};
}
#[test]
fn test_vchild_to_children_with_props_compiles() {
use crate::prelude::*;
#[component]
pub fn Comp() -> Html {
Html::default()
}
#[derive(Clone, Debug, PartialEq, Properties)]
pub struct Props {
#[prop_or_default]
pub header: ChildrenWithProps<Comp>,
#[prop_or_default]
pub children: Children,
#[prop_or_default]
pub footer: ChildrenWithProps<Comp>,
}
#[component]
pub fn App(props: &Props) -> Html {
let Props {
header,
children,
footer,
} = props.clone();
html! {
<div>
<header>
{for header}
</header>
<main>
{children}
</main>
<footer>
{for footer}
</footer>
</div>
}
}
let header = VChild::new((), None);
let footer = html_nested! { <Comp /> };
let children = html! { <div>{"main"}</div> };
let _ = html! {
<App {header} {footer}>
{children}
</App>
};
}
#[test]
fn test_vlist_to_children_compiles() {
use crate::prelude::*;
use crate::virtual_dom::VList;
#[component]
fn Foo() -> Html {
todo!()
}
#[derive(PartialEq, Properties)]
pub struct ChildProps {
#[prop_or_default]
pub children: Html,
}
#[component]
fn Child(_props: &ChildProps) -> Html {
html!()
}
#[derive(PartialEq, Properties)]
pub struct ParentProps {
pub children: VList,
}
#[component]
fn Parent(_props: &ParentProps) -> Html {
todo!()
}
let _ = html! {
<Parent>
<Child></Child>
</Parent>
};
let _ = html! {
<Parent>
<Child />
<Child />
</Parent>
};
let _ = html! {
<Parent>
<Child>
<Foo />
</Child>
</Parent>
};
}
#[test]
fn attr_value_children() {
use crate::prelude::*;
#[derive(PartialEq, Properties)]
pub struct ChildProps {
#[prop_or_default]
pub children: AttrValue,
}
#[component]
fn Child(_props: &ChildProps) -> Html {
html!()
}
{
let attr_value = AttrValue::from("foo");
let _ = html! { <Child>{attr_value}</Child> };
}
{
let attr_value = AttrValue::from("foo");
let _ = html! { <Child>{&attr_value}</Child> };
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/html/conversion/mod.rs | packages/yew/src/html/conversion/mod.rs | mod into_prop_value;
pub use into_prop_value::*;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/html/component/properties.rs | packages/yew/src/html/component/properties.rs | //! Component properties module
pub use yew_macro::Properties;
/// Trait for building properties for a component
pub trait Properties: PartialEq {
/// Builder that will be used to construct properties
type Builder;
/// Entrypoint for building properties
fn builder() -> Self::Builder;
}
#[doc(hidden)]
mod __macro {
/// A marker trait to ensure that the builder has received a specific required prop.
/// For each required impl in a property, we generate:
/// - a struct with the name of the prop, which takes the place of `P`.
/// - a token wrapper, `HasP<TokenTail>`, that records that the build state represented includes
/// the state in `TokenTail` + `P`. Such tokens are returned from the setter on the builder,
/// to verify the build state.
/// - An `impl<T> HasP<T>: HasProp<P, _>` saying that a state represented by a token of
/// `HasP<_>` indeed verifies P has been set.
/// - An `impl<Q> HasP<Tail>: HasProp<Q, _> where Tail: HasProp<Q>` saying that any props set
/// previously (represented by the tail) is still set after P has been set.
/// - ^ the two impls would be overlapping, where it not for the `How` argument, which resolves
/// the conflict.
#[diagnostic::on_unimplemented(
message = "property `{P}` is required but not provided",
label = "missing required property `{P}`"
)]
pub trait HasProp<P, How> {}
/// A marker trait to ensure that the builder has received all required props.
/// For each struct deriving [`Properties`], an impl is generated, requiring `HasProp<p>` for
/// all properties marked as required as a bound on the impl.
///
/// [`Properties`]: super::Properties
#[diagnostic::on_unimplemented(
message = "not all required properties have been provided for `{P}`",
label = "missing required properties"
)]
pub trait HasAllProps<P, How> {}
/// Trait finishing the builder and verifying all props were set.
/// The structure can be a bit surprising, and is related to how the proc macro reports errors
/// - why have a prepare_build method? This captures the argument types, but now `How`, and
/// returns an internal type with a method that can be called without further qualification.
/// We need the additional types, to avoid collision with property names in the Builder. We
/// want to avoid qualification to persuade rust not to report the `finish_build` method name.
/// - why have a AllPropsFor trait? We want the trait to be on the Token, not on a type
/// associated or derived from it, so that it shows up in errors directly instead of through
/// convoluted traces.
pub trait Buildable<Token> {
/// Property type being built
type Output;
/// Instead of `Token` directly, a wrapped token type is checked for trait impls in macro
/// code. This avoids problems related to blanket impls.
type WrappedToken;
/// This method "captures" the builder and token type, but does not verify yet.
fn prepare_build(builder: Self, _: &Token) -> PreBuild<Token, Self>
where
Self: Sized,
{
PreBuild {
builder,
_token: std::marker::PhantomData,
}
}
/// Build the props from self. Expected to panic if not all props where set.
fn build(this: Self) -> Self::Output;
}
/// Helper alias for a Builder, also capturing the prop Token recording the provided props.
#[derive(Debug)]
pub struct PreBuild<Token, B> {
_token: std::marker::PhantomData<Token>,
builder: B,
}
impl<Token, B: Buildable<Token>> PreBuild<Token, B> {
/// This is the method that introduces the actual bound verifying all props where set.
pub fn build<How>(self) -> B::Output
where
Token: AllPropsFor<B, How>,
{
B::build(self.builder)
}
}
/// Trait to specify the requirement for Self to be a valid token signaling all props have been
/// provided to the builder.
#[diagnostic::on_unimplemented(
message = "not all required properties have been provided",
label = "missing required properties for this component"
)]
pub trait AllPropsFor<Builder, How> {}
impl<Token, Builder: Buildable<Token>, How> AllPropsFor<Builder, How> for Token where
Builder::WrappedToken: HasAllProps<Builder::Output, How>
{
}
/// Dummy struct targeted by assertions that all props were set
#[derive(Debug)]
pub struct AssertAllProps;
/// Builder for when a component has no properties
#[derive(Debug, PartialEq, Eq)]
pub struct EmptyBuilder;
impl super::Properties for () {
type Builder = EmptyBuilder;
fn builder() -> Self::Builder {
EmptyBuilder
}
}
impl<T> Buildable<T> for EmptyBuilder {
type Output = ();
type WrappedToken = ();
/// Build empty properties
fn build(_: Self) {}
}
impl<T> HasAllProps<(), T> for T {}
}
#[doc(hidden)]
pub use __macro::{AllPropsFor, AssertAllProps, Buildable, HasAllProps, HasProp};
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/html/component/lifecycle.rs | packages/yew/src/html/component/lifecycle.rs | //! Component lifecycle module
use std::any::Any;
use std::rc::Rc;
#[cfg(feature = "csr")]
use web_sys::Element;
use super::scope::{AnyScope, Scope};
use super::BaseComponent;
#[cfg(feature = "hydration")]
use crate::dom_bundle::Fragment;
#[cfg(feature = "csr")]
use crate::dom_bundle::{BSubtree, Bundle, DomSlot, DynamicDomSlot};
#[cfg(feature = "hydration")]
use crate::html::RenderMode;
use crate::html::{Html, RenderError};
use crate::scheduler::{self, Runnable, Shared};
use crate::suspense::{BaseSuspense, Suspension};
use crate::{Callback, Context, HtmlResult};
pub(crate) enum ComponentRenderState {
#[cfg(feature = "csr")]
Render {
bundle: Bundle,
root: BSubtree,
parent: Element,
/// The dom position in front of the next sibling.
/// Gets updated when the bundle in which this component occurs gets re-rendered and is
/// shared with the children of this component.
sibling_slot: DynamicDomSlot,
/// The dom position in front of this component.
/// Gets updated whenever this component re-renders and is shared with the bundle in which
/// this component occurs.
own_slot: DynamicDomSlot,
},
#[cfg(feature = "hydration")]
Hydration {
fragment: Fragment,
root: BSubtree,
parent: Element,
sibling_slot: DynamicDomSlot,
own_slot: DynamicDomSlot,
},
#[cfg(feature = "ssr")]
Ssr {
sender: Option<crate::platform::pinned::oneshot::Sender<Html>>,
},
}
impl std::fmt::Debug for ComponentRenderState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
#[cfg(feature = "csr")]
Self::Render {
ref bundle,
root,
ref parent,
ref sibling_slot,
ref own_slot,
} => f
.debug_struct("ComponentRenderState::Render")
.field("bundle", bundle)
.field("root", root)
.field("parent", parent)
.field("sibling_slot", sibling_slot)
.field("own_slot", own_slot)
.finish(),
#[cfg(feature = "hydration")]
Self::Hydration {
ref fragment,
ref parent,
ref sibling_slot,
ref own_slot,
ref root,
} => f
.debug_struct("ComponentRenderState::Hydration")
.field("fragment", fragment)
.field("root", root)
.field("parent", parent)
.field("sibling_slot", sibling_slot)
.field("own_slot", own_slot)
.finish(),
#[cfg(feature = "ssr")]
Self::Ssr { ref sender } => {
let sender_repr = match sender {
Some(_) => "Some(_)",
None => "None",
};
f.debug_struct("ComponentRenderState::Ssr")
.field("sender", &sender_repr)
.finish()
}
}
}
}
#[cfg(feature = "csr")]
impl ComponentRenderState {
pub(crate) fn shift(&mut self, next_parent: Element, next_slot: DomSlot) {
match self {
#[cfg(feature = "csr")]
Self::Render {
bundle,
parent,
sibling_slot,
..
} => {
*parent = next_parent;
sibling_slot.reassign(next_slot);
bundle.shift(parent, sibling_slot.to_position());
}
#[cfg(feature = "hydration")]
Self::Hydration {
fragment,
parent,
sibling_slot,
..
} => {
*parent = next_parent;
sibling_slot.reassign(next_slot);
fragment.shift(parent, sibling_slot.to_position());
}
#[cfg(feature = "ssr")]
Self::Ssr { .. } => {
#[cfg(debug_assertions)]
panic!("shifting is not possible during SSR");
}
}
}
}
struct CompStateInner<COMP>
where
COMP: BaseComponent,
{
pub(crate) component: COMP,
pub(crate) context: Context<COMP>,
}
/// A trait to provide common,
/// generic free behaviour across all components to reduce code size.
///
/// Mostly a thin wrapper that passes the context to a component's lifecycle
/// methods.
pub(crate) trait Stateful {
fn view(&self) -> HtmlResult;
#[cfg(feature = "csr")]
fn rendered(&mut self, first_render: bool);
fn destroy(&mut self);
fn any_scope(&self) -> AnyScope;
fn flush_messages(&mut self) -> bool;
#[cfg(feature = "csr")]
fn props_changed(&mut self, props: Rc<dyn Any>) -> bool;
fn as_any(&self) -> &dyn Any;
#[cfg(feature = "hydration")]
fn creation_mode(&self) -> RenderMode;
}
impl<COMP> Stateful for CompStateInner<COMP>
where
COMP: BaseComponent,
{
fn view(&self) -> HtmlResult {
self.component.view(&self.context)
}
#[cfg(feature = "csr")]
fn rendered(&mut self, first_render: bool) {
self.component.rendered(&self.context, first_render)
}
fn destroy(&mut self) {
self.component.destroy(&self.context);
}
fn any_scope(&self) -> AnyScope {
self.context.link().clone().into()
}
#[cfg(feature = "hydration")]
fn creation_mode(&self) -> RenderMode {
self.context.creation_mode()
}
fn flush_messages(&mut self) -> bool {
self.context
.link()
.pending_messages
.drain()
.into_iter()
.fold(false, |acc, msg| {
self.component.update(&self.context, msg) || acc
})
}
#[cfg(feature = "csr")]
fn props_changed(&mut self, props: Rc<dyn Any>) -> bool {
let props = match Rc::downcast::<COMP::Properties>(props) {
Ok(m) => m,
_ => return false,
};
if self.context.props != props {
let old_props = std::mem::replace(&mut self.context.props, props);
self.component.changed(&self.context, &old_props)
} else {
false
}
}
fn as_any(&self) -> &dyn Any {
self
}
}
pub(crate) struct ComponentState {
pub(super) inner: Box<dyn Stateful>,
pub(super) render_state: ComponentRenderState,
#[cfg(feature = "csr")]
has_rendered: bool,
/// This deals with an edge case. Usually, we want to update props as fast as possible.
/// But, when a component hydrates and suspends, we want to continue using the intially given
/// props. This is prop updates are ignored during SSR, too.
#[cfg(feature = "hydration")]
pending_props: Option<Rc<dyn Any>>,
suspension: Option<Suspension>,
pub(crate) comp_id: usize,
}
impl ComponentState {
#[tracing::instrument(
level = tracing::Level::DEBUG,
name = "create",
skip_all,
fields(component.id = scope.id),
)]
fn new<COMP: BaseComponent>(
initial_render_state: ComponentRenderState,
scope: Scope<COMP>,
props: Rc<COMP::Properties>,
#[cfg(feature = "hydration")] prepared_state: Option<String>,
) -> Self {
let comp_id = scope.id;
#[cfg(feature = "hydration")]
let creation_mode = {
match initial_render_state {
ComponentRenderState::Render { .. } => RenderMode::Render,
ComponentRenderState::Hydration { .. } => RenderMode::Hydration,
#[cfg(feature = "ssr")]
ComponentRenderState::Ssr { .. } => RenderMode::Ssr,
}
};
let context = Context {
scope,
props,
#[cfg(feature = "hydration")]
creation_mode,
#[cfg(feature = "hydration")]
prepared_state,
};
let inner = Box::new(CompStateInner {
component: COMP::create(&context),
context,
});
Self {
inner,
render_state: initial_render_state,
suspension: None,
#[cfg(feature = "csr")]
has_rendered: false,
#[cfg(feature = "hydration")]
pending_props: None,
comp_id,
}
}
pub(crate) fn downcast_comp_ref<COMP>(&self) -> Option<&COMP>
where
COMP: BaseComponent + 'static,
{
self.inner
.as_any()
.downcast_ref::<CompStateInner<COMP>>()
.map(|m| &m.component)
}
fn resume_existing_suspension(&mut self) {
if let Some(m) = self.suspension.take() {
let comp_scope = self.inner.any_scope();
let suspense_scope = comp_scope.find_parent_scope::<BaseSuspense>().unwrap();
BaseSuspense::resume(&suspense_scope, m);
}
}
}
pub(crate) struct CreateRunner<COMP: BaseComponent> {
pub initial_render_state: ComponentRenderState,
pub props: Rc<COMP::Properties>,
pub scope: Scope<COMP>,
#[cfg(feature = "hydration")]
pub prepared_state: Option<String>,
}
impl<COMP: BaseComponent> Runnable for CreateRunner<COMP> {
fn run(self: Box<Self>) {
let mut current_state = self.scope.state.borrow_mut();
if current_state.is_none() {
*current_state = Some(ComponentState::new(
self.initial_render_state,
self.scope.clone(),
self.props,
#[cfg(feature = "hydration")]
self.prepared_state,
));
}
}
}
pub(crate) struct UpdateRunner {
pub state: Shared<Option<ComponentState>>,
}
impl ComponentState {
#[tracing::instrument(
level = tracing::Level::DEBUG,
skip(self),
fields(component.id = self.comp_id)
)]
fn update(&mut self) -> bool {
let schedule_render = self.inner.flush_messages();
tracing::trace!(schedule_render);
schedule_render
}
}
impl Runnable for UpdateRunner {
fn run(self: Box<Self>) {
if let Some(state) = self.state.borrow_mut().as_mut() {
let schedule_render = state.update();
if schedule_render {
scheduler::push_component_render(
state.comp_id,
Box::new(RenderRunner {
state: self.state.clone(),
}),
);
// Only run from the scheduler, so no need to call `scheduler::start()`
}
}
}
}
pub(crate) struct DestroyRunner {
pub state: Shared<Option<ComponentState>>,
pub parent_to_detach: bool,
}
impl ComponentState {
#[tracing::instrument(
level = tracing::Level::DEBUG,
skip(self),
fields(component.id = self.comp_id)
)]
fn destroy(mut self, parent_to_detach: bool) {
self.inner.destroy();
self.resume_existing_suspension();
match self.render_state {
#[cfg(feature = "csr")]
ComponentRenderState::Render {
bundle,
ref parent,
ref root,
..
} => {
bundle.detach(root, parent, parent_to_detach);
}
// We need to detach the hydrate fragment if the component is not hydrated.
#[cfg(feature = "hydration")]
ComponentRenderState::Hydration {
ref root,
fragment,
ref parent,
..
} => {
fragment.detach(root, parent, parent_to_detach);
}
#[cfg(feature = "ssr")]
ComponentRenderState::Ssr { .. } => {
let _ = parent_to_detach;
}
}
}
}
impl Runnable for DestroyRunner {
fn run(self: Box<Self>) {
if let Some(state) = self.state.borrow_mut().take() {
state.destroy(self.parent_to_detach);
}
}
}
pub(crate) struct RenderRunner {
pub state: Shared<Option<ComponentState>>,
}
impl ComponentState {
#[tracing::instrument(
level = tracing::Level::DEBUG,
skip_all,
fields(component.id = self.comp_id)
)]
fn render(&mut self, shared_state: &Shared<Option<ComponentState>>) {
let view = self.inner.view();
tracing::trace!(?view, "render result");
match view {
Ok(vnode) => self.commit_render(shared_state, vnode),
Err(RenderError::Suspended(susp)) => self.suspend(shared_state, susp),
};
}
fn suspend(&mut self, shared_state: &Shared<Option<ComponentState>>, suspension: Suspension) {
// Currently suspended, we re-use previous root node and send
// suspension to parent element.
if suspension.resumed() {
// schedule a render immediately if suspension is resumed.
scheduler::push_component_render(
self.comp_id,
Box::new(RenderRunner {
state: shared_state.clone(),
}),
);
} else {
// We schedule a render after current suspension is resumed.
let comp_scope = self.inner.any_scope();
let suspense_scope = comp_scope
.find_parent_scope::<BaseSuspense>()
.expect("To suspend rendering, a <Suspense /> component is required.");
let comp_id = self.comp_id;
let shared_state = shared_state.clone();
suspension.listen(Callback::from(move |_| {
scheduler::push_component_render(
comp_id,
Box::new(RenderRunner {
state: shared_state.clone(),
}),
);
scheduler::start();
}));
if let Some(ref last_suspension) = self.suspension {
if &suspension != last_suspension {
// We remove previous suspension from the suspense.
BaseSuspense::resume(&suspense_scope, last_suspension.clone());
}
}
self.suspension = Some(suspension.clone());
BaseSuspense::suspend(&suspense_scope, suspension);
}
}
fn commit_render(&mut self, shared_state: &Shared<Option<ComponentState>>, new_vdom: Html) {
// Currently not suspended, we remove any previous suspension and update
// normally.
self.resume_existing_suspension();
match self.render_state {
#[cfg(feature = "csr")]
ComponentRenderState::Render {
ref mut bundle,
ref parent,
ref root,
ref sibling_slot,
ref mut own_slot,
..
} => {
let scope = self.inner.any_scope();
let new_node_ref =
bundle.reconcile(root, &scope, parent, sibling_slot.to_position(), new_vdom);
own_slot.reassign(new_node_ref);
let first_render = !self.has_rendered;
self.has_rendered = true;
scheduler::push_component_rendered(
self.comp_id,
Box::new(RenderedRunner {
state: shared_state.clone(),
first_render,
}),
first_render,
);
}
#[cfg(feature = "hydration")]
ComponentRenderState::Hydration {
ref mut fragment,
ref parent,
ref mut own_slot,
ref mut sibling_slot,
ref root,
} => {
// We schedule a "first" render to run immediately after hydration.
// Most notably, only this render will trigger the "rendered" callback, hence we
// want to prioritize this.
scheduler::push_component_priority_render(
self.comp_id,
Box::new(RenderRunner {
state: shared_state.clone(),
}),
);
let scope = self.inner.any_scope();
let bundle = Bundle::hydrate(
root,
&scope,
parent,
fragment,
new_vdom,
&mut Some(own_slot.clone()),
);
// We trim all text nodes before checking as it's likely these are whitespaces.
fragment.trim_start_text_nodes();
assert!(fragment.is_empty(), "expected end of component, found node");
self.render_state = ComponentRenderState::Render {
root: root.clone(),
bundle,
parent: parent.clone(),
own_slot: own_slot.take(),
sibling_slot: sibling_slot.take(),
};
}
#[cfg(feature = "ssr")]
ComponentRenderState::Ssr { ref mut sender } => {
let _ = shared_state;
if let Some(tx) = sender.take() {
tx.send(new_vdom).unwrap();
}
}
};
}
}
impl Runnable for RenderRunner {
fn run(self: Box<Self>) {
let mut state = self.state.borrow_mut();
let state = match state.as_mut() {
None => return, // skip for components that have already been destroyed
Some(state) => state,
};
state.render(&self.state);
}
}
#[cfg(feature = "csr")]
mod feat_csr {
use super::*;
pub(crate) struct PropsUpdateRunner {
pub state: Shared<Option<ComponentState>>,
pub props: Option<Rc<dyn Any>>,
pub next_sibling_slot: Option<DomSlot>,
}
impl ComponentState {
#[tracing::instrument(
level = tracing::Level::DEBUG,
skip(self),
fields(component.id = self.comp_id)
)]
fn changed(
&mut self,
props: Option<Rc<dyn Any>>,
next_sibling_slot: Option<DomSlot>,
) -> bool {
if let Some(next_sibling_slot) = next_sibling_slot {
// When components are updated, their siblings were likely also updated
// We also need to shift the bundle so next sibling will be synced to child
// components.
match &mut self.render_state {
#[cfg(feature = "csr")]
ComponentRenderState::Render { sibling_slot, .. } => {
sibling_slot.reassign(next_sibling_slot);
}
#[cfg(feature = "hydration")]
ComponentRenderState::Hydration { sibling_slot, .. } => {
sibling_slot.reassign(next_sibling_slot);
}
#[cfg(feature = "ssr")]
ComponentRenderState::Ssr { .. } => {
#[cfg(debug_assertions)]
panic!("properties do not change during SSR");
}
}
}
let should_render = |props: Option<Rc<dyn Any>>, state: &mut ComponentState| -> bool {
props.map(|m| state.inner.props_changed(m)).unwrap_or(false)
};
#[cfg(feature = "hydration")]
let should_render_hydration =
|props: Option<Rc<dyn Any>>, state: &mut ComponentState| -> bool {
if let Some(props) = props.or_else(|| state.pending_props.take()) {
match state.has_rendered {
true => {
state.pending_props = None;
state.inner.props_changed(props)
}
false => {
state.pending_props = Some(props);
false
}
}
} else {
false
}
};
// Only trigger changed if props were changed / next sibling has changed.
let schedule_render = {
#[cfg(feature = "hydration")]
{
if self.inner.creation_mode() == RenderMode::Hydration {
should_render_hydration(props, self)
} else {
should_render(props, self)
}
}
#[cfg(not(feature = "hydration"))]
should_render(props, self)
};
tracing::trace!(
"props_update(has_rendered={} schedule_render={})",
self.has_rendered,
schedule_render
);
schedule_render
}
}
impl Runnable for PropsUpdateRunner {
fn run(self: Box<Self>) {
let Self {
next_sibling_slot,
props,
state: shared_state,
} = *self;
if let Some(state) = shared_state.borrow_mut().as_mut() {
let schedule_render = state.changed(props, next_sibling_slot);
if schedule_render {
scheduler::push_component_render(
state.comp_id,
Box::new(RenderRunner {
state: shared_state.clone(),
}),
);
// Only run from the scheduler, so no need to call `scheduler::start()`
}
};
}
}
pub(crate) struct RenderedRunner {
pub state: Shared<Option<ComponentState>>,
pub first_render: bool,
}
impl ComponentState {
#[tracing::instrument(
level = tracing::Level::DEBUG,
skip(self),
fields(component.id = self.comp_id)
)]
fn rendered(&mut self, first_render: bool) -> bool {
if self.suspension.is_none() {
self.inner.rendered(first_render);
}
#[cfg(feature = "hydration")]
{
self.pending_props.is_some()
}
#[cfg(not(feature = "hydration"))]
{
false
}
}
}
impl Runnable for RenderedRunner {
fn run(self: Box<Self>) {
if let Some(state) = self.state.borrow_mut().as_mut() {
let has_pending_props = state.rendered(self.first_render);
if has_pending_props {
scheduler::push_component_props_update(Box::new(PropsUpdateRunner {
state: self.state.clone(),
props: None,
next_sibling_slot: None,
}));
}
}
}
}
}
#[cfg(feature = "csr")]
pub(super) use feat_csr::*;
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
mod tests {
extern crate self as yew;
use std::cell::RefCell;
use std::ops::Deref;
use std::rc::Rc;
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use super::*;
use crate::dom_bundle::BSubtree;
use crate::html::*;
use crate::{html, Properties};
wasm_bindgen_test_configure!(run_in_browser);
#[derive(Clone, Properties, Default, PartialEq)]
struct ChildProps {
lifecycle: Rc<RefCell<Vec<String>>>,
}
struct Child {}
impl Component for Child {
type Message = ();
type Properties = ChildProps;
fn create(_ctx: &Context<Self>) -> Self {
Child {}
}
fn rendered(&mut self, ctx: &Context<Self>, _first_render: bool) {
ctx.props()
.lifecycle
.borrow_mut()
.push("child rendered".into());
}
fn update(&mut self, _ctx: &Context<Self>, _: Self::Message) -> bool {
false
}
fn changed(&mut self, _ctx: &Context<Self>, _old_props: &Self::Properties) -> bool {
false
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! {}
}
}
#[derive(Clone, Properties, Default, PartialEq)]
struct Props {
lifecycle: Rc<RefCell<Vec<String>>>,
#[allow(dead_code)]
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
create_message: Option<bool>,
update_message: RefCell<Option<bool>>,
view_message: RefCell<Option<bool>>,
rendered_message: RefCell<Option<bool>>,
}
struct Comp {
lifecycle: Rc<RefCell<Vec<String>>>,
}
impl Component for Comp {
type Message = bool;
type Properties = Props;
fn create(ctx: &Context<Self>) -> Self {
ctx.props().lifecycle.borrow_mut().push("create".into());
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
if let Some(msg) = ctx.props().create_message {
ctx.link().send_message(msg);
}
Comp {
lifecycle: Rc::clone(&ctx.props().lifecycle),
}
}
fn rendered(&mut self, ctx: &Context<Self>, first_render: bool) {
if let Some(msg) = ctx.props().rendered_message.borrow_mut().take() {
ctx.link().send_message(msg);
}
ctx.props()
.lifecycle
.borrow_mut()
.push(format!("rendered({})", first_render));
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
if let Some(msg) = ctx.props().update_message.borrow_mut().take() {
ctx.link().send_message(msg);
}
ctx.props()
.lifecycle
.borrow_mut()
.push(format!("update({})", msg));
msg
}
fn changed(&mut self, ctx: &Context<Self>, _old_props: &Self::Properties) -> bool {
self.lifecycle = Rc::clone(&ctx.props().lifecycle);
self.lifecycle.borrow_mut().push("change".into());
false
}
fn view(&self, ctx: &Context<Self>) -> Html {
if let Some(msg) = ctx.props().view_message.borrow_mut().take() {
ctx.link().send_message(msg);
}
self.lifecycle.borrow_mut().push("view".into());
html! { <Child lifecycle={self.lifecycle.clone()} /> }
}
}
impl Drop for Comp {
fn drop(&mut self) {
self.lifecycle.borrow_mut().push("drop".into());
}
}
fn test_lifecycle(props: Props, expected: &[&str]) {
let document = gloo::utils::document();
let scope = Scope::<Comp>::new(None);
let parent = document.create_element("div").unwrap();
let root = BSubtree::create_root(&parent);
let lifecycle = props.lifecycle.clone();
lifecycle.borrow_mut().clear();
let _ = scope.mount_in_place(root, parent, DomSlot::at_end(), Rc::new(props));
crate::scheduler::start_now();
assert_eq!(&lifecycle.borrow_mut().deref()[..], expected);
}
#[test]
fn lifecycle_tests() {
let lifecycle: Rc<RefCell<Vec<String>>> = Rc::default();
test_lifecycle(
Props {
lifecycle: lifecycle.clone(),
..Props::default()
},
&["create", "view", "child rendered", "rendered(true)"],
);
test_lifecycle(
Props {
lifecycle: lifecycle.clone(),
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
create_message: Some(false),
..Props::default()
},
&[
"create",
"view",
"child rendered",
"rendered(true)",
"update(false)",
],
);
test_lifecycle(
Props {
lifecycle: lifecycle.clone(),
view_message: RefCell::new(Some(true)),
..Props::default()
},
&[
"create",
"view",
"child rendered",
"rendered(true)",
"update(true)",
"view",
"rendered(false)",
],
);
test_lifecycle(
Props {
lifecycle: lifecycle.clone(),
view_message: RefCell::new(Some(false)),
..Props::default()
},
&[
"create",
"view",
"child rendered",
"rendered(true)",
"update(false)",
],
);
test_lifecycle(
Props {
lifecycle: lifecycle.clone(),
rendered_message: RefCell::new(Some(false)),
..Props::default()
},
&[
"create",
"view",
"child rendered",
"rendered(true)",
"update(false)",
],
);
test_lifecycle(
Props {
lifecycle: lifecycle.clone(),
rendered_message: RefCell::new(Some(true)),
..Props::default()
},
&[
"create",
"view",
"child rendered",
"rendered(true)",
"update(true)",
"view",
"rendered(false)",
],
);
// This also tests render deduplication after the first render
test_lifecycle(
Props {
lifecycle,
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
create_message: Some(true),
update_message: RefCell::new(Some(true)),
..Props::default()
},
&[
"create",
"view",
"child rendered",
"rendered(true)",
"update(true)",
"update(true)",
"view",
"rendered(false)",
],
);
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/html/component/scope.rs | packages/yew/src/html/component/scope.rs | //! Component scope module
use std::any::{Any, TypeId};
use std::future::Future;
use std::marker::PhantomData;
use std::ops::Deref;
use std::rc::Rc;
use std::{fmt, iter};
use futures::{Stream, StreamExt};
#[cfg(any(feature = "csr", feature = "ssr"))]
use super::lifecycle::ComponentState;
use super::BaseComponent;
use crate::callback::Callback;
use crate::context::{ContextHandle, ContextProvider};
use crate::platform::spawn_local;
#[cfg(any(feature = "csr", feature = "ssr"))]
use crate::scheduler::Shared;
/// Untyped scope used for accessing parent scope
#[derive(Clone)]
pub struct AnyScope {
type_id: TypeId,
parent: Option<Rc<AnyScope>>,
typed_scope: Rc<dyn Any>,
}
impl fmt::Debug for AnyScope {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AnyScope<_>")
}
}
impl<COMP: BaseComponent> From<Scope<COMP>> for AnyScope {
fn from(scope: Scope<COMP>) -> Self {
AnyScope {
type_id: TypeId::of::<COMP>(),
parent: scope.parent.clone(),
typed_scope: Rc::new(scope),
}
}
}
impl AnyScope {
/// Returns the parent scope
pub fn get_parent(&self) -> Option<&AnyScope> {
self.parent.as_deref()
}
/// Returns the type of the linked component
pub fn get_type_id(&self) -> &TypeId {
&self.type_id
}
/// Attempts to downcast into a typed scope
///
/// # Panics
///
/// If the self value can't be cast into the target type.
pub fn downcast<COMP: BaseComponent>(&self) -> Scope<COMP> {
self.try_downcast::<COMP>().unwrap()
}
/// Attempts to downcast into a typed scope
///
/// Returns [`None`] if the self value can't be cast into the target type.
pub fn try_downcast<COMP: BaseComponent>(&self) -> Option<Scope<COMP>> {
self.typed_scope.downcast_ref::<Scope<COMP>>().cloned()
}
/// Attempts to find a parent scope of a certain type
///
/// Returns [`None`] if no parent scope with the specified type was found.
pub fn find_parent_scope<COMP: BaseComponent>(&self) -> Option<Scope<COMP>> {
iter::successors(Some(self), |scope| scope.get_parent())
.find_map(AnyScope::try_downcast::<COMP>)
}
/// Accesses a value provided by a parent `ContextProvider` component of the
/// same type.
pub fn context<T: Clone + PartialEq + 'static>(
&self,
callback: Callback<T>,
) -> Option<(T, ContextHandle<T>)> {
let scope = self.find_parent_scope::<ContextProvider<T>>()?;
let scope_clone = scope.clone();
let component = scope.get_component()?;
Some(component.subscribe_consumer(callback, scope_clone))
}
}
/// A context which allows sending messages to a component.
pub struct Scope<COMP: BaseComponent> {
_marker: PhantomData<COMP>,
parent: Option<Rc<AnyScope>>,
#[cfg(any(feature = "csr", feature = "ssr"))]
pub(crate) pending_messages: MsgQueue<COMP::Message>,
#[cfg(any(feature = "csr", feature = "ssr"))]
pub(crate) state: Shared<Option<ComponentState>>,
pub(crate) id: usize,
}
impl<COMP: BaseComponent> fmt::Debug for Scope<COMP> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Scope<_>")
}
}
impl<COMP: BaseComponent> Clone for Scope<COMP> {
fn clone(&self) -> Self {
Scope {
_marker: PhantomData,
#[cfg(any(feature = "csr", feature = "ssr"))]
pending_messages: self.pending_messages.clone(),
parent: self.parent.clone(),
#[cfg(any(feature = "csr", feature = "ssr"))]
state: self.state.clone(),
id: self.id,
}
}
}
impl<COMP: BaseComponent> Scope<COMP> {
/// Returns the parent scope
pub fn get_parent(&self) -> Option<&AnyScope> {
self.parent.as_deref()
}
/// Creates a `Callback` which will send a message to the linked
/// component's update method when invoked.
///
/// If your callback function returns a [Future],
/// use [`callback_future`](Scope::callback_future) instead.
pub fn callback<F, IN, M>(&self, function: F) -> Callback<IN>
where
M: Into<COMP::Message>,
F: Fn(IN) -> M + 'static,
{
let scope = self.clone();
let closure = move |input| {
let output = function(input);
scope.send_message(output);
};
Callback::from(closure)
}
/// Creates a `Callback` which will send a batch of messages back
/// to the linked component's update method when invoked.
///
/// The callback function's return type is generic to allow for dealing with both
/// `Option` and `Vec` nicely. `Option` can be used when dealing with a callback that
/// might not need to send an update.
///
/// ```ignore
/// link.batch_callback(|_| vec![Msg::A, Msg::B]);
/// link.batch_callback(|_| Some(Msg::A));
/// ```
pub fn batch_callback<F, IN, OUT>(&self, function: F) -> Callback<IN>
where
F: Fn(IN) -> OUT + 'static,
OUT: SendAsMessage<COMP>,
{
let scope = self.clone();
let closure = move |input| {
let messages = function(input);
messages.send(&scope);
};
closure.into()
}
/// Accesses a value provided by a parent `ContextProvider` component of the
/// same type.
pub fn context<T: Clone + PartialEq + 'static>(
&self,
callback: Callback<T>,
) -> Option<(T, ContextHandle<T>)> {
AnyScope::from(self.clone()).context(callback)
}
/// This method asynchronously awaits a [Future] that returns a message and sends it
/// to the linked component.
///
/// # Panics
/// If the future panics, then the promise will not resolve, and will leak.
pub fn send_future<Fut, Msg>(&self, future: Fut)
where
Msg: Into<COMP::Message>,
Fut: Future<Output = Msg> + 'static,
{
let link = self.clone();
spawn_local(async move {
let message: COMP::Message = future.await.into();
link.send_message(message);
});
}
/// This method creates a [`Callback`] which, when emitted, asynchronously awaits the
/// message returned from the passed function before sending it to the linked component.
///
/// # Panics
/// If the future panics, then the promise will not resolve, and will leak.
pub fn callback_future<F, Fut, IN, Msg>(&self, function: F) -> Callback<IN>
where
Msg: Into<COMP::Message>,
Fut: Future<Output = Msg> + 'static,
F: Fn(IN) -> Fut + 'static,
{
let link = self.clone();
let closure = move |input: IN| {
link.send_future(function(input));
};
closure.into()
}
/// Asynchronously send a batch of messages to a component. This asynchronously awaits the
/// passed [Future], before sending the message batch to the linked component.
///
/// # Panics
/// If the future panics, then the promise will not resolve, and will leak.
pub fn send_future_batch<Fut>(&self, future: Fut)
where
Fut: Future + 'static,
Fut::Output: SendAsMessage<COMP>,
{
let link = self.clone();
let js_future = async move {
future.await.send(&link);
};
spawn_local(js_future);
}
/// This method asynchronously awaits a [`Stream`] that returns a series of messages and sends
/// them to the linked component.
///
/// # Panics
/// If the stream panics, then the promise will not resolve, and will leak.
///
/// # Note
///
/// This method will not notify the component when the stream has been fully exhausted. If
/// you want this feature, you can add an EOF message variant for your component and use
/// [`StreamExt::chain`] and [`stream::once`](futures::stream::once) to chain an EOF message to
/// the original stream. If your stream is produced by another crate, you can use
/// [`StreamExt::map`] to transform the stream's item type to the component message type.
pub fn send_stream<S, M>(&self, stream: S)
where
M: Into<COMP::Message>,
S: Stream<Item = M> + 'static,
{
let link = self.clone();
let js_future = async move {
futures::pin_mut!(stream);
while let Some(msg) = stream.next().await {
let message: COMP::Message = msg.into();
link.send_message(message);
}
};
spawn_local(js_future);
}
/// Returns the linked component if available
pub fn get_component(&self) -> Option<impl Deref<Target = COMP> + '_> {
self.arch_get_component()
}
/// Send a message to the component.
pub fn send_message<T>(&self, msg: T)
where
T: Into<COMP::Message>,
{
self.arch_send_message(msg)
}
/// Send a batch of messages to the component.
///
/// This is slightly more efficient than calling [`send_message`](Self::send_message)
/// in a loop.
pub fn send_message_batch(&self, messages: Vec<COMP::Message>) {
self.arch_send_message_batch(messages)
}
}
#[cfg(feature = "ssr")]
mod feat_ssr {
use std::fmt::Write;
use super::*;
use crate::feat_ssr::VTagKind;
use crate::html::component::lifecycle::{
ComponentRenderState, CreateRunner, DestroyRunner, RenderRunner,
};
use crate::platform::fmt::BufWriter;
use crate::platform::pinned::oneshot;
use crate::scheduler;
use crate::virtual_dom::Collectable;
impl<COMP: BaseComponent> Scope<COMP> {
pub(crate) async fn render_into_stream(
&self,
w: &mut BufWriter,
props: Rc<COMP::Properties>,
hydratable: bool,
parent_vtag_kind: VTagKind,
) {
// Rust's Future implementation is stack-allocated and incurs zero runtime-cost.
//
// If the content of this channel is ready before it is awaited, it is
// similar to taking the value from a mutex lock.
let (tx, rx) = oneshot::channel();
let state = ComponentRenderState::Ssr { sender: Some(tx) };
scheduler::push_component_create(
self.id,
Box::new(CreateRunner {
initial_render_state: state,
props,
scope: self.clone(),
#[cfg(feature = "hydration")]
prepared_state: None,
}),
Box::new(RenderRunner {
state: self.state.clone(),
}),
);
scheduler::start();
let collectable = Collectable::for_component::<COMP>();
if hydratable {
collectable.write_open_tag(w);
}
let html = rx.await.unwrap();
let self_any_scope = AnyScope::from(self.clone());
html.render_into_stream(w, &self_any_scope, hydratable, parent_vtag_kind)
.await;
if let Some(prepared_state) = self.get_component().unwrap().prepare_state() {
let _ = w.write_str(r#"<script type="application/x-yew-comp-state">"#);
let _ = w.write_str(&prepared_state);
let _ = w.write_str(r#"</script>"#);
}
if hydratable {
collectable.write_close_tag(w);
}
scheduler::push_component_destroy(Box::new(DestroyRunner {
state: self.state.clone(),
parent_to_detach: false,
}));
scheduler::start();
}
}
}
#[cfg(not(any(feature = "ssr", feature = "csr")))]
mod feat_no_csr_ssr {
use super::*;
// Skeleton code to provide public methods when no renderer are enabled.
impl<COMP: BaseComponent> Scope<COMP> {
pub(super) fn arch_get_component(&self) -> Option<impl Deref<Target = COMP> + '_> {
Option::<&COMP>::None
}
pub(super) fn arch_send_message<T>(&self, _msg: T)
where
T: Into<COMP::Message>,
{
}
pub(super) fn arch_send_message_batch(&self, _messages: Vec<COMP::Message>) {}
}
}
#[cfg(any(feature = "ssr", feature = "csr"))]
mod feat_csr_ssr {
use std::cell::{Ref, RefCell};
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
use crate::html::component::lifecycle::UpdateRunner;
use crate::scheduler::{self, Shared};
#[derive(Debug)]
pub(crate) struct MsgQueue<Msg>(Shared<Vec<Msg>>);
impl<Msg> MsgQueue<Msg> {
pub fn new() -> Self {
MsgQueue(Rc::default())
}
pub fn push(&self, msg: Msg) -> usize {
let mut inner = self.0.borrow_mut();
inner.push(msg);
inner.len()
}
pub fn append(&self, other: &mut Vec<Msg>) -> usize {
let mut inner = self.0.borrow_mut();
inner.append(other);
inner.len()
}
pub fn drain(&self) -> Vec<Msg> {
let mut other_queue = Vec::new();
let mut inner = self.0.borrow_mut();
std::mem::swap(&mut *inner, &mut other_queue);
other_queue
}
}
impl<Msg> Clone for MsgQueue<Msg> {
fn clone(&self) -> Self {
MsgQueue(self.0.clone())
}
}
static COMP_ID_COUNTER: AtomicUsize = AtomicUsize::new(0);
impl<COMP: BaseComponent> Scope<COMP> {
/// Crate a scope with an optional parent scope
pub(crate) fn new(parent: Option<AnyScope>) -> Self {
let parent = parent.map(Rc::new);
let state = Rc::new(RefCell::new(None));
let pending_messages = MsgQueue::new();
Scope {
_marker: PhantomData,
pending_messages,
state,
parent,
id: COMP_ID_COUNTER.fetch_add(1, Ordering::SeqCst),
}
}
#[inline]
pub(super) fn arch_get_component(&self) -> Option<impl Deref<Target = COMP> + '_> {
self.state.try_borrow().ok().and_then(|state_ref| {
Ref::filter_map(state_ref, |state| {
state.as_ref().and_then(|m| m.downcast_comp_ref::<COMP>())
})
.ok()
})
}
#[inline]
fn schedule_update(&self) {
scheduler::push_component_update(Box::new(UpdateRunner {
state: self.state.clone(),
}));
// Not guaranteed to already have the scheduler started
scheduler::start();
}
#[inline]
pub(super) fn arch_send_message<T>(&self, msg: T)
where
T: Into<COMP::Message>,
{
// We are the first message in queue, so we queue the update.
if self.pending_messages.push(msg.into()) == 1 {
self.schedule_update();
}
}
#[inline]
pub(super) fn arch_send_message_batch(&self, mut messages: Vec<COMP::Message>) {
let msg_len = messages.len();
// The queue was empty, so we queue the update
if self.pending_messages.append(&mut messages) == msg_len {
self.schedule_update();
}
}
}
}
#[cfg(any(feature = "ssr", feature = "csr"))]
pub(crate) use feat_csr_ssr::*;
#[cfg(feature = "csr")]
mod feat_csr {
use std::cell::Ref;
use web_sys::Element;
use super::*;
use crate::dom_bundle::{BSubtree, Bundle, DomSlot, DynamicDomSlot};
use crate::html::component::lifecycle::{
ComponentRenderState, CreateRunner, DestroyRunner, PropsUpdateRunner, RenderRunner,
};
use crate::scheduler;
impl AnyScope {
#[cfg(any(test, feature = "test"))]
pub(crate) fn test() -> Self {
Self {
type_id: TypeId::of::<()>(),
parent: None,
typed_scope: Rc::new(()),
}
}
}
fn schedule_props_update(
state: Shared<Option<ComponentState>>,
props: Rc<dyn Any>,
next_sibling_slot: DomSlot,
) {
scheduler::push_component_props_update(Box::new(PropsUpdateRunner {
state,
next_sibling_slot: Some(next_sibling_slot),
props: Some(props),
}));
// Not guaranteed to already have the scheduler started
scheduler::start();
}
impl<COMP> Scope<COMP>
where
COMP: BaseComponent,
{
/// Mounts a component with `props` to the specified `element` in the DOM.
pub(crate) fn mount_in_place(
&self,
root: BSubtree,
parent: Element,
slot: DomSlot,
props: Rc<COMP::Properties>,
) -> DynamicDomSlot {
let bundle = Bundle::new();
let sibling_slot = DynamicDomSlot::new(slot);
let own_slot = DynamicDomSlot::new(sibling_slot.to_position());
let shared_slot = own_slot.clone();
let state = ComponentRenderState::Render {
bundle,
root,
own_slot,
parent,
sibling_slot,
};
scheduler::push_component_create(
self.id,
Box::new(CreateRunner {
initial_render_state: state,
props,
scope: self.clone(),
#[cfg(feature = "hydration")]
prepared_state: None,
}),
Box::new(RenderRunner {
state: self.state.clone(),
}),
);
// Not guaranteed to already have the scheduler started
scheduler::start();
shared_slot
}
pub(crate) fn reuse(&self, props: Rc<COMP::Properties>, slot: DomSlot) {
schedule_props_update(self.state.clone(), props, slot)
}
}
pub(crate) trait Scoped {
fn to_any(&self) -> AnyScope;
/// Get the render state if it hasn't already been destroyed
fn render_state(&self) -> Option<Ref<'_, ComponentRenderState>>;
/// Shift the node associated with this scope to a new place
fn shift_node(&self, parent: Element, slot: DomSlot);
/// Process an event to destroy a component
fn destroy(self, parent_to_detach: bool);
fn destroy_boxed(self: Box<Self>, parent_to_detach: bool);
}
impl<COMP: BaseComponent> Scoped for Scope<COMP> {
fn to_any(&self) -> AnyScope {
self.clone().into()
}
fn render_state(&self) -> Option<Ref<'_, ComponentRenderState>> {
let state_ref = self.state.borrow();
// check that component hasn't been destroyed
state_ref.as_ref()?;
Some(Ref::map(state_ref, |state_ref| {
&state_ref.as_ref().unwrap().render_state
}))
}
/// Process an event to destroy a component
fn destroy(self, parent_to_detach: bool) {
scheduler::push_component_destroy(Box::new(DestroyRunner {
state: self.state,
parent_to_detach,
}));
// Not guaranteed to already have the scheduler started
scheduler::start();
}
fn destroy_boxed(self: Box<Self>, parent_to_detach: bool) {
self.destroy(parent_to_detach)
}
fn shift_node(&self, parent: Element, slot: DomSlot) {
let mut state_ref = self.state.borrow_mut();
if let Some(render_state) = state_ref.as_mut() {
render_state.render_state.shift(parent, slot)
}
}
}
}
#[cfg(feature = "csr")]
pub(crate) use feat_csr::*;
#[cfg(feature = "hydration")]
mod feat_hydration {
use wasm_bindgen::JsCast;
use web_sys::{Element, HtmlScriptElement};
use super::*;
use crate::dom_bundle::{BSubtree, DynamicDomSlot, Fragment};
use crate::html::component::lifecycle::{ComponentRenderState, CreateRunner, RenderRunner};
use crate::scheduler;
use crate::virtual_dom::Collectable;
impl<COMP> Scope<COMP>
where
COMP: BaseComponent,
{
/// Hydrates the component.
///
/// Returns the position of the hydrated node in DOM.
///
/// # Note
///
/// This method is expected to collect all the elements belongs to the current component
/// immediately.
pub(crate) fn hydrate_in_place(
&self,
root: BSubtree,
parent: Element,
fragment: &mut Fragment,
props: Rc<COMP::Properties>,
prev_next_sibling: &mut Option<DynamicDomSlot>,
) -> DynamicDomSlot {
// This is very helpful to see which component is failing during hydration
// which means this component may not having a stable layout / differs between
// client-side and server-side.
tracing::trace!(
component.id = self.id,
"hydration(type = {})",
std::any::type_name::<COMP>()
);
let collectable = Collectable::for_component::<COMP>();
let mut fragment = Fragment::collect_between(fragment, &collectable, &parent);
let prepared_state = match fragment
.back()
.cloned()
.and_then(|m| m.dyn_into::<HtmlScriptElement>().ok())
{
Some(m) if m.type_() == "application/x-yew-comp-state" => {
fragment.pop_back();
parent.remove_child(&m).unwrap();
Some(m.text().unwrap())
}
_ => None,
};
// These two references need to be fixed before the component is used.
// Our own slot gets fixed on the first render.
// The sibling slot gets shared with the caller to fix up when continuing through
// existing DOM.
let own_slot = DynamicDomSlot::new_debug_trapped();
let shared_slot = own_slot.clone();
let sibling_slot = DynamicDomSlot::new_debug_trapped();
if let Some(prev_next_sibling) = prev_next_sibling {
prev_next_sibling.reassign(shared_slot.to_position());
}
*prev_next_sibling = Some(sibling_slot.clone());
let state = ComponentRenderState::Hydration {
parent,
root,
own_slot,
sibling_slot,
fragment,
};
scheduler::push_component_create(
self.id,
Box::new(CreateRunner {
initial_render_state: state,
props,
scope: self.clone(),
prepared_state,
}),
Box::new(RenderRunner {
state: self.state.clone(),
}),
);
// Not guaranteed to already have the scheduler started
scheduler::start();
shared_slot
}
}
}
/// Defines a message type that can be sent to a component.
/// Used for the return value of closure given to
/// [Scope::batch_callback](struct.Scope.html#method.batch_callback).
pub trait SendAsMessage<COMP: BaseComponent> {
/// Sends the message to the given component's scope.
/// See [Scope::batch_callback](struct.Scope.html#method.batch_callback).
fn send(self, scope: &Scope<COMP>);
}
impl<COMP> SendAsMessage<COMP> for Option<COMP::Message>
where
COMP: BaseComponent,
{
fn send(self, scope: &Scope<COMP>) {
if let Some(msg) = self {
scope.send_message(msg);
}
}
}
impl<COMP> SendAsMessage<COMP> for Vec<COMP::Message>
where
COMP: BaseComponent,
{
fn send(self, scope: &Scope<COMP>) {
scope.send_message_batch(self);
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/html/component/mod.rs | packages/yew/src/html/component/mod.rs | //! Components wrapped with context including properties, state, and link
mod children;
#[cfg(any(feature = "csr", feature = "ssr"))]
mod lifecycle;
mod marker;
mod properties;
mod scope;
use std::rc::Rc;
pub use children::*;
pub use marker::*;
pub use properties::*;
#[cfg(feature = "csr")]
pub(crate) use scope::Scoped;
pub use scope::{AnyScope, Scope, SendAsMessage};
use super::{Html, HtmlResult, IntoHtmlResult};
#[cfg(feature = "hydration")]
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum RenderMode {
Hydration,
Render,
#[cfg(feature = "ssr")]
Ssr,
}
/// The [`Component`]'s context. This contains component's [`Scope`] and props and
/// is passed to every lifecycle method.
#[derive(Debug)]
pub struct Context<COMP: BaseComponent> {
scope: Scope<COMP>,
props: Rc<COMP::Properties>,
#[cfg(feature = "hydration")]
creation_mode: RenderMode,
#[cfg(feature = "hydration")]
prepared_state: Option<String>,
}
impl<COMP: BaseComponent> Context<COMP> {
/// The component scope
#[inline]
pub fn link(&self) -> &Scope<COMP> {
&self.scope
}
/// The component's props
#[inline]
pub fn props(&self) -> &COMP::Properties {
&self.props
}
#[cfg(feature = "hydration")]
pub(crate) fn creation_mode(&self) -> RenderMode {
self.creation_mode
}
/// The component's prepared state
pub fn prepared_state(&self) -> Option<&str> {
#[cfg(not(feature = "hydration"))]
let state = None;
#[cfg(feature = "hydration")]
let state = self.prepared_state.as_deref();
state
}
}
/// The common base of both function components and struct components.
///
/// If you are taken here by doc links, you might be looking for [`Component`] or
/// [`#[component]`](crate::functional::component).
///
/// We provide a blanket implementation of this trait for every member that implements
/// [`Component`].
///
/// # Warning
///
/// This trait may be subject to heavy changes between versions and is not intended for direct
/// implementation.
///
/// You should used the [`Component`] trait or the
/// [`#[component]`](crate::functional::component) macro to define your
/// components.
pub trait BaseComponent: Sized + 'static {
/// The Component's Message.
type Message: 'static;
/// The Component's Properties.
type Properties: Properties;
/// Creates a component.
fn create(ctx: &Context<Self>) -> Self;
/// Updates component's internal state.
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool;
/// React to changes of component properties.
fn changed(&mut self, ctx: &Context<Self>, _old_props: &Self::Properties) -> bool;
/// Returns a component layout to be rendered.
fn view(&self, ctx: &Context<Self>) -> HtmlResult;
/// Notified after a layout is rendered.
fn rendered(&mut self, ctx: &Context<Self>, first_render: bool);
/// Notified before a component is destroyed.
fn destroy(&mut self, ctx: &Context<Self>);
/// Prepares the server-side state.
fn prepare_state(&self) -> Option<String>;
}
/// Components are the basic building blocks of the UI in a Yew app. Each Component
/// chooses how to display itself using received props and self-managed state.
/// Components can be dynamic and interactive by declaring messages that are
/// triggered and handled asynchronously. This async update mechanism is inspired by
/// Elm and the actor model used in the Actix framework.
pub trait Component: Sized + 'static {
/// Messages are used to make Components dynamic and interactive. Simple
/// Component's can declare their Message type to be `()`. Complex Component's
/// commonly use an enum to declare multiple Message types.
type Message: 'static;
/// The Component's properties.
///
/// When the parent of a Component is re-rendered, it will either be re-created or
/// receive new properties in the context passed to the `changed` lifecycle method.
type Properties: Properties;
/// Called when component is created.
fn create(ctx: &Context<Self>) -> Self;
/// Called when a new message is sent to the component via its scope.
///
/// Components handle messages in their `update` method and commonly use this method
/// to update their state and (optionally) re-render themselves.
///
/// Returned bool indicates whether to render this Component after update.
///
/// By default, this function will return true and thus make the component re-render.
#[allow(unused_variables)]
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
true
}
/// Called when properties passed to the component change
///
/// Returned bool indicates whether to render this Component after changed.
///
/// By default, this function will return true and thus make the component re-render.
#[allow(unused_variables)]
fn changed(&mut self, ctx: &Context<Self>, _old_props: &Self::Properties) -> bool {
true
}
/// Components define their visual layout using a JSX-style syntax through the use of the
/// `html!` procedural macro. The full guide to using the macro can be found in [Yew's
/// documentation](https://yew.rs/concepts/html).
///
/// Note that `view()` calls do not always follow a render request from `update()` or
/// `changed()`. Yew may optimize some calls out to reduce virtual DOM tree generation overhead.
/// The `create()` call is always followed by a call to `view()`.
fn view(&self, ctx: &Context<Self>) -> Html;
/// The `rendered` method is called after each time a Component is rendered but
/// before the browser updates the page.
///
/// Note that `rendered()` calls do not always follow a render request from `update()` or
/// `changed()`. Yew may optimize some calls out to reduce virtual DOM tree generation overhead.
/// The `create()` call is always followed by a call to `view()` and later `rendered()`.
#[allow(unused_variables)]
fn rendered(&mut self, ctx: &Context<Self>, first_render: bool) {}
/// Prepares the state during server side rendering.
///
/// This state will be sent to the client side and is available via `ctx.prepared_state()`.
///
/// This method is only called during server-side rendering after the component has been
/// rendered.
fn prepare_state(&self) -> Option<String> {
None
}
/// Called right before a Component is unmounted.
#[allow(unused_variables)]
fn destroy(&mut self, ctx: &Context<Self>) {}
}
impl<T> BaseComponent for T
where
T: Sized + Component + 'static,
{
type Message = <T as Component>::Message;
type Properties = <T as Component>::Properties;
fn create(ctx: &Context<Self>) -> Self {
Component::create(ctx)
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
Component::update(self, ctx, msg)
}
fn changed(&mut self, ctx: &Context<Self>, old_props: &Self::Properties) -> bool {
Component::changed(self, ctx, old_props)
}
fn view(&self, ctx: &Context<Self>) -> HtmlResult {
Component::view(self, ctx).into_html_result()
}
fn rendered(&mut self, ctx: &Context<Self>, first_render: bool) {
Component::rendered(self, ctx, first_render)
}
fn destroy(&mut self, ctx: &Context<Self>) {
Component::destroy(self, ctx)
}
fn prepare_state(&self) -> Option<String> {
Component::prepare_state(self)
}
}
#[cfg(test)]
#[cfg(any(feature = "ssr", feature = "csr"))]
mod tests {
use super::*;
struct MyCustomComponent;
impl Component for MyCustomComponent {
type Message = ();
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, _ctx: &Context<Self>) -> Html {
Default::default()
}
}
#[test]
fn make_sure_component_update_and_changed_rerender() {
let mut comp = MyCustomComponent;
let ctx = Context {
scope: Scope::new(None),
props: Rc::new(()),
#[cfg(feature = "hydration")]
creation_mode: crate::html::RenderMode::Hydration,
#[cfg(feature = "hydration")]
prepared_state: None,
};
assert!(Component::update(&mut comp, &ctx, ()));
assert!(Component::changed(&mut comp, &ctx, &Rc::new(())));
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/html/component/children.rs | packages/yew/src/html/component/children.rs | //! Component children module
use std::fmt;
use std::rc::Rc;
use crate::html::{Html, ImplicitClone};
use crate::utils::RcExt;
use crate::virtual_dom::{VChild, VComp, VList, VNode};
use crate::{BaseComponent, Properties};
/// A type used for accepting children elements in Component::Properties.
///
/// # Example
/// **`model.rs`**
///
/// In this example, the `Wrapper` component is used to wrap other elements.
/// ```
/// # use yew::{Children, Html, Properties, Component, Context, html};
/// # #[derive(Clone, Properties, PartialEq)]
/// # struct WrapperProps {
/// # children: Children,
/// # }
/// # struct Wrapper;
/// # impl Component for Wrapper {
/// # type Message = ();
/// # type Properties = WrapperProps;
/// # fn create(ctx: &Context<Self>) -> Self { Self }
/// # fn view(&self, ctx: &Context<Self>) -> Html {
/// html! {
/// <Wrapper>
/// <h4>{ "Hi" }</h4>
/// <div>{ "Hello" }</div>
/// </Wrapper>
/// }
/// # }
/// # }
/// ```
///
/// **`wrapper.rs`**
///
/// The Wrapper component must define a `children` property in order to wrap other elements. The
/// children property can be used to render the wrapped elements.
/// ```
/// # use yew::{Children, Html, Properties, Component, Context, html};
/// #[derive(Clone, Properties, PartialEq)]
/// struct WrapperProps {
/// children: Children,
/// }
///
/// # struct Wrapper;
/// impl Component for Wrapper {
/// // ...
/// # type Message = ();
/// # type Properties = WrapperProps;
/// # fn create(ctx: &Context<Self>) -> Self { Self }
/// fn view(&self, ctx: &Context<Self>) -> Html {
/// html! {
/// <div id="container">
/// { ctx.props().children.clone() }
/// </div>
/// }
/// }
/// }
/// ```
pub type Children = ChildrenRenderer<Html>;
/// A type used for accepting children elements in Component::Properties and accessing their props.
///
/// # Example
/// **`model.rs`**
///
/// In this example, the `List` component can wrap `ListItem` components.
/// ```
/// # use yew::{html, Component, Html, Context, ChildrenWithProps, Properties};
/// #
/// # #[derive(Clone, Properties, PartialEq)]
/// # struct ListProps {
/// # children: ChildrenWithProps<ListItem>,
/// # }
/// # struct List;
/// # impl Component for List {
/// # type Message = ();
/// # type Properties = ListProps;
/// # fn create(ctx: &Context<Self>) -> Self { Self }
/// # fn view(&self, ctx: &Context<Self>) -> Html { unimplemented!() }
/// # }
/// # #[derive(Clone, Properties, PartialEq)]
/// # struct ListItemProps {
/// # value: String
/// # }
/// # struct ListItem;
/// # impl Component for ListItem {
/// # type Message = ();
/// # type Properties = ListItemProps;
/// # fn create(ctx: &Context<Self>) -> Self { Self }
/// # fn view(&self, ctx: &Context<Self>) -> Html { unimplemented!() }
/// # }
/// # fn view() -> Html {
/// html! {
/// <List>
/// <ListItem value="a" />
/// <ListItem value="b" />
/// <ListItem value="c" />
/// </List>
/// }
/// # }
/// ```
///
/// **`list.rs`**
///
/// The `List` component must define a `children` property in order to wrap the list items. The
/// `children` property can be used to filter, mutate, and render the items.
/// ```
/// # use yew::{html, Component, Html, ChildrenWithProps, Context, Properties};
/// # use std::rc::Rc;
/// #
/// #[derive(Clone, Properties, PartialEq)]
/// struct ListProps {
/// children: ChildrenWithProps<ListItem>,
/// }
///
/// # struct List;
/// impl Component for List {
/// # type Message = ();
/// # type Properties = ListProps;
/// # fn create(ctx: &Context<Self>) -> Self { Self }
/// # fn view(&self, ctx: &Context<Self>) -> Html {
/// html!{{
/// for ctx.props().children.iter().map(|mut item| {
/// let mut props = Rc::make_mut(&mut item.props);
/// props.value = format!("item-{}", props.value);
/// item
/// })
/// }}
/// }
/// }
/// #
/// # #[derive(Clone, Properties, PartialEq)]
/// # struct ListItemProps {
/// # #[prop_or_default]
/// # value: String
/// # }
/// #
/// # struct ListItem;
/// # impl Component for ListItem {
/// # type Message = ();
/// # type Properties = ListItemProps;
/// # fn create(ctx: &Context<Self>) -> Self { Self }
/// # fn view(&self, ctx: &Context<Self>) -> Html { unimplemented!() }
/// # }
/// ```
pub type ChildrenWithProps<CHILD> = ChildrenRenderer<VChild<CHILD>>;
/// A type used for rendering children html.
pub struct ChildrenRenderer<T> {
pub(crate) children: Option<Rc<Vec<T>>>,
}
impl<T> Clone for ChildrenRenderer<T> {
fn clone(&self) -> Self {
Self {
children: self.children.clone(),
}
}
}
impl<T> ImplicitClone for ChildrenRenderer<T> {}
impl<T: PartialEq> PartialEq for ChildrenRenderer<T> {
fn eq(&self, other: &Self) -> bool {
match (self.children.as_ref(), other.children.as_ref()) {
(Some(a), Some(b)) => a == b,
(Some(a), None) => a.is_empty(),
(None, Some(b)) => b.is_empty(),
(None, None) => true,
}
}
}
impl<T> ChildrenRenderer<T>
where
T: Clone,
{
/// Create children
pub fn new(children: Vec<T>) -> Self {
if children.is_empty() {
Self { children: None }
} else {
Self {
children: Some(Rc::new(children)),
}
}
}
/// Children list is empty
pub fn is_empty(&self) -> bool {
self.children.as_ref().map(|x| x.is_empty()).unwrap_or(true)
}
/// Number of children elements
pub fn len(&self) -> usize {
self.children.as_ref().map(|x| x.len()).unwrap_or(0)
}
/// Render children components and return `Iterator`
pub fn iter(&self) -> impl Iterator<Item = T> + '_ {
// clone each child lazily.
// This way `self.iter().next()` only has to clone a single node.
self.children.iter().flat_map(|x| x.iter()).cloned()
}
/// Convert the children elements to another object (if there are any).
///
/// ```
/// # let children = Children::new(Vec::new());
/// # use yew::{classes, html, Children};
/// # let _ =
/// children.map(|children| {
/// html! {
/// <div class={classes!("container")}>
/// {children}
/// </div>
/// }
/// })
/// # ;
/// ```
pub fn map<OUT: Default>(&self, closure: impl FnOnce(&Self) -> OUT) -> OUT {
if self.is_empty() {
Default::default()
} else {
closure(self)
}
}
}
impl<T> Default for ChildrenRenderer<T> {
fn default() -> Self {
Self {
children: Default::default(),
}
}
}
impl<T> fmt::Debug for ChildrenRenderer<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ChildrenRenderer<_>")
}
}
impl<T: Clone> IntoIterator for ChildrenRenderer<T> {
type IntoIter = std::vec::IntoIter<Self::Item>;
type Item = T;
fn into_iter(self) -> Self::IntoIter {
if let Some(children) = self.children {
let children = RcExt::unwrap_or_clone(children);
children.into_iter()
} else {
Vec::new().into_iter()
}
}
}
impl From<ChildrenRenderer<Html>> for Html {
fn from(mut val: ChildrenRenderer<Html>) -> Self {
if let Some(children) = val.children.as_mut() {
if children.len() == 1 {
let children = Rc::make_mut(children);
if let Some(m) = children.pop() {
return m;
}
}
}
Html::VList(Rc::new(val.into()))
}
}
impl From<ChildrenRenderer<Html>> for VList {
fn from(val: ChildrenRenderer<Html>) -> Self {
VList::from(val.children)
}
}
impl<COMP> From<ChildrenRenderer<VChild<COMP>>> for ChildrenRenderer<Html>
where
COMP: BaseComponent,
{
fn from(value: ChildrenRenderer<VChild<COMP>>) -> Self {
Self::new(
value
.into_iter()
.map(VComp::from)
.map(VNode::from)
.collect::<Vec<_>>(),
)
}
}
/// A [Properties] type with Children being the only property.
#[derive(Debug, Properties, PartialEq)]
pub struct ChildrenProps {
/// The Children of a Component.
#[prop_or_default]
pub children: Html,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn children_map() {
let children = Children::new(vec![]);
let res = children.map(|children| Some(children.clone()));
assert!(res.is_none());
let children = Children::new(vec![Default::default()]);
let res = children.map(|children| Some(children.clone()));
assert!(res.is_some());
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/html/component/marker.rs | packages/yew/src/html/component/marker.rs | //! Primitive Components & Properties Types
use crate::component;
use crate::html::{BaseComponent, ChildrenProps, Html};
/// A Component to represent a component that does not exist in current implementation.
///
/// During Hydration, Yew expected the Virtual DOM hierarchy to match the layout used in
/// server-side rendering. However, sometimes it is possible / reasonable to omit certain components
/// from one side of the implementation. This component is used to represent a component as if a
/// component "existed" in the place it is defined.
///
/// # Warning
///
/// The Real DOM hierarchy must also match the server-side rendered artifact. This component is
/// only usable when the original component does not introduce any additional elements. (e.g.:
/// Context Providers)
///
/// A generic parameter is provided to help identify the component to be substituted.
/// The type of the generic parameter is not required to be the same component that was in the other
/// implementation. However, this behaviour may change in the future if more debug assertions were
/// to be introduced. It is recommended that the generic parameter represents the component in the
/// other implementation.
///
/// # Example
///
/// ```
/// use yew::prelude::*;
/// # use yew::html::ChildrenProps;
/// #
/// # #[component]
/// # fn Comp(props: &ChildrenProps) -> Html {
/// # Html::default()
/// # }
/// #
/// # #[component]
/// # fn Provider(props: &ChildrenProps) -> Html {
/// # let children = props.children.clone();
/// #
/// # html! { <>{children}</> }
/// # }
/// # type Provider1 = Provider;
/// # type Provider2 = Provider;
/// # type Provider3 = Provider;
/// # type Provider4 = Provider;
///
/// #[component]
/// fn ServerApp() -> Html {
/// // The Server Side Rendering Application has 3 Providers.
/// html! {
/// <Provider1>
/// <Provider2>
/// <Provider3>
/// <Comp />
/// </Provider3>
/// </Provider2>
/// </Provider1>
/// }
/// }
///
/// #[component]
/// fn App() -> Html {
/// // The Client Side Rendering Application has 4 Providers.
/// html! {
/// <Provider1>
/// <Provider2>
/// <Provider3>
///
/// // This provider does not exist on the server-side
/// // Hydration will fail due to Virtual DOM layout mismatch.
/// <Provider4>
/// <Comp />
/// </Provider4>
///
/// </Provider3>
/// </Provider2>
/// </Provider1>
/// }
/// }
/// ```
///
/// To mitigate this, we can use a `PhantomComponent`:
///
/// ```
/// use yew::prelude::*;
/// # use yew::html::{PhantomComponent, ChildrenProps};
/// #
/// # #[component]
/// # fn Comp(props: &ChildrenProps) -> Html {
/// # Html::default()
/// # }
/// #
/// # #[component]
/// # fn Provider(props: &ChildrenProps) -> Html {
/// # let children = props.children.clone();
/// #
/// # html! { <>{children}</> }
/// # }
/// # type Provider1 = Provider;
/// # type Provider2 = Provider;
/// # type Provider3 = Provider;
/// # type Provider4 = Provider;
///
/// #[component]
/// fn ServerApp() -> Html {
/// html! {
/// <Provider1>
/// <Provider2>
/// <Provider3>
/// // We add a PhantomComponent for Provider4,
/// // it acts if a Provider4 component presents in this position.
/// <PhantomComponent<Provider4>>
/// <Comp />
/// </PhantomComponent<Provider4>>
/// </Provider3>
/// </Provider2>
/// </Provider1>
/// }
/// }
///
/// #[component]
/// fn App() -> Html {
/// html! {
/// <Provider1>
/// <Provider2>
/// <Provider3>
///
/// // Hydration will succeed as the PhantomComponent in the server-side
/// // implementation will represent a Provider4 component in this position.
/// <Provider4>
/// <Comp />
/// </Provider4>
///
/// </Provider3>
/// </Provider2>
/// </Provider1>
/// }
/// }
/// ```
#[component]
pub fn PhantomComponent<T>(props: &ChildrenProps) -> Html
where
T: BaseComponent,
{
props.children.clone()
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/html/listener/mod.rs | packages/yew/src/html/listener/mod.rs | #[macro_use]
mod events;
pub use events::*;
use wasm_bindgen::JsCast;
use web_sys::{Event, EventTarget};
use crate::Callback;
/// Cast [Event] `e` into it's target `T`.
///
/// This function mainly exists to provide type inference in the [impl_action] macro to the compiler
/// and avoid some verbosity by not having to type the signature over and over in closure
/// definitions.
#[inline]
pub(crate) fn cast_event<T>(e: Event) -> T
where
T: JsCast,
{
e.unchecked_into()
}
/// A trait to obtain a generic event target.
///
/// The methods in this trait are convenient helpers that use the [`JsCast`] trait internally
/// to do the conversion.
pub trait TargetCast
where
Self: AsRef<Event>,
{
/// Performs a dynamic cast (checked at runtime) of this events target into the type `T`.
///
/// This method can return [`None`] for two reasons:
/// - The event's target was [`None`]
/// - The event's target type did not match `T`
///
/// # Example
///
/// ```
/// use web_sys::HtmlTextAreaElement;
/// use yew::prelude::*;
/// # enum Msg {
/// # Value(String),
/// # }
/// # struct Comp;
/// # impl Component for Comp {
/// # type Message = Msg;
/// # type Properties = ();
/// # fn create(ctx: &Context<Self>) -> Self {
/// # Self
/// # }
///
/// fn view(&self, ctx: &Context<Self>) -> Html {
/// html! {
/// <div
/// onchange={ctx.link().batch_callback(|e: Event| {
/// if let Some(input) = e.target_dyn_into::<HtmlTextAreaElement>() {
/// Some(Msg::Value(input.value()))
/// } else {
/// None
/// }
/// })}
/// >
/// <textarea />
/// <input type="text" />
/// </div>
/// }
/// }
/// # }
/// ```
/// _Note: if you can apply the [`Callback`] directly onto an element which doesn't have a child
/// consider using [`TargetCast::target_unchecked_into<T>`]_
#[inline]
fn target_dyn_into<T>(&self) -> Option<T>
where
T: AsRef<EventTarget> + JsCast,
{
self.as_ref()
.target()
.and_then(|target| target.dyn_into().ok())
}
#[inline]
/// Performs a zero-cost unchecked cast of this events target into the type `T`.
///
/// This method **does not check whether the event target is an instance of `T`**. If used
/// incorrectly then this method may cause runtime exceptions in both Rust and JS, this should
/// be used with caution.
///
/// A common safe usage of this method is within a [`Callback`] that is applied directly to an
/// element that has no children, thus `T` will be the type of the element the [`Callback`] is
/// applied to.
///
/// # Example
///
/// ```
/// use web_sys::HtmlInputElement;
/// use yew::prelude::*;
/// # enum Msg {
/// # Value(String),
/// # }
/// # struct Comp;
/// # impl Component for Comp {
/// # type Message = Msg;
/// # type Properties = ();
/// # fn create(ctx: &Context<Self>) -> Self {
/// # Self
/// # }
///
/// fn view(&self, ctx: &Context<Self>) -> Html {
/// html! {
/// <input type="text"
/// onchange={ctx.link().callback(|e: Event| {
/// // Safe to use as callback is on an `input` element so this event can
/// // only come from this input!
/// let input: HtmlInputElement = e.target_unchecked_into();
/// Msg::Value(input.value())
/// })}
/// />
/// }
/// }
/// # }
/// ```
fn target_unchecked_into<T>(&self) -> T
where
T: AsRef<EventTarget> + JsCast,
{
self.as_ref().target().unwrap().unchecked_into()
}
}
impl<E: AsRef<Event>> TargetCast for E {}
/// A trait similar to `Into<T>` which allows conversion of a value into a [`Callback`].
/// This is used for event listeners.
pub trait IntoEventCallback<EVENT> {
/// Convert `self` to `Option<Callback<EVENT>>`
fn into_event_callback(self) -> Option<Callback<EVENT>>;
}
impl<EVENT> IntoEventCallback<EVENT> for Callback<EVENT> {
fn into_event_callback(self) -> Option<Callback<EVENT>> {
Some(self)
}
}
impl<EVENT> IntoEventCallback<EVENT> for &Callback<EVENT> {
fn into_event_callback(self) -> Option<Callback<EVENT>> {
Some(self.clone())
}
}
impl<EVENT> IntoEventCallback<EVENT> for Option<Callback<EVENT>> {
fn into_event_callback(self) -> Option<Callback<EVENT>> {
self
}
}
impl<T, EVENT> IntoEventCallback<EVENT> for T
where
T: Fn(EVENT) + 'static,
{
fn into_event_callback(self) -> Option<Callback<EVENT>> {
Some(Callback::from(self))
}
}
impl<T, EVENT> IntoEventCallback<EVENT> for Option<T>
where
T: Fn(EVENT) + 'static,
{
fn into_event_callback(self) -> Option<Callback<EVENT>> {
Some(Callback::from(self?))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn supported_into_event_callback_types() {
let f = |_: usize| ();
let cb = Callback::from(f);
// Callbacks
let _: Option<Callback<usize>> = cb.clone().into_event_callback();
let _: Option<Callback<usize>> = (&cb).into_event_callback();
let _: Option<Callback<usize>> = Some(cb).into_event_callback();
// Fns
let _: Option<Callback<usize>> = f.into_event_callback();
let _: Option<Callback<usize>> = Some(f).into_event_callback();
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/html/listener/events.rs | packages/yew/src/html/listener/events.rs | // Inspired by: http://package.elm-lang.org/packages/elm-lang/html/2.0.0/Html-Events
macro_rules! impl_action {
($($action:ident($type:ident) -> $ret:path => $convert:path)*) => {$(
impl_action!($action($type, false) -> $ret => $convert);
)*};
($($action:ident($type:ident, $passive:literal) -> $ret:path => $convert:path)*) => {$(
/// An abstract implementation of a listener.
#[doc(hidden)]
pub mod $action {
use crate::callback::Callback;
use crate::virtual_dom::{Listener, ListenerKind};
use std::rc::Rc;
/// A wrapper for a callback which attaches event listeners to elements.
#[derive(Clone, Debug)]
pub struct Wrapper {
callback: Callback<Event>,
}
impl Wrapper {
/// Create a wrapper for an event-typed callback
pub fn new(callback: Callback<Event>) -> Self {
Wrapper { callback }
}
#[doc(hidden)]
#[inline]
pub fn __macro_new(
callback: impl crate::html::IntoEventCallback<Event>,
) -> Option<Rc<dyn Listener>> {
let callback = callback.into_event_callback()?;
Some(Rc::new(Self::new(callback)))
}
}
/// And event type which keeps the returned type.
pub type Event = $ret;
impl Listener for Wrapper {
fn kind(&self) -> ListenerKind {
ListenerKind::$action
}
fn handle(&self, event: web_sys::Event) {
self.callback.emit($convert(event));
}
fn passive(&self) -> bool {
$passive
}
}
}
)*};
}
// Reduces repetition for common cases
macro_rules! impl_short {
($($action:ident)*) => {
impl_action! {
$(
$action(Event) -> web_sys::Event => std::convert::identity
)*
}
};
($($action:ident($type:ident))*) => {
impl_action! {
$(
$action($type) -> web_sys::$type => crate::html::listener::cast_event
)*
}
};
}
// Unspecialized event type
impl_short! {
onabort
oncancel
oncanplay
oncanplaythrough
onclose
oncuechange
ondurationchange
onemptied
onended
onerror
onformdata // web_sys doesn't have a struct for `FormDataEvent`
oninvalid
onload
onloadeddata
onloadedmetadata
onpause
onplay
onplaying
onratechange
onreset
onresize
onsecuritypolicyviolation
onseeked
onseeking
onselect
onslotchange
onstalled
onsuspend
ontimeupdate
ontoggle
onvolumechange
onwaiting
onchange
oncopy
oncut
onpaste
onpointerlockchange
onpointerlockerror
onselectionchange
onselectstart
onshow
}
// Specialized event type
impl_short! {
onauxclick(MouseEvent)
onclick(MouseEvent)
oncontextmenu(MouseEvent)
ondblclick(MouseEvent)
ondrag(DragEvent)
ondragend(DragEvent)
ondragenter(DragEvent)
ondragexit(DragEvent)
ondragleave(DragEvent)
ondragover(DragEvent)
ondragstart(DragEvent)
ondrop(DragEvent)
onblur(FocusEvent)
onfocus(FocusEvent)
onfocusin(FocusEvent)
onfocusout(FocusEvent)
onkeydown(KeyboardEvent)
onkeypress(KeyboardEvent)
onkeyup(KeyboardEvent)
onloadstart(ProgressEvent)
onprogress(ProgressEvent)
onloadend(ProgressEvent)
onmousedown(MouseEvent)
onmouseenter(MouseEvent)
onmouseleave(MouseEvent)
onmousemove(MouseEvent)
onmouseout(MouseEvent)
onmouseover(MouseEvent)
onmouseup(MouseEvent)
onwheel(WheelEvent)
oninput(InputEvent)
onsubmit(SubmitEvent)
onanimationcancel(AnimationEvent)
onanimationend(AnimationEvent)
onanimationiteration(AnimationEvent)
onanimationstart(AnimationEvent)
ongotpointercapture(PointerEvent)
onlostpointercapture(PointerEvent)
onpointercancel(PointerEvent)
onpointerdown(PointerEvent)
onpointerenter(PointerEvent)
onpointerleave(PointerEvent)
onpointermove(PointerEvent)
onpointerout(PointerEvent)
onpointerover(PointerEvent)
onpointerup(PointerEvent)
ontouchcancel(TouchEvent)
ontouchend(TouchEvent)
ontransitioncancel(TransitionEvent)
ontransitionend(TransitionEvent)
ontransitionrun(TransitionEvent)
ontransitionstart(TransitionEvent)
}
macro_rules! impl_passive {
($($action:ident($type:ident))*) => {
impl_action! {
$(
$action($type, true) -> web_sys::$type
=> crate::html::listener::cast_event
)*
}
};
}
// Best used with passive listeners for responsiveness
impl_passive! {
onscroll(Event)
ontouchmove(TouchEvent)
ontouchstart(TouchEvent)
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/dom_bundle/bsuspense.rs | packages/yew/src/dom_bundle/bsuspense.rs | //! This module contains the bundle version of a supsense [BSuspense]
use gloo::utils::document;
use web_sys::Element;
#[cfg(feature = "hydration")]
use super::Fragment;
use super::{BNode, BSubtree, DomSlot, Reconcilable, ReconcileTarget};
use crate::html::AnyScope;
use crate::virtual_dom::{Key, VSuspense};
#[derive(Debug)]
enum Fallback {
/// Suspense Fallback with fallback being rendered as placeholder.
Bundle(BNode),
/// Suspense Fallback with Hydration Fragment being rendered as placeholder.
#[cfg(feature = "hydration")]
Fragment(Fragment),
}
/// The bundle implementation to [VSuspense]
#[derive(Debug)]
pub(super) struct BSuspense {
children_bundle: BNode,
/// The supsense is suspended if fallback contains [Some] bundle
fallback: Option<Fallback>,
detached_parent: Element,
key: Option<Key>,
}
impl BSuspense {
/// Get the key of the underlying suspense
pub fn key(&self) -> Option<&Key> {
self.key.as_ref()
}
}
impl ReconcileTarget for BSuspense {
fn detach(self, root: &BSubtree, parent: &Element, parent_to_detach: bool) {
match self.fallback {
Some(m) => {
match m {
Fallback::Bundle(bundle) => {
bundle.detach(root, parent, parent_to_detach);
}
#[cfg(feature = "hydration")]
Fallback::Fragment(fragment) => {
fragment.detach(root, parent, parent_to_detach);
}
}
self.children_bundle
.detach(root, &self.detached_parent, false);
}
None => {
self.children_bundle.detach(root, parent, parent_to_detach);
}
}
}
fn shift(&self, next_parent: &Element, slot: DomSlot) -> DomSlot {
match self.fallback.as_ref() {
Some(Fallback::Bundle(bundle)) => bundle.shift(next_parent, slot),
#[cfg(feature = "hydration")]
Some(Fallback::Fragment(fragment)) => fragment.shift(next_parent, slot),
None => self.children_bundle.shift(next_parent, slot),
}
}
}
impl Reconcilable for VSuspense {
type Bundle = BSuspense;
fn attach(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
) -> (DomSlot, Self::Bundle) {
let VSuspense {
children,
fallback,
suspended,
key,
} = self;
let detached_parent = document()
.create_element("div")
.expect("failed to create detached element");
// When it's suspended, we render children into an element that is detached from the dom
// tree while rendering fallback UI into the original place where children resides in.
if suspended {
let (_child_ref, children_bundle) =
children.attach(root, parent_scope, &detached_parent, DomSlot::at_end());
let (fallback_ref, fallback) = fallback.attach(root, parent_scope, parent, slot);
(
fallback_ref,
BSuspense {
children_bundle,
fallback: Some(Fallback::Bundle(fallback)),
detached_parent,
key,
},
)
} else {
let (child_ref, children_bundle) = children.attach(root, parent_scope, parent, slot);
(
child_ref,
BSuspense {
children_bundle,
fallback: None,
detached_parent,
key,
},
)
}
}
fn reconcile_node(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
bundle: &mut BNode,
) -> DomSlot {
match bundle {
// We only preserve the child state if they are the same suspense.
BNode::Suspense(m) if m.key == self.key => {
self.reconcile(root, parent_scope, parent, slot, m)
}
_ => self.replace(root, parent_scope, parent, slot, bundle),
}
}
fn reconcile(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
suspense: &mut Self::Bundle,
) -> DomSlot {
let VSuspense {
children,
fallback: vfallback,
suspended,
key: _,
} = self;
let children_bundle = &mut suspense.children_bundle;
// no need to update key & detached_parent
// When it's suspended, we render children into an element that is detached from the dom
// tree while rendering fallback UI into the original place where children resides in.
match (suspended, &mut suspense.fallback) {
// Both suspended, reconcile children into detached_parent, fallback into the DOM
(true, Some(fallback)) => {
children.reconcile_node(
root,
parent_scope,
&suspense.detached_parent,
DomSlot::at_end(),
children_bundle,
);
match fallback {
Fallback::Bundle(bundle) => {
vfallback.reconcile_node(root, parent_scope, parent, slot, bundle)
}
#[cfg(feature = "hydration")]
Fallback::Fragment(fragment) => match fragment.front().cloned() {
Some(m) => DomSlot::at(m),
None => slot,
},
}
}
// Not suspended, just reconcile the children into the DOM
(false, None) => {
children.reconcile_node(root, parent_scope, parent, slot, children_bundle)
}
// Freshly suspended. Shift children into the detached parent, then add fallback to the
// DOM
(true, None) => {
children_bundle.shift(&suspense.detached_parent, DomSlot::at_end());
children.reconcile_node(
root,
parent_scope,
&suspense.detached_parent,
DomSlot::at_end(),
children_bundle,
);
// first render of fallback
let (fallback_ref, fallback) = vfallback.attach(root, parent_scope, parent, slot);
suspense.fallback = Some(Fallback::Bundle(fallback));
fallback_ref
}
// Freshly unsuspended. Detach fallback from the DOM, then shift children into it.
(false, Some(_)) => {
match suspense.fallback.take() {
Some(Fallback::Bundle(bundle)) => {
bundle.detach(root, parent, false);
}
#[cfg(feature = "hydration")]
Some(Fallback::Fragment(fragment)) => {
fragment.detach(root, parent, false);
}
None => {
unreachable!("None condition has been checked before.")
}
};
children_bundle.shift(parent, slot.clone());
children.reconcile_node(root, parent_scope, parent, slot, children_bundle)
}
}
}
}
#[cfg(feature = "hydration")]
mod feat_hydration {
use super::*;
use crate::dom_bundle::{DynamicDomSlot, Fragment, Hydratable};
use crate::virtual_dom::Collectable;
impl Hydratable for VSuspense {
fn hydrate(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
fragment: &mut Fragment,
previous_next_sibling: &mut Option<DynamicDomSlot>,
) -> Self::Bundle {
let detached_parent = document()
.create_element("div")
.expect("failed to create detached element");
let collectable = Collectable::Suspense;
let fallback_fragment = Fragment::collect_between(fragment, &collectable, parent);
let mut nodes = fallback_fragment.deep_clone();
for node in nodes.iter() {
detached_parent.append_child(node).unwrap();
}
// Even if initially suspended, these children correspond to the first non-suspended
// content Refer to VSuspense::render_to_string
let children_bundle = self.children.hydrate(
root,
parent_scope,
&detached_parent,
&mut nodes,
previous_next_sibling,
);
// We trim all leading text nodes before checking as it's likely these are whitespaces.
nodes.trim_start_text_nodes();
assert!(nodes.is_empty(), "expected end of suspense, found node.");
BSuspense {
children_bundle,
detached_parent,
key: self.key,
// We start hydration with the BSuspense being suspended.
// A subsequent render will resume the BSuspense if not needed to be suspended.
fallback: Some(Fallback::Fragment(fallback_fragment)),
}
}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/dom_bundle/fragment.rs | packages/yew/src/dom_bundle/fragment.rs | use std::collections::VecDeque;
use std::ops::{Deref, DerefMut};
use wasm_bindgen::JsCast;
use web_sys::{Element, Node};
use super::{BSubtree, DomSlot};
use crate::virtual_dom::Collectable;
/// A Hydration Fragment
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub(crate) struct Fragment(VecDeque<Node>, Option<Node>);
impl Deref for Fragment {
type Target = VecDeque<Node>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for Fragment {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl Fragment {
/// Collects child nodes of an element into a VecDeque.
pub fn collect_children(parent: &Element) -> Self {
let mut fragment = VecDeque::with_capacity(parent.child_nodes().length() as usize);
let mut current_node = parent.first_child();
// This is easier than iterating child nodes at the moment
// as we don't have to downcast iterator values.
while let Some(m) = current_node {
current_node = m.next_sibling();
fragment.push_back(m);
}
Self(fragment, None)
}
/// Collects nodes for a Component Bundle or a BSuspense.
pub fn collect_between(
collect_from: &mut Fragment,
collect_for: &Collectable,
parent: &Element,
) -> Self {
let is_open_tag = |node: &Node| {
let comment_text = node.text_content().unwrap_or_default();
comment_text.starts_with(collect_for.open_start_mark())
&& comment_text.ends_with(collect_for.end_mark())
};
let is_close_tag = |node: &Node| {
let comment_text = node.text_content().unwrap_or_default();
comment_text.starts_with(collect_for.close_start_mark())
&& comment_text.ends_with(collect_for.end_mark())
};
// We trim all leading text nodes as it's likely these are whitespaces.
collect_from.trim_start_text_nodes();
let first_node = collect_from
.pop_front()
.unwrap_or_else(|| panic!("expected {} opening tag, found EOF", collect_for.name()));
assert_eq!(
first_node.node_type(),
Node::COMMENT_NODE,
// TODO: improve error message with human readable node type name.
"expected {} start, found node type {}",
collect_for.name(),
first_node.node_type()
);
let mut nodes = VecDeque::new();
if !is_open_tag(&first_node) {
panic!(
"expected {} opening tag, found comment node",
collect_for.name()
);
}
// We remove the opening tag.
parent.remove_child(&first_node).unwrap();
let mut nested_layers = 1;
loop {
let current_node = collect_from.pop_front().unwrap_or_else(|| {
panic!("expected {} closing tag, found EOF", collect_for.name())
});
if current_node.node_type() == Node::COMMENT_NODE {
if is_open_tag(¤t_node) {
// We found another opening tag, we need to increase component counter.
nested_layers += 1;
} else if is_close_tag(¤t_node) {
// We found a closing tag, minus component counter.
nested_layers -= 1;
if nested_layers == 0 {
// We have found the end of the current tag we are collecting, breaking
// the loop.
// We remove the closing tag.
parent.remove_child(¤t_node).unwrap();
break;
}
}
}
nodes.push_back(current_node);
}
let next_child = collect_from.0.front().cloned();
Self(nodes, next_child)
}
/// Remove child nodes until first non-text node.
pub fn trim_start_text_nodes(&mut self) {
while let Some(ref m) = self.front().cloned() {
if m.node_type() == Node::TEXT_NODE {
self.pop_front();
m.unchecked_ref::<web_sys::Text>().remove();
} else {
break;
}
}
}
/// Deeply clones all nodes.
pub fn deep_clone(&self) -> Self {
let nodes = self
.iter()
.map(|m| m.clone_node_with_deep(true).expect("failed to clone node."))
.collect::<VecDeque<_>>();
// the cloned nodes are disconnected from the real dom, so next_child is `None`
Self(nodes, None)
}
// detaches current fragment.
pub fn detach(self, _root: &BSubtree, parent: &Element, parent_to_detach: bool) {
if !parent_to_detach {
for node in self.iter() {
parent
.remove_child(node)
.expect("failed to remove child element");
}
}
}
/// Shift current Fragment into a different position in the dom.
pub fn shift(&self, next_parent: &Element, slot: DomSlot) -> DomSlot {
for node in self.iter() {
slot.insert(next_parent, node);
}
self.front().cloned().map(DomSlot::at).unwrap_or(slot)
}
/// Return the node that comes after all the nodes in this fragment
pub fn sibling_at_end(&self) -> Option<&Node> {
self.1.as_ref()
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/dom_bundle/subtree_root.rs | packages/yew/src/dom_bundle/subtree_root.rs | //! Per-subtree state of apps
use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::rc::{Rc, Weak};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use wasm_bindgen::prelude::{wasm_bindgen, Closure};
use wasm_bindgen::{intern, JsCast, UnwrapThrowExt};
use web_sys::{
AddEventListenerOptions, Element, Event, EventTarget as HtmlEventTarget, ShadowRoot,
};
use super::{test_log, Registry};
use crate::virtual_dom::{Listener, ListenerKind};
/// DOM-Types that capture (bubbling) events. This generally includes event targets,
/// but also subtree roots.
pub trait EventGrating {
fn subtree_id(&self) -> Option<TreeId>;
fn set_subtree_id(&self, tree_id: TreeId);
// When caching, we key on the length of the `composed_path`. Important to check
// considering event retargeting!
fn cache_key(&self) -> Option<u32>;
fn set_cache_key(&self, key: u32);
}
#[wasm_bindgen]
extern "C" {
// Duck-typing, not a real class on js-side. On rust-side, use impls of EventGrating below
type EventTargetable;
#[wasm_bindgen(method, getter = __yew_subtree_id, structural)]
fn subtree_id(this: &EventTargetable) -> Option<TreeId>;
#[wasm_bindgen(method, setter = __yew_subtree_id, structural)]
fn set_subtree_id(this: &EventTargetable, id: TreeId);
#[wasm_bindgen(method, getter = __yew_subtree_cache_key, structural)]
fn cache_key(this: &EventTargetable) -> Option<u32>;
#[wasm_bindgen(method, setter = __yew_subtree_cache_key, structural)]
fn set_cache_key(this: &EventTargetable, key: u32);
}
macro_rules! impl_event_grating {
($($t:ty);* $(;)?) => {
$(
impl EventGrating for $t {
fn subtree_id(&self) -> Option<TreeId> {
self.unchecked_ref::<EventTargetable>().subtree_id()
}
fn set_subtree_id(&self, tree_id: TreeId) {
self.unchecked_ref::<EventTargetable>()
.set_subtree_id(tree_id);
}
fn cache_key(&self) -> Option<u32> {
self.unchecked_ref::<EventTargetable>().cache_key()
}
fn set_cache_key(&self, key: u32) {
self.unchecked_ref::<EventTargetable>().set_cache_key(key)
}
}
)*
}
}
impl_event_grating!(
HtmlEventTarget;
Event; // We cache the found subtree id on the event. This should speed up repeated searches
);
/// The TreeId is the additional payload attached to each listening element
/// It identifies the host responsible for the target. Events not matching
/// are ignored during handling
type TreeId = u32;
/// Special id for caching the fact that some event should not be handled
static NONE_TREE_ID: TreeId = 0;
static NEXT_ROOT_ID: AtomicU32 = AtomicU32::new(1);
fn next_root_id() -> TreeId {
NEXT_ROOT_ID.fetch_add(1, Ordering::SeqCst)
}
/// Data kept per controlled subtree. [Portal] and [AppHandle] serve as
/// hosts. Two controlled subtrees should never overlap.
///
/// [Portal]: super::bportal::BPortal
/// [AppHandle]: super::app_handle::AppHandle
#[derive(Debug, Clone)]
pub struct BSubtree(Rc<SubtreeData>);
/// The parent is the logical location where a subtree is mounted
/// Used to bubble events through portals, which are physically somewhere else in the DOM tree
/// but should bubble to logical ancestors in the virtual DOM tree
#[derive(Debug)]
struct ParentingInformation {
parent_root: Rc<SubtreeData>,
// Logical parent of the subtree. Might be the host element of another subtree,
// if mounted as a direct child, or a controlled element.
mount_element: Element,
}
#[derive(Clone, Hash, Eq, PartialEq, Debug)]
pub struct EventDescriptor {
kind: ListenerKind,
passive: bool,
}
impl From<&dyn Listener> for EventDescriptor {
fn from(l: &dyn Listener) -> Self {
Self {
kind: l.kind(),
passive: l.passive(),
}
}
}
// FIXME: this is a reproduction of gloo's EventListener to work around #2989
// change back to gloo's implementation once it has been decided how to fix this upstream
// The important part is that we use `Fn` instead of `FnMut` below!
type EventClosure = Closure<dyn Fn(&Event)>;
#[derive(Debug)]
#[must_use = "event listener will never be called after being dropped"]
struct EventListener {
target: HtmlEventTarget,
event_type: Cow<'static, str>,
callback: Option<EventClosure>,
}
impl Drop for EventListener {
#[inline]
fn drop(&mut self) {
if let Some(ref callback) = self.callback {
self.target
.remove_event_listener_with_callback_and_bool(
&self.event_type,
callback.as_ref().unchecked_ref(),
true, // Always capture
)
.unwrap_throw();
}
}
}
impl EventListener {
fn new(
target: &HtmlEventTarget,
desc: &EventDescriptor,
callback: impl 'static + Fn(&Event),
) -> Self {
let event_type = desc.kind.type_name();
let callback = Closure::wrap(Box::new(callback) as Box<dyn Fn(&Event)>);
// defaults: { once: false }
let options = AddEventListenerOptions::new();
options.set_capture(true);
options.set_passive(desc.passive);
target
.add_event_listener_with_callback_and_add_event_listener_options(
intern(&event_type),
callback.as_ref().unchecked_ref(),
&options,
)
.unwrap_throw();
EventListener {
target: target.clone(),
event_type,
callback: Some(callback),
}
}
#[cfg(not(test))]
fn forget(mut self) {
if let Some(callback) = self.callback.take() {
// Should always match, but no need to introduce a panic path here
callback.forget();
}
}
}
/// Ensures event handler registration.
// Separate struct to DRY, while avoiding partial struct mutability.
#[derive(Debug)]
struct HostHandlers {
/// The host element where events are registered
host: HtmlEventTarget,
/// Keep track of all listeners to drop them on registry drop.
/// The registry is never dropped in production.
#[cfg(test)]
registered: Vec<(ListenerKind, EventListener)>,
}
impl HostHandlers {
fn new(host: HtmlEventTarget) -> Self {
Self {
host,
#[cfg(test)]
registered: Vec::default(),
}
}
fn add_listener(&mut self, desc: &EventDescriptor, callback: impl 'static + Fn(&Event)) {
let cl = EventListener::new(&self.host, desc, callback);
// Never drop the closure as this event handler is static
#[cfg(not(test))]
cl.forget();
#[cfg(test)]
self.registered.push((desc.kind.clone(), cl));
}
}
/// Per subtree data
#[derive(Debug)]
struct SubtreeData {
/// Data shared between all trees in an app
app_data: Rc<RefCell<AppData>>,
/// Parent subtree
parent: Option<ParentingInformation>,
subtree_id: TreeId,
host: HtmlEventTarget,
event_registry: RefCell<Registry>,
global: RefCell<HostHandlers>,
}
#[derive(Debug)]
struct WeakSubtree {
subtree_id: TreeId,
weak_ref: Weak<SubtreeData>,
}
impl Hash for WeakSubtree {
fn hash<H: Hasher>(&self, state: &mut H) {
self.subtree_id.hash(state)
}
}
impl PartialEq for WeakSubtree {
fn eq(&self, other: &Self) -> bool {
self.subtree_id == other.subtree_id
}
}
impl Eq for WeakSubtree {}
/// Per tree data, shared between all subtrees in the hierarchy
#[derive(Debug, Default)]
struct AppData {
subtrees: HashSet<WeakSubtree>,
listening: HashSet<EventDescriptor>,
}
impl AppData {
fn add_subtree(&mut self, subtree: &Rc<SubtreeData>) {
for event in self.listening.iter() {
subtree.add_listener(event);
}
self.subtrees.insert(WeakSubtree {
subtree_id: subtree.subtree_id,
weak_ref: Rc::downgrade(subtree),
});
}
fn ensure_handled(&mut self, desc: &EventDescriptor) {
if !self.listening.insert(desc.clone()) {
return;
}
self.subtrees.retain(|subtree| {
if let Some(subtree) = subtree.weak_ref.upgrade() {
subtree.add_listener(desc);
true
} else {
false
}
})
}
}
/// Bubble events during delegation
static BUBBLE_EVENTS: AtomicBool = AtomicBool::new(true);
/// Set, if events should bubble up the DOM tree, calling any matching callbacks.
///
/// Bubbling is enabled by default. Disabling bubbling can lead to substantial improvements in event
/// handling performance.
///
/// This function should be called before any component is mounted.
#[cfg(feature = "csr")]
pub fn set_event_bubbling(bubble: bool) {
BUBBLE_EVENTS.store(bubble, Ordering::Relaxed);
}
struct BrandingSearchResult {
branding: TreeId,
closest_branded_ancestor: Element,
}
fn shadow_aware_parent(el: &Element) -> Option<Element> {
match el.parent_element() {
s @ Some(_) => s,
None => el.parent_node()?.dyn_ref::<ShadowRoot>().map(|h| h.host()),
}
}
/// Deduce the subtree an element is part of. This already partially starts the bubbling
/// process, as long as no listeners are encountered.
/// Subtree roots are always branded with their own subtree id.
fn find_closest_branded_element(mut el: Element, do_bubble: bool) -> Option<BrandingSearchResult> {
if !do_bubble {
let branding = el.subtree_id()?;
Some(BrandingSearchResult {
branding,
closest_branded_ancestor: el,
})
} else {
let responsible_tree_id = loop {
if let Some(tree_id) = el.subtree_id() {
break tree_id;
}
el = shadow_aware_parent(&el)?;
};
Some(BrandingSearchResult {
branding: responsible_tree_id,
closest_branded_ancestor: el,
})
}
}
/// Iterate over all potentially listening elements in bubbling order.
/// If bubbling is turned off, yields at most a single element.
fn start_bubbling_from(
subtree: &SubtreeData,
root_or_listener: Element,
should_bubble: bool,
) -> impl '_ + Iterator<Item = (&'_ SubtreeData, Element)> {
let start = subtree.bubble_to_inner_element(root_or_listener, should_bubble);
std::iter::successors(start, move |(subtree, element)| {
if !should_bubble {
return None;
}
let parent = shadow_aware_parent(element)?;
subtree.bubble_to_inner_element(parent, true)
})
}
impl SubtreeData {
fn new_ref(host_element: &HtmlEventTarget, parent: Option<ParentingInformation>) -> Rc<Self> {
let tree_root_id = next_root_id();
let event_registry = Registry::new();
let host_handlers = HostHandlers::new(host_element.clone());
let app_data = match parent {
Some(ref parent) => parent.parent_root.app_data.clone(),
None => Rc::default(),
};
let subtree = Rc::new(SubtreeData {
parent,
app_data,
subtree_id: tree_root_id,
host: host_element.clone(),
event_registry: RefCell::new(event_registry),
global: RefCell::new(host_handlers),
});
subtree.app_data.borrow_mut().add_subtree(&subtree);
subtree
}
fn event_registry(&self) -> &RefCell<Registry> {
&self.event_registry
}
fn host_handlers(&self) -> &RefCell<HostHandlers> {
&self.global
}
// Bubble a potential parent until it reaches an internal element
fn bubble_to_inner_element(
&self,
parent_el: Element,
should_bubble: bool,
) -> Option<(&Self, Element)> {
let mut next_subtree = self;
let mut next_el = parent_el;
if !should_bubble && next_subtree.host.eq(&next_el) {
return None;
}
while next_subtree.host.eq(&next_el) {
// we've reached the host, delegate to a parent if one exists
let parent = next_subtree.parent.as_ref()?;
next_subtree = &parent.parent_root;
next_el = parent.mount_element.clone();
}
Some((next_subtree, next_el))
}
fn start_bubbling_if_responsible<'s>(
&'s self,
event: &'s Event,
) -> Option<impl 's + Iterator<Item = (&'s SubtreeData, Element)>> {
// Note: the event is not necessarily identically the same object for all installed
// handlers hence this cache can be unreliable. Hence the cached repsonsible_tree_id
// might be missing. On the other hand, due to event retargeting at shadow roots,
// the cache might be wrong! Keep in mind that we handle events in the capture
// phase, so top-down. When descending and retargeting into closed shadow-dom, the
// event might have been handled 'prematurely'. TODO: figure out how to prevent this
// and establish correct event handling for closed shadow root. Note: Other
// frameworks also get this wrong and dispatch such events multiple times.
let event_path = event.composed_path();
let derived_cached_key = event_path.length();
let cached_branding = if matches!(event.cache_key(), Some(cache_key) if cache_key == derived_cached_key)
{
event.subtree_id()
} else {
None
};
if matches!(cached_branding, Some(responsible_tree_id) if responsible_tree_id != self.subtree_id)
{
// some other handler has determined (via this function, but other `self`) a subtree
// that is responsible for handling this event, and it's not this subtree.
return None;
}
// We're tasked with finding the subtree that is responsible with handling the event, and/or
// run the handling if that's `self`.
let target = event_path.get(0).dyn_into::<Element>().ok()?;
let should_bubble = BUBBLE_EVENTS.load(Ordering::Relaxed) && event.bubbles();
// We say that the most deeply nested subtree is "responsible" for handling the event.
let (responsible_tree_id, bubbling_start) = if let Some(branding) = cached_branding {
(branding, target.clone())
} else if let Some(branding) = find_closest_branded_element(target.clone(), should_bubble) {
let BrandingSearchResult {
branding,
closest_branded_ancestor,
} = branding;
event.set_subtree_id(branding);
event.set_cache_key(derived_cached_key);
(branding, closest_branded_ancestor)
} else {
// Possible only? if bubbling is disabled
// No tree should handle this event
event.set_subtree_id(NONE_TREE_ID);
event.set_cache_key(derived_cached_key);
return None;
};
if self.subtree_id != responsible_tree_id {
return None;
}
if self.host.eq(&target) {
// One more special case: don't handle events that get fired directly on a subtree host
return None;
}
Some(start_bubbling_from(self, bubbling_start, should_bubble))
// # More details: When nesting occurs
//
// Event listeners are installed only on the subtree roots. Still, those roots can
// nest. This could lead to events getting handled multiple times. We want event handling to
// start at the most deeply nested subtree.
//
// A nested subtree portals into an element that is controlled by the user and rendered
// with VNode::VRef. We get the following dom nesting:
//
// AppRoot > .. > UserControlledVRef > .. > NestedTree(PortalExit) > ..
// -------------- ----------------------------
// The underlined parts of the hierarchy are controlled by Yew.
//
// from the following virtual_dom
// <AppRoot>
// {VNode::VRef(<div><div id="portal_target" /></div>)}
// {create_portal(<NestedTree />, #portal_target)}
// </AppRoot>
}
/// Handle a global event firing
fn handle(&self, desc: EventDescriptor, event: Event) {
let run_handler = |root: &Self, el: &Element| {
let handler = Registry::get_handler(root.event_registry(), el, &desc);
if let Some(handler) = handler {
handler(&event)
}
};
if let Some(bubbling_it) = self.start_bubbling_if_responsible(&event) {
test_log!("Running handler on subtree {}", self.subtree_id);
for (subtree, el) in bubbling_it {
if event.cancel_bubble() {
break;
}
run_handler(subtree, &el);
}
}
}
fn add_listener(self: &Rc<Self>, desc: &EventDescriptor) {
let this = self.clone();
let listener = {
let desc = desc.clone();
move |e: &Event| {
this.handle(desc.clone(), e.clone());
}
};
self.host_handlers()
.borrow_mut()
.add_listener(desc, listener);
}
}
impl BSubtree {
fn do_create_root(
host_element: &HtmlEventTarget,
parent: Option<ParentingInformation>,
) -> Self {
let shared_inner = SubtreeData::new_ref(host_element, parent);
let root = BSubtree(shared_inner);
root.brand_element(host_element);
root
}
/// Create a bundle root at the specified host element
pub fn create_root(host_element: &HtmlEventTarget) -> Self {
Self::do_create_root(host_element, None)
}
/// Create a bundle root at the specified host element, that is logically
/// mounted under the specified element in this tree.
pub fn create_subroot(&self, mount_point: Element, host_element: &HtmlEventTarget) -> Self {
let parent_information = ParentingInformation {
parent_root: self.0.clone(),
mount_element: mount_point,
};
Self::do_create_root(host_element, Some(parent_information))
}
/// Ensure the event described is handled on all subtrees
pub fn ensure_handled(&self, desc: &EventDescriptor) {
self.0.app_data.borrow_mut().ensure_handled(desc);
}
/// Run f with access to global Registry
#[inline]
pub fn with_listener_registry<R>(&self, f: impl FnOnce(&mut Registry) -> R) -> R {
f(&mut self.0.event_registry().borrow_mut())
}
pub fn brand_element(&self, el: &dyn EventGrating) {
el.set_subtree_id(self.0.subtree_id);
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/dom_bundle/bcomp.rs | packages/yew/src/dom_bundle/bcomp.rs | //! This module contains the bundle implementation of a virtual component [BComp].
use std::any::TypeId;
use std::borrow::Borrow;
use std::fmt;
use web_sys::Element;
use super::{BNode, BSubtree, DomSlot, DynamicDomSlot, Reconcilable, ReconcileTarget};
use crate::html::{AnyScope, Scoped};
use crate::virtual_dom::{Key, VComp};
/// A virtual component. Compare with [VComp].
pub(super) struct BComp {
type_id: TypeId,
scope: Box<dyn Scoped>,
/// An internal [`DomSlot`] passed around to track this components position. This
/// will dynamically adjust when a lifecycle changes the render state of this component.
own_position: DynamicDomSlot,
key: Option<Key>,
}
impl BComp {
/// Get the key of the underlying component
pub fn key(&self) -> Option<&Key> {
self.key.as_ref()
}
}
impl fmt::Debug for BComp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BComp")
.field("root", &self.scope.as_ref().render_state())
.finish()
}
}
impl ReconcileTarget for BComp {
fn detach(self, _root: &BSubtree, _parent: &Element, parent_to_detach: bool) {
self.scope.destroy_boxed(parent_to_detach);
}
fn shift(&self, next_parent: &Element, slot: DomSlot) -> DomSlot {
self.scope.shift_node(next_parent.clone(), slot);
self.own_position.to_position()
}
}
impl Reconcilable for VComp {
type Bundle = BComp;
fn attach(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
) -> (DomSlot, Self::Bundle) {
let VComp {
type_id,
mountable,
key,
..
} = self;
let (scope, internal_ref) = mountable.mount(root, parent_scope, parent.to_owned(), slot);
(
internal_ref.to_position(),
BComp {
type_id,
scope,
own_position: internal_ref,
key,
},
)
}
fn reconcile_node(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
bundle: &mut BNode,
) -> DomSlot {
match bundle {
// If the existing bundle is the same type, reuse it and update its properties
BNode::Comp(ref mut bcomp)
if self.type_id == bcomp.type_id && self.key == bcomp.key =>
{
self.reconcile(root, parent_scope, parent, slot, bcomp)
}
_ => self.replace(root, parent_scope, parent, slot, bundle),
}
}
fn reconcile(
self,
_root: &BSubtree,
_parent_scope: &AnyScope,
_parent: &Element,
slot: DomSlot,
bcomp: &mut Self::Bundle,
) -> DomSlot {
let VComp { mountable, key, .. } = self;
bcomp.key = key;
mountable.reuse(bcomp.scope.borrow(), slot);
bcomp.own_position.to_position()
}
}
#[cfg(feature = "hydration")]
mod feat_hydration {
use super::*;
use crate::dom_bundle::{Fragment, Hydratable};
impl Hydratable for VComp {
fn hydrate(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
fragment: &mut Fragment,
prev_next_sibling: &mut Option<DynamicDomSlot>,
) -> Self::Bundle {
let VComp {
type_id,
mountable,
key,
..
} = self;
let (scope, own_slot) = mountable.hydrate(
root.clone(),
parent_scope,
parent.clone(),
fragment,
prev_next_sibling,
);
BComp {
type_id,
scope,
own_position: own_slot,
key,
}
}
}
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
mod tests {
use gloo::utils::document;
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use web_sys::Element;
use super::*;
use crate::dom_bundle::Reconcilable;
use crate::virtual_dom::{Key, VChild, VNode};
use crate::{html, scheduler, Children, Component, Context, Html, Properties};
wasm_bindgen_test_configure!(run_in_browser);
struct Comp;
#[derive(Clone, PartialEq, Properties)]
struct Props {
#[prop_or_default]
field_1: u32,
#[prop_or_default]
field_2: u32,
}
impl Component for Comp {
type Message = ();
type Properties = Props;
fn create(_: &Context<Self>) -> Self {
Comp
}
fn update(&mut self, _ctx: &Context<Self>, _: Self::Message) -> bool {
unimplemented!();
}
fn view(&self, _ctx: &Context<Self>) -> Html {
html! { <div/> }
}
}
#[test]
fn update_loop() {
let (root, scope, parent) = setup_parent();
let comp = html! { <Comp></Comp> };
let (_, mut bundle) = comp.attach(&root, &scope, &parent, DomSlot::at_end());
scheduler::start_now();
for _ in 0..10000 {
let node = html! { <Comp></Comp> };
node.reconcile_node(&root, &scope, &parent, DomSlot::at_end(), &mut bundle);
scheduler::start_now();
}
}
#[test]
fn set_properties_to_component() {
html! {
<Comp />
};
html! {
<Comp field_1=1 />
};
html! {
<Comp field_2=2 />
};
html! {
<Comp field_1=1 field_2=2 />
};
let props = Props {
field_1: 1,
field_2: 1,
};
html! {
<Comp ..props />
};
}
#[test]
fn set_component_key() {
let test_key: Key = "test".to_string().into();
let check_key = |vnode: VNode| {
assert_eq!(vnode.key(), Some(&test_key));
};
let props = Props {
field_1: 1,
field_2: 1,
};
let props_2 = props.clone();
check_key(html! { <Comp key={test_key.clone()} /> });
check_key(html! { <Comp key={test_key.clone()} field_1=1 /> });
check_key(html! { <Comp field_1=1 key={test_key.clone()} /> });
check_key(html! { <Comp key={test_key.clone()} ..props /> });
check_key(html! { <Comp key={test_key.clone()} ..props_2 /> });
}
#[test]
fn vchild_partialeq() {
let vchild1: VChild<Comp> = VChild::new(
Props {
field_1: 1,
field_2: 1,
},
None,
);
let vchild2: VChild<Comp> = VChild::new(
Props {
field_1: 1,
field_2: 1,
},
None,
);
let vchild3: VChild<Comp> = VChild::new(
Props {
field_1: 2,
field_2: 2,
},
None,
);
assert_eq!(vchild1, vchild2);
assert_ne!(vchild1, vchild3);
assert_ne!(vchild2, vchild3);
}
#[derive(Clone, Properties, PartialEq)]
pub struct ListProps {
pub children: Children,
}
pub struct List;
impl Component for List {
type Message = ();
type Properties = ListProps;
fn create(_: &Context<Self>) -> Self {
Self
}
fn update(&mut self, _ctx: &Context<Self>, _: Self::Message) -> bool {
unimplemented!();
}
fn changed(&mut self, _ctx: &Context<Self>, _old_props: &Self::Properties) -> bool {
unimplemented!();
}
fn view(&self, ctx: &Context<Self>) -> Html {
let item_iter = ctx
.props()
.children
.iter()
.map(|item| html! {<li>{ item }</li>});
html! {
<ul>{ for item_iter }</ul>
}
}
}
fn setup_parent() -> (BSubtree, AnyScope, Element) {
let scope = AnyScope::test();
let parent = document().create_element("div").unwrap();
let root = BSubtree::create_root(&parent);
document().body().unwrap().append_child(&parent).unwrap();
(root, scope, parent)
}
fn get_html(node: Html, root: &BSubtree, scope: &AnyScope, parent: &Element) -> String {
// clear parent
parent.set_inner_html("");
node.attach(root, scope, parent, DomSlot::at_end());
scheduler::start_now();
parent.inner_html()
}
#[test]
fn all_ways_of_passing_children_work() {
let (root, scope, parent) = setup_parent();
let children: Vec<_> = vec!["a", "b", "c"]
.drain(..)
.map(|text| html! {<span>{ text }</span>})
.collect();
let children_renderer = Children::new(children.clone());
let expected_html = "\
<ul><li><span>a</span></li><li><span>b</span></li><li><span>c</span></li></ul>";
let prop_method = html! {
<List children={children_renderer.clone()} />
};
assert_eq!(get_html(prop_method, &root, &scope, &parent), expected_html);
let children_renderer_method = html! {
<List>
{ children_renderer }
</List>
};
assert_eq!(
get_html(children_renderer_method, &root, &scope, &parent),
expected_html
);
let direct_method = html! {
<List>
{ children.clone() }
</List>
};
assert_eq!(
get_html(direct_method, &root, &scope, &parent),
expected_html
);
let for_method = html! {
<List>
{ for children }
</List>
};
assert_eq!(get_html(for_method, &root, &scope, &parent), expected_html);
}
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
mod layout_tests {
extern crate self as yew;
use std::marker::PhantomData;
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use crate::tests::layout_tests::{diff_layouts, TestLayout};
use crate::{html, Children, Component, Context, Html, Properties};
wasm_bindgen_test_configure!(run_in_browser);
struct Comp<T> {
_marker: PhantomData<T>,
}
#[derive(Properties, Clone, PartialEq)]
struct CompProps {
#[prop_or_default]
children: Children,
}
impl<T: 'static> Component for Comp<T> {
type Message = ();
type Properties = CompProps;
fn create(_: &Context<Self>) -> Self {
Comp {
_marker: PhantomData::default(),
}
}
fn update(&mut self, _ctx: &Context<Self>, _: Self::Message) -> bool {
unimplemented!();
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<>{ ctx.props().children.clone() }</>
}
}
}
struct A;
struct B;
#[test]
fn diff() {
let layout1 = TestLayout {
name: "1",
node: html! {
<Comp<A>>
<Comp<B>></Comp<B>>
{"C"}
</Comp<A>>
},
expected: "C",
};
let layout2 = TestLayout {
name: "2",
node: html! {
<Comp<A>>
{"A"}
</Comp<A>>
},
expected: "A",
};
let layout3 = TestLayout {
name: "3",
node: html! {
<Comp<B>>
<Comp<A>></Comp<A>>
{"B"}
</Comp<B>>
},
expected: "B",
};
let layout4 = TestLayout {
name: "4",
node: html! {
<Comp<B>>
<Comp<A>>{"A"}</Comp<A>>
{"B"}
</Comp<B>>
},
expected: "AB",
};
let layout5 = TestLayout {
name: "5",
node: html! {
<Comp<B>>
<>
<Comp<A>>
{"A"}
</Comp<A>>
</>
{"B"}
</Comp<B>>
},
expected: "AB",
};
let layout6 = TestLayout {
name: "6",
node: html! {
<Comp<B>>
<>
<Comp<A>>
{"A"}
</Comp<A>>
{"B"}
</>
{"C"}
</Comp<B>>
},
expected: "ABC",
};
let layout7 = TestLayout {
name: "7",
node: html! {
<Comp<B>>
<>
<Comp<A>>
{"A"}
</Comp<A>>
<Comp<A>>
{"B"}
</Comp<A>>
</>
{"C"}
</Comp<B>>
},
expected: "ABC",
};
let layout8 = TestLayout {
name: "8",
node: html! {
<Comp<B>>
<>
<Comp<A>>
{"A"}
</Comp<A>>
<Comp<A>>
<Comp<A>>
{"B"}
</Comp<A>>
</Comp<A>>
</>
{"C"}
</Comp<B>>
},
expected: "ABC",
};
let layout9 = TestLayout {
name: "9",
node: html! {
<Comp<B>>
<>
<>
{"A"}
</>
<Comp<A>>
<Comp<A>>
{"B"}
</Comp<A>>
</Comp<A>>
</>
{"C"}
</Comp<B>>
},
expected: "ABC",
};
let layout10 = TestLayout {
name: "10",
node: html! {
<Comp<B>>
<>
<Comp<A>>
<Comp<A>>
{"A"}
</Comp<A>>
</Comp<A>>
<>
{"B"}
</>
</>
{"C"}
</Comp<B>>
},
expected: "ABC",
};
let layout11 = TestLayout {
name: "11",
node: html! {
<Comp<B>>
<>
<>
<Comp<A>>
<Comp<A>>
{"A"}
</Comp<A>>
{"B"}
</Comp<A>>
</>
</>
{"C"}
</Comp<B>>
},
expected: "ABC",
};
let layout12 = TestLayout {
name: "12",
node: html! {
<Comp<B>>
<>
<Comp<A>></Comp<A>>
<>
<Comp<A>>
<>
<Comp<A>>
{"A"}
</Comp<A>>
<></>
<Comp<A>>
<Comp<A>></Comp<A>>
<></>
{"B"}
<></>
<Comp<A>></Comp<A>>
</Comp<A>>
</>
</Comp<A>>
<></>
</>
<Comp<A>></Comp<A>>
</>
{"C"}
<Comp<A>></Comp<A>>
<></>
</Comp<B>>
},
expected: "ABC",
};
diff_layouts(vec![
layout1, layout2, layout3, layout4, layout5, layout6, layout7, layout8, layout9,
layout10, layout11, layout12,
]);
}
#[test]
fn component_with_children() {
#[derive(Properties, PartialEq)]
struct Props {
children: Children,
}
struct ComponentWithChildren;
impl Component for ComponentWithChildren {
type Message = ();
type Properties = Props;
fn create(_ctx: &Context<Self>) -> Self {
Self
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<ul>
{ for ctx.props().children.iter().map(|child| html! { <li>{ child }</li> }) }
</ul>
}
}
}
let layout = TestLayout {
name: "13",
node: html! {
<ComponentWithChildren>
if true {
<span>{ "hello" }</span>
<span>{ "world" }</span>
} else {
<span>{ "goodbye" }</span>
<span>{ "world" }</span>
}
</ComponentWithChildren>
},
expected: "<ul><li><span>hello</span><span>world</span></li></ul>",
};
diff_layouts(vec![layout]);
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/dom_bundle/utils.rs | packages/yew/src/dom_bundle/utils.rs | #[cfg(all(test, target_arch = "wasm32", verbose_tests))]
macro_rules! test_log {
($fmt:literal, $($arg:expr),* $(,)?) => {
::wasm_bindgen_test::console_log!(concat!("\t ", $fmt), $($arg),*);
};
}
#[cfg(not(all(test, target_arch = "wasm32", verbose_tests)))]
macro_rules! test_log {
($fmt:literal, $($arg:expr),* $(,)?) => {
// Only type-check the format expression, do not run any side effects
let _ = || { std::format_args!(concat!("\t ", $fmt), $($arg),*); };
};
}
/// Log an operation during tests for debugging purposes
/// Set RUSTFLAGS="--cfg verbose_tests" environment variable to activate.
pub(super) use test_log;
#[cfg(feature = "hydration")]
mod feat_hydration {
use std::borrow::Cow;
use wasm_bindgen::JsCast;
use web_sys::{Element, Node};
pub(in crate::dom_bundle) fn node_type_str(node: &Node) -> Cow<'static, str> {
match node.node_type() {
Node::ELEMENT_NODE => {
let tag = node
.dyn_ref::<Element>()
.map(|m| m.tag_name().to_lowercase())
.unwrap_or_else(|| "unknown".to_owned());
format!("{tag} element node").into()
}
Node::ATTRIBUTE_NODE => "attribute node".into(),
Node::TEXT_NODE => "text node".into(),
Node::CDATA_SECTION_NODE => "cdata section node".into(),
Node::ENTITY_REFERENCE_NODE => "entity reference node".into(),
Node::ENTITY_NODE => "entity node".into(),
Node::PROCESSING_INSTRUCTION_NODE => "processing instruction node".into(),
Node::COMMENT_NODE => "comment node".into(),
Node::DOCUMENT_NODE => "document node".into(),
Node::DOCUMENT_TYPE_NODE => "document type node".into(),
Node::DOCUMENT_FRAGMENT_NODE => "document fragment node".into(),
Node::NOTATION_NODE => "notation node".into(),
_ => "unknown node".into(),
}
}
}
#[cfg(feature = "hydration")]
pub(super) use feat_hydration::*;
#[cfg(test)]
// this is needed because clippy doesn't like the import not being used
#[allow(unused_imports)]
pub(super) use tests::*;
#[cfg(test)]
mod tests {
#![allow(dead_code)]
use gloo::utils::document;
use web_sys::Element;
use crate::dom_bundle::{BSubtree, DomSlot};
use crate::html::AnyScope;
use crate::virtual_dom::vtag::SVG_NAMESPACE;
pub fn setup_parent() -> (BSubtree, AnyScope, Element) {
let scope = AnyScope::test();
let parent = document().create_element("div").unwrap();
let root = BSubtree::create_root(&parent);
document().body().unwrap().append_child(&parent).unwrap();
(root, scope, parent)
}
pub fn setup_parent_svg() -> (BSubtree, AnyScope, Element) {
let scope = AnyScope::test();
let parent = document()
.create_element_ns(Some(SVG_NAMESPACE), "svg")
.unwrap();
let root = BSubtree::create_root(&parent);
document().body().unwrap().append_child(&parent).unwrap();
(root, scope, parent)
}
pub const SIBLING_CONTENT: &str = "END";
pub(crate) fn setup_parent_and_sibling() -> (BSubtree, AnyScope, Element, DomSlot) {
let scope = AnyScope::test();
let parent = document().create_element("div").unwrap();
let root = BSubtree::create_root(&parent);
document().body().unwrap().append_child(&parent).unwrap();
let end = document().create_text_node(SIBLING_CONTENT);
parent.append_child(&end).unwrap();
let sibling = DomSlot::at(end.into());
(root, scope, parent, sibling)
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/dom_bundle/mod.rs | packages/yew/src/dom_bundle/mod.rs | //! Realizing a virtual dom on the actual DOM
//!
//! A bundle, borrowed from the mathematical meaning, is any structure over some base space.
//! In our case, the base space is the virtual dom we're trying to render.
//! In order to efficiently implement updates, and diffing, additional information has to be
//! kept around. This information is carried in the bundle.
use web_sys::Element;
use crate::html::AnyScope;
use crate::virtual_dom::VNode;
mod bcomp;
mod blist;
mod bnode;
mod bportal;
mod braw;
mod bsuspense;
mod btag;
mod btext;
mod position;
mod subtree_root;
mod traits;
mod utils;
use bcomp::BComp;
use blist::BList;
use bnode::BNode;
use bportal::BPortal;
use braw::BRaw;
use bsuspense::BSuspense;
use btag::{BTag, Registry};
use btext::BText;
pub(crate) use position::{DomSlot, DynamicDomSlot};
use subtree_root::EventDescriptor;
pub use subtree_root::{set_event_bubbling, BSubtree};
use traits::{Reconcilable, ReconcileTarget};
use utils::test_log;
/// A Bundle.
///
/// Each component holds a bundle that represents a realised layout, designated by a [VNode].
///
/// This is not to be confused with [BComp], which represents a component in the position of a
/// bundle layout.
#[derive(Debug)]
pub(crate) struct Bundle(BNode);
impl Bundle {
/// Creates a new bundle.
pub const fn new() -> Self {
Self(BNode::List(BList::new()))
}
/// Shifts the bundle into a different position.
pub fn shift(&self, next_parent: &Element, slot: DomSlot) {
self.0.shift(next_parent, slot);
}
/// Applies a virtual dom layout to current bundle.
pub fn reconcile(
&mut self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
next_node: VNode,
) -> DomSlot {
next_node.reconcile_node(root, parent_scope, parent, slot, &mut self.0)
}
/// Detaches current bundle.
pub fn detach(self, root: &BSubtree, parent: &Element, parent_to_detach: bool) {
self.0.detach(root, parent, parent_to_detach);
}
}
#[cfg(feature = "hydration")]
#[path = "."]
mod feat_hydration {
pub(super) use super::traits::Hydratable;
pub(super) use super::utils::node_type_str;
#[path = "./fragment.rs"]
mod fragment;
pub(crate) use fragment::Fragment;
use super::*;
impl Bundle {
/// Creates a bundle by hydrating a virtual dom layout.
pub fn hydrate(
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
fragment: &mut Fragment,
node: VNode,
previous_next_sibling: &mut Option<DynamicDomSlot>,
) -> Self {
let bundle = node.hydrate(root, parent_scope, parent, fragment, previous_next_sibling);
Self(bundle)
}
}
}
#[cfg(feature = "hydration")]
pub(crate) use feat_hydration::*;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/dom_bundle/bnode.rs | packages/yew/src/dom_bundle/bnode.rs | //! This module contains the bundle version of an abstract node [BNode]
use std::fmt;
use web_sys::{Element, Node};
use super::{BComp, BList, BPortal, BRaw, BSubtree, BSuspense, BTag, BText, DomSlot};
use crate::dom_bundle::{Reconcilable, ReconcileTarget};
use crate::html::AnyScope;
use crate::utils::RcExt;
use crate::virtual_dom::{Key, VNode};
/// The bundle implementation to [VNode].
pub(super) enum BNode {
/// A bind between `VTag` and `Element`.
Tag(Box<BTag>),
/// A bind between `VText` and `TextNode`.
Text(BText),
/// A bind between `VComp` and `Element`.
Comp(BComp),
/// A holder for a list of other nodes.
List(BList),
/// A portal to another part of the document
Portal(BPortal),
/// A holder for any `Node` (necessary for replacing node).
Ref(Node),
/// A suspendible document fragment.
Suspense(Box<BSuspense>),
/// A raw HTML string, represented by [`AttrValue`](crate::AttrValue).
Raw(BRaw),
}
impl BNode {
/// Get the key of the underlying node
pub fn key(&self) -> Option<&Key> {
match self {
Self::Comp(bsusp) => bsusp.key(),
Self::List(blist) => blist.key(),
Self::Ref(_) => None,
Self::Tag(btag) => btag.key(),
Self::Text(_) => None,
Self::Portal(bportal) => bportal.key(),
Self::Suspense(bsusp) => bsusp.key(),
Self::Raw(_) => None,
}
}
}
impl ReconcileTarget for BNode {
/// Remove VNode from parent.
fn detach(self, root: &BSubtree, parent: &Element, parent_to_detach: bool) {
match self {
Self::Tag(vtag) => vtag.detach(root, parent, parent_to_detach),
Self::Text(btext) => btext.detach(root, parent, parent_to_detach),
Self::Comp(bsusp) => bsusp.detach(root, parent, parent_to_detach),
Self::List(blist) => blist.detach(root, parent, parent_to_detach),
Self::Ref(ref node) => {
// Always remove user-defined nodes to clear possible parent references of them
if parent.remove_child(node).is_err() {
tracing::warn!("Node not found to remove VRef");
}
}
Self::Portal(bportal) => bportal.detach(root, parent, parent_to_detach),
Self::Suspense(bsusp) => bsusp.detach(root, parent, parent_to_detach),
Self::Raw(raw) => raw.detach(root, parent, parent_to_detach),
}
}
fn shift(&self, next_parent: &Element, slot: DomSlot) -> DomSlot {
match self {
Self::Tag(ref vtag) => vtag.shift(next_parent, slot),
Self::Text(ref btext) => btext.shift(next_parent, slot),
Self::Comp(ref bsusp) => bsusp.shift(next_parent, slot),
Self::List(ref vlist) => vlist.shift(next_parent, slot),
Self::Ref(ref node) => {
slot.insert(next_parent, node);
DomSlot::at(node.clone())
}
Self::Portal(ref vportal) => vportal.shift(next_parent, slot),
Self::Suspense(ref vsuspense) => vsuspense.shift(next_parent, slot),
Self::Raw(ref braw) => braw.shift(next_parent, slot),
}
}
}
impl Reconcilable for VNode {
type Bundle = BNode;
fn attach(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
) -> (DomSlot, Self::Bundle) {
match self {
VNode::VTag(vtag) => {
let (node_ref, tag) =
RcExt::unwrap_or_clone(vtag).attach(root, parent_scope, parent, slot);
(node_ref, tag.into())
}
VNode::VText(vtext) => {
let (node_ref, text) = vtext.attach(root, parent_scope, parent, slot);
(node_ref, text.into())
}
VNode::VComp(vcomp) => {
let (node_ref, comp) =
RcExt::unwrap_or_clone(vcomp).attach(root, parent_scope, parent, slot);
(node_ref, comp.into())
}
VNode::VList(vlist) => {
let (node_ref, list) =
RcExt::unwrap_or_clone(vlist).attach(root, parent_scope, parent, slot);
(node_ref, list.into())
}
VNode::VRef(node) => {
slot.insert(parent, &node);
(DomSlot::at(node.clone()), BNode::Ref(node))
}
VNode::VPortal(vportal) => {
let (node_ref, portal) =
RcExt::unwrap_or_clone(vportal).attach(root, parent_scope, parent, slot);
(node_ref, portal.into())
}
VNode::VSuspense(vsuspsense) => {
let (node_ref, suspsense) =
RcExt::unwrap_or_clone(vsuspsense).attach(root, parent_scope, parent, slot);
(node_ref, suspsense.into())
}
VNode::VRaw(vraw) => {
let (node_ref, raw) = vraw.attach(root, parent_scope, parent, slot);
(node_ref, raw.into())
}
}
}
fn reconcile_node(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
bundle: &mut BNode,
) -> DomSlot {
self.reconcile(root, parent_scope, parent, slot, bundle)
}
fn reconcile(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
bundle: &mut BNode,
) -> DomSlot {
match self {
VNode::VTag(vtag) => RcExt::unwrap_or_clone(vtag).reconcile_node(
root,
parent_scope,
parent,
slot,
bundle,
),
VNode::VText(vtext) => vtext.reconcile_node(root, parent_scope, parent, slot, bundle),
VNode::VComp(vcomp) => RcExt::unwrap_or_clone(vcomp).reconcile_node(
root,
parent_scope,
parent,
slot,
bundle,
),
VNode::VList(vlist) => RcExt::unwrap_or_clone(vlist).reconcile_node(
root,
parent_scope,
parent,
slot,
bundle,
),
VNode::VRef(node) => match bundle {
BNode::Ref(ref n) if &node == n => DomSlot::at(node),
_ => VNode::VRef(node).replace(root, parent_scope, parent, slot, bundle),
},
VNode::VPortal(vportal) => RcExt::unwrap_or_clone(vportal).reconcile_node(
root,
parent_scope,
parent,
slot,
bundle,
),
VNode::VSuspense(vsuspsense) => RcExt::unwrap_or_clone(vsuspsense).reconcile_node(
root,
parent_scope,
parent,
slot,
bundle,
),
VNode::VRaw(vraw) => vraw.reconcile_node(root, parent_scope, parent, slot, bundle),
}
}
}
impl From<BText> for BNode {
#[inline]
fn from(btext: BText) -> Self {
Self::Text(btext)
}
}
impl From<BList> for BNode {
#[inline]
fn from(blist: BList) -> Self {
Self::List(blist)
}
}
impl From<BTag> for BNode {
#[inline]
fn from(btag: BTag) -> Self {
Self::Tag(Box::new(btag))
}
}
impl From<BComp> for BNode {
#[inline]
fn from(bcomp: BComp) -> Self {
Self::Comp(bcomp)
}
}
impl From<BPortal> for BNode {
#[inline]
fn from(bportal: BPortal) -> Self {
Self::Portal(bportal)
}
}
impl From<BSuspense> for BNode {
#[inline]
fn from(bsusp: BSuspense) -> Self {
Self::Suspense(Box::new(bsusp))
}
}
impl From<BRaw> for BNode {
#[inline]
fn from(braw: BRaw) -> Self {
Self::Raw(braw)
}
}
impl fmt::Debug for BNode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::Tag(ref vtag) => vtag.fmt(f),
Self::Text(ref btext) => btext.fmt(f),
Self::Comp(ref bsusp) => bsusp.fmt(f),
Self::List(ref vlist) => vlist.fmt(f),
Self::Ref(ref vref) => write!(f, "VRef ( \"{}\" )", crate::utils::print_node(vref)),
Self::Portal(ref vportal) => vportal.fmt(f),
Self::Suspense(ref bsusp) => bsusp.fmt(f),
Self::Raw(ref braw) => braw.fmt(f),
}
}
}
#[cfg(feature = "hydration")]
mod feat_hydration {
use super::*;
use crate::dom_bundle::{DynamicDomSlot, Fragment, Hydratable};
impl Hydratable for VNode {
fn hydrate(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
fragment: &mut Fragment,
prev_next_sibling: &mut Option<DynamicDomSlot>,
) -> Self::Bundle {
match self {
VNode::VTag(vtag) => RcExt::unwrap_or_clone(vtag)
.hydrate(root, parent_scope, parent, fragment, prev_next_sibling)
.into(),
VNode::VText(vtext) => vtext
.hydrate(root, parent_scope, parent, fragment, prev_next_sibling)
.into(),
VNode::VComp(vcomp) => RcExt::unwrap_or_clone(vcomp)
.hydrate(root, parent_scope, parent, fragment, prev_next_sibling)
.into(),
VNode::VList(vlist) => RcExt::unwrap_or_clone(vlist)
.hydrate(root, parent_scope, parent, fragment, prev_next_sibling)
.into(),
// You cannot hydrate a VRef.
VNode::VRef(_) => {
panic!(
"VRef is not hydratable. Try moving it to a component mounted after an \
effect."
)
}
// You cannot hydrate a VPortal.
VNode::VPortal(_) => {
panic!(
"VPortal is not hydratable. Try creating your portal by delaying it with \
use_effect."
)
}
VNode::VSuspense(vsuspense) => RcExt::unwrap_or_clone(vsuspense)
.hydrate(root, parent_scope, parent, fragment, prev_next_sibling)
.into(),
VNode::VRaw(vraw) => vraw
.hydrate(root, parent_scope, parent, fragment, prev_next_sibling)
.into(),
}
}
}
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
mod layout_tests {
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use super::*;
use crate::tests::layout_tests::{diff_layouts, TestLayout};
wasm_bindgen_test_configure!(run_in_browser);
#[test]
fn diff() {
let document = gloo::utils::document();
let vref_node_1 = VNode::VRef(document.create_element("i").unwrap().into());
let vref_node_2 = VNode::VRef(document.create_element("b").unwrap().into());
let layout1 = TestLayout {
name: "1",
node: vref_node_1,
expected: "<i></i>",
};
let layout2 = TestLayout {
name: "2",
node: vref_node_2,
expected: "<b></b>",
};
diff_layouts(vec![layout1, layout2]);
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/dom_bundle/position.rs | packages/yew/src/dom_bundle/position.rs | //! Structs for keeping track where in the DOM a node belongs
use std::cell::RefCell;
use std::rc::Rc;
use web_sys::{Element, Node};
/// A position in the list of children of an implicit parent [`Element`].
///
/// This can either be in front of a `DomSlot::at(next_sibling)`, at the end of the list with
/// `DomSlot::at_end()`, or a dynamic position in the list with [`DynamicDomSlot::to_position`].
#[derive(Clone)]
pub(crate) struct DomSlot {
variant: DomSlotVariant,
}
#[derive(Clone)]
enum DomSlotVariant {
Node(Option<Node>),
Chained(DynamicDomSlot),
}
/// A dynamic dom slot can be reassigned. This change is also seen by the [`DomSlot`] from
/// [`Self::to_position`] before the reassignment took place.
#[derive(Clone)]
pub(crate) struct DynamicDomSlot {
target: Rc<RefCell<DomSlot>>,
}
impl std::fmt::Debug for DomSlot {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.with_next_sibling(|n| {
let formatted_node = match n {
None => None,
Some(n) if trap_impl::is_trap(n) => Some("<not yet initialized />".to_string()),
Some(n) => Some(crate::utils::print_node(n)),
};
write!(f, "DomSlot {{ next_sibling: {formatted_node:?} }}")
})
}
}
impl std::fmt::Debug for DynamicDomSlot {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:#?}", *self.target.borrow())
}
}
mod trap_impl {
use super::Node;
#[cfg(debug_assertions)]
thread_local! {
// A special marker element that should not be referenced
static TRAP: Node = gloo::utils::document().create_element("div").unwrap().into();
}
/// Get a "trap" node, or None if compiled without debug_assertions
#[cfg(feature = "hydration")]
pub fn get_trap_node() -> Option<Node> {
#[cfg(debug_assertions)]
{
TRAP.with(|trap| Some(trap.clone()))
}
#[cfg(not(debug_assertions))]
{
None
}
}
#[inline]
pub fn is_trap(node: &Node) -> bool {
#[cfg(debug_assertions)]
{
TRAP.with(|trap| node == trap)
}
#[cfg(not(debug_assertions))]
{
// When not running with debug_assertions, there is no trap node
let _ = node;
false
}
}
}
impl DomSlot {
/// Denotes the position just before the given node in its parent's list of children.
pub fn at(next_sibling: Node) -> Self {
Self::create(Some(next_sibling))
}
/// Denotes the position at the end of a list of children. The parent is implicit.
pub fn at_end() -> Self {
Self::create(None)
}
pub fn create(next_sibling: Option<Node>) -> Self {
Self {
variant: DomSlotVariant::Node(next_sibling),
}
}
/// A new "placeholder" [DomSlot] that should not be used to insert nodes
#[inline]
#[cfg(feature = "hydration")]
pub fn new_debug_trapped() -> Self {
Self::create(trap_impl::get_trap_node())
}
/// Get the [Node] that comes just after the position, or `None` if this denotes the position at
/// the end
fn with_next_sibling_check_trap<R>(&self, f: impl FnOnce(Option<&Node>) -> R) -> R {
let checkedf = |node: Option<&Node>| {
// MSRV 1.82 could rewrite this with `is_none_or`
let is_trapped = match node {
None => false,
Some(node) => trap_impl::is_trap(node),
};
assert!(
!is_trapped,
"Should not use a trapped DomSlot. Please report this as an internal bug in yew."
);
f(node)
};
self.with_next_sibling(checkedf)
}
fn with_next_sibling<R>(&self, f: impl FnOnce(Option<&Node>) -> R) -> R {
match &self.variant {
DomSlotVariant::Node(ref n) => f(n.as_ref()),
DomSlotVariant::Chained(ref chain) => chain.with_next_sibling(f),
}
}
/// Insert a [Node] at the position denoted by this slot. `parent` must be the actual parent
/// element of the children that this slot is implicitly a part of.
pub(super) fn insert(&self, parent: &Element, node: &Node) {
self.with_next_sibling_check_trap(|next_sibling: Option<&Node>| {
parent
.insert_before(node, next_sibling)
.unwrap_or_else(|err| {
let msg = if next_sibling.is_some() {
"failed to insert node before next sibling"
} else {
"failed to append child"
};
// Log normally, so we can inspect the nodes in console
gloo::console::error!(msg, err, parent, next_sibling, node);
// Log via tracing for consistency
tracing::error!(msg);
// Panic to short-curcuit and fail
panic!("{}", msg)
});
});
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
fn get(&self) -> Option<Node> {
self.with_next_sibling(|n| n.cloned())
}
}
impl DynamicDomSlot {
/// Create a dynamic dom slot that initially represents ("targets") the same slot as the
/// argument.
pub fn new(initial_position: DomSlot) -> Self {
Self {
target: Rc::new(RefCell::new(initial_position)),
}
}
#[cfg(feature = "hydration")]
pub fn new_debug_trapped() -> Self {
Self::new(DomSlot::new_debug_trapped())
}
/// Move out of self, leaving behind a trapped slot. `self` should not be used afterwards.
/// Used during the transition from a hydrating to a rendered component to move state between
/// enum variants.
#[cfg(feature = "hydration")]
pub fn take(&mut self) -> Self {
std::mem::replace(self, Self::new(DomSlot::new_debug_trapped()))
}
/// Change the [`DomSlot`] that is targeted. Subsequently, this will behave as if `self` was
/// created from the passed DomSlot in the first place.
pub fn reassign(&self, next_position: DomSlot) {
// TODO: is not defensive against accidental reference loops
*self.target.borrow_mut() = next_position;
}
/// Get a [`DomSlot`] that gets automatically updated when `self` gets reassigned. All such
/// slots are equivalent to each other and point to the same position.
pub fn to_position(&self) -> DomSlot {
DomSlot {
variant: DomSlotVariant::Chained(self.clone()),
}
}
fn with_next_sibling<R>(&self, f: impl FnOnce(Option<&Node>) -> R) -> R {
// we use an iterative approach to traverse a possible long chain for references
// see for example issue #3043 why a recursive call is impossible for large lists in vdom
// TODO: there could be some data structure that performs better here. E.g. a balanced tree
// with parent pointers come to mind, but they are a bit fiddly to implement in rust
let mut this = self.target.clone();
loop {
// v------- borrow lives for this match expression
let next_this = match &this.borrow().variant {
DomSlotVariant::Node(ref n) => break f(n.as_ref()),
// We clone an Rc here temporarily, so that we don't have to consume stack
// space. The alternative would be to keep the
// `Ref<'_, DomSlot>` above in some temporary buffer
DomSlotVariant::Chained(ref chain) => chain.target.clone(),
};
this = next_this;
}
}
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
mod layout_tests {
use gloo::utils::document;
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use super::*;
wasm_bindgen_test_configure!(run_in_browser);
#[test]
fn new_at_and_get() {
let node = document().create_element("p").unwrap();
let position = DomSlot::at(node.clone().into());
assert_eq!(
position.get().unwrap(),
node.clone().into(),
"expected the DomSlot to be at {node:#?}"
);
}
#[test]
fn new_at_end_and_get() {
let position = DomSlot::at_end();
assert!(
position.get().is_none(),
"expected the DomSlot to not have a next sibling"
);
}
#[test]
fn get_through_dynamic() {
let original = DomSlot::at(document().create_element("p").unwrap().into());
let target = DynamicDomSlot::new(original.clone());
assert_eq!(
target.to_position().get(),
original.get(),
"expected {target:#?} to point to the same position as {original:#?}"
);
}
#[test]
fn get_after_reassign() {
let target = DynamicDomSlot::new(DomSlot::at_end());
let target_pos = target.to_position();
// We reassign *after* we called `to_position` here to be strict in the test
let replacement = DomSlot::at(document().create_element("p").unwrap().into());
target.reassign(replacement.clone());
assert_eq!(
target_pos.get(),
replacement.get(),
"expected {target:#?} to point to the same position as {replacement:#?}"
);
}
#[test]
fn get_chain_after_reassign() {
let middleman = DynamicDomSlot::new(DomSlot::at_end());
let target = DynamicDomSlot::new(middleman.to_position());
let target_pos = target.to_position();
assert!(
target.to_position().get().is_none(),
"should not yet point to a node"
);
// Now reassign the middle man, but get the node from `target`
let replacement = DomSlot::at(document().create_element("p").unwrap().into());
middleman.reassign(replacement.clone());
assert_eq!(
target_pos.get(),
replacement.get(),
"expected {target:#?} to point to the same position as {replacement:#?}"
);
}
#[test]
fn debug_printing() {
// basic tests that these don't panic. We don't enforce any specific format.
println!("At end: {:?}", DomSlot::at_end());
println!("Trapped: {:?}", DomSlot::new_debug_trapped());
println!(
"At element: {:?}",
DomSlot::at(document().create_element("p").unwrap().into())
);
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/dom_bundle/traits.rs | packages/yew/src/dom_bundle/traits.rs | use web_sys::Element;
use super::{BNode, BSubtree, DomSlot};
use crate::html::AnyScope;
/// A Reconcile Target.
///
/// When a [Reconcilable] is attached, a reconcile target is created to store additional
/// information.
pub(super) trait ReconcileTarget {
/// Remove self from parent.
///
/// Parent to detach is `true` if the parent element will also be detached.
fn detach(self, root: &BSubtree, parent: &Element, parent_to_detach: bool);
/// Move elements from one parent to another parent.
/// This is for example used by `VSuspense` to preserve component state without detaching
/// (which destroys component state).
fn shift(&self, next_parent: &Element, slot: DomSlot) -> DomSlot;
}
/// This trait provides features to update a tree by calculating a difference against another tree.
pub(super) trait Reconcilable {
type Bundle: ReconcileTarget;
/// Attach a virtual node to the DOM tree.
///
/// Parameters:
/// - `root`: bundle of the subtree root
/// - `parent_scope`: the parent `Scope` used for passing messages to the parent `Component`.
/// - `parent`: the parent node in the DOM.
/// - `slot`: to find where to put the node.
///
/// Returns a reference to the newly inserted element.
/// The [`DomSlot`] points the first element (if there are multiple nodes created),
/// or is the passed in `slot` if there are no element is created.
fn attach(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
) -> (DomSlot, Self::Bundle);
/// Scoped diff apply to other tree.
///
/// Virtual rendering for the node. It uses parent node and existing
/// children (virtual and DOM) to check the difference and apply patches to
/// the actual DOM representation.
///
/// Parameters:
/// - `parent_scope`: the parent `Scope` used for passing messages to the parent `Component`.
/// - `parent`: the parent node in the DOM.
/// - `slot`: the slot in `parent`'s children where to put the node.
/// - `bundle`: the node that this node will be replacing in the DOM. This method will remove
/// the `bundle` from the `parent` if it is of the wrong kind, and otherwise reuse it.
///
/// Returns a reference to the newly inserted element.
fn reconcile_node(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
bundle: &mut BNode,
) -> DomSlot;
fn reconcile(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
bundle: &mut Self::Bundle,
) -> DomSlot;
/// Replace an existing bundle by attaching self and detaching the existing one
fn replace(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
bundle: &mut BNode,
) -> DomSlot
where
Self: Sized,
Self::Bundle: Into<BNode>,
{
let (self_ref, self_) = self.attach(root, parent_scope, parent, slot);
let ancestor = std::mem::replace(bundle, self_.into());
ancestor.detach(root, parent, false);
self_ref
}
}
#[cfg(feature = "hydration")]
mod feat_hydration {
use super::*;
use crate::dom_bundle::{DynamicDomSlot, Fragment};
pub(in crate::dom_bundle) trait Hydratable: Reconcilable {
/// hydrates current tree.
///
/// Returns a reference to the first node of the hydrated tree.
///
/// # Important
///
/// DOM tree is hydrated from top to bottom. This is different than [`Reconcilable`].
fn hydrate(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
fragment: &mut Fragment,
// We hydrate in document order, but need to know the "next sibling" in each component
// to shift elements. (blame Web API for having `Node.insertBefore` but no
// `Node.insertAfter`) Hence, we pass an optional argument to inform of the
// new hydrated node's position. This should end up assigning the same
// position that would have been returned from `Self::attach` on creation.
prev_next_sibling: &mut Option<DynamicDomSlot>,
) -> Self::Bundle;
}
}
#[cfg(feature = "hydration")]
pub(in crate::dom_bundle) use feat_hydration::*;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/dom_bundle/braw.rs | packages/yew/src/dom_bundle/braw.rs | use wasm_bindgen::JsCast;
use web_sys::{Element, Node};
use super::{BNode, BSubtree, DomSlot, Reconcilable, ReconcileTarget};
use crate::html::AnyScope;
use crate::virtual_dom::vtag::{MATHML_NAMESPACE, SVG_NAMESPACE};
use crate::virtual_dom::VRaw;
use crate::AttrValue;
#[derive(Debug)]
pub struct BRaw {
reference: Option<Node>,
children_count: usize,
html: AttrValue,
}
impl BRaw {
fn create_elements(html: &str, parent_namespace: Option<&str>) -> Vec<Node> {
let div = gloo::utils::document()
.create_element_ns(parent_namespace, "div")
.unwrap();
div.set_inner_html(html);
let children = div.child_nodes();
let children = js_sys::Array::from(&children);
let children = children.to_vec();
children
.into_iter()
.map(|it| it.unchecked_into())
.collect::<Vec<_>>()
}
fn detach_bundle(&self, parent: &Element) {
let mut next_node = self.reference.clone();
for _ in 0..self.children_count {
if let Some(node) = next_node {
next_node = node.next_sibling();
parent.remove_child(&node).unwrap();
}
}
}
fn position(&self, next_slot: DomSlot) -> DomSlot {
self.reference
.as_ref()
.map(|n| DomSlot::at(n.clone()))
.unwrap_or(next_slot)
}
}
impl ReconcileTarget for BRaw {
fn detach(self, _root: &BSubtree, parent: &Element, _parent_to_detach: bool) {
self.detach_bundle(parent);
}
fn shift(&self, next_parent: &Element, slot: DomSlot) -> DomSlot {
let mut next_node = self.reference.clone();
for _ in 0..self.children_count {
if let Some(node) = next_node {
next_node = node.next_sibling();
slot.insert(next_parent, &node);
}
}
self.position(slot)
}
}
impl Reconcilable for VRaw {
type Bundle = BRaw;
fn attach(
self,
_root: &BSubtree,
_parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
) -> (DomSlot, Self::Bundle) {
let namespace = if parent.namespace_uri().is_some_and(|ns| ns == SVG_NAMESPACE) {
Some(SVG_NAMESPACE)
} else if parent
.namespace_uri()
.is_some_and(|ns| ns == MATHML_NAMESPACE)
{
Some(MATHML_NAMESPACE)
} else {
None
};
let elements = BRaw::create_elements(&self.html, namespace);
let count = elements.len();
let mut iter = elements.into_iter();
let reference = iter.next();
if let Some(ref first) = reference {
slot.insert(parent, first);
for ref child in iter {
slot.insert(parent, child);
}
}
let this = BRaw {
reference,
children_count: count,
html: self.html,
};
(this.position(slot), this)
}
fn reconcile_node(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
bundle: &mut BNode,
) -> DomSlot {
match bundle {
BNode::Raw(raw) if raw.html == self.html => raw.position(slot),
BNode::Raw(raw) => self.reconcile(root, parent_scope, parent, slot, raw),
_ => self.replace(root, parent_scope, parent, slot, bundle),
}
}
fn reconcile(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
bundle: &mut Self::Bundle,
) -> DomSlot {
if self.html != bundle.html {
// we don't have a way to diff what's changed in the string so we remove the node and
// reattach it
bundle.detach_bundle(parent);
let (node_ref, braw) = self.attach(root, parent_scope, parent, slot);
*bundle = braw;
node_ref
} else {
bundle.position(slot)
}
}
}
#[cfg(feature = "hydration")]
mod feat_hydration {
use super::*;
use crate::dom_bundle::{DynamicDomSlot, Fragment, Hydratable};
use crate::virtual_dom::Collectable;
impl Hydratable for VRaw {
fn hydrate(
self,
_root: &BSubtree,
_parent_scope: &AnyScope,
parent: &Element,
fragment: &mut Fragment,
prev_next_sibling: &mut Option<DynamicDomSlot>,
) -> Self::Bundle {
let collectable = Collectable::Raw;
let fallback_fragment = Fragment::collect_between(fragment, &collectable, parent);
let first_child = fallback_fragment.iter().next().cloned();
if let (Some(first_child), prev_next_sibling) = (&first_child, prev_next_sibling) {
if let Some(prev_next_sibling) = prev_next_sibling {
prev_next_sibling.reassign(DomSlot::at(first_child.clone()));
}
*prev_next_sibling = None;
}
let Self { html } = self;
BRaw {
children_count: fallback_fragment.len(),
reference: first_child,
html,
}
}
}
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
mod tests {
use gloo::utils::document;
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use super::*;
use crate::dom_bundle::utils::{
setup_parent, setup_parent_and_sibling, setup_parent_svg, SIBLING_CONTENT,
};
use crate::virtual_dom::VNode;
wasm_bindgen_test_configure!(run_in_browser);
#[test]
fn braw_works_one_node() {
let (root, scope, parent) = setup_parent();
const HTML: &str = "<span>text</span>";
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), HTML);
}
#[test]
fn braw_works_svg() {
let (root, scope, parent) = setup_parent_svg();
const HTML: &str = r#"<circle cx="50" cy="50" r="40"></circle>"#;
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), HTML);
assert_eq!(
parent
.first_child()
.unwrap()
.unchecked_into::<Element>()
.namespace_uri(),
Some(SVG_NAMESPACE.to_owned())
);
}
#[test]
fn braw_works_no_node() {
let (root, scope, parent) = setup_parent();
const HTML: &str = "";
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), HTML)
}
#[test]
fn braw_works_one_node_nested() {
let (root, scope, parent) = setup_parent();
const HTML: &str =
r#"<p>one <a href="https://yew.rs">link</a> more paragraph</p><div>here</div>"#;
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), HTML)
}
#[test]
fn braw_works_multi_top_nodes() {
let (root, scope, parent) = setup_parent();
const HTML: &str = r#"<p>paragraph</p><a href="https://yew.rs">link</a>"#;
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), HTML)
}
#[test]
fn braw_detach_works_multi_node() {
let (root, scope, parent) = setup_parent();
const HTML: &str = r#"<p>paragraph</p><a href="https://yew.rs">link</a>"#;
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), HTML);
elem.detach(&root, &parent, false);
assert_eq!(parent.inner_html(), "");
}
#[test]
fn braw_detach_works_single_node() {
let (root, scope, parent) = setup_parent();
const HTML: &str = r#"<p>paragraph</p>"#;
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), HTML);
elem.detach(&root, &parent, false);
assert_eq!(parent.inner_html(), "");
}
#[test]
fn braw_detach_works_empty() {
let (root, scope, parent) = setup_parent();
const HTML: &str = "";
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), HTML);
elem.detach(&root, &parent, false);
assert_eq!(parent.inner_html(), "");
}
#[test]
fn braw_works_one_node_sibling_attached() {
let (root, scope, parent, sibling) = setup_parent_and_sibling();
const HTML: &str = "<span>text</span>";
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, sibling);
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), format!("{}{}", HTML, SIBLING_CONTENT));
}
#[test]
fn braw_works_no_node_sibling_attached() {
let (root, scope, parent, sibling) = setup_parent_and_sibling();
const HTML: &str = "";
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, sibling);
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), format!("{}{}", HTML, SIBLING_CONTENT));
}
#[test]
fn braw_works_one_node_nested_sibling_attached() {
let (root, scope, parent, sibling) = setup_parent_and_sibling();
const HTML: &str =
r#"<p>one <a href="https://yew.rs">link</a> more paragraph</p><div>here</div>"#;
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, sibling);
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), format!("{}{}", HTML, SIBLING_CONTENT));
}
#[test]
fn braw_works_multi_top_nodes_sibling_attached() {
let (root, scope, parent, sibling) = setup_parent_and_sibling();
const HTML: &str = r#"<p>paragraph</p><a href="https://yew.rs">link</a>"#;
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, sibling);
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), format!("{}{}", HTML, SIBLING_CONTENT));
}
#[test]
fn braw_detach_works_multi_node_sibling_attached() {
let (root, scope, parent, sibling) = setup_parent_and_sibling();
const HTML: &str = r#"<p>paragraph</p><a href="https://yew.rs">link</a>"#;
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, sibling);
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), format!("{}{}", HTML, SIBLING_CONTENT));
elem.detach(&root, &parent, false);
assert_eq!(parent.inner_html(), format!("{}", SIBLING_CONTENT))
}
#[test]
fn braw_detach_works_single_node_sibling_attached() {
let (root, scope, parent, sibling) = setup_parent_and_sibling();
const HTML: &str = r#"<p>paragraph</p>"#;
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, sibling);
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), format!("{}{}", HTML, SIBLING_CONTENT));
elem.detach(&root, &parent, false);
assert_eq!(parent.inner_html(), format!("{}", SIBLING_CONTENT))
}
#[test]
fn braw_detach_works_empty_sibling_attached() {
let (root, scope, parent, sibling) = setup_parent_and_sibling();
const HTML: &str = "";
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, sibling);
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), format!("{}{}", HTML, SIBLING_CONTENT));
elem.detach(&root, &parent, false);
assert_eq!(parent.inner_html(), format!("{}", SIBLING_CONTENT))
}
#[test]
fn braw_shift_works() {
let (root, scope, parent) = setup_parent();
const HTML: &str = r#"<p>paragraph</p>"#;
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), HTML);
let new_parent = document().create_element("section").unwrap();
document().body().unwrap().append_child(&parent).unwrap();
elem.shift(&new_parent, DomSlot::at_end());
assert_eq!(new_parent.inner_html(), HTML);
assert_eq!(parent.inner_html(), "");
}
#[test]
fn braw_shift_with_sibling_works() {
let (root, scope, parent, sibling) = setup_parent_and_sibling();
const HTML: &str = r#"<p>paragraph</p>"#;
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, sibling);
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), format!("{}{}", HTML, SIBLING_CONTENT));
let new_parent = document().create_element("section").unwrap();
document().body().unwrap().append_child(&parent).unwrap();
let new_sibling = document().create_text_node(SIBLING_CONTENT);
new_parent.append_child(&new_sibling).unwrap();
let new_sibling_ref = DomSlot::at(new_sibling.into());
elem.shift(&new_parent, new_sibling_ref);
assert_eq!(parent.inner_html(), SIBLING_CONTENT);
assert_eq!(
new_parent.inner_html(),
format!("{}{}", HTML, SIBLING_CONTENT)
);
}
#[test]
fn braw_shift_works_multi_node() {
let (root, scope, parent) = setup_parent();
const HTML: &str = r#"<p>paragraph</p><a href="https://yew.rs">link</a>"#;
let elem = VNode::from_html_unchecked(HTML.into());
let (_, mut elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
assert_braw(&mut elem);
assert_eq!(parent.inner_html(), HTML);
let new_parent = document().create_element("section").unwrap();
document().body().unwrap().append_child(&parent).unwrap();
elem.shift(&new_parent, DomSlot::at_end());
assert_eq!(parent.inner_html(), "");
assert_eq!(new_parent.inner_html(), HTML);
}
fn assert_braw(node: &mut BNode) -> &mut BRaw {
if let BNode::Raw(braw) = node {
return braw;
}
panic!("should be braw");
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/dom_bundle/blist.rs | packages/yew/src/dom_bundle/blist.rs | //! This module contains fragments bundles, a [BList]
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::collections::HashSet;
use std::hash::Hash;
use std::ops::Deref;
use web_sys::Element;
use super::{test_log, BNode, BSubtree, DomSlot};
use crate::dom_bundle::{Reconcilable, ReconcileTarget};
use crate::html::AnyScope;
use crate::utils::RcExt;
use crate::virtual_dom::{Key, VList, VNode};
/// This struct represents a mounted [VList]
#[derive(Debug)]
pub(super) struct BList {
/// The reverse (render order) list of child [BNode]s
rev_children: Vec<BNode>,
/// All [BNode]s in the BList have keys
fully_keyed: bool,
key: Option<Key>,
}
impl VList {
// Splits a VList for creating / reconciling to a BList.
fn split_for_blist(self) -> (Option<Key>, bool, Vec<VNode>) {
let fully_keyed = self.fully_keyed();
let children = self
.children
.map(RcExt::unwrap_or_clone)
.unwrap_or_default();
(self.key, fully_keyed, children)
}
}
impl Deref for BList {
type Target = Vec<BNode>;
fn deref(&self) -> &Self::Target {
&self.rev_children
}
}
/// Helper struct, that keeps the position where the next element is to be placed at
#[derive(Clone)]
struct NodeWriter<'s> {
root: &'s BSubtree,
parent_scope: &'s AnyScope,
parent: &'s Element,
slot: DomSlot,
}
impl NodeWriter<'_> {
/// Write a new node that has no ancestor
fn add(self, node: VNode) -> (Self, BNode) {
test_log!("adding: {:?}", node);
test_log!(
" parent={:?}, slot={:?}",
self.parent.outer_html(),
self.slot
);
let (next, bundle) = node.attach(self.root, self.parent_scope, self.parent, self.slot);
test_log!(" next_slot: {:?}", next);
(Self { slot: next, ..self }, bundle)
}
/// Shift a bundle into place without patching it
fn shift(&self, bundle: &BNode) {
bundle.shift(self.parent, self.slot.clone());
}
/// Patch a bundle with a new node
fn patch(self, node: VNode, bundle: &mut BNode) -> Self {
test_log!("patching: {:?} -> {:?}", bundle, node);
test_log!(
" parent={:?}, slot={:?}",
self.parent.outer_html(),
self.slot
);
// Advance the next sibling reference (from right to left)
let next =
node.reconcile_node(self.root, self.parent_scope, self.parent, self.slot, bundle);
test_log!(" next_position: {:?}", next);
Self { slot: next, ..self }
}
}
/// Helper struct implementing [Eq] and [Hash] by only looking at a node's key
struct KeyedEntry(usize, BNode);
impl Borrow<Key> for KeyedEntry {
fn borrow(&self) -> &Key {
self.1.key().expect("unkeyed child in fully keyed list")
}
}
impl Hash for KeyedEntry {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
<Self as Borrow<Key>>::borrow(self).hash(state)
}
}
impl PartialEq for KeyedEntry {
fn eq(&self, other: &Self) -> bool {
<Self as Borrow<Key>>::borrow(self) == <Self as Borrow<Key>>::borrow(other)
}
}
impl Eq for KeyedEntry {}
impl BNode {
/// Assert that a bundle node is a list, or convert it to a list with a single child
fn make_list(&mut self) -> &mut BList {
match self {
Self::List(blist) => blist,
self_ => {
let b = std::mem::replace(self_, BNode::List(BList::new()));
let self_list = match self_ {
BNode::List(blist) => blist,
_ => unreachable!("just been set to the variant"),
};
let key = b.key().cloned();
self_list.rev_children.push(b);
self_list.fully_keyed = key.is_some();
self_list.key = key;
self_list
}
}
}
}
impl BList {
/// Create a new empty [BList]
pub const fn new() -> BList {
BList {
rev_children: vec![],
fully_keyed: true,
key: None,
}
}
/// Get the key of the underlying fragment
pub fn key(&self) -> Option<&Key> {
self.key.as_ref()
}
/// Diff and patch unkeyed child lists
fn apply_unkeyed(
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
lefts: Vec<VNode>,
rights: &mut Vec<BNode>,
) -> DomSlot {
let mut writer = NodeWriter {
root,
parent_scope,
parent,
slot,
};
// Remove extra nodes
if lefts.len() < rights.len() {
for r in rights.drain(lefts.len()..) {
test_log!("removing: {:?}", r);
r.detach(root, parent, false);
}
}
let mut lefts_it = lefts.into_iter().rev();
for (r, l) in rights.iter_mut().zip(&mut lefts_it) {
writer = writer.patch(l, r);
}
// Add missing nodes
for l in lefts_it {
let (next_writer, el) = writer.add(l);
rights.push(el);
writer = next_writer;
}
writer.slot
}
/// Diff and patch fully keyed child lists.
///
/// Optimized for node addition or removal from either end of the list and small changes in the
/// middle.
fn apply_keyed(
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
left_vdoms: Vec<VNode>,
rev_bundles: &mut Vec<BNode>,
) -> DomSlot {
macro_rules! key {
($v:expr) => {
$v.key().expect("unkeyed child in fully keyed list")
};
}
/// Find the first differing key in 2 iterators
fn matching_len<'a, 'b>(
a: impl Iterator<Item = &'a Key>,
b: impl Iterator<Item = &'b Key>,
) -> usize {
a.zip(b).take_while(|(a, b)| a == b).count()
}
// Find first key mismatch from the back
let matching_len_end = matching_len(
left_vdoms.iter().map(|v| key!(v)).rev(),
rev_bundles.iter().map(|v| key!(v)),
);
if cfg!(debug_assertions) {
let mut keys = HashSet::with_capacity(left_vdoms.len());
for (idx, n) in left_vdoms.iter().enumerate() {
let key = key!(n);
debug_assert!(
keys.insert(key!(n)),
"duplicate key detected: {key} at index {idx}. Keys in keyed lists must be \
unique!",
);
}
}
// If there is no key mismatch, apply the unkeyed approach
// Corresponds to adding or removing items from the back of the list
if matching_len_end == std::cmp::min(left_vdoms.len(), rev_bundles.len()) {
// No key changes
return Self::apply_unkeyed(root, parent_scope, parent, slot, left_vdoms, rev_bundles);
}
// We partially drain the new vnodes in several steps.
let mut lefts = left_vdoms;
let mut writer = NodeWriter {
root,
parent_scope,
parent,
slot,
};
// Step 1. Diff matching children at the end
let lefts_to = lefts.len() - matching_len_end;
for (l, r) in lefts
.drain(lefts_to..)
.rev()
.zip(rev_bundles[..matching_len_end].iter_mut())
{
writer = writer.patch(l, r);
}
// Step 2. Diff matching children in the middle, that is between the first and last key
// mismatch Find first key mismatch from the front
let mut matching_len_start = matching_len(
lefts.iter().map(|v| key!(v)),
rev_bundles.iter().map(|v| key!(v)).rev(),
);
// Step 2.1. Splice out the existing middle part and build a lookup by key
let rights_to = rev_bundles.len() - matching_len_start;
let mut bundle_middle = matching_len_end..rights_to;
if bundle_middle.start > bundle_middle.end {
// If this range is "inverted", this implies that the incoming nodes in lefts contain a
// duplicate key!
// Pictogram:
// v lefts_to
// lefts: | SSSSSSSS | ------ | EEEEEEEE |
// ↕ matching_len_start
// rev_bundles.rev(): | SSS | ?? | EEE |
// ^ rights_to
// Both a key from the (S)tarting portion and (E)nding portion of lefts has matched a
// key in the ? portion of bundles. Since the former can't overlap, a key
// must be duplicate. Duplicates might lead to us forgetting about some
// bundles entirely. It is NOT straight forward to adjust the below code to
// consistently check and handle this. The duplicate keys might
// be in the start or end portion.
// With debug_assertions we can never reach this. For production code, hope for the best
// by pretending. We still need to adjust some things so splicing doesn't
// panic:
matching_len_start = 0;
bundle_middle = matching_len_end..rev_bundles.len();
}
let (matching_len_start, bundle_middle) = (matching_len_start, bundle_middle);
// BNode contains js objects that look suspicious to clippy but are harmless
#[allow(clippy::mutable_key_type)]
let mut spare_bundles: HashSet<KeyedEntry> = HashSet::with_capacity(bundle_middle.len());
let mut spliced_middle = rev_bundles.splice(bundle_middle, std::iter::empty());
for (idx, r) in (&mut spliced_middle).enumerate() {
#[cold]
fn duplicate_in_bundle(root: &BSubtree, parent: &Element, r: BNode) {
test_log!("removing: {:?}", r);
r.detach(root, parent, false);
}
if let Some(KeyedEntry(_, dup)) = spare_bundles.replace(KeyedEntry(idx, r)) {
duplicate_in_bundle(root, parent, dup);
}
}
// Step 2.2. Put the middle part back together in the new key order
let mut replacements: Vec<BNode> = Vec::with_capacity((matching_len_start..lefts_to).len());
// The goal is to shift as few nodes as possible.
// We handle runs of in-order nodes. When we encounter one out-of-order, we decide whether:
// - to shift all nodes in the current run to the position after the node before of the run,
// or to
// - "commit" to the current run, shift all nodes before the end of the run that we might
// encounter in the future, and then start a new run.
// Example of a run:
// barrier_idx --v v-- end_idx
// spliced_middle [ ... , M , N , C , D , E , F , G , ... ] (original element order)
// ^---^-----------^ the nodes that are part of the current
// run v start_writer
// replacements [ ... , M , C , D , G ] (new element order)
// ^-- start_idx
let mut barrier_idx = 0; // nodes from spliced_middle[..barrier_idx] are shifted unconditionally
struct RunInformation<'a> {
start_writer: NodeWriter<'a>,
start_idx: usize,
end_idx: usize,
}
let mut current_run: Option<RunInformation<'_>> = None;
for l in lefts
.drain(matching_len_start..) // lefts_to.. has been drained
.rev()
{
let ancestor = spare_bundles.take(key!(l));
// Check if we need to shift or commit a run
if let Some(run) = current_run.as_mut() {
if let Some(KeyedEntry(idx, _)) = ancestor {
// If there are only few runs, this is a cold path
if idx < run.end_idx {
// Have to decide whether to shift or commit the current run. A few
// calculations: A perfect estimate of the amount of
// nodes we have to shift if we move this run:
let run_length = replacements.len() - run.start_idx;
// A very crude estimate of the amount of nodes we will have to shift if we
// commit the run: Note nodes of the current run
// should not be counted here!
let estimated_skipped_nodes = run.end_idx - idx.max(barrier_idx);
// double run_length to counteract that the run is part of the
// estimated_skipped_nodes
if 2 * run_length > estimated_skipped_nodes {
// less work to commit to this run
barrier_idx = 1 + run.end_idx;
} else {
// Less work to shift this run
for r in replacements[run.start_idx..].iter_mut().rev() {
run.start_writer.shift(r);
}
}
current_run = None;
}
}
}
let bundle = if let Some(KeyedEntry(idx, mut r_bundle)) = ancestor {
match current_run.as_mut() {
// hot path
// We know that idx >= run.end_idx, so this node doesn't need to shift
Some(run) => run.end_idx = idx,
None => match idx.cmp(&barrier_idx) {
// peep hole optimization, don't start a run as the element is already where
// it should be
Ordering::Equal => barrier_idx += 1,
// shift the node unconditionally, don't start a run
Ordering::Less => writer.shift(&r_bundle),
// start a run
Ordering::Greater => {
current_run = Some(RunInformation {
start_writer: writer.clone(),
start_idx: replacements.len(),
end_idx: idx,
})
}
},
}
writer = writer.patch(l, &mut r_bundle);
r_bundle
} else {
// Even if there is an active run, we don't have to modify it
let (next_writer, bundle) = writer.add(l);
writer = next_writer;
bundle
};
replacements.push(bundle);
}
// drop the splice iterator and immediately replace the range with the reordered elements
drop(spliced_middle);
rev_bundles.splice(matching_len_end..matching_len_end, replacements);
// Step 2.3. Remove any extra rights
for KeyedEntry(_, r) in spare_bundles.drain() {
test_log!("removing: {:?}", r);
r.detach(root, parent, false);
}
// Step 3. Diff matching children at the start
let rights_to = rev_bundles.len() - matching_len_start;
for (l, r) in lefts
.drain(..) // matching_len_start.. has been drained already
.rev()
.zip(rev_bundles[rights_to..].iter_mut())
{
writer = writer.patch(l, r);
}
writer.slot
}
}
impl ReconcileTarget for BList {
fn detach(self, root: &BSubtree, parent: &Element, parent_to_detach: bool) {
for child in self.rev_children.into_iter() {
child.detach(root, parent, parent_to_detach);
}
}
fn shift(&self, next_parent: &Element, mut slot: DomSlot) -> DomSlot {
for node in self.rev_children.iter() {
slot = node.shift(next_parent, slot);
}
slot
}
}
impl Reconcilable for VList {
type Bundle = BList;
fn attach(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
) -> (DomSlot, Self::Bundle) {
let mut self_ = BList::new();
let node_ref = self.reconcile(root, parent_scope, parent, slot, &mut self_);
(node_ref, self_)
}
fn reconcile_node(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
bundle: &mut BNode,
) -> DomSlot {
// 'Forcefully' pretend the existing node is a list. Creates a
// singleton list if it isn't already.
let blist = bundle.make_list();
self.reconcile(root, parent_scope, parent, slot, blist)
}
fn reconcile(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
blist: &mut BList,
) -> DomSlot {
// Here, we will try to diff the previous list elements with the new
// ones we want to insert. For that, we will use two lists:
// - lefts: new elements to render in the DOM
// - rights: previously rendered elements.
//
// The left items are known since we want to insert them
// (self.children). For the right ones, we will look at the bundle,
// i.e. the current DOM list element that we want to replace with self.
let (key, fully_keyed, lefts) = self.split_for_blist();
let rights = &mut blist.rev_children;
test_log!("lefts: {:?}", lefts);
test_log!("rights: {:?}", rights);
if let Some(additional) = lefts.len().checked_sub(rights.len()) {
rights.reserve_exact(additional);
}
let first = if fully_keyed && blist.fully_keyed {
BList::apply_keyed(root, parent_scope, parent, slot, lefts, rights)
} else {
BList::apply_unkeyed(root, parent_scope, parent, slot, lefts, rights)
};
blist.fully_keyed = fully_keyed;
blist.key = key;
test_log!("result: {:?}", rights);
first
}
}
#[cfg(feature = "hydration")]
mod feat_hydration {
use super::*;
use crate::dom_bundle::{DynamicDomSlot, Fragment, Hydratable};
impl Hydratable for VList {
fn hydrate(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
fragment: &mut Fragment,
prev_next_sibling: &mut Option<DynamicDomSlot>,
) -> Self::Bundle {
let (key, fully_keyed, vchildren) = self.split_for_blist();
let mut children = Vec::with_capacity(vchildren.len());
for child in vchildren.into_iter() {
let child = child.hydrate(root, parent_scope, parent, fragment, prev_next_sibling);
children.push(child);
}
children.reverse();
BList {
rev_children: children,
fully_keyed,
key,
}
}
}
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
mod layout_tests {
extern crate self as yew;
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use crate::html;
use crate::tests::layout_tests::{diff_layouts, TestLayout};
wasm_bindgen_test_configure!(run_in_browser);
#[test]
fn diff() {
let layout1 = TestLayout {
name: "1",
node: html! {
<>
{"a"}
{"b"}
<>
{"c"}
{"d"}
</>
{"e"}
</>
},
expected: "abcde",
};
let layout2 = TestLayout {
name: "2",
node: html! {
<>
{"a"}
{"b"}
<></>
{"e"}
{"f"}
</>
},
expected: "abef",
};
let layout3 = TestLayout {
name: "3",
node: html! {
<>
{"a"}
<></>
{"b"}
{"e"}
</>
},
expected: "abe",
};
let layout4 = TestLayout {
name: "4",
node: html! {
<>
{"a"}
<>
{"c"}
{"d"}
</>
{"b"}
{"e"}
</>
},
expected: "acdbe",
};
diff_layouts(vec![layout1, layout2, layout3, layout4]);
}
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
mod layout_tests_keys {
extern crate self as yew;
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use web_sys::Node;
use crate::tests::layout_tests::{diff_layouts, TestLayout};
use crate::virtual_dom::VNode;
use crate::{html, Children, Component, Context, Html, Properties};
wasm_bindgen_test_configure!(run_in_browser);
struct Comp {}
#[derive(Properties, Clone, PartialEq)]
struct CountingCompProps {
id: usize,
#[prop_or(false)]
can_change: bool,
}
impl Component for Comp {
type Message = ();
type Properties = CountingCompProps;
fn create(_: &Context<Self>) -> Self {
Comp {}
}
fn update(&mut self, _ctx: &Context<Self>, _: Self::Message) -> bool {
unimplemented!();
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! { <p>{ ctx.props().id }</p> }
}
}
#[derive(Clone, Properties, PartialEq)]
pub struct ListProps {
pub children: Children,
}
pub struct List();
impl Component for List {
type Message = ();
type Properties = ListProps;
fn create(_: &Context<Self>) -> Self {
Self()
}
fn update(&mut self, _ctx: &Context<Self>, _: Self::Message) -> bool {
unimplemented!();
}
fn view(&self, ctx: &Context<Self>) -> Html {
html! { <>{ for ctx.props().children.iter() }</> }
}
}
#[test]
fn diff() {
let mut layouts = vec![];
let vref_node: Node = gloo::utils::document().create_element("i").unwrap().into();
layouts.push(TestLayout {
name: "All VNode types as children",
node: html! {
<>
{"a"}
<span key="vtag"></span>
{"c"}
{"d"}
<Comp id=0 key="vchild" />
<key="vlist">
{"foo"}
{"bar"}
</>
{VNode::VRef(vref_node)}
</>
},
expected: "a<span></span>cd<p>0</p>foobar<i></i>",
});
layouts.extend(vec![
TestLayout {
name: "Inserting into VList first child - before",
node: html! {
<>
<key="VList">
<i key="i"></i>
</>
<p key="p"></p>
</>
},
expected: "<i></i><p></p>",
},
TestLayout {
name: "Inserting into VList first child - after",
node: html! {
<>
<key="VList">
<i key="i"></i>
<e key="e"></e>
</>
<p key="p"></p>
</>
},
expected: "<i></i><e></e><p></p>",
},
]);
layouts.extend(vec![
TestLayout {
name: "No matches - before",
node: html! {
<>
<i key="i"></i>
<e key="e"></e>
</>
},
expected: "<i></i><e></e>",
},
TestLayout {
name: "No matches - after",
node: html! {
<>
<a key="a"></a>
<p key="p"></p>
</>
},
expected: "<a></a><p></p>",
},
]);
layouts.extend(vec![
TestLayout {
name: "Append - before",
node: html! {
<>
<i key="i"></i>
<e key="e"></e>
</>
},
expected: "<i></i><e></e>",
},
TestLayout {
name: "Append - after",
node: html! {
<>
<i key="i"></i>
<e key="e"></e>
<p key="p"></p>
</>
},
expected: "<i></i><e></e><p></p>",
},
]);
layouts.extend(vec![
TestLayout {
name: "Prepend - before",
node: html! {
<>
<i key="i"></i>
<e key="e"></e>
</>
},
expected: "<i></i><e></e>",
},
TestLayout {
name: "Prepend - after",
node: html! {
<>
<p key="p"></p>
<i key="i"></i>
<e key="e"></e>
</>
},
expected: "<p></p><i></i><e></e>",
},
]);
layouts.extend(vec![
TestLayout {
name: "Delete first - before",
node: html! {
<>
<i key="i"></i>
<e key="e"></e>
<p key="p"></p>
</>
},
expected: "<i></i><e></e><p></p>",
},
TestLayout {
name: "Delete first - after",
node: html! {
<>
<e key="e"></e>
<p key="p"></p>
</>
},
expected: "<e></e><p></p>",
},
]);
layouts.extend(vec![
TestLayout {
name: "Delete last - before",
node: html! {
<>
<i key="i"></i>
<e key="e"></e>
<p key="p"></p>
</>
},
expected: "<i></i><e></e><p></p>",
},
TestLayout {
name: "Delete last - after",
node: html! {
<>
<i key="i"></i>
<e key="e"></e>
</>
},
expected: "<i></i><e></e>",
},
]);
layouts.extend(vec![
TestLayout {
name: "Delete last and change node type - before",
node: html! {
<>
<i key="i"></i>
<e key="e"></e>
<p key="p"></p>
</>
},
expected: "<i></i><e></e><p></p>",
},
TestLayout {
name: "Delete last - after",
node: html! {
<>
<List key="i"><i/></List>
<List key="e"><e/></List>
<List key="a"><a/></List>
</>
},
expected: "<i></i><e></e><a></a>",
},
]);
layouts.extend(vec![
TestLayout {
name: "Delete middle - before",
node: html! {
<>
<i key="i"></i>
<e key="e"></e>
<p key="p"></p>
<a key="a"></a>
</>
},
expected: "<i></i><e></e><p></p><a></a>",
},
TestLayout {
name: "Delete middle - after",
node: html! {
<>
<i key="i"></i>
<e key="e2"></e>
<p key="p2"></p>
<a key="a"></a>
</>
},
expected: "<i></i><e></e><p></p><a></a>",
},
]);
layouts.extend(vec![
TestLayout {
name: "Delete middle and change node type - before",
node: html! {
<>
<i key="i"></i>
<e key="e"></e>
<p key="p"></p>
<a key="a"></a>
</>
},
expected: "<i></i><e></e><p></p><a></a>",
},
TestLayout {
name: "Delete middle and change node type- after",
node: html! {
<>
<List key="i2"><i/></List>
<e key="e"></e>
<List key="p"><p/></List>
<List key="a2"><a/></List>
</>
},
expected: "<i></i><e></e><p></p><a></a>",
},
]);
layouts.extend(vec![
TestLayout {
name: "Reverse - before",
node: html! {
<>
<i key="i"></i>
<e key="e"></e>
<p key="p"></p>
<u key="u"></u>
</>
},
expected: "<i></i><e></e><p></p><u></u>",
},
TestLayout {
name: "Reverse - after",
node: html! {
<>
<u key="u"></u>
<p key="p"></p>
<e key="e"></e>
<i key="i"></i>
</>
},
expected: "<u></u><p></p><e></e><i></i>",
},
]);
layouts.extend(vec![
TestLayout {
name: "Reverse and change node type - before",
node: html! {
<>
<i key="i"></i>
<key="i1"></>
<key="i2"></>
<key="i3"></>
<e key="e"></e>
<key="yo">
<p key="p"></p>
</>
<u key="u"></u>
</>
},
expected: "<i></i><e></e><p></p><u></u>",
},
TestLayout {
name: "Reverse and change node type - after",
node: html! {
<>
<List key="u"><u/></List>
<List key="p"><p/></List>
<List key="e"><e/></List>
<List key="i"><i/></List>
</>
},
expected: "<u></u><p></p><e></e><i></i>",
},
]);
layouts.extend(vec![
TestLayout {
name: "Swap 1&2 - before",
node: html! {
<>
<i key="1"></i>
<e key="2"></e>
<p key="3"></p>
<a key="4"></a>
<u key="5"></u>
</>
},
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | true |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/dom_bundle/bportal.rs | packages/yew/src/dom_bundle/bportal.rs | //! This module contains the bundle implementation of a portal [BPortal].
use web_sys::{Element, Node};
use super::{test_log, BNode, BSubtree, DomSlot};
use crate::dom_bundle::{Reconcilable, ReconcileTarget};
use crate::html::AnyScope;
use crate::virtual_dom::{Key, VPortal};
/// The bundle implementation to [VPortal].
#[derive(Debug)]
pub struct BPortal {
// The inner root
inner_root: BSubtree,
/// The element under which the content is inserted.
host: Element,
/// The next sibling after the inserted content
inner_sibling: Option<Node>,
/// The inserted node
node: Box<BNode>,
}
impl ReconcileTarget for BPortal {
fn detach(self, _root: &BSubtree, _parent: &Element, _parent_to_detach: bool) {
test_log!("Detaching portal from host",);
self.node.detach(&self.inner_root, &self.host, false);
}
fn shift(&self, _next_parent: &Element, slot: DomSlot) -> DomSlot {
// portals have nothing in its original place of DOM, we also do nothing.
slot
}
}
impl Reconcilable for VPortal {
type Bundle = BPortal;
fn attach(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
host_slot: DomSlot,
) -> (DomSlot, Self::Bundle) {
let Self {
host,
inner_sibling,
node,
} = self;
let inner_slot = DomSlot::create(inner_sibling.clone());
let inner_root = root.create_subroot(parent.clone(), &host);
let (_, inner) = node.attach(&inner_root, parent_scope, &host, inner_slot);
(
host_slot,
BPortal {
inner_root,
host,
node: Box::new(inner),
inner_sibling,
},
)
}
fn reconcile_node(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
bundle: &mut BNode,
) -> DomSlot {
match bundle {
BNode::Portal(portal) => self.reconcile(root, parent_scope, parent, slot, portal),
_ => self.replace(root, parent_scope, parent, slot, bundle),
}
}
fn reconcile(
self,
_root: &BSubtree,
parent_scope: &AnyScope,
_parent: &Element,
host_slot: DomSlot,
portal: &mut Self::Bundle,
) -> DomSlot {
let Self {
host,
inner_sibling,
node,
} = self;
let old_host = std::mem::replace(&mut portal.host, host);
let should_shift = old_host != portal.host || portal.inner_sibling != inner_sibling;
portal.inner_sibling = inner_sibling;
let inner_slot = DomSlot::create(portal.inner_sibling.clone());
if should_shift {
// Remount the inner node somewhere else instead of diffing
// Move the node, but keep the state
portal.node.shift(&portal.host, inner_slot.clone());
}
node.reconcile_node(
&portal.inner_root,
parent_scope,
&portal.host,
inner_slot,
&mut portal.node,
);
host_slot
}
}
impl BPortal {
/// Get the key of the underlying portal
pub fn key(&self) -> Option<&Key> {
self.node.key()
}
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
mod layout_tests {
extern crate self as yew;
use std::rc::Rc;
use gloo::utils::document;
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use web_sys::HtmlInputElement;
use yew::virtual_dom::VPortal;
use super::*;
use crate::html::NodeRef;
use crate::tests::layout_tests::{diff_layouts, TestLayout};
use crate::virtual_dom::VNode;
use crate::{create_portal, html};
wasm_bindgen_test_configure!(run_in_browser);
#[test]
fn diff() {
let mut layouts = vec![];
let first_target = gloo::utils::document().create_element("i").unwrap();
let second_target = gloo::utils::document().create_element("o").unwrap();
let target_with_child = gloo::utils::document().create_element("i").unwrap();
let target_child = gloo::utils::document().create_element("s").unwrap();
target_with_child.append_child(&target_child).unwrap();
layouts.push(TestLayout {
name: "Portal - first target",
node: html! {
<div>
{VNode::VRef(first_target.clone().into())}
{VNode::VRef(second_target.clone().into())}
{VNode::VPortal(Rc::new(VPortal::new(
html! { {"PORTAL"} },
first_target.clone(),
)))}
{"AFTER"}
</div>
},
expected: "<div><i>PORTAL</i><o></o>AFTER</div>",
});
layouts.push(TestLayout {
name: "Portal - second target",
node: html! {
<div>
{VNode::VRef(first_target.clone().into())}
{VNode::VRef(second_target.clone().into())}
{VNode::VPortal(Rc::new(VPortal::new(
html! { {"PORTAL"} },
second_target.clone(),
)))}
{"AFTER"}
</div>
},
expected: "<div><i></i><o>PORTAL</o>AFTER</div>",
});
layouts.push(TestLayout {
name: "Portal - update inner content",
node: html! {
<div>
{VNode::VRef(first_target.clone().into())}
{VNode::VRef(second_target.clone().into())}
{VNode::VPortal(Rc::new(VPortal::new(
html! { <> {"PORTAL"} <b /> </> },
second_target.clone(),
)))}
{"AFTER"}
</div>
},
expected: "<div><i></i><o>PORTAL<b></b></o>AFTER</div>",
});
layouts.push(TestLayout {
name: "Portal - replaced by text",
node: html! {
<div>
{VNode::VRef(first_target.clone().into())}
{VNode::VRef(second_target.clone().into())}
{"FOO"}
{"AFTER"}
</div>
},
expected: "<div><i></i><o></o>FOOAFTER</div>",
});
layouts.push(TestLayout {
name: "Portal - next sibling",
node: html! {
<div>
{VNode::VRef(target_with_child.clone().into())}
{VNode::VPortal(Rc::new(VPortal::new_before(
html! { {"PORTAL"} },
target_with_child.clone(),
Some(target_child.clone().into()),
)))}
</div>
},
expected: "<div><i>PORTAL<s></s></i></div>",
});
diff_layouts(layouts)
}
fn setup_parent_with_portal() -> (BSubtree, AnyScope, Element, Element) {
let scope = AnyScope::test();
let parent = document().create_element("div").unwrap();
let portal_host = document().create_element("div").unwrap();
let root = BSubtree::create_root(&parent);
let body = document().body().unwrap();
body.append_child(&parent).unwrap();
body.append_child(&portal_host).unwrap();
(root, scope, parent, portal_host)
}
#[test]
fn test_no_shift() {
// Portals shouldn't shift (which e.g. causes internal inputs to unfocus) when sibling
// doesn't change.
let (root, scope, parent, portal_host) = setup_parent_with_portal();
let input_ref = NodeRef::default();
let portal = create_portal(
html! { <input type="text" ref={&input_ref} /> },
portal_host,
);
let (_, mut bundle) = portal
.clone()
.attach(&root, &scope, &parent, DomSlot::at_end());
// Focus the input, then reconcile again
let input_el = input_ref.cast::<HtmlInputElement>().unwrap();
input_el.focus().unwrap();
let _ = portal.reconcile_node(&root, &scope, &parent, DomSlot::at_end(), &mut bundle);
let new_input_el = input_ref.cast::<HtmlInputElement>().unwrap();
assert_eq!(input_el, new_input_el);
assert_eq!(document().active_element(), Some(new_input_el.into()));
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/dom_bundle/btext.rs | packages/yew/src/dom_bundle/btext.rs | //! This module contains the bundle implementation of text [BText].
use gloo::utils::document;
use web_sys::{Element, Text as TextNode};
use super::{BNode, BSubtree, DomSlot, Reconcilable, ReconcileTarget};
use crate::html::AnyScope;
use crate::virtual_dom::{AttrValue, VText};
/// The bundle implementation to [VText]
pub(super) struct BText {
text: AttrValue,
text_node: TextNode,
}
impl ReconcileTarget for BText {
fn detach(self, _root: &BSubtree, parent: &Element, parent_to_detach: bool) {
if !parent_to_detach {
let result = parent.remove_child(&self.text_node);
if result.is_err() {
tracing::warn!("Node not found to remove VText");
}
}
}
fn shift(&self, next_parent: &Element, slot: DomSlot) -> DomSlot {
slot.insert(next_parent, &self.text_node);
DomSlot::at(self.text_node.clone().into())
}
}
impl Reconcilable for VText {
type Bundle = BText;
fn attach(
self,
_root: &BSubtree,
_parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
) -> (DomSlot, Self::Bundle) {
let Self { text } = self;
let text_node = document().create_text_node(&text);
slot.insert(parent, &text_node);
let node_ref = DomSlot::at(text_node.clone().into());
(node_ref, BText { text, text_node })
}
/// Renders virtual node over existing `TextNode`, but only if value of text has changed.
fn reconcile_node(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
bundle: &mut BNode,
) -> DomSlot {
match bundle {
BNode::Text(btext) => self.reconcile(root, parent_scope, parent, slot, btext),
_ => self.replace(root, parent_scope, parent, slot, bundle),
}
}
fn reconcile(
self,
_root: &BSubtree,
_parent_scope: &AnyScope,
_parent: &Element,
_slot: DomSlot,
btext: &mut Self::Bundle,
) -> DomSlot {
let Self { text } = self;
let ancestor_text = std::mem::replace(&mut btext.text, text);
if btext.text != ancestor_text {
btext.text_node.set_node_value(Some(&btext.text));
}
DomSlot::at(btext.text_node.clone().into())
}
}
impl std::fmt::Debug for BText {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BText").field("text", &self.text).finish()
}
}
#[cfg(feature = "hydration")]
mod feat_hydration {
use wasm_bindgen::JsCast;
use web_sys::Node;
use super::*;
use crate::dom_bundle::{DynamicDomSlot, Fragment, Hydratable};
impl Hydratable for VText {
fn hydrate(
self,
_root: &BSubtree,
_parent_scope: &AnyScope,
parent: &Element,
fragment: &mut Fragment,
previous_next_sibling: &mut Option<DynamicDomSlot>,
) -> Self::Bundle {
let create_at = |next_sibling: Option<Node>, text: AttrValue| {
// If there are multiple text nodes placed back-to-back in SSR, it may be parsed as
// a single text node by browser, hence we need to add extra text
// nodes here if the next node is not a text node. Similarly, the
// value of the text node may be a combination of multiple VText
// vnodes. So we always need to override their values.
let text_node = document().create_text_node(text.as_ref());
DomSlot::create(next_sibling).insert(parent, &text_node);
BText { text, text_node }
};
let btext = if let Some(m) = fragment.front().cloned() {
if m.node_type() == Node::TEXT_NODE {
let m = m.unchecked_into::<TextNode>();
// pop current node.
fragment.pop_front();
// TODO: It may make sense to assert the text content in the text node
// against the VText when #[cfg(debug_assertions)]
// is true, but this may be complicated.
// We always replace the text value for now.
//
// Please see the next comment for a detailed explanation.
m.set_node_value(Some(self.text.as_ref()));
BText {
text: self.text,
text_node: m,
}
} else {
create_at(Some(m), self.text)
}
} else {
create_at(fragment.sibling_at_end().cloned(), self.text)
};
if let Some(previous_next_sibling) = previous_next_sibling {
previous_next_sibling.reassign(DomSlot::at(btext.text_node.clone().into()));
}
*previous_next_sibling = None;
btext
}
}
}
#[cfg(test)]
mod test {
extern crate self as yew;
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use crate::html;
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
wasm_bindgen_test_configure!(run_in_browser);
#[test]
fn text_as_root() {
let _ = html! {
"Text Node As Root"
};
let _ = html! {
{ "Text Node As Root" }
};
}
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
mod layout_tests {
extern crate self as yew;
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use crate::html;
use crate::tests::layout_tests::{diff_layouts, TestLayout};
wasm_bindgen_test_configure!(run_in_browser);
#[test]
fn diff() {
let layout1 = TestLayout {
name: "1",
node: html! { "a" },
expected: "a",
};
let layout2 = TestLayout {
name: "2",
node: html! { "b" },
expected: "b",
};
let layout3 = TestLayout {
name: "3",
node: html! {
<>
{"a"}
{"b"}
</>
},
expected: "ab",
};
let layout4 = TestLayout {
name: "4",
node: html! {
<>
{"b"}
{"a"}
</>
},
expected: "ba",
};
diff_layouts(vec![layout1, layout2, layout3, layout4]);
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/dom_bundle/btag/listeners.rs | packages/yew/src/dom_bundle/btag/listeners.rs | use std::cell::RefCell;
use std::collections::HashMap;
use std::ops::Deref;
use std::rc::Rc;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsCast;
use web_sys::{Element, Event, EventTarget as HtmlEventTarget};
use super::Apply;
use crate::dom_bundle::{test_log, BSubtree, EventDescriptor};
use crate::virtual_dom::{Listener, Listeners};
#[wasm_bindgen]
extern "C" {
// Duck-typing, not a real class on js-side. On rust-side, use impls of EventTarget below
type EventTargetable;
#[wasm_bindgen(method, getter = __yew_listener_id, structural)]
fn listener_id(this: &EventTargetable) -> Option<u32>;
#[wasm_bindgen(method, setter = __yew_listener_id, structural)]
fn set_listener_id(this: &EventTargetable, id: u32);
}
/// DOM-Types that can have listeners registered on them.
/// Uses the duck-typed interface from above in impls.
pub trait EventListening {
fn listener_id(&self) -> Option<u32>;
fn set_listener_id(&self, id: u32);
}
impl EventListening for Element {
fn listener_id(&self) -> Option<u32> {
self.unchecked_ref::<EventTargetable>().listener_id()
}
fn set_listener_id(&self, id: u32) {
self.unchecked_ref::<EventTargetable>().set_listener_id(id);
}
}
/// An active set of listeners on an element
#[derive(Debug)]
pub(super) enum ListenerRegistration {
/// No listeners registered.
NoReg,
/// Added to global registry by ID
Registered(u32),
}
impl Apply for Listeners {
type Bundle = ListenerRegistration;
type Element = Element;
fn apply(self, root: &BSubtree, el: &Self::Element) -> ListenerRegistration {
match self {
Self::Pending(pending) => ListenerRegistration::register(root, el, &pending),
Self::None => ListenerRegistration::NoReg,
}
}
fn apply_diff(self, root: &BSubtree, el: &Self::Element, bundle: &mut ListenerRegistration) {
use ListenerRegistration::*;
use Listeners::*;
match (self, bundle) {
(Pending(pending), Registered(ref id)) => {
// Reuse the ID
test_log!("reusing listeners for {}", id);
root.with_listener_registry(|reg| reg.patch(root, id, &pending));
}
(Pending(pending), bundle @ NoReg) => {
*bundle = ListenerRegistration::register(root, el, &pending);
test_log!(
"registering listeners for {}",
match bundle {
ListenerRegistration::Registered(id) => id,
_ => unreachable!(),
}
);
}
(None, bundle @ Registered(_)) => {
let id = match bundle {
ListenerRegistration::Registered(ref id) => id,
_ => unreachable!(),
};
test_log!("unregistering listeners for {}", id);
root.with_listener_registry(|reg| reg.unregister(id));
*bundle = NoReg;
}
(None, NoReg) => {
test_log!("{}", &"unchanged empty listeners");
}
};
}
}
impl ListenerRegistration {
/// Register listeners and return their handle ID
fn register(root: &BSubtree, el: &Element, pending: &[Option<Rc<dyn Listener>>]) -> Self {
Self::Registered(root.with_listener_registry(|reg| {
let id = reg.set_listener_id(root, el);
reg.register(root, id, pending);
id
}))
}
/// Remove any registered event listeners from the global registry
pub fn unregister(&self, root: &BSubtree) {
if let Self::Registered(id) = self {
root.with_listener_registry(|r| r.unregister(id));
}
}
}
/// Global multiplexing event handler registry
#[derive(Debug)]
pub struct Registry {
/// Counter for assigning new IDs
id_counter: u32,
/// Contains all registered event listeners by listener ID
by_id: HashMap<u32, HashMap<EventDescriptor, Vec<Rc<dyn Listener>>>>,
}
impl Registry {
pub fn new() -> Self {
Self {
id_counter: u32::default(),
by_id: HashMap::default(),
}
}
/// Handle a single event, given the listening element and event descriptor.
pub fn get_handler(
registry: &RefCell<Registry>,
listening: &dyn EventListening,
desc: &EventDescriptor,
) -> Option<impl FnOnce(&Event)> {
// The tricky part is that we want to drop the reference to the registry before
// calling any actual listeners (since that might end up running lifecycle methods
// and modify the registry). So we clone the current listeners and return a closure
let listener_id = listening.listener_id()?;
let registry_ref = registry.borrow();
let handlers = registry_ref.by_id.get(&listener_id)?;
let listeners = handlers.get(desc)?.clone();
drop(registry_ref); // unborrow the registry, before running any listeners
Some(move |event: &Event| {
for l in listeners {
l.handle(event.clone());
}
})
}
/// Register all passed listeners under ID
fn register(&mut self, root: &BSubtree, id: u32, listeners: &[Option<Rc<dyn Listener>>]) {
let mut by_desc =
HashMap::<EventDescriptor, Vec<Rc<dyn Listener>>>::with_capacity(listeners.len());
for l in listeners.iter().filter_map(|l| l.as_ref()).cloned() {
let desc = EventDescriptor::from(l.deref());
root.ensure_handled(&desc);
by_desc.entry(desc).or_default().push(l);
}
self.by_id.insert(id, by_desc);
}
/// Patch an already registered set of handlers
fn patch(&mut self, root: &BSubtree, id: &u32, listeners: &[Option<Rc<dyn Listener>>]) {
if let Some(by_desc) = self.by_id.get_mut(id) {
// Keeping empty vectors is fine. Those don't do much and should happen rarely.
for v in by_desc.values_mut() {
v.clear()
}
for l in listeners.iter().filter_map(|l| l.as_ref()).cloned() {
let desc = EventDescriptor::from(l.deref());
root.ensure_handled(&desc);
by_desc.entry(desc).or_default().push(l);
}
}
}
/// Unregister any existing listeners for ID
fn unregister(&mut self, id: &u32) {
self.by_id.remove(id);
}
/// Set unique listener ID onto element and return it
fn set_listener_id(&mut self, root: &BSubtree, el: &Element) -> u32 {
let id = self.id_counter;
self.id_counter += 1;
root.brand_element(el as &HtmlEventTarget);
el.set_listener_id(id);
id
}
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
mod tests {
use std::marker::PhantomData;
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use web_sys::{Event, EventInit, FocusEvent, HtmlElement, MouseEvent};
wasm_bindgen_test_configure!(run_in_browser);
use gloo::utils::document;
use wasm_bindgen::JsCast;
use yew::Callback;
use crate::html::TargetCast;
use crate::virtual_dom::VNode;
use crate::{
create_portal, html, scheduler, AppHandle, Component, Context, Html, NodeRef, Properties,
};
#[derive(Clone)]
enum Message {
Action,
StopListening,
SetText(String),
}
#[derive(Default)]
struct State {
stop_listening: bool,
action: u32,
text: String,
}
#[derive(Default, PartialEq, Properties)]
struct MixinProps<M: Properties> {
state_ref: NodeRef,
wrapped: M,
}
trait Mixin: Properties + Sized {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message, Properties = MixinProps<Self>>;
}
struct Comp<M>
where
M: Mixin + 'static,
{
state: State,
pd: PhantomData<M>,
}
impl<M> Component for Comp<M>
where
M: Mixin + Properties + 'static,
{
type Message = Message;
type Properties = MixinProps<M>;
fn create(_: &Context<Self>) -> Self {
Comp {
state: Default::default(),
pd: PhantomData,
}
}
fn update(&mut self, _: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Message::Action => {
self.state.action += 1;
}
Message::StopListening => {
self.state.stop_listening = true;
}
Message::SetText(s) => {
self.state.text = s;
}
};
true
}
fn view(&self, ctx: &Context<Self>) -> crate::Html {
M::view(ctx, &self.state)
}
}
#[track_caller]
fn assert_count(el: &NodeRef, count: isize) {
let text = el
.get()
.expect("State ref not bound in the test case?")
.text_content();
assert_eq!(text, Some(count.to_string()))
}
#[track_caller]
fn click(el: &NodeRef) {
el.get().unwrap().dyn_into::<HtmlElement>().unwrap().click();
scheduler::start_now();
}
fn get_el_by_selector(selector: &str) -> web_sys::HtmlElement {
document()
.query_selector(selector)
.unwrap()
.unwrap()
.dyn_into::<web_sys::HtmlElement>()
.unwrap()
}
fn init<M>() -> (AppHandle<Comp<M>>, NodeRef)
where
M: Mixin + Properties + Default,
{
// Remove any existing elements
let body = document().query_selector("#output").unwrap().unwrap();
while let Some(child) = body.query_selector("div#testroot").unwrap() {
body.remove_child(&child).unwrap();
}
let root = document().create_element("div").unwrap();
root.set_id("testroot");
body.append_child(&root).unwrap();
let props = <Comp<M> as Component>::Properties::default();
let el_ref = props.state_ref.clone();
let app = crate::Renderer::<Comp<M>>::with_root_and_props(root, props).render();
scheduler::start_now();
(app, el_ref)
}
#[test]
fn synchronous() {
#[derive(Default, PartialEq, Properties)]
struct Synchronous;
impl Mixin for Synchronous {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message, Properties = MixinProps<Self>>,
{
let onclick = ctx.link().callback(|_| Message::Action);
if state.stop_listening {
html! {
<a ref={&ctx.props().state_ref}>{state.action}</a>
}
} else {
html! {
<a {onclick} ref={&ctx.props().state_ref}>
{state.action}
</a>
}
}
}
}
let (link, el) = init::<Synchronous>();
assert_count(&el, 0);
click(&el);
assert_count(&el, 1);
click(&el);
assert_count(&el, 2);
link.send_message(Message::StopListening);
scheduler::start_now();
click(&el);
assert_count(&el, 2);
}
#[test]
async fn non_bubbling_event() {
#[derive(Default, PartialEq, Properties)]
struct NonBubbling;
impl Mixin for NonBubbling {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message, Properties = MixinProps<Self>>,
{
let link = ctx.link().clone();
let onblur = Callback::from(move |_| {
link.send_message(Message::Action);
scheduler::start_now();
});
html! {
<div>
<a ref={&ctx.props().state_ref}>
<input id="input" {onblur} type="text" />
{state.action}
</a>
</div>
}
}
}
let (_, el) = init::<NonBubbling>();
assert_count(&el, 0);
let input = document().get_element_by_id("input").unwrap();
input
.dispatch_event(
&Event::new_with_event_init_dict("blur", &{
let mut dict = EventInit::new();
dict.bubbles(false);
dict
})
.unwrap(),
)
.unwrap();
assert_count(&el, 1);
}
#[test]
fn bubbling() {
#[derive(Default, PartialEq, Properties)]
struct Bubbling;
impl Mixin for Bubbling {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message, Properties = MixinProps<Self>>,
{
if state.stop_listening {
html! {
<div>
<a ref={&ctx.props().state_ref}>
{state.action}
</a>
</div>
}
} else {
let cb = ctx.link().callback(|_| Message::Action);
html! {
<div onclick={cb.clone()}>
<a onclick={cb} ref={&ctx.props().state_ref}>
{state.action}
</a>
</div>
}
}
}
}
let (link, el) = init::<Bubbling>();
assert_count(&el, 0);
click(&el);
assert_count(&el, 2);
click(&el);
assert_count(&el, 4);
link.send_message(Message::StopListening);
scheduler::start_now();
click(&el);
assert_count(&el, 4);
}
#[test]
fn cancel_bubbling() {
#[derive(Default, PartialEq, Properties)]
struct CancelBubbling;
impl Mixin for CancelBubbling {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message, Properties = MixinProps<Self>>,
{
let onclick = ctx.link().callback(|_| Message::Action);
let onclick2 = ctx.link().callback(|e: MouseEvent| {
e.stop_propagation();
Message::Action
});
html! {
<div onclick={onclick}>
<a onclick={onclick2} ref={&ctx.props().state_ref}>
{state.action}
</a>
</div>
}
}
}
let (_, el) = init::<CancelBubbling>();
assert_count(&el, 0);
click(&el);
assert_count(&el, 1);
click(&el);
assert_count(&el, 2);
}
#[test]
fn cancel_bubbling_nested() {
// Here an event is being delivered to a DOM node which does
// _not_ have a listener but which is contained within an
// element that does and which cancels the bubble.
#[derive(Default, PartialEq, Properties)]
struct CancelBubbling;
impl Mixin for CancelBubbling {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message, Properties = MixinProps<Self>>,
{
let onclick = ctx.link().callback(|_| Message::Action);
let onclick2 = ctx.link().callback(|e: MouseEvent| {
e.stop_propagation();
Message::Action
});
html! {
<div onclick={onclick}>
<div onclick={onclick2}>
<a ref={&ctx.props().state_ref}>
{state.action}
</a>
</div>
</div>
}
}
}
let (_, el) = init::<CancelBubbling>();
assert_count(&el, 0);
click(&el);
assert_count(&el, 1);
click(&el);
assert_count(&el, 2);
}
#[test]
fn non_bubbling() {
#[derive(Default, PartialEq, Properties)]
struct NonBubbling;
impl Mixin for NonBubbling {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message, Properties = MixinProps<Self>>,
{
let onfocus = ctx.link().callback(|_| Message::Action);
let onfocus_inner = ctx.link().callback(|e: FocusEvent| {
assert!(!e.bubbles(), "event should be non-bubbling");
Message::Action
});
html! {
<div {onfocus}>
<button onfocus={onfocus_inner} ref={&ctx.props().state_ref}>
{state.action}
</button>
</div>
}
}
}
// Should only trigger the inner listener, not also the outer one
let (_, el) = init::<NonBubbling>();
assert_count(&el, 0);
el.get()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap()
.focus()
.unwrap();
scheduler::start_now();
assert_count(&el, 1);
}
/// Here an event is being delivered to a DOM node which is contained
/// in a portal. It should bubble through the portal and reach the containing
/// element.
#[test]
fn portal_bubbling() {
#[derive(PartialEq, Properties)]
struct PortalBubbling {
host: web_sys::Element,
}
impl Default for PortalBubbling {
fn default() -> Self {
let host = document().create_element("div").unwrap();
PortalBubbling { host }
}
}
impl Mixin for PortalBubbling {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message, Properties = MixinProps<Self>>,
{
let portal_target = ctx.props().wrapped.host.clone();
let onclick = ctx.link().callback(|_| Message::Action);
html! {
<>
<div onclick={onclick}>
{create_portal(html! {
<a ref={&ctx.props().state_ref}>
{state.action}
</a>
}, portal_target.clone())}
</div>
{VNode::VRef(portal_target.into())}
</>
}
}
}
let (_, el) = init::<PortalBubbling>();
assert_count(&el, 0);
click(&el);
assert_count(&el, 1);
}
/// Here an event is being from inside a shadow root. It should only be caught exactly once on
/// each handler
#[test]
fn open_shadow_dom_bubbling() {
use web_sys::{ShadowRootInit, ShadowRootMode};
#[derive(PartialEq, Properties)]
struct OpenShadowDom {
host: web_sys::Element,
inner_root: web_sys::Element,
}
impl Default for OpenShadowDom {
fn default() -> Self {
let host = document().create_element("div").unwrap();
let inner_root = document().create_element("div").unwrap();
let shadow = host
.attach_shadow(&ShadowRootInit::new(ShadowRootMode::Open))
.unwrap();
shadow.append_child(&inner_root).unwrap();
OpenShadowDom { host, inner_root }
}
}
impl Mixin for OpenShadowDom {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message, Properties = MixinProps<Self>>,
{
let onclick = ctx.link().callback(|_| Message::Action);
let mixin = &ctx.props().wrapped;
html! {
<div onclick={onclick.clone()}>
<div {onclick}>
{create_portal(html! {
<a ref={&ctx.props().state_ref}>
{state.action}
</a>
}, mixin.inner_root.clone())}
</div>
{VNode::VRef(mixin.host.clone().into())}
</div>
}
}
}
let (_, el) = init::<OpenShadowDom>();
assert_count(&el, 0);
click(&el);
assert_count(&el, 2); // Once caught per handler
}
fn test_input_listener<E>(make_event: impl Fn() -> E)
where
E: Into<Event> + std::fmt::Debug,
{
#[derive(Default, PartialEq, Properties)]
struct Input;
impl Mixin for Input {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message, Properties = MixinProps<Self>>,
{
if state.stop_listening {
html! {
<div>
<input type="text" />
<p ref={&ctx.props().state_ref}>{state.text.clone()}</p>
</div>
}
} else {
let onchange = ctx.link().callback(|e: web_sys::Event| {
let el: web_sys::HtmlInputElement = e.target_unchecked_into();
Message::SetText(el.value())
});
let oninput = ctx.link().callback(|e: web_sys::InputEvent| {
let el: web_sys::HtmlInputElement = e.target_unchecked_into();
Message::SetText(el.value())
});
html! {
<div>
<input type="text" {onchange} {oninput} />
<p ref={&ctx.props().state_ref}>{state.text.clone()}</p>
</div>
}
}
}
}
let (link, state_ref) = init::<Input>();
let input_el = get_el_by_selector("input")
.dyn_into::<web_sys::HtmlInputElement>()
.unwrap();
assert_eq!(&state_ref.get().unwrap().text_content().unwrap(), "");
for mut s in ["foo", "bar", "baz"].iter() {
input_el.set_value(s);
if s == &"baz" {
link.send_message(Message::StopListening);
scheduler::start_now();
s = &"bar";
}
input_el.dispatch_event(&make_event().into()).unwrap();
scheduler::start_now();
assert_eq!(&state_ref.get().unwrap().text_content().unwrap(), s);
}
}
#[test]
fn oninput() {
test_input_listener(|| {
web_sys::InputEvent::new_with_event_init_dict(
"input",
web_sys::InputEventInit::new().bubbles(true),
)
.unwrap()
})
}
#[test]
fn onchange() {
test_input_listener(|| {
web_sys::Event::new_with_event_init_dict(
"change",
web_sys::EventInit::new().bubbles(true),
)
.unwrap()
})
}
#[test]
fn reentrant_listener() {
#[derive(PartialEq, Properties, Default)]
struct Reetrant {
secondary_target_ref: NodeRef,
}
impl Mixin for Reetrant {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message, Properties = MixinProps<Self>>,
{
let targetref = &ctx.props().wrapped.secondary_target_ref;
let onclick = {
let targetref = targetref.clone();
ctx.link().callback(move |_| {
// Note: `click` (and dispatchEvent for that matter) swallows errors thrown
// from listeners and reports them as uncaught to the console. Hence, we
// assert that we got to the second event listener instead, by dispatching a
// second Message::Action
click(&targetref);
Message::Action
})
};
let onclick2 = ctx.link().callback(move |_| Message::Action);
html! {
<div>
<button {onclick} ref={&ctx.props().state_ref}>{state.action}</button>
<a onclick={onclick2} ref={targetref}></a>
</div>
}
}
}
let (_, el) = init::<Reetrant>();
assert_count(&el, 0);
click(&el);
assert_count(&el, 2);
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/dom_bundle/btag/mod.rs | packages/yew/src/dom_bundle/btag/mod.rs | //! This module contains the bundle implementation of a tag [BTag]
mod attributes;
mod listeners;
use std::cell::RefCell;
use std::collections::HashMap;
use std::hint::unreachable_unchecked;
use std::ops::DerefMut;
use gloo::utils::document;
use listeners::ListenerRegistration;
pub use listeners::Registry;
use wasm_bindgen::JsCast;
use web_sys::{Element, HtmlTextAreaElement as TextAreaElement};
use super::{BNode, BSubtree, DomSlot, Reconcilable, ReconcileTarget};
use crate::html::AnyScope;
#[cfg(feature = "hydration")]
use crate::virtual_dom::vtag::HTML_NAMESPACE;
use crate::virtual_dom::vtag::{
InputFields, TextareaFields, VTagInner, Value, MATHML_NAMESPACE, SVG_NAMESPACE,
};
use crate::virtual_dom::{AttrValue, Attributes, Key, VTag};
use crate::NodeRef;
/// Applies contained changes to DOM [web_sys::Element]
trait Apply {
/// [web_sys::Element] subtype to apply the changes to
type Element;
type Bundle;
/// Apply contained values to [Element](Self::Element) with no ancestor
fn apply(self, root: &BSubtree, el: &Self::Element) -> Self::Bundle;
/// Apply diff between [self] and `bundle` to [Element](Self::Element).
fn apply_diff(self, root: &BSubtree, el: &Self::Element, bundle: &mut Self::Bundle);
}
/// [BTag] fields that are specific to different [BTag] kinds.
/// Decreases the memory footprint of [BTag] by avoiding impossible field and value combinations.
#[derive(Debug)]
enum BTagInner {
/// Fields specific to
/// [InputElement](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input)
Input(InputFields),
/// Fields specific to
/// [TextArea](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea)
Textarea {
/// Contains a value of an
/// [TextArea](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea)
value: Value<TextAreaElement>,
},
/// Fields for all other kinds of [VTag]s
Other {
/// A tag of the element.
tag: AttrValue,
/// Child node.
child_bundle: BNode,
},
}
/// The bundle implementation to [VTag]
#[derive(Debug)]
pub(super) struct BTag {
/// [BTag] fields that are specific to different [BTag] kinds.
inner: BTagInner,
listeners: ListenerRegistration,
attributes: Attributes,
/// A reference to the DOM [`Element`].
reference: Element,
/// A node reference used for DOM access in Component lifecycle methods
node_ref: NodeRef,
key: Option<Key>,
}
impl ReconcileTarget for BTag {
fn detach(self, root: &BSubtree, parent: &Element, parent_to_detach: bool) {
self.listeners.unregister(root);
let node = self.reference;
// recursively remove its children
if let BTagInner::Other { child_bundle, .. } = self.inner {
// This tag will be removed, so there's no point to remove any child.
child_bundle.detach(root, &node, true);
}
if !parent_to_detach {
let result = parent.remove_child(&node);
if result.is_err() {
tracing::warn!("Node not found to remove VTag");
}
}
// It could be that the ref was already reused when rendering another element.
// Only unset the ref it still belongs to our node
if self.node_ref.get().as_ref() == Some(&node) {
self.node_ref.set(None);
}
}
fn shift(&self, next_parent: &Element, slot: DomSlot) -> DomSlot {
slot.insert(next_parent, &self.reference);
DomSlot::at(self.reference.clone().into())
}
}
impl Reconcilable for VTag {
type Bundle = BTag;
fn attach(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
) -> (DomSlot, Self::Bundle) {
let el = self.create_element(parent);
let Self {
listeners,
attributes,
node_ref,
key,
..
} = self;
// Apply attributes BEFORE inserting the element into the DOM
// This is crucial for SVG animation elements where the animation
// starts immediately upon DOM insertion
let attributes = attributes.apply(root, &el);
let listeners = listeners.apply(root, &el);
// Now insert the element with attributes already set
slot.insert(parent, &el);
let inner = match self.inner {
VTagInner::Input(f) => {
let f = f.apply(root, el.unchecked_ref());
BTagInner::Input(f)
}
VTagInner::Textarea(f) => {
let value = f.apply(root, el.unchecked_ref());
BTagInner::Textarea { value }
}
VTagInner::Other { children, tag } => {
let (_, child_bundle) = children.attach(root, parent_scope, &el, DomSlot::at_end());
BTagInner::Other { child_bundle, tag }
}
};
node_ref.set(Some(el.clone().into()));
(
DomSlot::at(el.clone().into()),
BTag {
inner,
listeners,
reference: el,
attributes,
key,
node_ref,
},
)
}
fn reconcile_node(
self,
root: &BSubtree,
parent_scope: &AnyScope,
parent: &Element,
slot: DomSlot,
bundle: &mut BNode,
) -> DomSlot {
// This kind of branching patching routine reduces branch predictor misses and the need to
// unpack the enums (including `Option`s) all the time, resulting in a more streamlined
// patching flow
match bundle {
// If the ancestor is a tag of the same type, don't recreate, keep the
// old tag and update its attributes and children.
BNode::Tag(ex) if self.key == ex.key => {
if match (&self.inner, &ex.inner) {
(VTagInner::Input(_), BTagInner::Input(_)) => true,
(VTagInner::Textarea { .. }, BTagInner::Textarea { .. }) => true,
(VTagInner::Other { tag: l, .. }, BTagInner::Other { tag: r, .. })
if l == r =>
{
true
}
_ => false,
} {
return self.reconcile(root, parent_scope, parent, slot, ex.deref_mut());
}
}
_ => {}
};
self.replace(root, parent_scope, parent, slot, bundle)
}
fn reconcile(
self,
root: &BSubtree,
parent_scope: &AnyScope,
_parent: &Element,
_slot: DomSlot,
tag: &mut Self::Bundle,
) -> DomSlot {
let el = &tag.reference;
self.attributes.apply_diff(root, el, &mut tag.attributes);
self.listeners.apply_diff(root, el, &mut tag.listeners);
match (self.inner, &mut tag.inner) {
(VTagInner::Input(new), BTagInner::Input(old)) => {
new.apply_diff(root, el.unchecked_ref(), old);
}
(
VTagInner::Textarea(TextareaFields { value: new, .. }),
BTagInner::Textarea { value: old },
) => {
new.apply_diff(root, el.unchecked_ref(), old);
}
(
VTagInner::Other { children: new, .. },
BTagInner::Other {
child_bundle: old, ..
},
) => {
new.reconcile(root, parent_scope, el, DomSlot::at_end(), old);
}
// Can not happen, because we checked for tag equability above
_ => unsafe { unreachable_unchecked() },
}
tag.key = self.key;
if self.node_ref != tag.node_ref && tag.node_ref.get().as_ref() == Some(el) {
tag.node_ref.set(None);
}
if self.node_ref != tag.node_ref {
tag.node_ref = self.node_ref;
tag.node_ref.set(Some(el.clone().into()));
}
DomSlot::at(el.clone().into())
}
}
impl VTag {
fn create_element(&self, parent: &Element) -> Element {
let tag = self.tag();
// check for an xmlns attribute. If it exists, create an element with the specified
// namespace
if let Some(xmlns) = self
.attributes
.iter()
.find(|(k, _)| *k == "xmlns")
.map(|(_, v)| v)
{
document()
.create_element_ns(Some(xmlns), tag)
.expect("can't create namespaced element for vtag")
} else if tag == "svg" || parent.namespace_uri().is_some_and(|ns| ns == SVG_NAMESPACE) {
let namespace = Some(SVG_NAMESPACE);
document()
.create_element_ns(namespace, tag)
.expect("can't create namespaced element for vtag")
} else if tag == "math"
|| parent
.namespace_uri()
.is_some_and(|ns| ns == MATHML_NAMESPACE)
{
let namespace = Some(MATHML_NAMESPACE);
document()
.create_element_ns(namespace, tag)
.expect("can't create namespaced element for vtag")
} else {
thread_local! {
static CACHED_ELEMENTS: RefCell<HashMap<String, Element>> = RefCell::new(HashMap::with_capacity(32));
}
CACHED_ELEMENTS.with(|cache| {
let mut cache = cache.borrow_mut();
let cached = cache.get(tag).map(|el| {
el.clone_node()
.expect("couldn't clone cached element")
.unchecked_into::<Element>()
});
cached.unwrap_or_else(|| {
let to_be_cached = document()
.create_element(tag)
.expect("can't create element for vtag");
cache.insert(
tag.to_string(),
to_be_cached
.clone_node()
.expect("couldn't clone node to be cached")
.unchecked_into(),
);
to_be_cached
})
})
}
}
}
impl BTag {
/// Get the key of the underlying tag
pub fn key(&self) -> Option<&Key> {
self.key.as_ref()
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
fn reference(&self) -> &Element {
&self.reference
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
fn children(&self) -> Option<&BNode> {
match &self.inner {
BTagInner::Other { child_bundle, .. } => Some(child_bundle),
_ => None,
}
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
fn tag(&self) -> &str {
match &self.inner {
BTagInner::Input { .. } => "input",
BTagInner::Textarea { .. } => "textarea",
BTagInner::Other { tag, .. } => tag.as_ref(),
}
}
}
#[cfg(feature = "hydration")]
mod feat_hydration {
use web_sys::Node;
use super::*;
use crate::dom_bundle::{node_type_str, DynamicDomSlot, Fragment, Hydratable};
impl Hydratable for VTag {
fn hydrate(
self,
root: &BSubtree,
parent_scope: &AnyScope,
_parent: &Element,
fragment: &mut Fragment,
prev_next_sibling: &mut Option<DynamicDomSlot>,
) -> Self::Bundle {
let tag_name = self.tag().to_owned();
let Self {
inner,
listeners,
attributes,
node_ref,
key,
} = self;
// We trim all text nodes as it's likely these are whitespaces.
fragment.trim_start_text_nodes();
let node = fragment
.pop_front()
.unwrap_or_else(|| panic!("expected element of type {tag_name}, found EOF."));
assert_eq!(
node.node_type(),
Node::ELEMENT_NODE,
"expected element, found node type {}.",
node_type_str(&node),
);
let el = node.dyn_into::<Element>().expect("expected an element.");
{
let el_tag_name = el.tag_name();
let parent_namespace = _parent.namespace_uri();
// In HTML namespace (or no namespace), createElement is case-insensitive
// In other namespaces (SVG, MathML), createElementNS is case-sensitive
let should_compare_case_insensitive = parent_namespace.is_none()
|| parent_namespace.as_deref() == Some(HTML_NAMESPACE);
if should_compare_case_insensitive {
// Case-insensitive comparison for HTML elements
assert!(
tag_name.eq_ignore_ascii_case(&el_tag_name),
"expected element of kind {tag_name}, found {el_tag_name}.",
);
} else {
// Case-sensitive comparison for namespaced elements (SVG, MathML)
assert_eq!(
el_tag_name, tag_name,
"expected element of kind {tag_name}, found {el_tag_name}.",
);
}
}
// We simply register listeners and update all attributes.
let attributes = attributes.apply(root, &el);
let listeners = listeners.apply(root, &el);
// For input and textarea elements, we update their value anyways.
let inner = match inner {
VTagInner::Input(f) => {
let f = f.apply(root, el.unchecked_ref());
BTagInner::Input(f)
}
VTagInner::Textarea(f) => {
let value = f.apply(root, el.unchecked_ref());
BTagInner::Textarea { value }
}
VTagInner::Other { children, tag } => {
let mut nodes = Fragment::collect_children(&el);
let mut prev_next_child = None;
let child_bundle =
children.hydrate(root, parent_scope, &el, &mut nodes, &mut prev_next_child);
if let Some(prev_next_child) = prev_next_child {
prev_next_child.reassign(DomSlot::at_end());
}
nodes.trim_start_text_nodes();
assert!(nodes.is_empty(), "expected EOF, found node.");
BTagInner::Other { child_bundle, tag }
}
};
node_ref.set(Some((*el).clone()));
if let Some(prev_next_sibling) = prev_next_sibling {
prev_next_sibling.reassign(DomSlot::at((*el).clone()));
}
*prev_next_sibling = None;
BTag {
inner,
listeners,
attributes,
reference: el,
node_ref,
key,
}
}
}
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
mod tests {
use std::rc::Rc;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use web_sys::HtmlInputElement as InputElement;
use super::*;
use crate::dom_bundle::utils::setup_parent;
use crate::dom_bundle::{BNode, Reconcilable, ReconcileTarget};
use crate::utils::RcExt;
use crate::virtual_dom::vtag::{HTML_NAMESPACE, SVG_NAMESPACE};
use crate::virtual_dom::{AttrValue, VNode, VTag};
use crate::{html, Html, NodeRef};
wasm_bindgen_test_configure!(run_in_browser);
#[test]
fn it_compares_tags() {
let a = html! {
<div></div>
};
let b = html! {
<div></div>
};
let c = html! {
<p></p>
};
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn it_compares_text() {
let a = html! {
<div>{ "correct" }</div>
};
let b = html! {
<div>{ "correct" }</div>
};
let c = html! {
<div>{ "incorrect" }</div>
};
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn it_compares_attributes_static() {
let a = html! {
<div a="test"></div>
};
let b = html! {
<div a="test"></div>
};
let c = html! {
<div a="fail"></div>
};
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn it_compares_attributes_dynamic() {
let a = html! {
<div a={"test".to_owned()}></div>
};
let b = html! {
<div a={"test".to_owned()}></div>
};
let c = html! {
<div a={"fail".to_owned()}></div>
};
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn it_compares_children() {
let a = html! {
<div>
<p></p>
</div>
};
let b = html! {
<div>
<p></p>
</div>
};
let c = html! {
<div>
<span></span>
</div>
};
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn it_compares_classes_static() {
let a = html! {
<div class="test"></div>
};
let b = html! {
<div class="test"></div>
};
let c = html! {
<div class="fail"></div>
};
let d = html! {
<div class={format!("fail{}", "")}></div>
};
assert_eq!(a, b);
assert_ne!(a, c);
assert_ne!(a, d);
}
#[test]
fn it_compares_classes_dynamic() {
let a = html! {
<div class={"test".to_owned()}></div>
};
let b = html! {
<div class={"test".to_owned()}></div>
};
let c = html! {
<div class={"fail".to_owned()}></div>
};
let d = html! {
<div class={format!("fail{}", "")}></div>
};
assert_eq!(a, b);
assert_ne!(a, c);
assert_ne!(a, d);
}
fn assert_vtag(node: VNode) -> VTag {
if let VNode::VTag(vtag) = node {
return RcExt::unwrap_or_clone(vtag);
}
panic!("should be vtag");
}
fn assert_btag_ref(node: &BNode) -> &BTag {
if let BNode::Tag(vtag) = node {
return vtag;
}
panic!("should be btag");
}
fn assert_vtag_ref(node: &VNode) -> &VTag {
if let VNode::VTag(vtag) = node {
return vtag;
}
panic!("should be vtag");
}
fn assert_btag_mut(node: &mut BNode) -> &mut BTag {
if let BNode::Tag(btag) = node {
return btag;
}
panic!("should be btag");
}
fn assert_namespace(vtag: &BTag, namespace: &'static str) {
assert_eq!(vtag.reference().namespace_uri().unwrap(), namespace);
}
#[test]
fn supports_svg() {
let (root, scope, parent) = setup_parent();
let document = web_sys::window().unwrap().document().unwrap();
let namespace = SVG_NAMESPACE;
let namespace = Some(namespace);
let svg_el = document.create_element_ns(namespace, "svg").unwrap();
let g_node = html! { <g class="segment"></g> };
let path_node = html! { <path></path> };
let svg_node = html! { <svg>{path_node}</svg> };
let svg_tag = assert_vtag(svg_node);
let (_, svg_tag) = svg_tag.attach(&root, &scope, &parent, DomSlot::at_end());
assert_namespace(&svg_tag, SVG_NAMESPACE);
let path_tag = assert_btag_ref(svg_tag.children().unwrap());
assert_namespace(path_tag, SVG_NAMESPACE);
let g_tag = assert_vtag(g_node.clone());
let (_, g_tag) = g_tag.attach(&root, &scope, &parent, DomSlot::at_end());
assert_namespace(&g_tag, HTML_NAMESPACE);
let g_tag = assert_vtag(g_node);
let (_, g_tag) = g_tag.attach(&root, &scope, &svg_el, DomSlot::at_end());
assert_namespace(&g_tag, SVG_NAMESPACE);
}
#[test]
fn supports_mathml() {
let (root, scope, parent) = setup_parent();
let mfrac_node = html! { <mfrac> </mfrac> };
let math_node = html! { <math>{mfrac_node}</math> };
let math_tag = assert_vtag(math_node);
let (_, math_tag) = math_tag.attach(&root, &scope, &parent, DomSlot::at_end());
assert_namespace(&math_tag, MATHML_NAMESPACE);
let mfrac_tag = assert_btag_ref(math_tag.children().unwrap());
assert_namespace(mfrac_tag, MATHML_NAMESPACE);
}
#[test]
fn it_compares_values() {
let a = html! {
<input value="test"/>
};
let b = html! {
<input value="test"/>
};
let c = html! {
<input value="fail"/>
};
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn it_compares_kinds() {
let a = html! {
<input type="text"/>
};
let b = html! {
<input type="text"/>
};
let c = html! {
<input type="hidden"/>
};
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn it_compares_checked() {
let a = html! {
<input type="checkbox" checked=false />
};
let b = html! {
<input type="checkbox" checked=false />
};
let c = html! {
<input type="checkbox" checked=true />
};
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn it_allows_aria_attributes() {
let a = html! {
<p aria-controls="it-works">
<a class="btn btn-primary"
data-toggle="collapse"
href="#collapseExample"
role="button"
aria-expanded="false"
aria-controls="collapseExample">
{ "Link with href" }
</a>
<button class="btn btn-primary"
type="button"
data-toggle="collapse"
data-target="#collapseExample"
aria-expanded="false"
aria-controls="collapseExample">
{ "Button with data-target" }
</button>
<div own-attribute-with-multiple-parts="works" />
</p>
};
if let VNode::VTag(vtag) = a {
assert_eq!(
vtag.attributes
.iter()
.find(|(k, _)| k == &"aria-controls")
.map(|(_, v)| v),
Some("it-works")
);
} else {
panic!("vtag expected");
}
}
#[test]
fn it_does_not_set_missing_class_name() {
let (root, scope, parent) = setup_parent();
let elem = html! { <div></div> };
let (_, mut elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
let vtag = assert_btag_mut(&mut elem);
// test if the className has not been set
assert!(!vtag.reference().has_attribute("class"));
}
fn test_set_class_name(gen_html: impl FnOnce() -> Html) {
let (root, scope, parent) = setup_parent();
let elem = gen_html();
let (_, mut elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
let vtag = assert_btag_mut(&mut elem);
// test if the className has been set
assert!(vtag.reference().has_attribute("class"));
}
#[test]
fn it_sets_class_name_static() {
test_set_class_name(|| html! { <div class="ferris the crab"></div> });
}
#[test]
fn it_sets_class_name_dynamic() {
test_set_class_name(|| html! { <div class={"ferris the crab".to_owned()}></div> });
}
#[test]
fn controlled_input_synced() {
let (root, scope, parent) = setup_parent();
let expected = "not_changed_value";
// Initial state
let elem = html! { <input value={expected} /> };
let (_, mut elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
let vtag = assert_btag_ref(&elem);
// User input
let input_ref = &vtag.reference();
let input = input_ref.dyn_ref::<InputElement>();
input.unwrap().set_value("User input");
let next_elem = html! { <input value={expected} /> };
let elem_vtag = assert_vtag(next_elem);
// Sync happens here
elem_vtag.reconcile_node(&root, &scope, &parent, DomSlot::at_end(), &mut elem);
let vtag = assert_btag_ref(&elem);
// Get new current value of the input element
let input_ref = &vtag.reference();
let input = input_ref.dyn_ref::<InputElement>().unwrap();
let current_value = input.value();
// check whether not changed virtual dom value has been set to the input element
assert_eq!(current_value, expected);
}
#[test]
fn uncontrolled_input_unsynced() {
let (root, scope, parent) = setup_parent();
// Initial state
let elem = html! { <input /> };
let (_, mut elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
let vtag = assert_btag_ref(&elem);
// User input
let input_ref = &vtag.reference();
let input = input_ref.dyn_ref::<InputElement>();
input.unwrap().set_value("User input");
let next_elem = html! { <input /> };
let elem_vtag = assert_vtag(next_elem);
// Value should not be refreshed
elem_vtag.reconcile_node(&root, &scope, &parent, DomSlot::at_end(), &mut elem);
let vtag = assert_btag_ref(&elem);
// Get user value of the input element
let input_ref = &vtag.reference();
let input = input_ref.dyn_ref::<InputElement>().unwrap();
let current_value = input.value();
// check whether not changed virtual dom value has been set to the input element
assert_eq!(current_value, "User input");
// Need to remove the element to clean up the dirty state of the DOM. Failing this causes
// event listener tests to fail.
parent.remove();
}
#[test]
fn dynamic_tags_work() {
let (root, scope, parent) = setup_parent();
let elem = html! { <@{{
let mut builder = String::new();
builder.push('a');
builder
}}/> };
let (_, mut elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
let vtag = assert_btag_mut(&mut elem);
// make sure the new tag name is used internally
assert_eq!(vtag.tag(), "a");
// Element.tagName is always in the canonical upper-case form.
assert_eq!(vtag.reference().tag_name(), "A");
}
#[test]
fn dynamic_tags_handle_value_attribute() {
let div_el = html! {
<@{"div"} value="Hello"/>
};
let div_vtag = assert_vtag_ref(&div_el);
assert!(div_vtag.value().is_none());
let v: Option<&str> = div_vtag
.attributes
.iter()
.find(|(k, _)| k == &"value")
.map(|(_, v)| AsRef::as_ref(v));
assert_eq!(v, Some("Hello"));
let input_el = html! {
<@{"input"} value="World"/>
};
let input_vtag = assert_vtag_ref(&input_el);
assert_eq!(input_vtag.value(), Some(&AttrValue::Static("World")));
assert!(!input_vtag.attributes.iter().any(|(k, _)| k == "value"));
}
#[test]
fn dynamic_tags_handle_weird_capitalization() {
let el = html! {
<@{"tExTAREa"}/>
};
let vtag = assert_vtag_ref(&el);
// textarea is a special element, so it gets normalized
assert_eq!(vtag.tag(), "textarea");
}
#[test]
fn dynamic_tags_allow_custom_capitalization() {
let el = html! {
<@{"clipPath"}/>
};
let vtag = assert_vtag_ref(&el);
// no special treatment for elements not recognized e.g. clipPath
assert_eq!(vtag.tag(), "clipPath");
}
#[test]
fn reset_node_ref() {
let (root, scope, parent) = setup_parent();
let node_ref = NodeRef::default();
let elem: VNode = html! { <div ref={node_ref.clone()}></div> };
assert_vtag_ref(&elem);
let (_, elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
assert_eq!(node_ref.get(), parent.first_child());
elem.detach(&root, &parent, false);
assert!(node_ref.get().is_none());
}
#[test]
fn vtag_reuse_should_reset_ancestors_node_ref() {
let (root, scope, parent) = setup_parent();
let node_ref_a = NodeRef::default();
let elem_a = html! { <div id="a" ref={node_ref_a.clone()} /> };
let (_, mut elem) = elem_a.attach(&root, &scope, &parent, DomSlot::at_end());
// save the Node to check later that it has been reused.
let node_a = node_ref_a.get().unwrap();
let node_ref_b = NodeRef::default();
let elem_b = html! { <div id="b" ref={node_ref_b.clone()} /> };
elem_b.reconcile_node(&root, &scope, &parent, DomSlot::at_end(), &mut elem);
let node_b = node_ref_b.get().unwrap();
assert_eq!(node_a, node_b, "VTag should have reused the element");
assert!(
node_ref_a.get().is_none(),
"node_ref_a should have been reset when the element was reused."
);
}
#[test]
fn vtag_should_not_touch_newly_bound_refs() {
let (root, scope, parent) = setup_parent();
let test_ref = NodeRef::default();
let before = html! {
<>
<div ref={&test_ref} id="before" />
</>
};
let after = html! {
<>
<h6 />
<div ref={&test_ref} id="after" />
</>
};
// The point of this diff is to first render the "after" div and then detach the "before"
// div, while both should be bound to the same node ref
let (_, mut elem) = before.attach(&root, &scope, &parent, DomSlot::at_end());
after.reconcile_node(&root, &scope, &parent, DomSlot::at_end(), &mut elem);
assert_eq!(
test_ref
.get()
.unwrap()
.dyn_ref::<web_sys::Element>()
.unwrap()
.outer_html(),
"<div id=\"after\"></div>"
);
}
// test for bug: https://github.com/yewstack/yew/pull/2653
#[test]
fn test_index_map_attribute_diff() {
let (root, scope, parent) = setup_parent();
let test_ref = NodeRef::default();
// We want to test appy_diff with Attributes::IndexMap, so we
// need to create the VTag manually
// Create <div disabled="disabled" tabindex="0">
let mut vtag = VTag::new("div");
vtag.node_ref = test_ref.clone();
vtag.add_attribute("disabled", "disabled");
vtag.add_attribute("tabindex", "0");
let elem = VNode::VTag(Rc::new(vtag));
let (_, mut elem) = elem.attach(&root, &scope, &parent, DomSlot::at_end());
// Create <div tabindex="0"> (removed first attribute "disabled")
let mut vtag = VTag::new("div");
vtag.node_ref = test_ref.clone();
vtag.add_attribute("tabindex", "0");
let next_elem = VNode::VTag(Rc::new(vtag));
let elem_vtag = assert_vtag(next_elem);
// Sync happens here
// this should remove the "disabled" attribute
elem_vtag.reconcile_node(&root, &scope, &parent, DomSlot::at_end(), &mut elem);
assert_eq!(
test_ref
.get()
.unwrap()
.dyn_ref::<web_sys::Element>()
.unwrap()
.outer_html(),
"<div tabindex=\"0\"></div>"
);
}
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
mod layout_tests {
extern crate self as yew;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | true |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/dom_bundle/btag/attributes.rs | packages/yew/src/dom_bundle/btag/attributes.rs | use std::collections::HashMap;
use std::ops::Deref;
use indexmap::IndexMap;
use wasm_bindgen::{intern, JsValue};
use web_sys::{Element, HtmlInputElement as InputElement, HtmlTextAreaElement as TextAreaElement};
use yew::AttrValue;
use super::Apply;
use crate::dom_bundle::BSubtree;
use crate::virtual_dom::vtag::{InputFields, TextareaFields, Value};
use crate::virtual_dom::{AttributeOrProperty, Attributes};
impl<T: AccessValue> Apply for Value<T> {
type Bundle = Self;
type Element = T;
fn apply(self, _root: &BSubtree, el: &Self::Element) -> Self {
if let Some(v) = self.deref() {
el.set_value(v);
}
self
}
fn apply_diff(self, _root: &BSubtree, el: &Self::Element, bundle: &mut Self) {
match (self.deref(), (*bundle).deref()) {
(Some(new), Some(_)) => {
// Refresh value from the DOM. It might have changed.
if new.as_ref() != el.value() {
el.set_value(new);
}
}
(Some(new), None) => el.set_value(new),
(None, Some(_)) => el.set_value(""),
(None, None) => (),
}
}
}
macro_rules! impl_access_value {
($( $type:ty )*) => {
$(
impl AccessValue for $type {
#[inline]
fn value(&self) -> String {
<$type>::value(&self)
}
#[inline]
fn set_value(&self, v: &str) {
<$type>::set_value(&self, v)
}
}
)*
};
}
impl_access_value! {InputElement TextAreaElement}
/// Able to have its value read or set
pub(super) trait AccessValue {
fn value(&self) -> String;
fn set_value(&self, v: &str);
}
impl Apply for InputFields {
type Bundle = Self;
type Element = InputElement;
fn apply(mut self, root: &BSubtree, el: &Self::Element) -> Self {
// IMPORTANT! This parameter has to be set every time it's explicitly given
// to prevent strange behaviour in the browser when the DOM changes
if let Some(checked) = self.checked {
el.set_checked(checked);
}
self.value = self.value.apply(root, el);
self
}
fn apply_diff(self, root: &BSubtree, el: &Self::Element, bundle: &mut Self) {
// IMPORTANT! This parameter has to be set every time it's explicitly given
// to prevent strange behaviour in the browser when the DOM changes
if let Some(checked) = self.checked {
el.set_checked(checked);
}
self.value.apply_diff(root, el, &mut bundle.value);
}
}
impl Apply for TextareaFields {
type Bundle = Value<TextAreaElement>;
type Element = TextAreaElement;
fn apply(self, root: &BSubtree, el: &Self::Element) -> Self::Bundle {
if let Some(def) = self.defaultvalue {
_ = el.set_default_value(def.as_str());
}
self.value.apply(root, el)
}
fn apply_diff(self, root: &BSubtree, el: &Self::Element, bundle: &mut Self::Bundle) {
self.value.apply_diff(root, el, bundle)
}
}
impl Attributes {
#[cold]
fn apply_diff_index_maps(
el: &Element,
new: &IndexMap<AttrValue, AttributeOrProperty>,
old: &IndexMap<AttrValue, AttributeOrProperty>,
) {
for (key, value) in new.iter() {
match old.get(key) {
Some(old_value) => {
if value != old_value {
Self::set(el, key, value);
}
}
None => Self::set(el, key, value),
}
}
for (key, value) in old.iter() {
if !new.contains_key(key) {
Self::remove(el, key, value);
}
}
}
/// Convert [Attributes] pair to [HashMap]s and patch changes to `el`.
/// Works with any [Attributes] variants.
#[cold]
fn apply_diff_as_maps<'a>(el: &Element, new: &'a Self, old: &'a Self) {
fn collect(src: &Attributes) -> HashMap<&str, &AttributeOrProperty> {
use Attributes::*;
match src {
Static(arr) => (*arr).iter().map(|(k, v)| (*k, v)).collect(),
Dynamic { keys, values } => keys
.iter()
.zip(values.iter())
.filter_map(|(k, v)| v.as_ref().map(|v| (*k, v)))
.collect(),
IndexMap(m) => m.iter().map(|(k, v)| (k.as_ref(), v)).collect(),
}
}
let new = collect(new);
let old = collect(old);
// Update existing or set new
for (k, new) in new.iter() {
if match old.get(k) {
Some(old) => old != new,
None => true,
} {
Self::set(el, k, new);
}
}
// Remove missing
for (k, old_value) in old.iter() {
if !new.contains_key(k) {
Self::remove(el, k, old_value);
}
}
}
fn set(el: &Element, key: &str, value: &AttributeOrProperty) {
match value {
AttributeOrProperty::Attribute(value) => el
.set_attribute(intern(key), value)
.expect("invalid attribute key"),
AttributeOrProperty::Static(value) => el
.set_attribute(intern(key), value)
.expect("invalid attribute key"),
AttributeOrProperty::Property(value) => {
let key = JsValue::from_str(key);
js_sys::Reflect::set(el.as_ref(), &key, value).expect("could not set property");
}
}
}
fn remove(el: &Element, key: &str, old_value: &AttributeOrProperty) {
match old_value {
AttributeOrProperty::Attribute(_) | AttributeOrProperty::Static(_) => el
.remove_attribute(intern(key))
.expect("could not remove attribute"),
AttributeOrProperty::Property(_) => {
let key = JsValue::from_str(key);
js_sys::Reflect::set(el.as_ref(), &key, &JsValue::UNDEFINED)
.expect("could not remove property");
}
}
}
}
impl Apply for Attributes {
type Bundle = Self;
type Element = Element;
fn apply(self, _root: &BSubtree, el: &Element) -> Self {
match &self {
Self::Static(arr) => {
for (k, v) in arr.iter() {
Self::set(el, k, v);
}
}
Self::Dynamic { keys, values } => {
for (k, v) in keys.iter().zip(values.iter()) {
if let Some(v) = v {
Self::set(el, k, v)
}
}
}
Self::IndexMap(m) => {
for (k, v) in m.iter() {
Self::set(el, k, v)
}
}
}
self
}
fn apply_diff(self, _root: &BSubtree, el: &Element, bundle: &mut Self) {
#[inline]
fn ptr_eq<T>(a: &[T], b: &[T]) -> bool {
std::ptr::eq(a, b)
}
let ancestor = std::mem::replace(bundle, self);
let bundle = &*bundle; // reborrow it immutably from here
match (bundle, ancestor) {
// Hot path
(Self::Static(new), Self::Static(old)) if ptr_eq(new, old) => (),
// Hot path
(
Self::Dynamic {
keys: new_k,
values: new_v,
},
Self::Dynamic {
keys: old_k,
values: old_v,
},
) if ptr_eq(new_k, old_k) => {
// Double zipping does not optimize well, so use asserts and unsafe instead
assert_eq!(new_k.len(), new_v.len());
assert_eq!(new_k.len(), old_v.len());
for i in 0..new_k.len() {
macro_rules! key {
() => {
unsafe { new_k.get_unchecked(i) }
};
}
macro_rules! set {
($new:expr) => {
Self::set(el, key!(), $new)
};
}
match unsafe { (new_v.get_unchecked(i), old_v.get_unchecked(i)) } {
(Some(new), Some(old)) => {
if new != old {
set!(new);
}
}
(Some(new), None) => set!(new),
(None, Some(old)) => {
Self::remove(el, key!(), old);
}
(None, None) => (),
}
}
}
// For VTag's constructed outside the html! macro
(Self::IndexMap(new), Self::IndexMap(ref old)) => {
Self::apply_diff_index_maps(el, new, old);
}
// Cold path. Happens only with conditional swapping and reordering of `VTag`s with the
// same tag and no keys.
(new, ref ancestor) => {
Self::apply_diff_as_maps(el, new, ancestor);
}
}
}
}
#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
#[cfg(test)]
mod tests {
use std::rc::Rc;
use std::time::Duration;
use gloo::utils::document;
use js_sys::Reflect;
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use super::*;
use crate::{component, html, Html};
wasm_bindgen_test_configure!(run_in_browser);
fn create_element() -> (Element, BSubtree) {
let element = document()
.create_element("a")
.expect("failed to create element");
let btree = BSubtree::create_root(&element);
(element, btree)
}
#[test]
fn properties_are_set() {
let attrs = indexmap::indexmap! {
AttrValue::Static("href") => AttributeOrProperty::Property(JsValue::from_str("https://example.com/")),
AttrValue::Static("alt") => AttributeOrProperty::Property(JsValue::from_str("somewhere")),
};
let attrs = Attributes::IndexMap(Rc::new(attrs));
let (element, btree) = create_element();
attrs.apply(&btree, &element);
assert_eq!(
Reflect::get(element.as_ref(), &JsValue::from_str("href"))
.expect("no href")
.as_string()
.expect("not a string"),
"https://example.com/",
"property `href` not set properly"
);
assert_eq!(
Reflect::get(element.as_ref(), &JsValue::from_str("alt"))
.expect("no alt")
.as_string()
.expect("not a string"),
"somewhere",
"property `alt` not set properly"
);
}
#[test]
fn respects_apply_as() {
let attrs = indexmap::indexmap! {
AttrValue::Static("href") => AttributeOrProperty::Attribute(AttrValue::from("https://example.com/")),
AttrValue::Static("alt") => AttributeOrProperty::Property(JsValue::from_str("somewhere")),
};
let attrs = Attributes::IndexMap(Rc::new(attrs));
let (element, btree) = create_element();
attrs.apply(&btree, &element);
assert_eq!(
element.outer_html(),
"<a href=\"https://example.com/\"></a>",
"should be set as attribute"
);
assert_eq!(
Reflect::get(element.as_ref(), &JsValue::from_str("alt"))
.expect("no alt")
.as_string()
.expect("not a string"),
"somewhere",
"property `alt` not set properly"
);
}
#[test]
fn class_is_always_attrs() {
let attrs = Attributes::Static(&[("class", AttributeOrProperty::Static("thing"))]);
let (element, btree) = create_element();
attrs.apply(&btree, &element);
assert_eq!(element.get_attribute("class").unwrap(), "thing");
}
#[test]
async fn macro_syntax_works() {
#[component]
fn Comp() -> Html {
html! { <a href="https://example.com/" ~alt={"abc"} ~data-bool={JsValue::from_bool(true)} /> }
}
let output = document().get_element_by_id("output").unwrap();
yew::Renderer::<Comp>::with_root(output.clone()).render();
gloo::timers::future::sleep(Duration::from_secs(1)).await;
let element = output.query_selector("a").unwrap().unwrap();
assert_eq!(
element.get_attribute("href").unwrap(),
"https://example.com/"
);
assert_eq!(
Reflect::get(element.as_ref(), &JsValue::from_str("alt"))
.expect("no alt")
.as_string()
.expect("not a string"),
"abc",
"property `alt` not set properly"
);
assert!(
Reflect::get(element.as_ref(), &JsValue::from_str("data-bool"))
.expect("no alt")
.as_bool()
.expect("not a bool"),
"property `alt` not set properly"
);
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/suspense/suspension.rs | packages/yew/src/suspense/suspension.rs | use std::cell::RefCell;
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::{Context, Poll};
use thiserror::Error;
use crate::platform::spawn_local;
use crate::Callback;
thread_local! {
static SUSPENSION_ID: RefCell<usize> = RefCell::default();
}
/// A Suspension.
///
/// This type can be sent back as an `Err(_)` to suspend a component until the underlying task
/// completes.
#[derive(Error, Debug, Clone)]
#[error("suspend component rendering")]
pub struct Suspension {
id: usize,
listeners: Rc<RefCell<Vec<Callback<Self>>>>,
resumed: Rc<AtomicBool>,
}
impl PartialEq for Suspension {
fn eq(&self, rhs: &Self) -> bool {
self.id == rhs.id
}
}
impl Suspension {
/// Creates a Suspension.
pub fn new() -> (Self, SuspensionHandle) {
let id = SUSPENSION_ID.with(|m| {
let mut m = m.borrow_mut();
*m += 1;
*m
});
let self_ = Suspension {
id,
listeners: Rc::default(),
resumed: Rc::default(),
};
(self_.clone(), SuspensionHandle { inner: self_ })
}
/// Returns `true` if the current suspension is already resumed.
pub fn resumed(&self) -> bool {
self.resumed.load(Ordering::Relaxed)
}
/// Creates a Suspension that resumes when the [`Future`] resolves.
pub fn from_future(f: impl Future<Output = ()> + 'static) -> Self {
let (self_, handle) = Self::new();
spawn_local(async move {
f.await;
handle.resume();
});
self_
}
/// Listens to a suspension and get notified when it resumes.
pub(crate) fn listen(&self, cb: Callback<Self>) {
if self.resumed() {
cb.emit(self.clone());
return;
}
let mut listeners = self.listeners.borrow_mut();
listeners.push(cb);
}
fn resume_by_ref(&self) {
// The component can resume rendering by returning a non-suspended result after a state is
// updated, so we always need to check here.
if !self.resumed() {
self.resumed.store(true, Ordering::Relaxed);
let listeners = self.listeners.borrow();
for listener in listeners.iter() {
listener.emit(self.clone());
}
}
}
}
impl Future for Suspension {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.resumed() {
return Poll::Ready(());
}
let waker = cx.waker().clone();
self.listen(Callback::from(move |_| {
waker.wake_by_ref();
}));
Poll::Pending
}
}
/// A Suspension Result.
pub type SuspensionResult<T> = std::result::Result<T, Suspension>;
/// A Suspension Handle.
///
/// This type is used to control the corresponding [`Suspension`].
///
/// When the current struct is dropped or `resume` is called, it will resume rendering of current
/// component.
#[derive(Debug, PartialEq)]
pub struct SuspensionHandle {
inner: Suspension,
}
impl SuspensionHandle {
/// Resumes component rendering.
pub fn resume(self) {
self.inner.resume_by_ref();
}
}
impl Drop for SuspensionHandle {
fn drop(&mut self) {
self.inner.resume_by_ref();
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/suspense/hooks.rs | packages/yew/src/suspense/hooks.rs | use std::cell::Cell;
use std::fmt;
use std::future::Future;
use std::ops::Deref;
use std::rc::Rc;
use yew::prelude::*;
use yew::suspense::{Suspension, SuspensionResult};
/// This hook is used to await a future in a suspending context.
///
/// A [Suspension] is created from the passed future and the result of the future
/// is the output of the suspension.
pub struct UseFutureHandle<O> {
inner: UseStateHandle<Option<O>>,
}
impl<O> Clone for UseFutureHandle<O> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<O> Deref for UseFutureHandle<O> {
type Target = O;
fn deref(&self) -> &Self::Target {
self.inner.as_ref().unwrap()
}
}
impl<T: fmt::Debug> fmt::Debug for UseFutureHandle<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UseFutureHandle")
.field("value", &format!("{:?}", self.inner))
.finish()
}
}
/// Use the result of an async computation, suspending while waiting.
///
/// Awaits the future returned from the first call to `init_f`, and returns
/// its result in a [`UseFutureHandle`]. Always suspends initially, even if
/// the future is immediately [ready].
///
/// [ready]: std::task::Poll::Ready
///
/// # Example
///
/// ```
/// # use yew::prelude::*;
/// # use yew::suspense::use_future;
/// use gloo::net::http::Request;
///
/// const URL: &str = "https://en.wikipedia.org/w/api.php?\
/// action=query&origin=*&format=json&generator=search&\
/// gsrnamespace=0&gsrlimit=5&gsrsearch='New_England_Patriots'";
///
/// #[component]
/// fn WikipediaSearch() -> HtmlResult {
/// let res = use_future(|| async { Request::get(URL).send().await?.text().await })?;
/// let result_html = match *res {
/// Ok(ref res) => html! { res },
/// Err(ref failure) => failure.to_string().into(),
/// };
/// Ok(html! {
/// <p>
/// {"Wikipedia search result: "}
/// {result_html}
/// </p>
/// })
/// }
/// ```
#[hook]
pub fn use_future<F, T, O>(init_f: F) -> SuspensionResult<UseFutureHandle<O>>
where
F: FnOnce() -> T,
T: Future<Output = O> + 'static,
O: 'static,
{
use_future_with((), move |_| init_f())
}
/// Use the result of an async computation with dependencies, suspending while waiting.
///
/// Awaits the future returned from `f` for the latest `deps`. Even if the future is immediately
/// [ready], the hook suspends at least once. If the dependencies
/// change while a future is still pending, the result is never used. This guarantees that your
/// component always sees up-to-date values while it is not suspended.
///
/// [ready]: std::task::Poll::Ready
#[hook]
pub fn use_future_with<F, D, T, O>(deps: D, f: F) -> SuspensionResult<UseFutureHandle<O>>
where
F: FnOnce(Rc<D>) -> T,
T: Future<Output = O> + 'static,
O: 'static,
D: PartialEq + 'static,
{
let output = use_state(|| None);
// We only commit a result if it comes from the latest spawned future. Otherwise, this
// might trigger pointless updates or even override newer state.
let latest_id = use_ref(|| Cell::new(0u32));
let suspension = {
let output = output.clone();
use_memo_base(
move |deps| {
let self_id = latest_id.get().wrapping_add(1);
// As long as less than 2**32 futures are in flight wrapping_add is fine
(*latest_id).set(self_id);
let deps = Rc::new(deps);
let task = f(deps.clone());
let suspension = Suspension::from_future(async move {
let result = task.await;
if latest_id.get() == self_id {
output.set(Some(result));
}
});
(suspension, deps)
},
deps,
)
};
if suspension.resumed() {
Ok(UseFutureHandle { inner: output })
} else {
Err((*suspension).clone())
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/suspense/mod.rs | packages/yew/src/suspense/mod.rs | //! This module provides suspense support.
mod component;
mod hooks;
mod suspension;
#[cfg(any(feature = "csr", feature = "ssr"))]
pub(crate) use component::BaseSuspense;
pub use component::{Suspense, SuspenseProps};
pub use hooks::*;
pub use suspension::{Suspension, SuspensionHandle, SuspensionResult};
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/suspense/component.rs | packages/yew/src/suspense/component.rs | use crate::html::{Html, Properties};
/// Properties for [Suspense].
#[derive(Properties, PartialEq, Debug, Clone)]
pub struct SuspenseProps {
/// The Children of the current Suspense Component.
#[prop_or_default]
pub children: Html,
/// The Fallback UI of the current Suspense Component.
#[prop_or_default]
pub fallback: Html,
}
#[cfg(any(feature = "csr", feature = "ssr"))]
mod feat_csr_ssr {
use super::*;
use crate::html::{Component, Context, Html, Scope};
use crate::suspense::Suspension;
#[cfg(feature = "hydration")]
use crate::suspense::SuspensionHandle;
use crate::virtual_dom::{VNode, VSuspense};
use crate::{component, html};
#[derive(Properties, PartialEq, Debug, Clone)]
pub(crate) struct BaseSuspenseProps {
pub children: Html,
#[prop_or(None)]
pub fallback: Option<Html>,
}
#[derive(Debug)]
pub(crate) enum BaseSuspenseMsg {
Suspend(Suspension),
Resume(Suspension),
}
#[derive(Debug)]
pub(crate) struct BaseSuspense {
suspensions: Vec<Suspension>,
#[cfg(feature = "hydration")]
hydration_handle: Option<SuspensionHandle>,
}
impl Component for BaseSuspense {
type Message = BaseSuspenseMsg;
type Properties = BaseSuspenseProps;
fn create(_ctx: &Context<Self>) -> Self {
#[cfg(not(feature = "hydration"))]
let suspensions = Vec::new();
// We create a suspension to block suspense until its rendered method is notified.
#[cfg(feature = "hydration")]
let (suspensions, hydration_handle) = {
use crate::callback::Callback;
use crate::html::RenderMode;
match _ctx.creation_mode() {
RenderMode::Hydration => {
let link = _ctx.link().clone();
let (s, handle) = Suspension::new();
s.listen(Callback::from(move |s| {
link.send_message(BaseSuspenseMsg::Resume(s));
}));
(vec![s], Some(handle))
}
_ => (Vec::new(), None),
}
};
Self {
suspensions,
#[cfg(feature = "hydration")]
hydration_handle,
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Self::Message::Suspend(m) => {
assert!(
ctx.props().fallback.is_some(),
"You cannot suspend from a component rendered as a fallback."
);
if m.resumed() {
return false;
}
// If a suspension already exists, ignore it.
if self.suspensions.iter().any(|n| n == &m) {
return false;
}
self.suspensions.push(m);
true
}
Self::Message::Resume(ref m) => {
let suspensions_len = self.suspensions.len();
self.suspensions.retain(|n| m != n);
suspensions_len != self.suspensions.len()
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
let BaseSuspenseProps { children, fallback } = (*ctx.props()).clone();
let children = html! {<>{children}</>};
match fallback {
Some(fallback) => {
let vsuspense = VSuspense::new(
children,
fallback,
!self.suspensions.is_empty(),
// We don't need to key this as the key will be applied to the component.
None,
);
VNode::from(vsuspense)
}
None => children,
}
}
#[cfg(feature = "hydration")]
fn rendered(&mut self, _ctx: &Context<Self>, first_render: bool) {
if first_render {
if let Some(m) = self.hydration_handle.take() {
m.resume();
}
}
}
}
impl BaseSuspense {
pub(crate) fn suspend(scope: &Scope<Self>, s: Suspension) {
scope.send_message(BaseSuspenseMsg::Suspend(s));
}
pub(crate) fn resume(scope: &Scope<Self>, s: Suspension) {
scope.send_message(BaseSuspenseMsg::Resume(s));
}
}
/// Suspend rendering and show a fallback UI until the underlying task completes.
#[component]
pub fn Suspense(props: &SuspenseProps) -> Html {
let SuspenseProps { children, fallback } = props.clone();
let fallback = html! {
<BaseSuspense>
{fallback}
</BaseSuspense>
};
html! {
<BaseSuspense {fallback}>
{children}
</BaseSuspense>
}
}
}
#[cfg(any(feature = "csr", feature = "ssr"))]
pub use feat_csr_ssr::*;
#[cfg(not(any(feature = "ssr", feature = "csr")))]
mod feat_no_csr_ssr {
use super::*;
use crate::component;
/// Suspend rendering and show a fallback UI until the underlying task completes.
#[component]
pub fn Suspense(_props: &SuspenseProps) -> Html {
Html::default()
}
}
#[cfg(not(any(feature = "ssr", feature = "csr")))]
pub use feat_no_csr_ssr::*;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/mod.rs | packages/yew/src/functional/mod.rs | //! Function components are a simplified version of normal components.
//! They consist of a single function annotated with the attribute `#[component]`
//! that receives props and determines what should be rendered by returning [`Html`](crate::Html).
//!
//! Functions with the attribute have to return `Html` and may take a single parameter for the type
//! of props the component should accept. The parameter type needs to be a reference to a
//! `Properties` type (ex. `props: &MyProps`). If the function doesn't have any parameters the
//! resulting component doesn't accept any props.
//!
//! Just mark the component with the attribute. The component will be named after the function.
//!
//! ```rust
//! # use yew::prelude::*;
//! #
//! #[component]
//! fn HelloWorld() -> Html {
//! html! { "Hello world" }
//! }
//! ```
//!
//! More details about function components and Hooks can be found on [Yew Docs](https://yew.rs/docs/next/concepts/function-components/introduction)
use std::any::Any;
use std::cell::RefCell;
use std::fmt;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
#[cfg(all(feature = "hydration", feature = "ssr"))]
use crate::html::RenderMode;
use crate::html::{AnyScope, BaseComponent, Context, HtmlResult};
use crate::Properties;
mod hooks;
pub use hooks::*;
/// This attribute creates a function component from a normal Rust function.
///
/// Functions with this attribute **must** return `Html` and can optionally take an argument
/// for props. Note that the function only receives a reference to the props.
///
/// When using this attribute you need to provide a name for the component:
/// `#component(ComponentName)]`.
/// The attribute will then automatically create a [`FunctionComponent`] with the given
/// identifier which you can use like a normal component.
///
/// # Example
/// ```rust
/// # use yew::prelude::*;
/// #
/// # #[derive(Properties, Clone, PartialEq)]
/// # pub struct Props {
/// # text: String
/// # }
/// #
/// #[component(NameOfComponent)]
/// pub fn component(props: &Props) -> Html {
/// html! {
/// <p>{ &props.text }</p>
/// }
/// }
/// ```
pub use yew_macro::function_component as component;
/// A re-export of [`component`](yew_macro::function_component) with the older name.
#[deprecated(since = "0.22.0", note = "renamed to `#[component]")]
pub use yew_macro::function_component;
/// This attribute creates a user-defined hook from a normal Rust function.
pub use yew_macro::hook;
type ReRender = Rc<dyn Fn()>;
/// Primitives of a prepared state hook.
#[cfg(any(feature = "hydration", feature = "ssr"))]
pub(crate) trait PreparedState {
#[cfg(feature = "ssr")]
fn prepare(&self) -> String;
}
/// Primitives of an effect hook.
pub(crate) trait Effect {
fn rendered(&self) {}
}
/// A hook context to be passed to hooks.
pub struct HookContext {
pub(crate) scope: AnyScope,
#[cfg(all(feature = "hydration", feature = "ssr"))]
creation_mode: RenderMode,
re_render: ReRender,
states: Vec<Rc<dyn Any>>,
effects: Vec<Rc<dyn Effect>>,
#[cfg(any(feature = "hydration", feature = "ssr"))]
prepared_states: Vec<Rc<dyn PreparedState>>,
#[cfg(feature = "hydration")]
prepared_states_data: Vec<Rc<str>>,
#[cfg(feature = "hydration")]
prepared_state_counter: usize,
counter: usize,
#[cfg(debug_assertions)]
total_hook_counter: Option<usize>,
}
impl HookContext {
fn new(
scope: AnyScope,
re_render: ReRender,
#[cfg(all(feature = "hydration", feature = "ssr"))] creation_mode: RenderMode,
#[cfg(feature = "hydration")] prepared_state: Option<&str>,
) -> RefCell<Self> {
RefCell::new(HookContext {
scope,
re_render,
#[cfg(all(feature = "hydration", feature = "ssr"))]
creation_mode,
states: Vec::new(),
#[cfg(any(feature = "hydration", feature = "ssr"))]
prepared_states: Vec::new(),
effects: Vec::new(),
#[cfg(feature = "hydration")]
prepared_states_data: {
match prepared_state {
Some(m) => m.split(',').map(Rc::from).collect(),
None => Vec::new(),
}
},
#[cfg(feature = "hydration")]
prepared_state_counter: 0,
counter: 0,
#[cfg(debug_assertions)]
total_hook_counter: None,
})
}
pub(crate) fn next_state<T>(&mut self, initializer: impl FnOnce(ReRender) -> T) -> Rc<T>
where
T: 'static,
{
// Determine which hook position we're at and increment for the next hook
let hook_pos = self.counter;
self.counter += 1;
let state = match self.states.get(hook_pos).cloned() {
Some(m) => m,
None => {
let initial_state = Rc::new(initializer(self.re_render.clone()));
self.states.push(initial_state.clone());
initial_state
}
};
state.downcast().unwrap_throw()
}
pub(crate) fn next_effect<T>(&mut self, initializer: impl FnOnce(ReRender) -> T) -> Rc<T>
where
T: 'static + Effect,
{
let prev_state_len = self.states.len();
let t = self.next_state(initializer);
// This is a new effect, we add it to effects.
if self.states.len() != prev_state_len {
self.effects.push(t.clone());
}
t
}
#[cfg(any(feature = "hydration", feature = "ssr"))]
pub(crate) fn next_prepared_state<T>(
&mut self,
initializer: impl FnOnce(ReRender, Option<&str>) -> T,
) -> Rc<T>
where
T: 'static + PreparedState,
{
#[cfg(not(feature = "hydration"))]
let prepared_state = Option::<Rc<str>>::None;
#[cfg(feature = "hydration")]
let prepared_state = {
let prepared_state_pos = self.prepared_state_counter;
self.prepared_state_counter += 1;
self.prepared_states_data.get(prepared_state_pos).cloned()
};
let prev_state_len = self.states.len();
let t = self.next_state(move |re_render| initializer(re_render, prepared_state.as_deref()));
// This is a new effect, we add it to effects.
if self.states.len() != prev_state_len {
self.prepared_states.push(t.clone());
}
t
}
#[inline(always)]
fn prepare_run(&mut self) {
#[cfg(feature = "hydration")]
{
self.prepared_state_counter = 0;
}
self.counter = 0;
}
/// asserts hook counter.
///
/// This function asserts that the number of hooks matches for every render.
#[cfg(debug_assertions)]
fn assert_hook_context(&mut self, render_ok: bool) {
// Procedural Macros can catch most conditionally called hooks at compile time, but it
// cannot detect early return (as the return can be Err(_), Suspension).
match (render_ok, self.total_hook_counter) {
// First rendered,
// we store the hook counter.
(true, None) => {
self.total_hook_counter = Some(self.counter);
}
// Component is suspended before it's first rendered.
// We don't have a total count to compare with.
(false, None) => {}
// Subsequent render,
// we compare stored total count and current render count.
(true, Some(total_hook_counter)) => assert_eq!(
total_hook_counter, self.counter,
"Hooks are called conditionally."
),
// Subsequent suspension,
// components can have less hooks called when suspended, but not more.
(false, Some(total_hook_counter)) => assert!(
self.counter <= total_hook_counter,
"Hooks are called conditionally."
),
}
}
fn run_effects(&self) {
for effect in self.effects.iter() {
effect.rendered();
}
}
fn drain_states(&mut self) {
// We clear the effects as these are also references to states.
self.effects.clear();
for state in self.states.drain(..) {
drop(state);
}
}
#[cfg(not(feature = "ssr"))]
fn prepare_state(&self) -> Option<String> {
None
}
#[cfg(feature = "ssr")]
fn prepare_state(&self) -> Option<String> {
if self.prepared_states.is_empty() {
return None;
}
let prepared_states = self.prepared_states.clone();
let mut states = Vec::new();
for state in prepared_states.iter() {
let state = state.prepare();
states.push(state);
}
Some(states.join(","))
}
}
impl fmt::Debug for HookContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("HookContext<_>")
}
}
/// Trait that allows a struct to act as Function Component.
pub trait FunctionProvider {
/// Properties for the Function Component.
type Properties: Properties + PartialEq;
/// Render the component. This function returns the [`Html`](crate::Html) to be rendered for the
/// component.
///
/// Equivalent of [`Component::view`](crate::html::Component::view).
fn run(ctx: &mut HookContext, props: &Self::Properties) -> HtmlResult;
}
/// A type that interacts [`FunctionProvider`] to provide lifecycle events to be bridged to
/// [`BaseComponent`].
///
/// # Note
///
/// Function Components should not be implemented with this type directly.
///
/// Use the `#[component]` macro instead.
#[doc(hidden)]
pub struct FunctionComponent<T>
where
T: FunctionProvider,
{
_never: std::marker::PhantomData<T>,
hook_ctx: RefCell<HookContext>,
}
impl<T> FunctionComponent<T>
where
T: FunctionProvider + 'static,
{
/// Creates a new function component.
pub fn new(ctx: &Context<T>) -> Self
where
T: BaseComponent<Message = ()> + FunctionProvider + 'static,
{
let scope = AnyScope::from(ctx.link().clone());
let re_render = {
let link = ctx.link().clone();
Rc::new(move || link.send_message(()))
};
Self {
_never: std::marker::PhantomData,
hook_ctx: HookContext::new(
scope,
re_render,
#[cfg(all(feature = "hydration", feature = "ssr"))]
ctx.creation_mode(),
#[cfg(feature = "hydration")]
ctx.prepared_state(),
),
}
}
/// Renders a function component.
pub fn render(&self, props: &T::Properties) -> HtmlResult {
let mut hook_ctx = self.hook_ctx.borrow_mut();
hook_ctx.prepare_run();
#[allow(clippy::let_and_return)]
let result = T::run(&mut hook_ctx, props);
#[cfg(debug_assertions)]
hook_ctx.assert_hook_context(result.is_ok());
result
}
/// Run Effects of a function component.
pub fn rendered(&self) {
let hook_ctx = self.hook_ctx.borrow();
hook_ctx.run_effects();
}
/// Destroys the function component.
pub fn destroy(&self) {
let mut hook_ctx = self.hook_ctx.borrow_mut();
hook_ctx.drain_states();
}
/// Prepares the server-side state.
pub fn prepare_state(&self) -> Option<String> {
let hook_ctx = self.hook_ctx.borrow();
hook_ctx.prepare_state()
}
}
impl<T> fmt::Debug for FunctionComponent<T>
where
T: FunctionProvider + 'static,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("FunctionComponent<_>")
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_effect.rs | packages/yew/src/functional/hooks/use_effect.rs | use std::cell::RefCell;
use crate::functional::{hook, Effect, Hook, HookContext};
/// Trait describing the destructor of [`use_effect`] hook.
pub trait TearDown: Sized + 'static {
/// The function that is executed when destructor is called
fn tear_down(self);
}
impl TearDown for () {
fn tear_down(self) {}
}
impl<F: FnOnce() + 'static> TearDown for F {
fn tear_down(self) {
self()
}
}
struct UseEffectBase<T, F, D>
where
F: FnOnce(&T) -> D + 'static,
T: 'static,
D: TearDown,
{
runner_with_deps: Option<(T, F)>,
destructor: Option<D>,
deps: Option<T>,
effect_changed_fn: fn(Option<&T>, Option<&T>) -> bool,
}
impl<T, F, D> Effect for RefCell<UseEffectBase<T, F, D>>
where
F: FnOnce(&T) -> D + 'static,
T: 'static,
D: TearDown,
{
fn rendered(&self) {
let mut this = self.borrow_mut();
if let Some((deps, runner)) = this.runner_with_deps.take() {
if !(this.effect_changed_fn)(Some(&deps), this.deps.as_ref()) {
return;
}
if let Some(de) = this.destructor.take() {
de.tear_down();
}
let new_destructor = runner(&deps);
this.deps = Some(deps);
this.destructor = Some(new_destructor);
}
}
}
impl<T, F, D> Drop for UseEffectBase<T, F, D>
where
F: FnOnce(&T) -> D + 'static,
T: 'static,
D: TearDown,
{
fn drop(&mut self) {
if let Some(destructor) = self.destructor.take() {
destructor.tear_down()
}
}
}
fn use_effect_base<T, D>(
runner: impl FnOnce(&T) -> D + 'static,
deps: T,
effect_changed_fn: fn(Option<&T>, Option<&T>) -> bool,
) -> impl Hook<Output = ()>
where
T: 'static,
D: TearDown,
{
struct HookProvider<T, F, D>
where
F: FnOnce(&T) -> D + 'static,
T: 'static,
D: TearDown,
{
runner: F,
deps: T,
effect_changed_fn: fn(Option<&T>, Option<&T>) -> bool,
}
impl<T, F, D> Hook for HookProvider<T, F, D>
where
F: FnOnce(&T) -> D + 'static,
T: 'static,
D: TearDown,
{
type Output = ();
fn run(self, ctx: &mut HookContext) -> Self::Output {
let Self {
runner,
deps,
effect_changed_fn,
} = self;
let state = ctx.next_effect(|_| -> RefCell<UseEffectBase<T, F, D>> {
RefCell::new(UseEffectBase {
runner_with_deps: None,
destructor: None,
deps: None,
effect_changed_fn,
})
});
state.borrow_mut().runner_with_deps = Some((deps, runner));
}
}
HookProvider {
runner,
deps,
effect_changed_fn,
}
}
/// `use_effect` is used for hooking into the component's lifecycle and creating side effects.
///
/// The callback is called every time after the component's render has finished.
///
/// # Example
///
/// ```rust
/// use yew::prelude::*;
/// # use std::rc::Rc;
///
/// #[component(UseEffect)]
/// fn effect() -> Html {
/// let counter = use_state(|| 0);
///
/// let counter_one = counter.clone();
/// use_effect(move || {
/// // Make a call to DOM API after component is rendered
/// gloo::utils::document().set_title(&format!("You clicked {} times", *counter_one));
///
/// // Perform the cleanup
/// || gloo::utils::document().set_title(&format!("You clicked 0 times"))
/// });
///
/// let onclick = {
/// let counter = counter.clone();
/// Callback::from(move |_| counter.set(*counter + 1))
/// };
///
/// html! {
/// <button {onclick}>{ format!("Increment to {}", *counter) }</button>
/// }
/// }
/// ```
///
/// # Destructor
///
/// Any type implementing [`TearDown`] can be used as destructor, which is called when the component
/// is re-rendered
///
/// ## Tip
///
/// The callback can return [`()`] if there is no destructor to run.
#[hook]
pub fn use_effect<F, D>(f: F)
where
F: FnOnce() -> D + 'static,
D: TearDown,
{
use_effect_base(|_| f(), (), |_, _| true);
}
/// This hook is similar to [`use_effect`] but it accepts dependencies.
///
/// Whenever the dependencies are changed, the effect callback is called again.
/// To detect changes, dependencies must implement [`PartialEq`].
///
/// # Note
/// The destructor also runs when dependencies change.
///
/// # Example
///
/// ```rust
/// use yew::{component, html, use_effect_with, Html, Properties};
/// # use gloo::console::log;
///
/// #[derive(Properties, PartialEq)]
/// pub struct Props {
/// pub is_loading: bool,
/// }
///
/// #[component]
/// fn HelloWorld(props: &Props) -> Html {
/// let is_loading = props.is_loading.clone();
///
/// use_effect_with(is_loading, move |_| {
/// log!(" Is loading prop changed!");
/// });
///
/// html! {
/// <>{"Am I loading? - "}{is_loading}</>
/// }
/// }
/// ```
///
/// # Tips
///
/// ## Only on first render
///
/// Provide a empty tuple `()` as dependencies when you need to do something only on the first
/// render of a component.
///
/// ```rust
/// use yew::{component, html, use_effect_with, Html};
/// # use gloo::console::log;
///
/// #[component]
/// fn HelloWorld() -> Html {
/// use_effect_with((), move |_| {
/// log!("I got rendered, yay!");
/// });
///
/// html! { "Hello" }
/// }
/// ```
///
/// ## On destructing or last render
///
/// Use [Only on first render](#only-on-first-render) but put the code in the cleanup function.
/// It will only get called when the component is removed from view / gets destroyed.
///
/// ```rust
/// use yew::{component, html, use_effect_with, Html};
/// # use gloo::console::log;
///
/// #[component]
/// fn HelloWorld() -> Html {
/// use_effect_with((), move |_| {
/// || {
/// log!("Noo dont kill me, ahhh!");
/// }
/// });
///
/// html! { "Hello" }
/// }
/// ```
///
/// Any type implementing [`TearDown`] can be used as destructor
///
/// ### Tip
///
/// The callback can return [`()`] if there is no destructor to run.
pub fn use_effect_with<T, F, D>(deps: T, f: F) -> impl Hook<Output = ()>
where
T: PartialEq + 'static,
F: FnOnce(&T) -> D + 'static,
D: TearDown,
{
use_effect_base(f, deps, |lhs, rhs| lhs != rhs)
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_state.rs | packages/yew/src/functional/hooks/use_state.rs | use std::fmt;
use std::ops::Deref;
use std::rc::Rc;
use implicit_clone::ImplicitClone;
use super::{use_reducer, use_reducer_eq, Reducible, UseReducerDispatcher, UseReducerHandle};
use crate::functional::hook;
use crate::html::IntoPropValue;
use crate::Callback;
struct UseStateReducer<T> {
value: T,
}
impl<T> Reducible for UseStateReducer<T> {
type Action = T;
fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
Rc::new(Self { value: action })
}
}
impl<T> PartialEq for UseStateReducer<T>
where
T: PartialEq,
{
fn eq(&self, rhs: &Self) -> bool {
self.value == rhs.value
}
}
/// This hook is used to manage state in a function component.
///
/// This hook will always trigger a re-render upon receiving a new state. See [`use_state_eq`]
/// if you want the component to only re-render when the new state compares unequal
/// to the existing one.
///
/// # Example
///
/// ```rust
/// use yew::prelude::*;
/// # use std::rc::Rc;
///
/// #[component(UseState)]
/// fn state() -> Html {
/// let counter = use_state(|| 0);
/// let onclick = {
/// let counter = counter.clone();
/// Callback::from(move |_| counter.set(*counter + 1))
/// };
///
/// html! {
/// <div>
/// <button {onclick}>{ "Increment value" }</button>
/// <p>
/// <b>{ "Current value: " }</b>
/// { *counter }
/// </p>
/// </div>
/// }
/// }
/// ```
///
/// # Caution
///
/// The value held in the handle will reflect the value of at the time the
/// handle is returned by the `use_state()` call. It is possible that the handle does
/// not dereference to an up to date value, for example if you are moving it into a
/// `use_effect_with` hook. You can register the
/// state to the dependents so the hook can be updated when the value changes.
///
/// # Tip
///
/// The setter function is guaranteed to be the same across the entire
/// component lifecycle. You can safely omit the `UseStateHandle` from the
/// dependents of `use_effect_with` if you only intend to set
/// values from within the hook.
#[hook]
pub fn use_state<T, F>(init_fn: F) -> UseStateHandle<T>
where
T: 'static,
F: FnOnce() -> T,
{
let handle = use_reducer(move || UseStateReducer { value: init_fn() });
UseStateHandle { inner: handle }
}
/// [`use_state`] but only re-renders when `prev_state != next_state`.
///
/// This hook requires the state to implement [`PartialEq`].
#[hook]
pub fn use_state_eq<T, F>(init_fn: F) -> UseStateHandle<T>
where
T: PartialEq + 'static,
F: FnOnce() -> T,
{
let handle = use_reducer_eq(move || UseStateReducer { value: init_fn() });
UseStateHandle { inner: handle }
}
/// State handle for the [`use_state`] hook.
pub struct UseStateHandle<T> {
inner: UseReducerHandle<UseStateReducer<T>>,
}
impl<T: fmt::Debug> fmt::Debug for UseStateHandle<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UseStateHandle")
.field("value", &format!("{:?}", self.inner.value))
.finish()
}
}
impl<T> UseStateHandle<T> {
/// Replaces the value
pub fn set(&self, value: T) {
self.inner.dispatch(value)
}
/// Returns the setter of current state.
pub fn setter(&self) -> UseStateSetter<T> {
UseStateSetter {
inner: self.inner.dispatcher(),
}
}
}
impl<T> Deref for UseStateHandle<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&(*self.inner).value
}
}
impl<T> Clone for UseStateHandle<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T> PartialEq for UseStateHandle<T>
where
T: PartialEq,
{
fn eq(&self, rhs: &Self) -> bool {
*self.inner == *rhs.inner
}
}
impl<T> ImplicitClone for UseStateHandle<T> {}
/// Setter handle for [`use_state`] and [`use_state_eq`] hook
pub struct UseStateSetter<T> {
inner: UseReducerDispatcher<UseStateReducer<T>>,
}
impl<T> Clone for UseStateSetter<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T> fmt::Debug for UseStateSetter<T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UseStateSetter").finish()
}
}
impl<T> From<UseStateSetter<T>> for Callback<T> {
fn from(value: UseStateSetter<T>) -> Self {
Self::from(value.inner)
}
}
impl<T> IntoPropValue<Callback<T>> for UseStateSetter<T> {
fn into_prop_value(self) -> Callback<T> {
self.inner.into_prop_value()
}
}
impl<T> PartialEq for UseStateSetter<T> {
fn eq(&self, rhs: &Self) -> bool {
self.inner == rhs.inner
}
}
impl<T> ImplicitClone for UseStateSetter<T> {}
impl<T> UseStateSetter<T> {
/// Replaces the value
pub fn set(&self, value: T) {
self.inner.dispatch(value)
}
/// Get a callback, invoking which is equivalent to calling `set()`
/// on this same setter.
pub fn to_callback(&self) -> Callback<T> {
self.inner.to_callback()
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_callback.rs | packages/yew/src/functional/hooks/use_callback.rs | use std::rc::Rc;
use crate::callback::Callback;
use crate::functional::{hook, use_memo};
/// Get a immutable reference to a memoized `Callback`. Its state persists across renders.
/// It will be recreated only if any of the dependencies changes value.
///
/// Memoization means it will only get recreated when provided dependencies update/change.
/// This is useful when passing callbacks to optimized child components that rely on
/// PartialEq to prevent unnecessary renders.
///
/// # Example
///
/// ```rust
/// # use yew::prelude::*;
/// #
/// #[derive(Properties, PartialEq)]
/// pub struct Props {
/// pub callback: Callback<String, String>,
/// }
///
/// #[component(MyComponent)]
/// fn my_component(props: &Props) -> Html {
/// let greeting = props.callback.emit("Yew".to_string());
///
/// html! {
/// <>{ &greeting }</>
/// }
/// }
///
/// #[component(UseCallback)]
/// fn callback() -> Html {
/// let counter = use_state(|| 0);
/// let onclick = {
/// let counter = counter.clone();
/// Callback::from(move |_| counter.set(*counter + 1))
/// };
///
/// // This callback depends on (), so it's created only once, then MyComponent
/// // will be rendered only once even when you click the button multiple times.
/// let callback = use_callback((), move |name, _| format!("Hello, {}!", name));
///
/// // It can also be used for events, this callback depends on `counter`.
/// let oncallback = use_callback(counter.clone(), move |_e, counter| {
/// let _ = **counter;
/// });
///
/// html! {
/// <div>
/// <button {onclick}>{ "Increment value" }</button>
/// <button onclick={oncallback}>{ "Callback" }</button>
/// <p>
/// <b>{ "Current value: " }</b>
/// { *counter }
/// </p>
/// <MyComponent {callback} />
/// </div>
/// }
/// }
/// ```
#[hook]
pub fn use_callback<IN, OUT, F, D>(deps: D, f: F) -> Callback<IN, OUT>
where
IN: 'static,
OUT: 'static,
F: Fn(IN, &D) -> OUT + 'static,
D: PartialEq + 'static,
{
let deps = Rc::new(deps);
(*use_memo(deps, move |deps| {
let deps = deps.clone();
let f = move |value: IN| f(value, deps.as_ref());
Callback::from(f)
}))
.clone()
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_ref.rs | packages/yew/src/functional/hooks/use_ref.rs | use std::cell::RefCell;
use std::rc::Rc;
use crate::functional::{hook, use_state, Hook, HookContext};
use crate::NodeRef;
struct UseRef<F> {
init_fn: F,
}
impl<T: 'static, F: FnOnce() -> T> Hook for UseRef<F> {
type Output = Rc<T>;
fn run(self, ctx: &mut HookContext) -> Self::Output {
ctx.next_state(|_| (self.init_fn)())
}
}
/// This hook is used for obtaining a reference to a stateful value.
/// Its state persists across renders.
///
/// Mutation must be done via interior mutability, such as `Cell` or `RefCell`.
///
/// It is important to note that you do not get notified of state changes.
/// If you need the component to be re-rendered on state change, consider using
/// [`use_state`](super::use_state()).
///
/// # Example
/// ```rust
/// use std::cell::Cell;
/// use std::ops::{Deref, DerefMut};
/// use std::rc::Rc;
///
/// use web_sys::HtmlInputElement;
/// use yew::prelude::*;
///
/// #[component(UseRef)]
/// fn ref_hook() -> Html {
/// let message = use_state(|| "".to_string());
/// let message_count = use_ref(|| Cell::new(0));
///
/// let onclick = Callback::from(move |e| {
/// let window = gloo::utils::window();
///
/// if message_count.get() > 3 {
/// window.alert_with_message("Message limit reached");
/// } else {
/// message_count.set(message_count.get() + 1);
/// window.alert_with_message("Message sent");
/// }
/// });
///
/// let onchange = {
/// let message = message.clone();
/// Callback::from(move |e: Event| {
/// let input: HtmlInputElement = e.target_unchecked_into();
/// message.set(input.value())
/// })
/// };
///
/// html! {
/// <div>
/// <input {onchange} value={(*message).clone()} />
/// <button {onclick}>{ "Send" }</button>
/// </div>
/// }
/// }
pub fn use_ref<T: 'static, F>(init_fn: F) -> impl Hook<Output = Rc<T>>
where
F: FnOnce() -> T,
{
UseRef { init_fn }
}
/// This hook is used for obtaining a mutable reference to a stateful value.
/// Its state persists across renders.
///
/// It is important to note that you do not get notified of state changes.
/// If you need the component to be re-rendered on state change, consider using
/// [`use_state`](super::use_state()).
///
/// # Example
/// ```rust
/// use std::cell::RefCell;
/// use std::ops::{Deref, DerefMut};
/// use std::rc::Rc;
///
/// use web_sys::HtmlInputElement;
/// use yew::prelude::*;
///
/// #[component(UseRef)]
/// fn ref_hook() -> Html {
/// let message = use_state(|| "".to_string());
/// let message_count = use_mut_ref(|| 0);
///
/// let onclick = Callback::from(move |e| {
/// let window = gloo::utils::window();
///
/// if *message_count.borrow_mut() > 3 {
/// window.alert_with_message("Message limit reached");
/// } else {
/// *message_count.borrow_mut() += 1;
/// window.alert_with_message("Message sent");
/// }
/// });
///
/// let onchange = {
/// let message = message.clone();
/// Callback::from(move |e: Event| {
/// let input: HtmlInputElement = e.target_unchecked_into();
/// message.set(input.value())
/// })
/// };
///
/// html! {
/// <div>
/// <input {onchange} value={(*message).clone()} />
/// <button {onclick}>{ "Send" }</button>
/// </div>
/// }
/// }
/// ```
pub fn use_mut_ref<T: 'static, F>(init_fn: F) -> impl Hook<Output = Rc<RefCell<T>>>
where
F: FnOnce() -> T,
{
UseRef {
init_fn: || RefCell::new(init_fn()),
}
}
/// This hook is used for obtaining a [`NodeRef`].
/// It persists across renders.
///
/// The `ref` attribute can be used to attach the [`NodeRef`] to an HTML element. In callbacks,
/// you can then get the DOM `Element` that the `ref` is attached to.
///
/// # Example
///
/// ```rust
/// use wasm_bindgen::prelude::Closure;
/// use wasm_bindgen::JsCast;
/// use web_sys::{Event, HtmlElement};
/// use yew::{component, html, use_effect_with, use_node_ref, Html};
///
/// #[component(UseNodeRef)]
/// pub fn node_ref_hook() -> Html {
/// let div_ref = use_node_ref();
///
/// {
/// let div_ref = div_ref.clone();
///
/// use_effect_with(div_ref, |div_ref| {
/// let div = div_ref
/// .cast::<HtmlElement>()
/// .expect("div_ref not attached to div element");
///
/// let listener = Closure::<dyn Fn(Event)>::wrap(Box::new(|_| {
/// web_sys::console::log_1(&"Clicked!".into());
/// }));
///
/// div.add_event_listener_with_callback("click", listener.as_ref().unchecked_ref())
/// .unwrap();
///
/// move || {
/// div.remove_event_listener_with_callback(
/// "click",
/// listener.as_ref().unchecked_ref(),
/// )
/// .unwrap();
/// }
/// });
/// }
///
/// html! {
/// <div ref={div_ref}>
/// { "Click me and watch the console log!" }
/// </div>
/// }
/// }
/// ```
///
/// # Tip
///
/// When conditionally rendering elements you can use `NodeRef` in conjunction with
/// `use_effect_with` to perform actions each time an element is rendered and just before the
/// component where the hook is used in is going to be removed from the DOM.
#[hook]
pub fn use_node_ref() -> NodeRef {
(*use_state(NodeRef::default)).clone()
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_reducer.rs | packages/yew/src/functional/hooks/use_reducer.rs | use std::cell::RefCell;
use std::fmt;
use std::marker::PhantomData;
use std::ops::Deref;
use std::rc::Rc;
use implicit_clone::ImplicitClone;
use crate::functional::{hook, Hook, HookContext};
use crate::html::IntoPropValue;
use crate::Callback;
type DispatchFn<T> = Rc<dyn Fn(<T as Reducible>::Action)>;
/// A trait that implements a reducer function of a type.
pub trait Reducible {
/// The action type of the reducer.
type Action;
/// The reducer function.
fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self>;
}
struct UseReducer<T>
where
T: Reducible,
{
current_state: Rc<RefCell<Rc<T>>>,
dispatch: DispatchFn<T>,
}
/// State handle for [`use_reducer`] and [`use_reducer_eq`] hook
pub struct UseReducerHandle<T>
where
T: Reducible,
{
value: Rc<T>,
dispatch: DispatchFn<T>,
}
impl<T> UseReducerHandle<T>
where
T: Reducible,
{
/// Dispatch the given action to the reducer.
pub fn dispatch(&self, value: T::Action) {
(self.dispatch)(value)
}
/// Returns the dispatcher of the current state.
pub fn dispatcher(&self) -> UseReducerDispatcher<T> {
UseReducerDispatcher {
dispatch: self.dispatch.clone(),
}
}
}
impl<T> Deref for UseReducerHandle<T>
where
T: Reducible,
{
type Target = T;
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl<T> Clone for UseReducerHandle<T>
where
T: Reducible,
{
fn clone(&self) -> Self {
Self {
value: Rc::clone(&self.value),
dispatch: Rc::clone(&self.dispatch),
}
}
}
impl<T> fmt::Debug for UseReducerHandle<T>
where
T: Reducible + fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UseReducerHandle")
.field("value", &format!("{:?}", self.value))
.finish()
}
}
impl<T> PartialEq for UseReducerHandle<T>
where
T: Reducible + PartialEq,
{
fn eq(&self, rhs: &Self) -> bool {
self.value == rhs.value
}
}
impl<T> ImplicitClone for UseReducerHandle<T> where T: Reducible {}
/// Dispatcher handle for [`use_reducer`] and [`use_reducer_eq`] hook
pub struct UseReducerDispatcher<T>
where
T: Reducible,
{
dispatch: DispatchFn<T>,
}
impl<T> Clone for UseReducerDispatcher<T>
where
T: Reducible,
{
fn clone(&self) -> Self {
Self {
dispatch: Rc::clone(&self.dispatch),
}
}
}
impl<T> fmt::Debug for UseReducerDispatcher<T>
where
T: Reducible + fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UseReducerDispatcher").finish()
}
}
impl<T> PartialEq for UseReducerDispatcher<T>
where
T: Reducible,
{
fn eq(&self, rhs: &Self) -> bool {
// We are okay with comparisons from different compilation units to result in false
// not-equal results. This should only lead in the worst-case to some unneeded
// re-renders.
#[allow(ambiguous_wide_pointer_comparisons)]
Rc::ptr_eq(&self.dispatch, &rhs.dispatch)
}
}
impl<T> ImplicitClone for UseReducerDispatcher<T> where T: Reducible {}
impl<T> From<UseReducerDispatcher<T>> for Callback<<T as Reducible>::Action>
where
T: Reducible,
{
fn from(val: UseReducerDispatcher<T>) -> Self {
Callback { cb: val.dispatch }
}
}
impl<T> IntoPropValue<Callback<<T as Reducible>::Action>> for UseReducerDispatcher<T>
where
T: Reducible,
{
fn into_prop_value(self) -> Callback<<T as Reducible>::Action> {
Callback { cb: self.dispatch }
}
}
impl<T> UseReducerDispatcher<T>
where
T: Reducible,
{
/// Dispatch the given action to the reducer.
pub fn dispatch(&self, value: T::Action) {
(self.dispatch)(value)
}
/// Get a callback, invoking which is equivalent to calling `dispatch()`
/// on this same dispatcher.
pub fn to_callback(&self) -> Callback<<T as Reducible>::Action> {
Callback {
cb: self.dispatch.clone(),
}
}
}
/// The base function of [`use_reducer`] and [`use_reducer_eq`]
fn use_reducer_base<'hook, T>(
init_fn: impl 'hook + FnOnce() -> T,
should_render_fn: fn(&T, &T) -> bool,
) -> impl 'hook + Hook<Output = UseReducerHandle<T>>
where
T: Reducible + 'static,
{
struct HookProvider<'hook, T, F>
where
T: Reducible + 'static,
F: 'hook + FnOnce() -> T,
{
_marker: PhantomData<&'hook ()>,
init_fn: F,
should_render_fn: fn(&T, &T) -> bool,
}
impl<'hook, T, F> Hook for HookProvider<'hook, T, F>
where
T: Reducible + 'static,
F: 'hook + FnOnce() -> T,
{
type Output = UseReducerHandle<T>;
fn run(self, ctx: &mut HookContext) -> Self::Output {
let Self {
init_fn,
should_render_fn,
..
} = self;
let state = ctx.next_state(move |re_render| {
let val = Rc::new(RefCell::new(Rc::new(init_fn())));
let should_render_fn = Rc::new(should_render_fn);
UseReducer {
current_state: val.clone(),
dispatch: Rc::new(move |action: T::Action| {
let should_render = {
let should_render_fn = should_render_fn.clone();
let mut val = val.borrow_mut();
let next_val = (*val).clone().reduce(action);
let should_render = should_render_fn(&next_val, &val);
*val = next_val;
should_render
};
// Currently, this triggers a render immediately, so we need to release the
// borrowed reference first.
if should_render {
re_render()
}
}),
}
});
let value = state.current_state.borrow().clone();
let dispatch = state.dispatch.clone();
UseReducerHandle { value, dispatch }
}
}
HookProvider {
_marker: PhantomData,
init_fn,
should_render_fn,
}
}
/// This hook is an alternative to [`use_state`](super::use_state()).
/// It is used to handle component's state and is used when complex actions needs to be performed on
/// said state.
///
/// The state is expected to implement the [`Reducible`] trait which provides an `Action` type and a
/// reducer function.
///
/// The state object returned by the initial state function is required to
/// implement a `Reducible` trait which defines the associated `Action` type and a
/// reducer function.
///
/// This hook will always trigger a re-render upon receiving an action. See
/// [`use_reducer_eq`] if you want the component to only re-render when the state changes.
///
/// # Example
/// ```rust
/// # use yew::prelude::*;
/// # use std::rc::Rc;
/// #
///
/// /// reducer's Action
/// enum CounterAction {
/// Double,
/// Square,
/// }
///
/// /// reducer's State
/// struct CounterState {
/// counter: i32,
/// }
///
/// impl Default for CounterState {
/// fn default() -> Self {
/// Self { counter: 1 }
/// }
/// }
///
/// impl Reducible for CounterState {
/// /// Reducer Action Type
/// type Action = CounterAction;
///
/// /// Reducer Function
/// fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
/// let next_ctr = match action {
/// CounterAction::Double => self.counter * 2,
/// CounterAction::Square => self.counter.pow(2),
/// };
///
/// Self { counter: next_ctr }.into()
/// }
/// }
///
/// #[component(UseReducer)]
/// fn reducer() -> Html {
/// // The use_reducer hook takes an initialization function which will be called only once.
/// let counter = use_reducer(CounterState::default);
///
/// let double_onclick = {
/// let counter = counter.clone();
/// Callback::from(move |_| counter.dispatch(CounterAction::Double))
/// };
/// let square_onclick = {
/// let counter = counter.clone();
/// Callback::from(move |_| counter.dispatch(CounterAction::Square))
/// };
///
/// html! {
/// <>
/// <div id="result">{ counter.counter }</div>
///
/// <button onclick={double_onclick}>{ "Double" }</button>
/// <button onclick={square_onclick}>{ "Square" }</button>
/// </>
/// }
/// }
/// ```
///
/// # Tip
///
/// The dispatch function is guaranteed to be the same across the entire
/// component lifecycle. You can safely omit the `UseReducerHandle` from the
/// dependents of `use_effect_with` if you only intend to dispatch
/// values from within the hooks.
///
/// # Caution
///
/// The value held in the handle will reflect the value of at the time the
/// handle is returned by the `use_reducer`. It is possible that the handle does
/// not dereference to an up to date value if you are moving it into a
/// `use_effect_with` hook. You can register the
/// state to the dependents so the hook can be updated when the value changes.
#[hook]
pub fn use_reducer<T, F>(init_fn: F) -> UseReducerHandle<T>
where
T: Reducible + 'static,
F: FnOnce() -> T,
{
use_reducer_base(init_fn, |_, _| true)
}
/// [`use_reducer`] but only re-renders when `prev_state != next_state`.
///
/// This requires the state to implement [`PartialEq`] in addition to the [`Reducible`] trait
/// required by [`use_reducer`].
#[hook]
pub fn use_reducer_eq<T, F>(init_fn: F) -> UseReducerHandle<T>
where
T: Reducible + PartialEq + 'static,
F: FnOnce() -> T,
{
use_reducer_base(init_fn, T::ne)
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/mod.rs | packages/yew/src/functional/hooks/mod.rs | mod use_callback;
mod use_context;
mod use_effect;
mod use_force_update;
mod use_memo;
mod use_prepared_state;
mod use_reducer;
mod use_ref;
mod use_state;
mod use_transitive_state;
pub use use_callback::*;
pub use use_context::*;
pub use use_effect::*;
pub use use_force_update::*;
pub use use_memo::*;
pub use use_prepared_state::*;
pub use use_reducer::*;
pub use use_ref::*;
pub use use_state::*;
pub use use_transitive_state::*;
use crate::functional::HookContext;
/// A trait that is implemented on hooks.
///
/// Hooks are defined via the [`#[hook]`](crate::functional::hook) macro. It provides rewrites to
/// hook invocations and ensures that hooks can only be called at the top-level of a function
/// component or a hook. Please refer to its documentation on how to implement hooks.
pub trait Hook {
/// The return type when a hook is run.
type Output;
/// Runs the hook inside current state, returns output upon completion.
fn run(self, ctx: &mut HookContext) -> Self::Output;
}
/// The blanket implementation of boxed hooks.
#[doc(hidden)]
#[allow(missing_debug_implementations, missing_docs)]
pub struct BoxedHook<'hook, T> {
inner: Box<dyn 'hook + FnOnce(&mut HookContext) -> T>,
}
impl<'hook, T> BoxedHook<'hook, T> {
#[allow(missing_docs)]
pub fn new(inner: Box<dyn 'hook + FnOnce(&mut HookContext) -> T>) -> Self {
Self { inner }
}
}
impl<T> Hook for BoxedHook<'_, T> {
type Output = T;
fn run(self, ctx: &mut HookContext) -> Self::Output {
(self.inner)(ctx)
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_force_update.rs | packages/yew/src/functional/hooks/use_force_update.rs | use std::fmt;
use super::{Hook, HookContext};
use crate::functional::ReRender;
/// A handle which can be used to force a re-render of the associated
/// function component.
#[derive(Clone)]
pub struct UseForceUpdateHandle {
trigger: ReRender,
}
impl fmt::Debug for UseForceUpdateHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UseForceUpdate").finish()
}
}
impl UseForceUpdateHandle {
/// Trigger an unconditional re-render of the associated function component
pub fn force_update(&self) {
(self.trigger)()
}
}
#[cfg(nightly_yew)]
mod feat_nightly {
use super::*;
impl FnOnce<()> for UseForceUpdateHandle {
type Output = ();
extern "rust-call" fn call_once(self, _args: ()) -> Self::Output {
self.force_update()
}
}
impl FnMut<()> for UseForceUpdateHandle {
extern "rust-call" fn call_mut(&mut self, _args: ()) -> Self::Output {
self.force_update()
}
}
impl Fn<()> for UseForceUpdateHandle {
extern "rust-call" fn call(&self, _args: ()) -> Self::Output {
self.force_update()
}
}
}
/// This hook is used to manually force a function component to re-render.
///
/// # Note
///
/// Often, using this hook means that you're doing something wrong.
/// Try to use more specialized hooks, such as [`use_state`] and [`use_reducer`].
/// This hook should only be used when your component depends on external state where you
/// can't subscribe to changes, or as a low-level primitive to enable such a subscription-based
/// approach.
///
/// # Use-case
///
/// Use this hook when wrapping an API that doesn't expose precise subscription events for fetched
/// data. You could then, at some point, invalidate your local cache of the fetched data and trigger
/// a re-render to let the normal render flow of components tell you again which data to fetch, and
/// repopulate the cache accordingly.
///
/// A large externally managed cache, such as a app-wide cache for GraphQL data
/// should not rerender every component whenever new data arrives, but only those where a query
/// changed.
///
/// If the state of your component is not shared, you should need to use this hook.
///
/// # Example
///
/// This example implements a silly, manually updated display of the current time. The component
/// is re-rendered every time the button is clicked. You should usually use a timeout and
/// `use_state` to automatically trigger a re-render every second without having to use this hook.
///
/// ```rust
/// use yew::prelude::*;
///
/// #[component]
/// fn ManuallyUpdatedDate() -> Html {
/// let trigger = use_force_update();
/// let onclick = use_state(move || Callback::from(move |_| trigger.force_update()));
/// let last_update = js_sys::Date::new_0().to_utc_string();
/// html! {
/// <div>
/// <button onclick={&*onclick}>{"Update now!"}</button>
/// <p>{"Last updated: "}{last_update}</p>
/// </div>
/// }
/// }
/// ```
///
/// [`use_state`]: super::use_state()
/// [`use_reducer`]: super::use_reducer()
pub fn use_force_update() -> impl Hook<Output = UseForceUpdateHandle> {
struct UseRerenderHook;
impl Hook for UseRerenderHook {
type Output = UseForceUpdateHandle;
fn run(self, ctx: &mut HookContext) -> Self::Output {
UseForceUpdateHandle {
trigger: ctx.re_render.clone(),
}
}
}
UseRerenderHook
}
#[cfg(all(test, nightly_yew))]
mod nightly_test {
use yew::prelude::*;
#[component]
fn ManuallyUpdatedDate() -> Html {
let trigger = use_force_update();
let _ = move || trigger();
html! {}
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_memo.rs | packages/yew/src/functional/hooks/use_memo.rs | use std::borrow::Borrow;
use std::rc::Rc;
use super::use_mut_ref;
use crate::functional::hook;
/// Get a immutable reference to a memoized value.
///
/// This version allows for a key cache key derivation that only borrows
/// like the original argument. For example, using ` K = Rc<D>`, we only
/// create a shared reference to dependencies *after* they change.
#[hook]
pub(crate) fn use_memo_base<T, F, D, K>(f: F, deps: D) -> Rc<T>
where
T: 'static,
F: FnOnce(D) -> (T, K),
K: 'static + Borrow<D>,
D: PartialEq,
{
struct MemoState<T, K> {
memo_key: K,
result: Rc<T>,
}
let state = use_mut_ref(|| -> Option<MemoState<T, K>> { None });
let mut state = state.borrow_mut();
match &*state {
Some(existing) if existing.memo_key.borrow() != &deps => {
// Drop old state if it's outdated
*state = None;
}
_ => {}
};
let state = state.get_or_insert_with(|| {
let (result, memo_key) = f(deps);
let result = Rc::new(result);
MemoState { result, memo_key }
});
state.result.clone()
}
/// Get a immutable reference to a memoized value.
///
/// Memoization means it will only get recalculated when provided dependencies update/change.
///
/// It can be useful for keeping things in scope for the lifetime of the component,
/// so long as you don't store a clone of the resulting `Rc` anywhere that outlives the component.
///
/// # Example
///
/// ```rust
/// use yew::prelude::*;
///
/// #[derive(PartialEq, Properties)]
/// pub struct Props {
/// pub step: usize,
/// }
///
/// #[component(UseMemo)]
/// fn memo(props: &Props) -> Html {
/// // Will only get recalculated if `props.step` value changes
/// let message = use_memo(props.step, |step| {
/// format!("{}. Do Some Expensive Calculation", step)
/// });
///
/// html! {
/// <div>
/// <span>{ (*message).clone() }</span>
/// </div>
/// }
/// }
/// ```
#[hook]
pub fn use_memo<T, F, D>(deps: D, f: F) -> Rc<T>
where
T: 'static,
F: FnOnce(&D) -> T,
D: 'static + PartialEq,
{
use_memo_base(|d| (f(&d), d), deps)
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_context.rs | packages/yew/src/functional/hooks/use_context.rs | use std::cell::RefCell;
use std::marker::PhantomData;
use std::rc::Rc;
use crate::callback::Callback;
use crate::context::ContextHandle;
use crate::functional::{Hook, HookContext};
/// Hook for consuming context values in function components.
/// The context of the type passed as `T` is returned. If there is no such context in scope, `None`
/// is returned. A component which calls `use_context` will re-render when the data of the context
/// changes.
///
/// More information about contexts and how to define and consume them can be found on [Yew Docs](https://yew.rs/docs/concepts/contexts).
///
/// # Example
///
/// ```rust
/// use yew::{ContextProvider, component, html, use_context, use_state, Html};
///
///
/// /// App theme
/// #[derive(Clone, Debug, PartialEq)]
/// struct Theme {
/// foreground: String,
/// background: String,
/// }
///
/// /// Main component
/// #[component]
/// pub fn App() -> Html {
/// let ctx = use_state(|| Theme {
/// foreground: "#000000".to_owned(),
/// background: "#eeeeee".to_owned(),
/// });
///
/// html! {
/// // `ctx` is type `Rc<UseStateHandle<Theme>>` while we need `Theme`
/// // so we deref it.
/// // It derefs to `&Theme`, hence the clone
/// <ContextProvider<Theme> context={(*ctx).clone()}>
/// // Every child here and their children will have access to this context.
/// <Toolbar />
/// </ContextProvider<Theme>>
/// }
/// }
///
/// /// The toolbar.
/// /// This component has access to the context
/// #[component]
/// pub fn Toolbar() -> Html {
/// html! {
/// <div>
/// <ThemedButton />
/// </div>
/// }
/// }
///
/// /// Button placed in `Toolbar`.
/// /// As this component is a child of `ThemeContextProvider` in the component tree, it also has access to the context.
/// #[component]
/// pub fn ThemedButton() -> Html {
/// let theme = use_context::<Theme>().expect("no ctx found");
///
/// html! {
/// <button style={format!("background: {}; color: {};", theme.background, theme.foreground)}>
/// { "Click me!" }
/// </button>
/// }
/// }
/// ```
pub fn use_context<T: Clone + PartialEq + 'static>() -> impl Hook<Output = Option<T>> {
struct HookProvider<T: Clone + PartialEq + 'static> {
_marker: PhantomData<T>,
}
struct UseContext<T: Clone + PartialEq + 'static> {
_handle: Option<ContextHandle<T>>,
value: Rc<RefCell<Option<T>>>,
}
impl<T> Hook for HookProvider<T>
where
T: Clone + PartialEq + 'static,
{
type Output = Option<T>;
fn run(self, ctx: &mut HookContext) -> Self::Output {
let scope = ctx.scope.clone();
let state = ctx.next_state(move |re_render| -> UseContext<T> {
let value_cell: Rc<RefCell<Option<T>>> = Rc::default();
let (init_value, handle) = {
let value_cell = value_cell.clone();
scope.context(Callback::from(move |m| {
*(value_cell.borrow_mut()) = Some(m);
re_render()
}))
}
.map(|(value, handle)| (Some(value), Some(handle)))
.unwrap_or((None, None));
*(value_cell.borrow_mut()) = init_value;
UseContext {
_handle: handle,
value: value_cell,
}
});
let value = state.value.borrow();
value.clone()
}
}
HookProvider {
_marker: PhantomData,
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_transitive_state/feat_hydration.rs | packages/yew/src/functional/hooks/use_transitive_state/feat_hydration.rs | //! The hydration variant.
//!
//! This is the same as the use_prepared_state.
#[doc(hidden)]
pub use crate::functional::hooks::use_prepared_state::feat_hydration::use_prepared_state as use_transitive_state;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_transitive_state/feat_hydration_ssr.rs | packages/yew/src/functional/hooks/use_transitive_state/feat_hydration_ssr.rs | //! The client-and-server-side rendering variant.
use std::rc::Rc;
use serde::de::DeserializeOwned;
use serde::Serialize;
use super::{feat_hydration, feat_ssr};
use crate::functional::{Hook, HookContext};
use crate::html::RenderMode;
use crate::suspense::SuspensionResult;
#[doc(hidden)]
pub fn use_transitive_state<T, D, F>(
deps: D,
f: F,
) -> impl Hook<Output = SuspensionResult<Option<Rc<T>>>>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
struct HookProvider<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
deps: D,
f: F,
}
impl<T, D, F> Hook for HookProvider<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
type Output = SuspensionResult<Option<Rc<T>>>;
fn run(self, ctx: &mut HookContext) -> Self::Output {
match ctx.creation_mode {
RenderMode::Ssr => feat_ssr::use_transitive_state(self.deps, self.f).run(ctx),
_ => feat_hydration::use_transitive_state(self.deps).run(ctx),
}
}
}
HookProvider::<T, D, F> { deps, f }
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_transitive_state/mod.rs | packages/yew/src/functional/hooks/use_transitive_state/mod.rs | #[cfg(feature = "hydration")]
mod feat_hydration;
#[cfg(all(feature = "ssr", feature = "hydration"))]
mod feat_hydration_ssr;
#[cfg(not(any(feature = "hydration", feature = "ssr")))]
mod feat_none;
#[cfg(feature = "ssr")]
mod feat_ssr;
#[cfg(all(feature = "hydration", not(feature = "ssr")))]
pub use feat_hydration::*;
#[cfg(all(feature = "ssr", feature = "hydration"))]
pub use feat_hydration_ssr::*;
#[cfg(not(any(feature = "hydration", feature = "ssr")))]
pub use feat_none::*;
#[cfg(all(feature = "ssr", not(feature = "hydration")))]
pub use feat_ssr::*;
/// Use a state created as an artifact of the server-side rendering.
///
/// This value is created after the server-side rendering artifact is created.
///
/// It accepts a closure as the first argument and a dependency type as the second argument.
/// It returns `SuspensionResult<Option<Rc<T>>>`.
///
/// It will always return `Ok(None)` during server-side rendering.
///
/// During hydration, it will only return `Ok(Some(Rc<T>))` if the component is hydrated from a
/// server-side rendering artifact and its dependency value matches.
///
/// `let state = use_transitive_state!(deps, |deps| -> ReturnType { ... });`
///
/// It has the following function signature:
///
/// ```
/// # use serde::de::DeserializeOwned;
/// # use serde::Serialize;
/// # use std::rc::Rc;
/// use yew::prelude::*;
/// use yew::suspense::SuspensionResult;
///
/// #[hook]
/// pub fn use_transitive_state<T, D, F>(deps: D, f: F) -> SuspensionResult<Option<Rc<T>>>
/// where
/// D: Serialize + DeserializeOwned + PartialEq + 'static,
/// T: Serialize + DeserializeOwned + 'static,
/// F: 'static + FnOnce(Rc<D>) -> T,
/// # { todo!() }
/// ```
///
/// If the bundle is compiled without server-side rendering, the closure will be stripped
/// automatically.
///
/// # Note
///
/// You MUST denote the return type of the closure with `|deps| -> ReturnType { ... }`. This
/// type is used during client side rendering to deserialize the state prepared on the server
/// side.
pub use use_transitive_state_macro as use_transitive_state;
// With SSR.
#[doc(hidden)]
#[cfg(feature = "ssr")]
pub use yew_macro::use_transitive_state_with_closure as use_transitive_state_macro;
// Without SSR.
#[doc(hidden)]
#[cfg(not(feature = "ssr"))]
pub use yew_macro::use_transitive_state_without_closure as use_transitive_state_macro;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_transitive_state/feat_ssr.rs | packages/yew/src/functional/hooks/use_transitive_state/feat_ssr.rs | //! The server-side rendering variant.
use std::cell::RefCell;
use std::rc::Rc;
use base64ct::{Base64, Encoding};
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::functional::{Hook, HookContext, PreparedState};
use crate::suspense::SuspensionResult;
pub(super) struct TransitiveStateBase<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
pub state_fn: RefCell<Option<F>>,
pub deps: Rc<D>,
}
impl<T, D, F> PreparedState for TransitiveStateBase<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
fn prepare(&self) -> String {
let f = self.state_fn.borrow_mut().take().unwrap();
let state = f(self.deps.clone());
let state = bincode::serde::encode_to_vec(
(Some(&state), Some(&*self.deps)),
bincode::config::standard(),
)
.expect("failed to prepare state");
Base64::encode_string(&state)
}
}
#[doc(hidden)]
pub fn use_transitive_state<T, D, F>(
deps: D,
f: F,
) -> impl Hook<Output = SuspensionResult<Option<Rc<T>>>>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
struct HookProvider<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
deps: D,
f: F,
}
impl<T, D, F> Hook for HookProvider<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: 'static + FnOnce(Rc<D>) -> T,
{
type Output = SuspensionResult<Option<Rc<T>>>;
fn run(self, ctx: &mut HookContext) -> Self::Output {
let f = self.f;
ctx.next_prepared_state(move |_re_render, _| -> TransitiveStateBase<T, D, F> {
TransitiveStateBase {
state_fn: Some(f).into(),
deps: self.deps.into(),
}
});
Ok(None)
}
}
HookProvider::<T, D, F> { deps, f }
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_transitive_state/feat_none.rs | packages/yew/src/functional/hooks/use_transitive_state/feat_none.rs | //! The noop variant. This is used for client side rendering when hydration is disabled.
#[doc(hidden)]
pub use crate::functional::hooks::use_prepared_state::feat_none::use_prepared_state as use_transitive_state;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_prepared_state/feat_hydration.rs | packages/yew/src/functional/hooks/use_prepared_state/feat_hydration.rs | //! The client-side rendering variant. This is used for client side rendering.
use std::marker::PhantomData;
use std::rc::Rc;
use serde::de::DeserializeOwned;
use serde::Serialize;
use wasm_bindgen::JsValue;
use super::PreparedStateBase;
use crate::functional::{use_state, Hook, HookContext};
use crate::platform::spawn_local;
use crate::suspense::{Suspension, SuspensionResult};
#[cfg(all(
target_arch = "wasm32",
not(target_os = "wasi"),
not(feature = "not_browser_env")
))]
async fn decode_base64(s: &str) -> Result<Vec<u8>, JsValue> {
use gloo::utils::window;
use js_sys::Uint8Array;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
let fetch_promise = window().fetch_with_str(s);
let content_promise = JsFuture::from(fetch_promise)
.await
.and_then(|m| m.dyn_into::<web_sys::Response>())
.and_then(|m| m.array_buffer())?;
let content_array = JsFuture::from(content_promise)
.await
.as_ref()
.map(Uint8Array::new)?;
Ok(content_array.to_vec())
}
#[cfg(any(
not(target_arch = "wasm32"),
target_os = "wasi",
feature = "not_browser_env"
))]
async fn decode_base64(_s: &str) -> Result<Vec<u8>, JsValue> {
unreachable!("this function is not callable under non-wasm targets!");
}
#[doc(hidden)]
pub fn use_prepared_state<T, D>(deps: D) -> impl Hook<Output = SuspensionResult<Option<Rc<T>>>>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
{
struct HookProvider<T, D>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
{
_marker: PhantomData<T>,
deps: D,
}
impl<T, D> Hook for HookProvider<T, D>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
{
type Output = SuspensionResult<Option<Rc<T>>>;
fn run(self, ctx: &mut HookContext) -> Self::Output {
let data = use_state(|| {
let (s, handle) = Suspension::new();
(
SuspensionResult::<(Option<Rc<T>>, Option<Rc<D>>)>::Err(s),
Some(handle),
)
})
.run(ctx);
let state = {
let data = data.clone();
ctx.next_prepared_state(move |_re_render, buf| -> PreparedStateBase<T, D> {
if let Some(buf) = buf {
let buf = format!("data:application/octet-binary;base64,{buf}");
spawn_local(async move {
let buf = decode_base64(&buf)
.await
.expect("failed to deserialize state");
let ((state, deps), _) =
bincode::serde::decode_from_slice::<(Option<T>, Option<D>), _>(
&buf,
bincode::config::standard(),
)
.map(|((state, deps), consumed)| {
((state.map(Rc::new), deps.map(Rc::new)), consumed)
})
.expect("failed to deserialize state");
data.set((Ok((state, deps)), None));
});
}
PreparedStateBase {
#[cfg(feature = "ssr")]
state: None,
#[cfg(feature = "ssr")]
deps: None,
has_buf: buf.is_some(),
_marker: PhantomData,
}
})
};
if state.has_buf {
let (data, deps) = data.0.clone()?;
if deps.as_deref() == Some(&self.deps) {
return Ok(data);
}
}
Ok(None)
}
}
HookProvider::<T, D> {
_marker: PhantomData,
deps,
}
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_prepared_state/feat_hydration_ssr.rs | packages/yew/src/functional/hooks/use_prepared_state/feat_hydration_ssr.rs | //! The client-and-server-side rendering variant.
use std::future::Future;
use std::rc::Rc;
use serde::de::DeserializeOwned;
use serde::Serialize;
use super::{feat_hydration, feat_ssr};
use crate::functional::{Hook, HookContext};
use crate::html::RenderMode;
use crate::suspense::SuspensionResult;
#[doc(hidden)]
pub fn use_prepared_state<T, D, F>(
deps: D,
f: F,
) -> impl Hook<Output = SuspensionResult<Option<Rc<T>>>>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: FnOnce(Rc<D>) -> T,
{
struct HookProvider<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: FnOnce(Rc<D>) -> T,
{
deps: D,
f: F,
}
impl<T, D, F> Hook for HookProvider<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: FnOnce(Rc<D>) -> T,
{
type Output = SuspensionResult<Option<Rc<T>>>;
fn run(self, ctx: &mut HookContext) -> Self::Output {
match ctx.creation_mode {
RenderMode::Ssr => feat_ssr::use_prepared_state(self.deps, self.f).run(ctx),
_ => feat_hydration::use_prepared_state(self.deps).run(ctx),
}
}
}
HookProvider::<T, D, F> { deps, f }
}
#[doc(hidden)]
pub fn use_prepared_state_with_suspension<T, D, F, U>(
deps: D,
f: F,
) -> impl Hook<Output = SuspensionResult<Option<Rc<T>>>>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: FnOnce(Rc<D>) -> U,
U: 'static + Future<Output = T>,
{
struct HookProvider<T, D, F, U>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: FnOnce(Rc<D>) -> U,
U: 'static + Future<Output = T>,
{
deps: D,
f: F,
}
impl<T, D, F, U> Hook for HookProvider<T, D, F, U>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: FnOnce(Rc<D>) -> U,
U: 'static + Future<Output = T>,
{
type Output = SuspensionResult<Option<Rc<T>>>;
fn run(self, ctx: &mut HookContext) -> Self::Output {
match ctx.creation_mode {
RenderMode::Ssr => {
feat_ssr::use_prepared_state_with_suspension(self.deps, self.f).run(ctx)
}
_ => feat_hydration::use_prepared_state(self.deps).run(ctx),
}
}
}
HookProvider::<T, D, F, U> { deps, f }
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_prepared_state/mod.rs | packages/yew/src/functional/hooks/use_prepared_state/mod.rs | #[cfg(feature = "hydration")]
pub(super) mod feat_hydration;
#[cfg(all(feature = "hydration", feature = "ssr"))]
mod feat_hydration_ssr;
#[cfg(not(any(feature = "hydration", feature = "ssr")))]
pub(super) mod feat_none;
#[cfg(feature = "ssr")]
mod feat_ssr;
#[cfg(all(feature = "hydration", not(feature = "ssr")))]
pub use feat_hydration::*;
#[cfg(all(feature = "ssr", feature = "hydration"))]
pub use feat_hydration_ssr::*;
#[cfg(not(any(feature = "hydration", feature = "ssr")))]
pub use feat_none::*;
#[cfg(all(feature = "ssr", not(feature = "hydration")))]
pub use feat_ssr::*;
/// Use a state prepared on the server side and its value is sent to the client side during
/// hydration.
///
/// The component sees the same value on the server side and client side if the component is
/// hydrated.
///
/// It accepts a closure as the second argument and its dependency value as the first argument.
/// It returns `SuspensionResult<Option<Rc<T>>>`.
///
/// During hydration, it will only return `Ok(Some(Rc<T>))` if the component is hydrated from a
/// server-side rendering artifact and its dependency value matches.
///
/// `let state = use_prepared_state!(deps, |deps| -> ReturnType { ... })?;`
///
/// It has the following signature:
///
/// ```
/// # use serde::de::DeserializeOwned;
/// # use serde::Serialize;
/// # use std::rc::Rc;
/// use yew::prelude::*;
/// use yew::suspense::SuspensionResult;
///
/// #[hook]
/// pub fn use_prepared_state<T, D, F>(deps: D, f: F) -> SuspensionResult<Option<Rc<T>>>
/// where
/// D: Serialize + DeserializeOwned + PartialEq + 'static,
/// T: Serialize + DeserializeOwned + 'static,
/// F: FnOnce(Rc<D>) -> T,
/// # { todo!() }
/// ```
///
/// The first argument can also be an async closure
///
/// `let state = use_prepared_state!(deps, async |deps| -> ReturnType { ... })?;`
///
/// When accepting an async closure, it has the following signature:
///
/// ```
/// # use serde::de::DeserializeOwned;
/// # use serde::Serialize;
/// # use std::rc::Rc;
/// # use std::future::Future;
/// use yew::prelude::*;
/// use yew::suspense::SuspensionResult;
///
/// #[hook]
/// pub fn use_prepared_state<T, D, F, U>(
/// deps: D,
/// f: F,
/// ) -> SuspensionResult<Option<Rc<T>>>
/// where
/// D: Serialize + DeserializeOwned + PartialEq + 'static,
/// T: Serialize + DeserializeOwned + 'static,
/// F: FnOnce(Rc<D>) -> U,
/// U: 'static + Future<Output = T>,
/// # { todo!() }
/// ```
///
/// During server-side rendering, a value of type `T` will be calculated from the first
/// closure.
///
/// If the bundle is compiled without server-side rendering, the closure will be stripped
/// automatically.
///
/// # Note
///
/// You MUST denote the return type of the closure with `|deps| -> ReturnType { ... }`. This
/// type is used during client side rendering to deserialize the state prepared on the server
/// side.
pub use use_prepared_state_macro as use_prepared_state;
// With SSR.
#[doc(hidden)]
#[cfg(feature = "ssr")]
pub use yew_macro::use_prepared_state_with_closure as use_prepared_state_macro;
// Without SSR.
#[doc(hidden)]
#[cfg(not(feature = "ssr"))]
pub use yew_macro::use_prepared_state_without_closure as use_prepared_state_macro;
#[cfg(any(feature = "hydration", feature = "ssr"))]
mod feat_any_hydration_ssr {
use std::marker::PhantomData;
#[cfg(feature = "ssr")]
use std::rc::Rc;
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::functional::PreparedState;
pub(super) struct PreparedStateBase<T, D>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
{
#[cfg(feature = "ssr")]
pub state: Option<Rc<T>>,
#[cfg(feature = "ssr")]
pub deps: Option<Rc<D>>,
#[cfg(feature = "hydration")]
pub has_buf: bool,
pub _marker: PhantomData<(T, D)>,
}
impl<T, D> PreparedState for PreparedStateBase<T, D>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
{
#[cfg(feature = "ssr")]
fn prepare(&self) -> String {
use base64ct::{Base64, Encoding};
let state = bincode::serde::encode_to_vec(
(self.state.as_deref(), self.deps.as_deref()),
bincode::config::standard(),
)
.expect("failed to prepare state");
Base64::encode_string(&state)
}
}
}
#[cfg(any(feature = "hydration", feature = "ssr"))]
use feat_any_hydration_ssr::PreparedStateBase;
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_prepared_state/feat_ssr.rs | packages/yew/src/functional/hooks/use_prepared_state/feat_ssr.rs | //! The server-side rendering variant. This is used for server side rendering.
use std::future::Future;
use std::marker::PhantomData;
use std::rc::Rc;
use serde::de::DeserializeOwned;
use serde::Serialize;
use super::PreparedStateBase;
use crate::functional::{use_memo, use_state, Hook, HookContext};
use crate::platform::spawn_local;
use crate::suspense::{Suspension, SuspensionResult};
#[doc(hidden)]
pub fn use_prepared_state<T, D, F>(
deps: D,
f: F,
) -> impl Hook<Output = SuspensionResult<Option<Rc<T>>>>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: FnOnce(Rc<D>) -> T,
{
struct HookProvider<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: FnOnce(Rc<D>) -> T,
{
deps: D,
f: F,
}
impl<T, D, F> Hook for HookProvider<T, D, F>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: FnOnce(Rc<D>) -> T,
{
type Output = SuspensionResult<Option<Rc<T>>>;
fn run(self, ctx: &mut HookContext) -> Self::Output {
let f = self.f;
let deps = Rc::new(self.deps);
let state = {
let deps = deps.clone();
use_memo((), move |_| f(deps)).run(ctx)
};
let state = PreparedStateBase {
state: Some(state),
deps: Some(deps),
#[cfg(feature = "hydration")]
has_buf: true,
_marker: PhantomData,
};
let state =
ctx.next_prepared_state(|_re_render, _| -> PreparedStateBase<T, D> { state });
Ok(state.state.clone())
}
}
HookProvider::<T, D, F> { deps, f }
}
#[doc(hidden)]
pub fn use_prepared_state_with_suspension<T, D, F, U>(
deps: D,
f: F,
) -> impl Hook<Output = SuspensionResult<Option<Rc<T>>>>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: FnOnce(Rc<D>) -> U,
U: 'static + Future<Output = T>,
{
struct HookProvider<T, D, F, U>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: FnOnce(Rc<D>) -> U,
U: 'static + Future<Output = T>,
{
deps: D,
f: F,
}
impl<T, D, F, U> Hook for HookProvider<T, D, F, U>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
F: FnOnce(Rc<D>) -> U,
U: 'static + Future<Output = T>,
{
type Output = SuspensionResult<Option<Rc<T>>>;
fn run(self, ctx: &mut HookContext) -> Self::Output {
let f = self.f;
let deps = Rc::new(self.deps);
let result = use_state(|| {
let (s, handle) = Suspension::new();
(Err(s), Some(handle))
})
.run(ctx);
{
let deps = deps.clone();
let result = result.clone();
use_state(move || {
let state_f = f(deps.clone());
spawn_local(async move {
let state = state_f.await;
result.set((Ok(Rc::new(state)), None));
})
})
.run(ctx);
}
let state = result.0.clone()?;
let state = PreparedStateBase {
state: Some(state),
deps: Some(deps),
#[cfg(feature = "hydration")]
has_buf: true,
_marker: PhantomData,
};
let state =
ctx.next_prepared_state(|_re_render, _| -> PreparedStateBase<T, D> { state });
Ok(state.state.clone())
}
}
HookProvider::<T, D, F, U> { deps, f }
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/src/functional/hooks/use_prepared_state/feat_none.rs | packages/yew/src/functional/hooks/use_prepared_state/feat_none.rs | //! The noop variant. This is used for client side rendering when hydration is disabled.
use std::rc::Rc;
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::hook;
use crate::suspense::SuspensionResult;
#[doc(hidden)]
#[hook]
pub fn use_prepared_state<T, D>(_deps: D) -> SuspensionResult<Option<Rc<T>>>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
{
Ok(None)
}
#[doc(hidden)]
#[hook]
pub fn use_prepared_state_with_suspension<T, D>(_deps: D) -> SuspensionResult<Option<Rc<T>>>
where
D: Serialize + DeserializeOwned + PartialEq + 'static,
T: Serialize + DeserializeOwned + 'static,
{
Ok(None)
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/tests/use_effect.rs | packages/yew/tests/use_effect.rs | #![cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
mod common;
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::time::Duration;
use common::obtain_result;
use wasm_bindgen_test::*;
use yew::platform::time::sleep;
use yew::prelude::*;
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
async fn use_effect_destroys_on_component_drop() {
#[derive(Properties, Clone)]
struct WrapperProps {
destroy_called: Rc<dyn Fn()>,
}
impl PartialEq for WrapperProps {
fn eq(&self, _other: &Self) -> bool {
false
}
}
#[derive(Properties, Clone)]
struct FunctionProps {
effect_called: Rc<dyn Fn()>,
destroy_called: Rc<dyn Fn()>,
}
impl PartialEq for FunctionProps {
fn eq(&self, _other: &Self) -> bool {
false
}
}
#[component(UseEffectComponent)]
fn use_effect_comp(props: &FunctionProps) -> Html {
let effect_called = props.effect_called.clone();
let destroy_called = props.destroy_called.clone();
use_effect_with((), move |_| {
effect_called();
#[allow(clippy::redundant_closure)] // Otherwise there is a build error
move || destroy_called()
});
html! {}
}
#[component(UseEffectWrapperComponent)]
fn use_effect_wrapper_comp(props: &WrapperProps) -> Html {
let show = use_state(|| true);
if *show {
let effect_called: Rc<dyn Fn()> = { Rc::new(move || show.set(false)) };
html! {
<UseEffectComponent destroy_called={props.destroy_called.clone()} {effect_called} />
}
} else {
html! {
<div>{ "EMPTY" }</div>
}
}
}
let destroy_counter = Rc::new(std::cell::RefCell::new(0));
let destroy_counter_c = destroy_counter.clone();
yew::Renderer::<UseEffectWrapperComponent>::with_root_and_props(
gloo::utils::document().get_element_by_id("output").unwrap(),
WrapperProps {
destroy_called: Rc::new(move || *destroy_counter_c.borrow_mut().deref_mut() += 1),
},
)
.render();
sleep(Duration::ZERO).await;
assert_eq!(1, *destroy_counter.borrow().deref());
}
#[wasm_bindgen_test]
async fn use_effect_works_many_times() {
#[component(UseEffectComponent)]
fn use_effect_comp() -> Html {
let counter = use_state(|| 0);
let counter_clone = counter.clone();
use_effect_with(*counter, move |_| {
if *counter_clone < 4 {
counter_clone.set(*counter_clone + 1);
}
|| {}
});
html! {
<div>
{ "The test result is" }
<div id="result">{ *counter }</div>
{ "\n" }
</div>
}
}
yew::Renderer::<UseEffectComponent>::with_root(
gloo::utils::document().get_element_by_id("output").unwrap(),
)
.render();
sleep(Duration::ZERO).await;
let result = obtain_result();
assert_eq!(result.as_str(), "4");
}
#[wasm_bindgen_test]
async fn use_effect_works_once() {
#[component(UseEffectComponent)]
fn use_effect_comp() -> Html {
let counter = use_state(|| 0);
let counter_clone = counter.clone();
use_effect_with((), move |_| {
counter_clone.set(*counter_clone + 1);
|| panic!("Destructor should not have been called")
});
html! {
<div>
{ "The test result is" }
<div id="result">{ *counter }</div>
{ "\n" }
</div>
}
}
yew::Renderer::<UseEffectComponent>::with_root(
gloo::utils::document().get_element_by_id("output").unwrap(),
)
.render();
sleep(Duration::ZERO).await;
let result = obtain_result();
assert_eq!(result.as_str(), "1");
}
#[wasm_bindgen_test]
async fn use_effect_refires_on_dependency_change() {
#[component(UseEffectComponent)]
fn use_effect_comp() -> Html {
let number_ref = use_mut_ref(|| 0);
let number_ref_c = number_ref.clone();
let number_ref2 = use_mut_ref(|| 0);
let number_ref2_c = number_ref2.clone();
let arg = *number_ref.borrow_mut().deref_mut();
let counter = use_state(|| 0);
use_effect_with(arg, move |dep| {
let mut ref_mut = number_ref_c.borrow_mut();
let inner_ref_mut = ref_mut.deref_mut();
if *inner_ref_mut < 1 {
*inner_ref_mut += 1;
assert_eq!(dep, &0);
} else {
assert_eq!(dep, &1);
}
counter.set(10); // we just need to make sure it does not panic
move || {
counter.set(11);
*number_ref2_c.borrow_mut().deref_mut() += 1;
}
});
html! {
<div>
{"The test result is"}
<div id="result">{*number_ref.borrow_mut().deref_mut()}{*number_ref2.borrow_mut().deref_mut()}</div>
{"\n"}
</div>
}
}
yew::Renderer::<UseEffectComponent>::with_root(
gloo::utils::document().get_element_by_id("output").unwrap(),
)
.render();
sleep(Duration::ZERO).await;
let result: String = obtain_result();
assert_eq!(result.as_str(), "11");
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/tests/suspense.rs | packages/yew/tests/suspense.rs | #![cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
mod common;
use std::cell::RefCell;
use std::rc::Rc;
use std::time::Duration;
use common::obtain_result;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
use web_sys::{HtmlElement, HtmlTextAreaElement};
use yew::platform::spawn_local;
use yew::platform::time::sleep;
use yew::prelude::*;
use yew::suspense::{use_future, use_future_with, Suspension, SuspensionResult};
use yew::UseStateHandle;
wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
async fn suspense_works() {
#[derive(PartialEq)]
pub struct SleepState {
s: Suspension,
}
impl SleepState {
fn new() -> Self {
let (s, handle) = Suspension::new();
spawn_local(async move {
sleep(Duration::from_millis(50)).await;
handle.resume();
});
Self { s }
}
}
impl Reducible for SleepState {
type Action = ();
fn reduce(self: Rc<Self>, _action: Self::Action) -> Rc<Self> {
Self::new().into()
}
}
#[hook]
pub fn use_sleep() -> SuspensionResult<Rc<dyn Fn()>> {
let sleep_state = use_reducer(SleepState::new);
if sleep_state.s.resumed() {
Ok(Rc::new(move || sleep_state.dispatch(())))
} else {
Err(sleep_state.s.clone())
}
}
#[component(Content)]
fn content() -> HtmlResult {
let resleep = use_sleep()?;
let value = use_state(|| 0);
let on_increment = {
let value = value.clone();
Callback::from(move |_: MouseEvent| {
value.set(*value + 1);
})
};
let on_take_a_break = Callback::from(move |_: MouseEvent| (resleep.clone())());
Ok(html! {
<div class="content-area">
<div class="actual-result">{*value}</div>
<button class="increase" onclick={on_increment}>{"increase"}</button>
<div class="action-area">
<button class="take-a-break" onclick={on_take_a_break}>{"Take a break!"}</button>
</div>
</div>
})
}
#[component(App)]
fn app() -> Html {
let fallback = html! {<div>{"wait..."}</div>};
html! {
<div id="result">
<Suspense {fallback}>
<Content />
</Suspense>
</div>
}
}
yew::Renderer::<App>::with_root(gloo::utils::document().get_element_by_id("output").unwrap())
.render();
sleep(Duration::from_millis(10)).await;
let result = obtain_result();
assert_eq!(result.as_str(), "<div>wait...</div>");
sleep(Duration::from_millis(50)).await;
let result = obtain_result();
assert_eq!(
result.as_str(),
r#"<div class="content-area"><div class="actual-result">0</div><button class="increase">increase</button><div class="action-area"><button class="take-a-break">Take a break!</button></div></div>"#
);
sleep(Duration::from_millis(10)).await;
gloo::utils::document()
.query_selector(".increase")
.unwrap()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap()
.click();
sleep(Duration::ZERO).await;
gloo::utils::document()
.query_selector(".increase")
.unwrap()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap()
.click();
sleep(Duration::from_millis(1)).await;
let result = obtain_result();
assert_eq!(
result.as_str(),
r#"<div class="content-area"><div class="actual-result">2</div><button class="increase">increase</button><div class="action-area"><button class="take-a-break">Take a break!</button></div></div>"#
);
gloo::utils::document()
.query_selector(".take-a-break")
.unwrap()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap()
.click();
sleep(Duration::from_millis(10)).await;
let result = obtain_result();
assert_eq!(result.as_str(), "<div>wait...</div>");
sleep(Duration::from_millis(50)).await;
let result = obtain_result();
assert_eq!(
result.as_str(),
r#"<div class="content-area"><div class="actual-result">2</div><button class="increase">increase</button><div class="action-area"><button class="take-a-break">Take a break!</button></div></div>"#
);
}
#[wasm_bindgen_test]
async fn suspense_not_suspended_at_start() {
#[derive(PartialEq)]
pub struct SleepState {
s: Option<Suspension>,
}
impl SleepState {
fn new() -> Self {
Self { s: None }
}
}
impl Reducible for SleepState {
type Action = ();
fn reduce(self: Rc<Self>, _action: Self::Action) -> Rc<Self> {
let (s, handle) = Suspension::new();
spawn_local(async move {
sleep(Duration::from_millis(50)).await;
handle.resume();
});
Self { s: Some(s) }.into()
}
}
#[hook]
pub fn use_sleep() -> SuspensionResult<Rc<dyn Fn()>> {
let sleep_state = use_reducer(SleepState::new);
let s = match sleep_state.s.clone() {
Some(m) => m,
None => return Ok(Rc::new(move || sleep_state.dispatch(()))),
};
if s.resumed() {
Ok(Rc::new(move || sleep_state.dispatch(())))
} else {
Err(s)
}
}
#[component(Content)]
fn content() -> HtmlResult {
let resleep = use_sleep()?;
let value = use_state(|| "I am writing a long story...".to_string());
let on_text_input = {
let value = value.clone();
Callback::from(move |e: InputEvent| {
let input: HtmlTextAreaElement = e.target_unchecked_into();
value.set(input.value());
})
};
let on_take_a_break = Callback::from(move |_| (resleep.clone())());
Ok(html! {
<div class="content-area">
<textarea value={value.to_string()} oninput={on_text_input}/>
<div class="action-area">
<button class="take-a-break" onclick={on_take_a_break}>{"Take a break!"}</button>
</div>
</div>
})
}
#[component(App)]
fn app() -> Html {
let fallback = html! {<div>{"wait..."}</div>};
html! {
<div id="result">
<Suspense {fallback}>
<Content />
</Suspense>
</div>
}
}
yew::Renderer::<App>::with_root(gloo::utils::document().get_element_by_id("output").unwrap())
.render();
sleep(Duration::from_millis(10)).await;
let result = obtain_result();
assert_eq!(
result.as_str(),
r#"<div class="content-area"><textarea></textarea><div class="action-area"><button class="take-a-break">Take a break!</button></div></div>"#
);
gloo::utils::document()
.query_selector(".take-a-break")
.unwrap()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap()
.click();
sleep(Duration::from_millis(10)).await;
let result = obtain_result();
assert_eq!(result.as_str(), "<div>wait...</div>");
sleep(Duration::from_millis(50)).await;
let result = obtain_result();
assert_eq!(
result.as_str(),
r#"<div class="content-area"><textarea></textarea><div class="action-area"><button class="take-a-break">Take a break!</button></div></div>"#
);
}
#[wasm_bindgen_test]
async fn suspense_nested_suspense_works() {
#[derive(PartialEq)]
pub struct SleepState {
s: Suspension,
}
impl SleepState {
fn new() -> Self {
let (s, handle) = Suspension::new();
spawn_local(async move {
sleep(Duration::from_millis(50)).await;
handle.resume();
});
Self { s }
}
}
impl Reducible for SleepState {
type Action = ();
fn reduce(self: Rc<Self>, _action: Self::Action) -> Rc<Self> {
Self::new().into()
}
}
#[hook]
pub fn use_sleep() -> SuspensionResult<Rc<dyn Fn()>> {
let sleep_state = use_reducer(SleepState::new);
if sleep_state.s.resumed() {
Ok(Rc::new(move || sleep_state.dispatch(())))
} else {
Err(sleep_state.s.clone())
}
}
#[component(InnerContent)]
fn inner_content() -> HtmlResult {
let resleep = use_sleep()?;
let on_take_a_break = Callback::from(move |_: MouseEvent| (resleep.clone())());
Ok(html! {
<div class="content-area">
<div class="action-area">
<button class="take-a-break2" onclick={on_take_a_break}>{"Take a break!"}</button>
</div>
</div>
})
}
#[component(Content)]
fn content() -> HtmlResult {
let resleep = use_sleep()?;
let fallback = html! {<div>{"wait...(inner)"}</div>};
let on_take_a_break = Callback::from(move |_: MouseEvent| (resleep.clone())());
Ok(html! {
<div class="content-area">
<div class="action-area">
<button class="take-a-break" onclick={on_take_a_break}>{"Take a break!"}</button>
</div>
<Suspense {fallback}>
<InnerContent />
</Suspense>
</div>
})
}
#[component(App)]
fn app() -> Html {
let fallback = html! {<div>{"wait...(outer)"}</div>};
html! {
<div id="result">
<Suspense {fallback}>
<Content />
</Suspense>
</div>
}
}
yew::Renderer::<App>::with_root(gloo::utils::document().get_element_by_id("output").unwrap())
.render();
sleep(Duration::from_millis(10)).await;
let result = obtain_result();
assert_eq!(result.as_str(), "<div>wait...(outer)</div>");
sleep(Duration::from_millis(50)).await;
let result = obtain_result();
assert_eq!(
result.as_str(),
r#"<div class="content-area"><div class="action-area"><button class="take-a-break">Take a break!</button></div><div>wait...(inner)</div></div>"#
);
sleep(Duration::from_millis(50)).await;
let result = obtain_result();
assert_eq!(
result.as_str(),
r#"<div class="content-area"><div class="action-area"><button class="take-a-break">Take a break!</button></div><div class="content-area"><div class="action-area"><button class="take-a-break2">Take a break!</button></div></div></div>"#
);
gloo::utils::document()
.query_selector(".take-a-break2")
.unwrap()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap()
.click();
sleep(Duration::from_millis(10)).await;
let result = obtain_result();
assert_eq!(
result.as_str(),
r#"<div class="content-area"><div class="action-area"><button class="take-a-break">Take a break!</button></div><div>wait...(inner)</div></div>"#
);
sleep(Duration::from_millis(50)).await;
let result = obtain_result();
assert_eq!(
result.as_str(),
r#"<div class="content-area"><div class="action-area"><button class="take-a-break">Take a break!</button></div><div class="content-area"><div class="action-area"><button class="take-a-break2">Take a break!</button></div></div></div>"#
);
}
#[wasm_bindgen_test]
async fn effects_not_run_when_suspended() {
#[derive(PartialEq)]
pub struct SleepState {
s: Suspension,
}
impl SleepState {
fn new() -> Self {
let (s, handle) = Suspension::new();
spawn_local(async move {
sleep(Duration::from_millis(50)).await;
handle.resume();
});
Self { s }
}
}
impl Reducible for SleepState {
type Action = ();
fn reduce(self: Rc<Self>, _action: Self::Action) -> Rc<Self> {
Self::new().into()
}
}
#[hook]
pub fn use_sleep() -> SuspensionResult<Rc<dyn Fn()>> {
let sleep_state = use_reducer(SleepState::new);
if sleep_state.s.resumed() {
Ok(Rc::new(move || sleep_state.dispatch(())))
} else {
Err(sleep_state.s.clone())
}
}
#[derive(Properties, Clone)]
struct Props {
counter: Rc<RefCell<u64>>,
}
impl PartialEq for Props {
fn eq(&self, _rhs: &Self) -> bool {
true
}
}
#[component(Content)]
fn content(props: &Props) -> HtmlResult {
{
let counter = props.counter.clone();
use_effect(move || {
let mut counter = counter.borrow_mut();
*counter += 1;
|| {}
});
}
let resleep = use_sleep()?;
let value = use_state(|| 0);
let on_increment = {
let value = value.clone();
Callback::from(move |_: MouseEvent| {
value.set(*value + 1);
})
};
let on_take_a_break = Callback::from(move |_: MouseEvent| (resleep.clone())());
Ok(html! {
<div class="content-area">
<div class="actual-result">{*value}</div>
<button class="increase" onclick={on_increment}>{"increase"}</button>
<div class="action-area">
<button class="take-a-break" onclick={on_take_a_break}>{"Take a break!"}</button>
</div>
</div>
})
}
#[component(App)]
fn app(props: &Props) -> Html {
let fallback = html! {<div>{"wait..."}</div>};
html! {
<div id="result">
<Suspense {fallback}>
<Content counter={props.counter.clone()} />
</Suspense>
</div>
}
}
let counter = Rc::new(RefCell::new(0_u64));
let props = Props {
counter: counter.clone(),
};
yew::Renderer::<App>::with_root_and_props(
gloo::utils::document().get_element_by_id("output").unwrap(),
props,
)
.render();
sleep(Duration::from_millis(10)).await;
let result = obtain_result();
assert_eq!(result.as_str(), "<div>wait...</div>");
assert_eq!(*counter.borrow(), 0); // effects not called.
sleep(Duration::from_millis(50)).await;
let result = obtain_result();
assert_eq!(
result.as_str(),
r#"<div class="content-area"><div class="actual-result">0</div><button class="increase">increase</button><div class="action-area"><button class="take-a-break">Take a break!</button></div></div>"#
);
assert_eq!(*counter.borrow(), 1); // effects ran 1 time.
sleep(Duration::from_millis(10)).await;
gloo::utils::document()
.query_selector(".increase")
.unwrap()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap()
.click();
sleep(Duration::ZERO).await;
gloo::utils::document()
.query_selector(".increase")
.unwrap()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap()
.click();
sleep(Duration::from_millis(0)).await;
let result = obtain_result();
assert_eq!(
result.as_str(),
r#"<div class="content-area"><div class="actual-result">2</div><button class="increase">increase</button><div class="action-area"><button class="take-a-break">Take a break!</button></div></div>"#
);
assert_eq!(*counter.borrow(), 3); // effects ran 3 times.
gloo::utils::document()
.query_selector(".take-a-break")
.unwrap()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap()
.click();
sleep(Duration::from_millis(10)).await;
let result = obtain_result();
assert_eq!(result.as_str(), "<div>wait...</div>");
assert_eq!(*counter.borrow(), 3); // effects ran 3 times.
sleep(Duration::from_millis(50)).await;
let result = obtain_result();
assert_eq!(
result.as_str(),
r#"<div class="content-area"><div class="actual-result">2</div><button class="increase">increase</button><div class="action-area"><button class="take-a-break">Take a break!</button></div></div>"#
);
assert_eq!(*counter.borrow(), 4); // effects ran 4 times.
}
#[wasm_bindgen_test]
async fn use_suspending_future_works() {
#[component(Content)]
fn content() -> HtmlResult {
let _sleep_handle = use_future(|| async move {
sleep(Duration::from_millis(50)).await;
})?;
Ok(html! {
<div>
{"Content"}
</div>
})
}
#[component(App)]
fn app() -> Html {
let fallback = html! {<div>{"wait..."}</div>};
html! {
<div id="result">
<Suspense {fallback}>
<Content />
</Suspense>
</div>
}
}
yew::Renderer::<App>::with_root(gloo::utils::document().get_element_by_id("output").unwrap())
.render();
sleep(Duration::from_millis(10)).await;
let result = obtain_result();
assert_eq!(result.as_str(), "<div>wait...</div>");
sleep(Duration::from_millis(50)).await;
let result = obtain_result();
assert_eq!(result.as_str(), r#"<div>Content</div>"#);
}
#[wasm_bindgen_test]
async fn use_suspending_future_with_deps_works() {
#[derive(PartialEq, Properties)]
struct ContentProps {
delay_millis: u64,
}
#[component(Content)]
fn content(ContentProps { delay_millis }: &ContentProps) -> HtmlResult {
let delayed_result = use_future_with(*delay_millis, |delay_millis| async move {
sleep(Duration::from_millis(*delay_millis)).await;
42
})?;
Ok(html! {
<div>
{*delayed_result}
</div>
})
}
#[component(App)]
fn app() -> Html {
let fallback = html! {<div>{"wait..."}</div>};
html! {
<div id="result">
<Suspense {fallback}>
<Content delay_millis={50} />
</Suspense>
</div>
}
}
yew::Renderer::<App>::with_root(gloo::utils::document().get_element_by_id("output").unwrap())
.render();
sleep(Duration::from_millis(10)).await;
let result = obtain_result();
assert_eq!(result.as_str(), "<div>wait...</div>");
sleep(Duration::from_millis(50)).await;
let result = obtain_result();
assert_eq!(result.as_str(), r#"<div>42</div>"#);
}
#[wasm_bindgen_test]
async fn test_suspend_forever() {
/// A component that its suspension never resumes.
/// We test that this can be used with to trigger a suspension and unsuspend upon unmount.
#[component]
fn SuspendForever() -> HtmlResult {
let (s, handle) = Suspension::new();
use_state(move || handle);
Err(s.into())
}
#[component]
fn App() -> Html {
let page = use_state(|| 1);
{
let page_setter = page.setter();
use_effect_with((), move |_| {
spawn_local(async move {
sleep(Duration::from_secs(1)).await;
page_setter.set(2);
});
});
}
let content = if *page == 1 {
html! { <SuspendForever /> }
} else {
html! { <div id="result">{"OK"}</div> }
};
html! {
<Suspense fallback={html! {<div>{"Loading..."}</div>}}>
{content}
</Suspense>
}
}
yew::Renderer::<App>::with_root(gloo::utils::document().get_element_by_id("output").unwrap())
.render();
sleep(Duration::from_millis(1500)).await;
let result = obtain_result();
assert_eq!(result.as_str(), r#"OK"#);
}
#[wasm_bindgen_test]
async fn resume_after_unmount() {
#[derive(Clone, Properties, PartialEq)]
struct ContentProps {
state: UseStateHandle<bool>,
}
#[component(Content)]
fn content(ContentProps { state }: &ContentProps) -> HtmlResult {
let state = state.clone();
let _sleep_handle = use_future(|| async move {
sleep(Duration::from_millis(50)).await;
state.set(false);
sleep(Duration::from_millis(50)).await;
})?;
Ok(html! {
<div>{"Content"}</div>
})
}
#[component(App)]
fn app() -> Html {
let fallback = html! {<div>{"wait..."}</div>};
let state = use_state(|| true);
html! {
<div id="result">
if *state {
<Suspense {fallback}>
<Content {state} />
</Suspense>
} else {
<div>{"Content replacement"}</div>
}
</div>
}
}
yew::Renderer::<App>::with_root(gloo::utils::document().get_element_by_id("output").unwrap())
.render();
sleep(Duration::from_millis(25)).await;
let result = obtain_result();
assert_eq!(result.as_str(), "<div>wait...</div>");
sleep(Duration::from_millis(50)).await;
let result = obtain_result();
assert_eq!(result.as_str(), "<div>Content replacement</div>");
}
#[wasm_bindgen_test]
async fn test_duplicate_suspension() {
use yew::html::ChildrenProps;
#[component]
fn FetchingProvider(props: &ChildrenProps) -> HtmlResult {
use_future(|| async {
sleep(Duration::ZERO).await;
})?;
Ok(html! { <>{props.children.clone()}</> })
}
#[component]
fn Child() -> Html {
html! {<div id="result">{"hello!"}</div>}
}
#[component]
fn App() -> Html {
let fallback = Html::default();
html! {
<Suspense {fallback}>
<FetchingProvider>
<Child />
</FetchingProvider>
</Suspense>
}
}
yew::Renderer::<App>::with_root(gloo::utils::document().get_element_by_id("output").unwrap())
.render();
sleep(Duration::from_millis(50)).await;
let result = obtain_result();
assert_eq!(result.as_str(), "hello!");
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/tests/use_state.rs | packages/yew/tests/use_state.rs | #![cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
mod common;
use std::time::Duration;
use common::obtain_result;
use wasm_bindgen_test::*;
use yew::platform::time::sleep;
use yew::prelude::*;
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
async fn use_state_works() {
#[component(UseComponent)]
fn use_state_comp() -> Html {
let counter = use_state(|| 0);
if *counter < 5 {
counter.set(*counter + 1)
}
html! {
<div>
{"Test Output: "}
<div id="result">{*counter}</div>
{"\n"}
</div>
}
}
yew::Renderer::<UseComponent>::with_root(
gloo::utils::document().get_element_by_id("output").unwrap(),
)
.render();
sleep(Duration::ZERO).await;
let result = obtain_result();
assert_eq!(result.as_str(), "5");
}
#[wasm_bindgen_test]
async fn multiple_use_state_setters() {
#[component(UseComponent)]
fn use_state_comp() -> Html {
let counter = use_state(|| 0);
let counter_clone = counter.clone();
use_effect_with((), move |_| {
// 1st location
counter_clone.set(*counter_clone + 1);
|| {}
});
let another_scope = {
let counter = counter.clone();
move || {
if *counter < 11 {
// 2nd location
counter.set(*counter + 10)
}
}
};
another_scope();
html! {
<div>
{ "Test Output: " }
// expected output
<div id="result">{ *counter }</div>
{ "\n" }
</div>
}
}
yew::Renderer::<UseComponent>::with_root(
gloo::utils::document().get_element_by_id("output").unwrap(),
)
.render();
sleep(Duration::ZERO).await;
let result = obtain_result();
assert_eq!(result.as_str(), "11");
}
#[wasm_bindgen_test]
async fn use_state_eq_works() {
use std::sync::atomic::{AtomicUsize, Ordering};
static RENDER_COUNT: AtomicUsize = AtomicUsize::new(0);
#[component(UseComponent)]
fn use_state_comp() -> Html {
RENDER_COUNT.fetch_add(1, Ordering::Relaxed);
let counter = use_state_eq(|| 0);
counter.set(1);
html! {
<div>
{"Test Output: "}
<div id="result">{*counter}</div>
{"\n"}
</div>
}
}
yew::Renderer::<UseComponent>::with_root(
gloo::utils::document().get_element_by_id("output").unwrap(),
)
.render();
sleep(Duration::ZERO).await;
let result = obtain_result();
assert_eq!(result.as_str(), "1");
assert_eq!(RENDER_COUNT.load(Ordering::Relaxed), 2);
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/tests/use_callback.rs | packages/yew/tests/use_callback.rs | #![cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
use std::sync::atomic::{AtomicBool, Ordering};
mod common;
use std::time::Duration;
use common::obtain_result;
use wasm_bindgen_test::*;
use yew::platform::time::sleep;
use yew::prelude::*;
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
async fn use_callback_works() {
#[derive(Properties, PartialEq)]
struct Props {
callback: Callback<String, String>,
}
#[component(MyComponent)]
fn my_component(props: &Props) -> Html {
let greeting = props.callback.emit("Yew".to_string());
static CTR: AtomicBool = AtomicBool::new(false);
if CTR.swap(true, Ordering::Relaxed) {
panic!("multiple times rendered!");
}
html! {
<div>
{"The test output is: "}
<div id="result">{&greeting}</div>
{"\n"}
</div>
}
}
#[component(UseCallbackComponent)]
fn use_callback_comp() -> Html {
let state = use_state(|| 0);
let callback = use_callback((), move |name, _| format!("Hello, {}!", name));
use_effect(move || {
if *state < 5 {
state.set(*state + 1);
}
|| {}
});
html! {
<div>
<MyComponent {callback} />
</div>
}
}
yew::Renderer::<UseCallbackComponent>::with_root(
gloo::utils::document().get_element_by_id("output").unwrap(),
)
.render();
sleep(Duration::ZERO).await;
let result = obtain_result();
assert_eq!(result.as_str(), "Hello, Yew!");
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/tests/use_transitive_state.rs | packages/yew/tests/use_transitive_state.rs | #![cfg(feature = "hydration")]
#![cfg(target_arch = "wasm32")]
use std::time::Duration;
mod common;
use common::obtain_result_by_id;
use wasm_bindgen_test::*;
use yew::platform::time::sleep;
use yew::prelude::*;
use yew::{Renderer, ServerRenderer};
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
async fn use_transitive_state_works() {
#[component]
fn Comp() -> HtmlResult {
let ctr = use_transitive_state!((), |_| -> u32 { 12345 })?.unwrap_or_default();
Ok(html! {
<div>
{*ctr}
</div>
})
}
#[component]
fn App() -> Html {
html! {
<Suspense fallback={Html::default()}>
<div>
<Comp />
</div>
</Suspense>
}
}
let s = ServerRenderer::<App>::new().render().await;
assert_eq!(
s,
// div text content should be 0 but state should be 12345.
r#"<!--<[use_transitive_state::use_transitive_state_works::{{closure}}::App]>--><!--<[yew::suspense::component::feat_csr_ssr::Suspense]>--><!--<[yew::suspense::component::feat_csr_ssr::BaseSuspense]>--><!--<?>--><div><!--<[use_transitive_state::use_transitive_state_works::{{closure}}::Comp]>--><div>0</div><script type="application/x-yew-comp-state">Afs5MAE=</script><!--</[use_transitive_state::use_transitive_state_works::{{closure}}::Comp]>--></div><!--</?>--><!--</[yew::suspense::component::feat_csr_ssr::BaseSuspense]>--><!--</[yew::suspense::component::feat_csr_ssr::Suspense]>--><!--</[use_transitive_state::use_transitive_state_works::{{closure}}::App]>-->"#
);
gloo::utils::document()
.query_selector("#output")
.unwrap()
.unwrap()
.set_inner_html(&s);
sleep(Duration::ZERO).await;
Renderer::<App>::with_root(gloo::utils::document().get_element_by_id("output").unwrap())
.hydrate();
sleep(Duration::from_millis(100)).await;
let result = obtain_result_by_id("output");
// no placeholders, hydration is successful and div text content now becomes 12345.
assert_eq!(result, r#"<div><div>12345</div></div>"#);
}
| rust | Apache-2.0 | 2019f4577cbdcd389b34973fdec3164be3af941a | 2026-01-04T15:33:05.007302Z | false |
yewstack/yew | https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/tests/use_ref.rs | packages/yew/tests/use_ref.rs | #![cfg(all(target_arch = "wasm32", not(target_os = "wasi")))]
mod common;
use std::ops::DerefMut;
use std::time::Duration;
use common::obtain_result;
use wasm_bindgen_test::*;
use yew::platform::time::sleep;
use yew::prelude::*;
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
async fn use_ref_works() {
#[component(UseRefComponent)]
fn use_ref_comp() -> Html {
let ref_example = use_mut_ref(|| 0);
*ref_example.borrow_mut().deref_mut() += 1;
let counter = use_state(|| 0);
if *counter < 5 {
counter.set(*counter + 1)
}
html! {
<div>
{"The test output is: "}
<div id="result">{*ref_example.borrow_mut().deref_mut() > 4}</div>
{"\n"}
</div>
}
}
yew::Renderer::<UseRefComponent>::with_root(
gloo::utils::document().get_element_by_id("output").unwrap(),
)
.render();
sleep(Duration::ZERO).await;
let result = obtain_result();
assert_eq!(result.as_str(), "true");
}
| 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.