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/packages/yew/tests/use_prepared_state.rs
packages/yew/tests/use_prepared_state.rs
#![cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] #![cfg(feature = "hydration")] #![cfg_attr(nightly_yew, feature(async_closure))] 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_prepared_state_works() { #[component] fn Comp() -> HtmlResult { let ctr = use_prepared_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, r#"<!--<[use_prepared_state::use_prepared_state_works::{{closure}}::App]>--><!--<[yew::suspense::component::feat_csr_ssr::Suspense]>--><!--<[yew::suspense::component::feat_csr_ssr::BaseSuspense]>--><!--<?>--><div><!--<[use_prepared_state::use_prepared_state_works::{{closure}}::Comp]>--><div>12345</div><script type="application/x-yew-comp-state">Afs5MAE=</script><!--</[use_prepared_state::use_prepared_state_works::{{closure}}::Comp]>--></div><!--</?>--><!--</[yew::suspense::component::feat_csr_ssr::BaseSuspense]>--><!--</[yew::suspense::component::feat_csr_ssr::Suspense]>--><!--</[use_prepared_state::use_prepared_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 state 12345 is preserved. assert_eq!(result, r#"<div><div>12345</div></div>"#); } #[wasm_bindgen_test] async fn use_prepared_state_with_suspension_works() { #[component] fn Comp() -> HtmlResult { let ctr = use_prepared_state!((), async move |_| -> 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, r#"<!--<[use_prepared_state::use_prepared_state_with_suspension_works::{{closure}}::App]>--><!--<[yew::suspense::component::feat_csr_ssr::Suspense]>--><!--<[yew::suspense::component::feat_csr_ssr::BaseSuspense]>--><!--<?>--><div><!--<[use_prepared_state::use_prepared_state_with_suspension_works::{{closure}}::Comp]>--><div>12345</div><script type="application/x-yew-comp-state">Afs5MAE=</script><!--</[use_prepared_state::use_prepared_state_with_suspension_works::{{closure}}::Comp]>--></div><!--</?>--><!--</[yew::suspense::component::feat_csr_ssr::BaseSuspense]>--><!--</[yew::suspense::component::feat_csr_ssr::Suspense]>--><!--</[use_prepared_state::use_prepared_state_with_suspension_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 state 12345 is preserved. 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/hydration.rs
packages/yew/tests/hydration.rs
#![cfg(feature = "hydration")] #![cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] use std::ops::Range; use std::rc::Rc; use std::time::Duration; mod common; use common::{obtain_result, obtain_result_by_id}; use wasm_bindgen::JsCast; use wasm_bindgen_futures::spawn_local; use wasm_bindgen_test::*; use web_sys::{HtmlElement, HtmlTextAreaElement}; use yew::platform::time::sleep; use yew::prelude::*; use yew::suspense::{use_future, Suspension, SuspensionResult}; use yew::virtual_dom::VNode; use yew::{component, Renderer, ServerRenderer}; wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); // If any of the assertions fail due to a modification to hydration logic, cargo will suggest the // expected result and you can copy it into the test to fix it. #[wasm_bindgen_test] async fn hydration_works() { #[component] fn Comp() -> Html { let ctr = use_state_eq(|| 0); let onclick = { let ctr = ctr.clone(); Callback::from(move |_| { ctr.set(*ctr + 1); }) }; html! { <div> {"Counter: "}{*ctr} <button {onclick} class="increase">{"+1"}</button> </div> } } #[component] fn App() -> Html { html! { <div> <Comp /> </div> } } let s = ServerRenderer::<App>::new().render().await; 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::ZERO).await; let result = obtain_result_by_id("output"); // no placeholders, hydration is successful. assert_eq!( result, r#"<div><div>Counter: 0<button class="increase">+1</button></div></div>"# ); gloo::utils::document() .query_selector(".increase") .unwrap() .unwrap() .dyn_into::<HtmlElement>() .unwrap() .click(); sleep(Duration::ZERO).await; let result = obtain_result_by_id("output"); assert_eq!( result, r#"<div><div>Counter: 1<button class="increase">+1</button></div></div>"# ); } #[wasm_bindgen_test] async fn hydration_with_raw() { #[component(Content)] fn content() -> Html { let vnode = VNode::from_html_unchecked("<div><p>Hello World</p></div>".into()); html! { <div class="content-area"> {vnode} </div> } } #[component(App)] fn app() -> Html { html! { <div id="result"> <Content /> </div> } } let s = ServerRenderer::<App>::new().render().await; gloo::utils::document() .query_selector("#output") .unwrap() .unwrap() .set_inner_html(&s); sleep(Duration::from_millis(10)).await; Renderer::<App>::with_root(gloo::utils::document().get_element_by_id("output").unwrap()) .hydrate(); let result = obtain_result(); // still hydrating, during hydration, the server rendered result is shown. assert_eq!( result.as_str(), r#"<!--<[hydration::hydration_with_raw::{{closure}}::Content]>--><div class="content-area"><!--<#>--><div><p>Hello World</p></div><!--</#>--></div><!--</[hydration::hydration_with_raw::{{closure}}::Content]>-->"# ); sleep(Duration::from_millis(50)).await; let result = obtain_result(); // hydrated. assert_eq!( result.as_str(), r#"<div class="content-area"><div><p>Hello World</p></div></div>"# ); } #[wasm_bindgen_test] async fn hydration_with_suspense() { #[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> } } let s = ServerRenderer::<App>::new().render().await; 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(10)).await; let result = obtain_result(); // still hydrating, during hydration, the server rendered result is shown. assert_eq!( result.as_str(), r#"<!--<[hydration::hydration_with_suspense::{{closure}}::Content]>--><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><!--</[hydration::hydration_with_suspense::{{closure}}::Content]>-->"# ); sleep(Duration::from_millis(50)).await; let result = obtain_result(); // hydrated. 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>"# ); gloo::utils::document() .query_selector(".increase") .unwrap() .unwrap() .dyn_into::<HtmlElement>() .unwrap() .click(); sleep(Duration::from_millis(50)).await; let result = obtain_result(); assert_eq!( result.as_str(), r#"<div class="content-area"><div class="actual-result">1</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">1</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 hydration_with_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> } } let s = ServerRenderer::<App>::new().render().await; 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(10)).await; let result = obtain_result(); assert_eq!( result.as_str(), r#"<div class="content-area"><textarea>I am writing a long story...</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>I am writing a long story...</textarea><div class="action-area"><button class="take-a-break">Take a break!</button></div></div>"# ); } #[wasm_bindgen_test] async fn hydration_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> } } let s = ServerRenderer::<App>::new().render().await; 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(); // outer suspense is hydrating... sleep(Duration::from_millis(10)).await; let result = obtain_result(); assert_eq!( result.as_str(), r#"<!--<[hydration::hydration_nested_suspense_works::{{closure}}::Content]>--><div class="content-area"><div class="action-area"><button class="take-a-break">Take a break!</button></div><!--<[yew::suspense::component::feat_csr_ssr::Suspense]>--><!--<[yew::suspense::component::feat_csr_ssr::BaseSuspense]>--><!--<?>--><!--<[hydration::hydration_nested_suspense_works::{{closure}}::InnerContent]>--><div class="content-area"><div class="action-area"><button class="take-a-break2">Take a break!</button></div></div><!--</[hydration::hydration_nested_suspense_works::{{closure}}::InnerContent]>--><!--</?>--><!--</[yew::suspense::component::feat_csr_ssr::BaseSuspense]>--><!--</[yew::suspense::component::feat_csr_ssr::Suspense]>--></div><!--</[hydration::hydration_nested_suspense_works::{{closure}}::Content]>-->"# ); sleep(Duration::from_millis(50)).await; // inner suspense is hydrating... 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><!--<[hydration::hydration_nested_suspense_works::{{closure}}::InnerContent]>--><div class="content-area"><div class="action-area"><button class="take-a-break2">Take a break!</button></div></div><!--</[hydration::hydration_nested_suspense_works::{{closure}}::InnerContent]>--></div>"# ); sleep(Duration::from_millis(50)).await; // hydrated. 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-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...(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 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 hydration_node_ref_works() { #[component(App)] pub fn app() -> Html { let size = use_state(|| 4); let callback = { let size = size.clone(); Callback::from(move |_| { size.set(10); }) }; html! { <div onclick={callback}> <List size={*size}/> </div> } } #[derive(Properties, PartialEq)] struct ListProps { size: u32, } #[component(Test1)] fn test1() -> Html { html! { <span>{"test"}</span> } } #[component(Test2)] fn test2() -> Html { html! { <Test1/> } } #[component(List)] fn list(props: &ListProps) -> Html { let elems = 0..props.size; html! { <> { for elems.map(|_| html! { <Test2/> } )} </> } } let s = ServerRenderer::<App>::new().render().await; 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::ZERO).await; let result = obtain_result_by_id("output"); assert_eq!( result.as_str(), r#"<div><span>test</span><span>test</span><span>test</span><span>test</span></div>"# ); gloo::utils::document() .query_selector("span") .unwrap() .unwrap() .dyn_into::<HtmlElement>() .unwrap() .click(); sleep(Duration::ZERO).await; let result = obtain_result_by_id("output"); assert_eq!( result.as_str(), r#"<div><span>test</span><span>test</span><span>test</span><span>test</span><span>test</span><span>test</span><span>test</span><span>test</span><span>test</span><span>test</span></div>"# ); } #[wasm_bindgen_test] async fn hydration_list_order_works() { #[component(App)] pub fn app() -> Html { let elems = 0..10; html! { <> { for elems.map(|number| html! { <ToSuspendOrNot {number}/> } )} </> } } #[derive(Properties, PartialEq)] struct NumberProps { number: u32, } #[component(Number)] fn number(props: &NumberProps) -> Html { html! { <div>{props.number.to_string()}</div> } } #[component(SuspendedNumber)] fn suspended_number(props: &NumberProps) -> HtmlResult { use_suspend()?; Ok(html! { <div>{props.number.to_string()}</div> }) } #[component(ToSuspendOrNot)] fn suspend_or_not(props: &NumberProps) -> Html { let number = props.number; html! { <Suspense> if number % 3 == 0 { <SuspendedNumber {number}/> } else { <Number {number}/> } </Suspense> } } #[hook] pub fn use_suspend() -> SuspensionResult<()> { use_future(|| async {})?; Ok(()) } let s = ServerRenderer::<App>::new().render().await; 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(); // Wait until all suspended components becomes revealed. sleep(Duration::ZERO).await; sleep(Duration::ZERO).await; sleep(Duration::ZERO).await; sleep(Duration::ZERO).await; let result = obtain_result_by_id("output"); assert_eq!( result.as_str(), // Until all components become revealed, there will be component markers. // As long as there's no component markers all components have become unsuspended. r#"<div>0</div><div>1</div><div>2</div><div>3</div><div>4</div><div>5</div><div>6</div><div>7</div><div>8</div><div>9</div>"# ); } #[wasm_bindgen_test] async fn hydration_suspense_no_flickering() { #[component(App)] pub fn app() -> Html { let fallback = html! { <h1>{"Loading..."}</h1> }; html! { <Suspense {fallback}> <Suspended/> </Suspense> } } #[derive(Properties, PartialEq, Clone)] struct NumberProps { number: u32, } #[component(SuspendedNumber)] fn suspended_number(props: &NumberProps) -> HtmlResult { use_suspend()?; Ok(html! { <Number ..{props.clone()}/> }) } #[component(Number)] fn number(props: &NumberProps) -> Html { html! { <div> {props.number.to_string()} </div> } } #[component(Suspended)] fn suspended() -> HtmlResult { use_suspend()?; Ok(html! { { for (0..10).map(|number| html! { <SuspendedNumber {number}/> } )} }) } #[hook] pub fn use_suspend() -> SuspensionResult<()> { use_future(|| async { yew::platform::time::sleep(std::time::Duration::from_millis(200)).await; })?; Ok(()) } let s = ServerRenderer::<App>::new().render().await; 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(); // Wait until all suspended components becomes revealed. sleep(Duration::ZERO).await; let result = obtain_result_by_id("output"); assert_eq!( result.as_str(), // outer still suspended. r#"<!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Suspended]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>0</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>1</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>2</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>3</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>4</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>5</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>6</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>7</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>8</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>9</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Suspended]>-->"# ); sleep(Duration::from_millis(103)).await; let result = obtain_result_by_id("output"); assert_eq!( result.as_str(), r#"<!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Suspended]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>0</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>1</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>2</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>3</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>4</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>5</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>6</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>7</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>8</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--<[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><div>9</div><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Number]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::SuspendedNumber]>--><!--</[hydration::hydration_suspense_no_flickering::{{closure}}::Suspended]>-->"# ); sleep(Duration::from_millis(103)).await; let result = obtain_result_by_id("output"); assert_eq!( result.as_str(),
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
true
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/tests/use_reducer.rs
packages/yew/tests/use_reducer.rs
#![cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] use std::collections::HashSet; use std::rc::Rc; use std::time::Duration; use gloo::utils::document; use wasm_bindgen::JsCast; use wasm_bindgen_test::*; use web_sys::HtmlElement; use yew::platform::time::sleep; use yew::prelude::*; mod common; use common::obtain_result; wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); #[derive(Debug)] struct CounterState { counter: i32, } impl Reducible for CounterState { type Action = i32; fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> { Self { counter: self.counter + action, } .into() } } #[wasm_bindgen_test] async fn use_reducer_works() { #[component(UseReducerComponent)] fn use_reducer_comp() -> Html { let counter = use_reducer(|| CounterState { counter: 10 }); let counter_clone = counter.clone(); use_effect_with((), move |_| { counter_clone.dispatch(1); || {} }); html! { <div> {"The test result is"} <div id="result">{counter.counter}</div> {"\n"} </div> } } yew::Renderer::<UseReducerComponent>::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"); } #[derive(Debug, Clone, PartialEq)] struct ContentState { content: HashSet<String>, } impl Reducible for ContentState { type Action = String; fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> { let mut self_: Self = (*self).clone(); self_.content.insert(action); self_.into() } } #[wasm_bindgen_test] async fn use_reducer_eq_works() { #[component(UseReducerComponent)] fn use_reducer_comp() -> Html { let content = use_reducer_eq(|| ContentState { content: HashSet::default(), }); let render_count = use_mut_ref(|| 0); let render_count = { let mut render_count = render_count.borrow_mut(); *render_count += 1; *render_count }; let add_content_a = { let content = content.clone(); Callback::from(move |_| content.dispatch("A".to_string())) }; let add_content_b = Callback::from(move |_| content.dispatch("B".to_string())); html! { <> <div> {"This component has been rendered: "}<span id="result">{render_count}</span>{" Time(s)."} </div> <button onclick={add_content_a} id="add-a">{"Add A to Content"}</button> <button onclick={add_content_b} id="add-b">{"Add B to Content"}</button> </> } } yew::Renderer::<UseReducerComponent>::with_root( document().get_element_by_id("output").unwrap(), ) .render(); sleep(Duration::ZERO).await; let result = obtain_result(); assert_eq!(result.as_str(), "1"); document() .get_element_by_id("add-a") .unwrap() .unchecked_into::<HtmlElement>() .click(); sleep(Duration::ZERO).await; let result = obtain_result(); assert_eq!(result.as_str(), "2"); document() .get_element_by_id("add-a") .unwrap() .unchecked_into::<HtmlElement>() .click(); sleep(Duration::ZERO).await; let result = obtain_result(); assert_eq!(result.as_str(), "2"); document() .get_element_by_id("add-b") .unwrap() .unchecked_into::<HtmlElement>() .click(); sleep(Duration::ZERO).await; let result = obtain_result(); assert_eq!(result.as_str(), "3"); document() .get_element_by_id("add-b") .unwrap() .unchecked_into::<HtmlElement>() .click(); sleep(Duration::ZERO).await; let result = obtain_result(); assert_eq!(result.as_str(), "3"); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/tests/mod.rs
packages/yew/tests/mod.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 props_are_passed() { #[derive(Properties, Clone, PartialEq)] struct PropsPassedFunctionProps { value: String, } #[component] fn PropsComponent(props: &PropsPassedFunctionProps) -> Html { assert_eq!(&props.value, "props"); html! { <div id="result"> {"done"} </div> } } yew::Renderer::<PropsComponent>::with_root_and_props( gloo::utils::document().get_element_by_id("output").unwrap(), PropsPassedFunctionProps { value: "props".to_string(), }, ) .render(); sleep(Duration::ZERO).await; let result = obtain_result(); assert_eq!(result.as_str(), "done"); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/tests/layout.rs
packages/yew/tests/layout.rs
#![cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] mod common; wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); use std::time::Duration; use common::obtain_result; use wasm_bindgen_futures::spawn_local; use wasm_bindgen_test::*; use yew::platform::time::sleep; use yew::prelude::*; #[wasm_bindgen_test] async fn change_nested_after_append() { #[component] fn Nested() -> Html { let delayed_trigger = use_state(|| true); { let delayed_trigger = delayed_trigger.clone(); use_effect_with((), move |_| { spawn_local(async move { sleep(Duration::from_millis(50)).await; delayed_trigger.set(false); }); || {} }); } if *delayed_trigger { html! { <div>{"failure"}</div> } } else { html! { <><i></i><span id="result">{"success"}</span></> } } } #[component] fn Top() -> Html { html! { <Nested /> } } #[component] fn App() -> Html { let show_bottom = use_state_eq(|| false); { let show_bottom = show_bottom.clone(); use_effect_with((), move |_| { show_bottom.set(true); || {} }); } html! { <> <Top /> if *show_bottom { <div>{"<div>Bottom</div>"}</div> } </> } } yew::Renderer::<App>::with_root(gloo::utils::document().get_element_by_id("output").unwrap()) .render(); sleep(Duration::from_millis(100)).await; let result = obtain_result(); assert_eq!(result.as_str(), "success"); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/tests/raw_html.rs
packages/yew/tests/raw_html.rs
mod common; #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] use wasm_bindgen::JsCast; #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] use wasm_bindgen_test::wasm_bindgen_test as test; use yew::prelude::*; #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] use tokio::test; macro_rules! create_test { ($name:ident, $html:expr) => { create_test!($name, $html, $html); }; ($name:ident, $raw:expr, $expected:expr) => { #[test] async fn $name() { #[component] fn App() -> Html { let raw = Html::from_html_unchecked(AttrValue::from($raw)); html! { <div id="raw-container"> {raw} </div> } } #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] { use std::time::Duration; use yew::platform::time::sleep; yew::Renderer::<App>::with_root( gloo::utils::document().get_element_by_id("output").unwrap(), ) .render(); // wait for render to finish sleep(Duration::from_millis(100)).await; let e = gloo::utils::document() .get_element_by_id("raw-container") .unwrap(); assert_eq!(e.inner_html(), $expected); } #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] { let actual = yew::LocalServerRenderer::<App>::new() .hydratable(false) .render() .await; assert_eq!( actual, format!(r#"<div id="raw-container">{}</div>"#, $expected) ); } } }; } create_test!(empty_string, ""); create_test!(one_node, "<span>text</span>"); create_test!( one_but_nested_node, r#"<p>one <a href="https://yew.rs">link</a> more paragraph</p>"# ); create_test!( multi_node, r#"<p>paragraph</p><a href="https://yew.rs">link</a>"# ); #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] macro_rules! create_update_html_test { ($name:ident, $initial:expr, $updated:expr) => { #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] #[test] async fn $name() { #[component] fn App() -> Html { let raw_html = use_state(|| ($initial)); let onclick = { let raw_html = raw_html.clone(); move |_| raw_html.set($updated) }; let raw = Html::from_html_unchecked(AttrValue::from(*raw_html)); html! { <> <div id="raw-container"> {raw} </div> <button id="click-me-btn" {onclick}>{"Click me"}</button> </> } } use std::time::Duration; use yew::platform::time::sleep; yew::Renderer::<App>::with_root( gloo::utils::document().get_element_by_id("output").unwrap(), ) .render(); // wait for render to finish sleep(Duration::from_millis(100)).await; let e = gloo::utils::document() .get_element_by_id("raw-container") .unwrap(); assert_eq!(e.inner_html(), $initial); gloo::utils::document() .get_element_by_id("click-me-btn") .unwrap() .unchecked_into::<web_sys::HtmlButtonElement>() .click(); sleep(Duration::from_millis(100)).await; let e = gloo::utils::document() .get_element_by_id("raw-container") .unwrap(); assert_eq!(e.inner_html(), $updated); } }; } #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] create_update_html_test!( set_new_html_string, "<span>first</span>", "<span>second</span>" ); #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] create_update_html_test!( set_new_html_string_multiple_children, "<span>first</span><span>second</span>", "<span>second</span>" ); #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] create_update_html_test!( clear_html_string_multiple_children, "<span>first</span><span>second</span>", "" ); #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] create_update_html_test!( nothing_changes, "<span>first</span><span>second</span>", "<span>first</span><span>second</span>" ); #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] #[test] async fn change_vnode_types_from_other_to_vraw() { #[component] fn App() -> Html { let node = use_state(|| html!("text")); let onclick = { let node = node.clone(); move |_| { node.set(Html::from_html_unchecked(AttrValue::from( "<span>second</span>", ))) } }; html! { <> <div id="raw-container"> {(*node).clone()} </div> <button id="click-me-btn" {onclick}>{"Click me"}</button> </> } } use std::time::Duration; use yew::platform::time::sleep; yew::Renderer::<App>::with_root(gloo::utils::document().get_element_by_id("output").unwrap()) .render(); // wait for render to finish sleep(Duration::from_millis(100)).await; let e = gloo::utils::document() .get_element_by_id("raw-container") .unwrap(); assert_eq!(e.inner_html(), "text"); gloo::utils::document() .get_element_by_id("click-me-btn") .unwrap() .unchecked_into::<web_sys::HtmlButtonElement>() .click(); sleep(Duration::from_millis(100)).await; let e = gloo::utils::document() .get_element_by_id("raw-container") .unwrap(); assert_eq!(e.inner_html(), "<span>second</span>"); } #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] #[test] async fn change_vnode_types_from_vraw_to_other() { #[component] fn App() -> Html { let node = use_state(|| Html::from_html_unchecked(AttrValue::from("<span>second</span>"))); let onclick = { let node = node.clone(); move |_| node.set(html!("text")) }; html! { <> <div id="raw-container"> {(*node).clone()} </div> <button id="click-me-btn" {onclick}>{"Click me"}</button> </> } } use std::time::Duration; use yew::platform::time::sleep; yew::Renderer::<App>::with_root(gloo::utils::document().get_element_by_id("output").unwrap()) .render(); // wait for render to finish sleep(Duration::from_millis(100)).await; let e = gloo::utils::document() .get_element_by_id("raw-container") .unwrap(); assert_eq!(e.inner_html(), "<span>second</span>"); gloo::utils::document() .get_element_by_id("click-me-btn") .unwrap() .unchecked_into::<web_sys::HtmlButtonElement>() .click(); sleep(Duration::from_millis(100)).await; let e = gloo::utils::document() .get_element_by_id("raw-container") .unwrap(); assert_eq!(e.inner_html(), "text"); }
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_memo.rs
packages/yew/tests/use_memo.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_memo_works() { #[component(UseMemoComponent)] fn use_memo_comp() -> Html { let state = use_state(|| 0); let memoed_val = use_memo((), |_| { static CTR: AtomicBool = AtomicBool::new(false); if CTR.swap(true, Ordering::Relaxed) { panic!("multiple times rendered!"); } "true" }); use_effect(move || { if *state < 5 { state.set(*state + 1); } || {} }); html! { <div> {"The test output is: "} <div id="result">{*memoed_val}</div> {"\n"} </div> } } yew::Renderer::<UseMemoComponent>::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
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/tests/use_context.rs
packages/yew/tests/use_context.rs
#![cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] mod common; use std::rc::Rc; use std::time::Duration; use common::obtain_result_by_id; 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_context_scoping_works() { #[derive(Clone, Debug, PartialEq)] struct ExampleContext(String); #[component] fn ExpectNoContextComponent() -> Html { let example_context = use_context::<ExampleContext>(); if example_context.is_some() { console_log!( "Context should be None here, but was {:?}!", example_context ); }; html! { <div></div> } } #[component] fn UseContextComponent() -> Html { type ExampleContextProvider = ContextProvider<ExampleContext>; html! { <div> <ExampleContextProvider context={ExampleContext("wrong1".into())}> <div>{"ignored"}</div> </ExampleContextProvider> <ExampleContextProvider context={ExampleContext("wrong2".into())}> <ExampleContextProvider context={ExampleContext("correct".into())}> <ExampleContextProvider context={ExampleContext("wrong1".into())}> <div>{"ignored"}</div> </ExampleContextProvider> <UseContextComponentInner /> </ExampleContextProvider> </ExampleContextProvider> <ExampleContextProvider context={ExampleContext("wrong3".into())}> <div>{"ignored"}</div> </ExampleContextProvider> <ExpectNoContextComponent /> </div> } } #[component] fn UseContextComponentInner() -> Html { let context = use_context::<ExampleContext>(); html! { <div id="result">{ &context.unwrap().0 }</div> } } yew::Renderer::<UseContextComponent>::with_root( gloo::utils::document().get_element_by_id("output").unwrap(), ) .render(); sleep(Duration::ZERO).await; let result: String = obtain_result_by_id("result"); assert_eq!("correct", result); } #[wasm_bindgen_test] async fn use_context_works_with_multiple_types() { #[derive(Clone, Debug, PartialEq)] struct ContextA(u32); #[derive(Clone, Debug, PartialEq)] struct ContextB(u32); #[component] fn Test1() -> Html { let ctx_a = use_context::<ContextA>(); let ctx_b = use_context::<ContextB>(); assert_eq!(ctx_a, Some(ContextA(2))); assert_eq!(ctx_b, Some(ContextB(1))); html! {} } #[component] fn Test2() -> Html { let ctx_a = use_context::<ContextA>(); let ctx_b = use_context::<ContextB>(); assert_eq!(ctx_a, Some(ContextA(0))); assert_eq!(ctx_b, Some(ContextB(1))); html! {} } #[component] fn Test3() -> Html { let ctx_a = use_context::<ContextA>(); let ctx_b = use_context::<ContextB>(); assert_eq!(ctx_a, Some(ContextA(0))); assert_eq!(ctx_b, None); html! {} } #[component] fn Test4() -> Html { let ctx_a = use_context::<ContextA>(); let ctx_b = use_context::<ContextB>(); assert_eq!(ctx_a, None); assert_eq!(ctx_b, None); html! {} } #[component] fn TestComponent() -> Html { type ContextAProvider = ContextProvider<ContextA>; type ContextBProvider = ContextProvider<ContextB>; html! { <div> <ContextAProvider context={ContextA(0)}> <ContextBProvider context={ContextB(1)}> <ContextAProvider context={ContextA(2)}> <Test1/> </ContextAProvider> <Test2/> </ContextBProvider> <Test3/> </ContextAProvider> <Test4 /> </div> } } yew::Renderer::<TestComponent>::with_root( gloo::utils::document().get_element_by_id("output").unwrap(), ) .render(); sleep(Duration::ZERO).await; } #[wasm_bindgen_test] async fn use_context_update_works() { #[derive(Clone, Debug, PartialEq)] struct MyContext(String); #[derive(Clone, Debug, PartialEq, Properties)] struct RenderCounterProps { id: String, children: Children, } #[component] fn RenderCounter(props: &RenderCounterProps) -> Html { let counter = use_mut_ref(|| 0); *counter.borrow_mut() += 1; html! { <> <div id={props.id.clone()}> { format!("total: {}", counter.borrow()) } </div> { props.children.clone() } </> } } #[derive(Clone, Debug, PartialEq, Properties)] struct ContextOutletProps { id: String, #[prop_or_default] magic: usize, } #[component] fn ContextOutlet(props: &ContextOutletProps) -> Html { let counter = use_mut_ref(|| 0); *counter.borrow_mut() += 1; let ctx = use_context::<Rc<MyContext>>().expect("context not passed down"); html! { <> <div>{ format!("magic: {}\n", props.magic) }</div> <div id={props.id.clone()}> { format!("current: {}, total: {}", ctx.0, counter.borrow()) } </div> </> } } #[component] fn TestComponent() -> Html { type MyContextProvider = ContextProvider<Rc<MyContext>>; let ctx = use_state(|| MyContext("hello".into())); let rendered = use_mut_ref(|| 0); // this is used to force an update specific to test-2 let magic_rc = use_state(|| 0); let magic: usize = *magic_rc; { let ctx = ctx.clone(); use_effect(move || { let count = *rendered.borrow(); match count { 0 => { ctx.set(MyContext("world".into())); *rendered.borrow_mut() += 1; } 1 => { // force test-2 to re-render. magic_rc.set(1); *rendered.borrow_mut() += 1; } 2 => { ctx.set(MyContext("hello world!".into())); *rendered.borrow_mut() += 1; } _ => (), }; || {} }); } html! { <MyContextProvider context={Rc::new((*ctx).clone())}> <RenderCounter id="test-0"> <ContextOutlet id="test-1" /> <ContextOutlet id="test-2" {magic} /> </RenderCounter> </MyContextProvider> } } yew::Renderer::<TestComponent>::with_root( gloo::utils::document().get_element_by_id("output").unwrap(), ) .render(); sleep(Duration::ZERO).await; // 1 initial render + 1 magic assert_eq!(obtain_result_by_id("test-0"), "total: 2"); // 1 initial + 2 context update assert_eq!( obtain_result_by_id("test-1"), "current: hello world!, total: 3" ); // 1 initial + 1 context update + 1 magic update + 1 context update assert_eq!( obtain_result_by_id("test-2"), "current: hello world!, total: 4" ); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew/tests/common/mod.rs
packages/yew/tests/common/mod.rs
#![allow(dead_code)] pub fn obtain_result() -> String { gloo::utils::document() .get_element_by_id("result") .expect("No result found. Most likely, the application crashed and burned") .inner_html() } pub fn obtain_result_by_id(id: &str) -> String { gloo::utils::document() .get_element_by_id(id) .expect("No result found. Most likely, the application crashed and burned") .inner_html() } pub fn output_element() -> web_sys::Element { gloo::utils::document().get_element_by_id("output").unwrap() }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router-macro/src/lib.rs
packages/yew-router-macro/src/lib.rs
mod routable_derive; use routable_derive::{routable_derive_impl, Routable}; use syn::parse_macro_input; /// Derive macro used to mark an enum as Routable. /// /// This macro can only be used on enums. Every varient of the macro needs to be marked /// with the `at` attribute to specify the URL of the route. It generates an implementation of /// `yew_router::Routable` trait and `const`s for the routes passed which are used with `Route` /// component. /// /// # Example /// /// ``` /// # use yew_router::Routable; /// #[derive(Debug, Clone, Copy, PartialEq, Routable)] /// enum Routes { /// #[at("/")] /// Home, /// #[at("/secure")] /// Secure, /// #[at("/404")] /// NotFound, /// } /// ``` #[proc_macro_derive(Routable, attributes(at, not_found))] pub fn routable_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse_macro_input!(input as Routable); routable_derive_impl(input).into() }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router-macro/src/routable_derive.rs
packages/yew-router-macro/src/routable_derive.rs
use proc_macro2::TokenStream; use quote::quote; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{Data, DeriveInput, Fields, Ident, LitStr, Variant}; const AT_ATTR_IDENT: &str = "at"; const NOT_FOUND_ATTR_IDENT: &str = "not_found"; pub struct Routable { ident: Ident, ats: Vec<LitStr>, variants: Punctuated<Variant, syn::token::Comma>, not_found_route: Option<Ident>, } impl Parse for Routable { fn parse(input: ParseStream) -> syn::Result<Self> { let DeriveInput { ident, data, .. } = input.parse()?; let data = match data { Data::Enum(data) => data, Data::Struct(s) => { return Err(syn::Error::new( s.struct_token.span(), "expected enum, found struct", )) } Data::Union(u) => { return Err(syn::Error::new( u.union_token.span(), "expected enum, found union", )) } }; let (not_found_route, ats) = parse_variants_attributes(&data.variants)?; Ok(Self { ident, variants: data.variants, ats, not_found_route, }) } } fn parse_variants_attributes( variants: &Punctuated<Variant, syn::token::Comma>, ) -> syn::Result<(Option<Ident>, Vec<LitStr>)> { let mut not_founds = vec![]; let mut ats: Vec<LitStr> = vec![]; let mut not_found_attrs = vec![]; for variant in variants.iter() { if let Fields::Unnamed(ref field) = variant.fields { return Err(syn::Error::new( field.span(), "only named fields are supported", )); } let attrs = &variant.attrs; let at_attrs = attrs .iter() .filter(|attr| attr.path().is_ident(AT_ATTR_IDENT)) .collect::<Vec<_>>(); let attr = match at_attrs.len() { 1 => *at_attrs.first().unwrap(), 0 => { return Err(syn::Error::new( variant.span(), format!("{AT_ATTR_IDENT} attribute must be present on every variant"), )) } _ => { return Err(syn::Error::new_spanned( quote! { #(#at_attrs)* }, format!("only one {AT_ATTR_IDENT} attribute must be present"), )) } }; let lit = attr.parse_args::<LitStr>()?; let val = lit.value(); if val.find('#').is_some() { return Err(syn::Error::new_spanned( lit, "You cannot use `#` in your routes. Please consider `HashRouter` instead.", )); } if !val.starts_with('/') { return Err(syn::Error::new_spanned( lit, "relative paths are not supported at this moment.", )); } ats.push(lit); for attr in attrs.iter() { if attr.path().is_ident(NOT_FOUND_ATTR_IDENT) { not_found_attrs.push(attr); not_founds.push(variant.ident.clone()) } } } if not_founds.len() > 1 { return Err(syn::Error::new_spanned( quote! { #(#not_found_attrs)* }, format!("there can only be one {NOT_FOUND_ATTR_IDENT}"), )); } Ok((not_founds.into_iter().next(), ats)) } impl Routable { fn build_from_path(&self) -> TokenStream { let from_path_matches = self.variants.iter().enumerate().map(|(i, variant)| { let ident = &variant.ident; let right = match &variant.fields { Fields::Unit => quote! { Self::#ident }, Fields::Named(field) => { let fields = field.named.iter().map(|it| { // named fields have idents it.ident.as_ref().unwrap() }); quote! { Self::#ident { #(#fields: { let param = params.get(stringify!(#fields))?; let param = &*::yew_router::__macro::decode_for_url(param).ok()?; let param = param.parse().ok()?; param },)* } } } Fields::Unnamed(_) => unreachable!(), // already checked }; let left = self.ats.get(i).unwrap(); quote! { #left => ::std::option::Option::Some(#right) } }); quote! { fn from_path(path: &str, params: &::std::collections::HashMap<&str, &str>) -> ::std::option::Option<Self> { match path { #(#from_path_matches),*, _ => ::std::option::Option::None, } } } } fn build_to_path(&self) -> TokenStream { let to_path_matches = self.variants.iter().enumerate().map(|(i, variant)| { let ident = &variant.ident; let mut right = self.ats.get(i).unwrap().value(); match &variant.fields { Fields::Unit => quote! { Self::#ident => ::std::string::ToString::to_string(#right) }, Fields::Named(field) => { let fields = field .named .iter() .map(|it| it.ident.as_ref().unwrap()) .collect::<Vec<_>>(); for field in fields.iter() { // :param -> {param} // *param -> {param} // so we can pass it to `format!("...", param)` right = right.replace(&format!(":{field}"), &format!("{{{field}}}")); right = right.replace(&format!("*{field}"), &format!("{{{field}}}")); } quote! { Self::#ident { #(#fields),* } => ::std::format!(#right, #(#fields = ::yew_router::__macro::encode_for_url(&::std::format!("{}", #fields))),*) } } Fields::Unnamed(_) => unreachable!(), // already checked } }); quote! { fn to_path(&self) -> ::std::string::String { match self { #(#to_path_matches),*, } } } } } pub fn routable_derive_impl(input: Routable) -> TokenStream { let Routable { ats, not_found_route, ident, .. } = &input; let from_path = input.build_from_path(); let to_path = input.build_to_path(); let maybe_not_found_route = match not_found_route { Some(route) => quote! { ::std::option::Option::Some(Self::#route) }, None => quote! { ::std::option::Option::None }, }; let maybe_default = match not_found_route { Some(route) => { quote! { impl ::std::default::Default for #ident { fn default() -> Self { Self::#route } } } } None => TokenStream::new(), }; quote! { #[automatically_derived] impl ::yew_router::Routable for #ident { #from_path #to_path fn routes() -> ::std::vec::Vec<&'static str> { ::std::vec![#(#ats),*] } fn not_found_route() -> ::std::option::Option<Self> { #maybe_not_found_route } fn recognize(pathname: &str) -> ::std::option::Option<Self> { ::std::thread_local! { static ROUTER: ::yew_router::__macro::Router = ::yew_router::__macro::build_router::<#ident>(); } ROUTER.with(|router| ::yew_router::__macro::recognize_with_router(router, pathname)) } } #maybe_default } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router-macro/tests/routable_derive_test.rs
packages/yew-router-macro/tests/routable_derive_test.rs
#[allow(dead_code)] #[rustversion::attr(stable(1.84.0), test)] fn tests() { let t = trybuild::TestCases::new(); t.pass("tests/routable_derive/*-pass.rs"); t.compile_fail("tests/routable_derive/*-fail.rs"); } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router-macro/tests/routable_derive/unnamed-fields-fail.rs
packages/yew-router-macro/tests/routable_derive/unnamed-fields-fail.rs
#[derive(yew_router::Routable)] enum Routes { #[at("/one/:two")] One(u32), } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router-macro/tests/routable_derive/struct-fail.rs
packages/yew-router-macro/tests/routable_derive/struct-fail.rs
#[derive(yew_router::Routable)] struct Test {} fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router-macro/tests/routable_derive/route-with-hash-fail.rs
packages/yew-router-macro/tests/routable_derive/route-with-hash-fail.rs
#[derive(yew_router::Routable)] enum Routes { #[at("/#/one")] One, } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router-macro/tests/routable_derive/valid-pass.rs
packages/yew-router-macro/tests/routable_derive/valid-pass.rs
#![no_implicit_prelude] #[derive(Debug, PartialEq, Clone, ::yew_router::Routable)] enum Routes { #[at("/")] One, #[at("/two/:id")] Two { id: u32 }, #[at("/:a/:b/*rest")] Three { a: u32, b: u32, rest: ::std::string::String }, #[at("/404")] #[not_found] NotFound, } #[derive(Debug, PartialEq, Clone, ::yew_router::Routable)] enum MoreRoutes { #[at("/subpath/*rest")] Subpath { rest: ::std::string::String }, #[at("/*all")] CatchAll { all: ::std::string::String }, } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router-macro/tests/routable_derive/relative-path-fail.rs
packages/yew-router-macro/tests/routable_derive/relative-path-fail.rs
#[derive(yew_router::Routable)] enum Routes { #[at("one")] One, } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router-macro/tests/routable_derive/bad-ats-fail.rs
packages/yew-router-macro/tests/routable_derive/bad-ats-fail.rs
#[derive(yew_router::Routable)] enum Routes { One, } #[derive(yew_router::Routable)] enum RoutesTwo { #[at("/one")] #[at("/two")] One, } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-router-macro/tests/routable_derive/invalid-not-found-fail.rs
packages/yew-router-macro/tests/routable_derive/invalid-not-found-fail.rs
#[derive(Debug, PartialEq, yew_router::Routable)] enum RoutesOne { #[at("/")] #[not_found] Home, #[at("/404")] #[not_found] NotFound, } #[derive(Debug, PartialEq, yew_router::Routable)] enum RoutesTwo { #[at("/404")] #[not_found] #[not_found] NotFound, } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent-macro/src/lib.rs
packages/yew-agent-macro/src/lib.rs
use proc_macro::TokenStream; use syn::parse_macro_input; mod agent_fn; mod oneshot; mod reactor; use agent_fn::{AgentFn, AgentName}; use oneshot::{oneshot_impl, OneshotFn}; use reactor::{reactor_impl, ReactorFn}; #[proc_macro_attribute] pub fn reactor(attr: TokenStream, item: TokenStream) -> TokenStream { let item = parse_macro_input!(item as AgentFn<ReactorFn>); let attr = parse_macro_input!(attr as AgentName); reactor_impl(attr, item) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro_attribute] pub fn oneshot(attr: TokenStream, item: TokenStream) -> TokenStream { let item = parse_macro_input!(item as AgentFn<OneshotFn>); let attr = parse_macro_input!(attr as AgentName); oneshot_impl(attr, item) .unwrap_or_else(|err| err.to_compile_error()) .into() }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent-macro/src/agent_fn.rs
packages/yew-agent-macro/src/agent_fn.rs
use proc_macro2::{Span, TokenStream}; use quote::ToTokens; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::token::Comma; use syn::{Attribute, FnArg, Generics, Ident, Item, ItemFn, Signature, Type, Visibility}; pub trait AgentFnType { type RecvType; type OutputType; fn attr_name() -> &'static str; fn agent_type_name() -> &'static str; fn parse_recv_type(sig: &Signature) -> syn::Result<Self::RecvType>; fn parse_output_type(sig: &Signature) -> syn::Result<Self::OutputType>; fn extract_fn_arg_type(arg: &FnArg) -> syn::Result<Type> { let ty = match arg { FnArg::Typed(arg) => arg.ty.clone(), FnArg::Receiver(_) => { return Err(syn::Error::new_spanned( arg, format!("{} agents can't accept a receiver", Self::agent_type_name()), )); } }; Ok(*ty) } fn assert_no_left_argument<I, T>(rest_inputs: I, expected_len: usize) -> syn::Result<()> where I: ExactSizeIterator + IntoIterator<Item = T>, T: ToTokens, { // Checking after param parsing may make it a little inefficient // but that's a requirement for better error messages in case of receivers // `>0` because first one is already consumed. if rest_inputs.len() > 0 { let params: TokenStream = rest_inputs .into_iter() .map(|it| it.to_token_stream()) .collect(); return Err(syn::Error::new_spanned( params, format!( "{} agent can accept at most {} argument{}", Self::agent_type_name(), expected_len, if expected_len > 1 { "s" } else { "" } ), )); } Ok(()) } } #[derive(Clone)] pub struct AgentFn<F> where F: AgentFnType + 'static, { pub recv_type: F::RecvType, pub output_type: F::OutputType, pub generics: Generics, pub vis: Visibility, pub attrs: Vec<Attribute>, pub name: Ident, pub agent_name: Option<Ident>, pub is_async: bool, pub func: ItemFn, } impl<F> Parse for AgentFn<F> where F: AgentFnType + 'static, { fn parse(input: ParseStream) -> syn::Result<Self> { let parsed: Item = input.parse()?; let func = match parsed { Item::Fn(m) => m, item => { return Err(syn::Error::new_spanned( item, format!( "`{}` attribute can only be applied to functions", F::attr_name() ), )) } }; let ItemFn { attrs, vis, sig, .. } = func.clone(); if sig.generics.lifetimes().next().is_some() { return Err(syn::Error::new_spanned( sig.generics, format!( "{} agents can't have generic lifetime parameters", F::agent_type_name() ), )); } if sig.constness.is_some() { return Err(syn::Error::new_spanned( sig.constness, format!("const functions can't be {} agents", F::agent_type_name()), )); } if sig.abi.is_some() { return Err(syn::Error::new_spanned( sig.abi, format!("extern functions can't be {} agents", F::agent_type_name()), )); } let recv_type = F::parse_recv_type(&sig)?; let output_type = F::parse_output_type(&sig)?; let is_async = sig.asyncness.is_some(); Ok(Self { recv_type, output_type, generics: sig.generics, is_async, vis, attrs, name: sig.ident, agent_name: None, func, }) } } impl<F> AgentFn<F> where F: AgentFnType + 'static, { /// Filters attributes that should be copied to agent definition. pub fn filter_attrs_for_agent_struct(&self) -> Vec<Attribute> { self.attrs .iter() .filter_map(|m| { m.path() .get_ident() .and_then(|ident| match ident.to_string().as_str() { "doc" | "allow" => Some(m.clone()), _ => None, }) }) .collect() } /// Filters attributes that should be copied to the agent impl block. pub fn filter_attrs_for_agent_impl(&self) -> Vec<Attribute> { self.attrs .iter() .filter_map(|m| { m.path() .get_ident() .and_then(|ident| match ident.to_string().as_str() { "allow" => Some(m.clone()), _ => None, }) }) .collect() } pub fn phantom_generics(&self) -> Punctuated<Ident, Comma> { self.generics .type_params() .map(|ty_param| ty_param.ident.clone()) // create a new Punctuated sequence without any type bounds .collect::<Punctuated<_, Comma>>() } pub fn merge_agent_name(&mut self, name: AgentName) -> syn::Result<()> { if let Some(ref m) = name.agent_name { if m == &self.name { return Err(syn::Error::new_spanned( m, format!( "the {} must not have the same name as the function", F::agent_type_name() ), )); } } self.agent_name = name.agent_name; Ok(()) } pub fn inner_fn_ident(&self) -> Ident { if self.agent_name.is_some() { self.name.clone() } else { Ident::new("inner", Span::mixed_site()) } } pub fn agent_name(&self) -> Ident { self.agent_name.clone().unwrap_or_else(|| self.name.clone()) } pub fn print_inner_fn(&self) -> ItemFn { let mut func = self.func.clone(); func.sig.ident = self.inner_fn_ident(); func.vis = Visibility::Inherited; func } } pub struct AgentName { agent_name: Option<Ident>, } impl Parse for AgentName { fn parse(input: ParseStream) -> syn::Result<Self> { if input.is_empty() { return Ok(Self { agent_name: None }); } let agent_name = input.parse()?; Ok(Self { agent_name: Some(agent_name), }) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent-macro/src/oneshot.rs
packages/yew-agent-macro/src/oneshot.rs
use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{parse_quote, Ident, ReturnType, Signature, Type}; use crate::agent_fn::{AgentFn, AgentFnType, AgentName}; pub struct OneshotFn {} impl AgentFnType for OneshotFn { type OutputType = Type; type RecvType = Type; fn attr_name() -> &'static str { "oneshot" } fn agent_type_name() -> &'static str { "oneshot" } fn parse_recv_type(sig: &Signature) -> syn::Result<Self::RecvType> { let mut inputs = sig.inputs.iter(); let arg = inputs .next() .ok_or_else(|| syn::Error::new_spanned(&sig.ident, "expected 1 argument"))?; let ty = Self::extract_fn_arg_type(arg)?; Self::assert_no_left_argument(inputs, 1)?; Ok(ty) } fn parse_output_type(sig: &Signature) -> syn::Result<Self::OutputType> { let ty = match &sig.output { ReturnType::Default => { parse_quote! { () } } ReturnType::Type(_, ty) => *ty.clone(), }; Ok(ty) } } pub fn oneshot_impl(name: AgentName, mut agent_fn: AgentFn<OneshotFn>) -> syn::Result<TokenStream> { agent_fn.merge_agent_name(name)?; let struct_attrs = agent_fn.filter_attrs_for_agent_struct(); let oneshot_impl_attrs = agent_fn.filter_attrs_for_agent_impl(); let phantom_generics = agent_fn.phantom_generics(); let oneshot_name = agent_fn.agent_name(); let fn_name = agent_fn.inner_fn_ident(); let inner_fn = agent_fn.print_inner_fn(); let AgentFn { recv_type: input_type, generics, output_type, vis, is_async, .. } = agent_fn; let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let fn_generics = ty_generics.as_turbofish(); let in_ident = Ident::new("_input", Span::mixed_site()); let fn_call = if is_async { quote! { #fn_name #fn_generics (#in_ident).await } } else { quote! { #fn_name #fn_generics (#in_ident) } }; let crate_name = quote! { yew_agent }; let quoted = quote! { #(#struct_attrs)* #[allow(unused_parens)] #vis struct #oneshot_name #generics #where_clause { inner: ::std::pin::Pin<::std::boxed::Box<dyn ::std::future::Future<Output = #output_type>>>, _marker: ::std::marker::PhantomData<(#phantom_generics)>, } // we cannot disable any lints here because it will be applied to the function body // as well. #(#oneshot_impl_attrs)* impl #impl_generics ::#crate_name::oneshot::Oneshot for #oneshot_name #ty_generics #where_clause { type Input = #input_type; fn create(#in_ident: Self::Input) -> Self { #inner_fn Self { inner: ::std::boxed::Box::pin( async move { #fn_call } ), _marker: ::std::marker::PhantomData, } } } impl #impl_generics ::std::future::Future for #oneshot_name #ty_generics #where_clause { type Output = #output_type; fn poll(mut self: ::std::pin::Pin<&mut Self>, cx: &mut ::std::task::Context<'_>) -> ::std::task::Poll<Self::Output> { ::std::future::Future::poll(::std::pin::Pin::new(&mut self.inner), cx) } } impl #impl_generics ::#crate_name::Registrable for #oneshot_name #ty_generics #where_clause { type Registrar = ::#crate_name::oneshot::OneshotRegistrar<Self>; fn registrar() -> Self::Registrar { ::#crate_name::oneshot::OneshotRegistrar::<Self>::new() } } impl #impl_generics ::#crate_name::Spawnable for #oneshot_name #ty_generics #where_clause { type Spawner = ::#crate_name::oneshot::OneshotSpawner<Self>; fn spawner() -> Self::Spawner { ::#crate_name::oneshot::OneshotSpawner::<Self>::new() } } }; Ok(quoted) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-agent-macro/src/reactor.rs
packages/yew-agent-macro/src/reactor.rs
use proc_macro2::{Span, TokenStream}; use quote::quote; use syn::{Ident, ReturnType, Signature, Type}; use crate::agent_fn::{AgentFn, AgentFnType, AgentName}; pub struct ReactorFn {} impl AgentFnType for ReactorFn { type OutputType = (); type RecvType = Type; fn attr_name() -> &'static str { "reactor" } fn agent_type_name() -> &'static str { "reactor" } fn parse_recv_type(sig: &Signature) -> syn::Result<Self::RecvType> { let mut inputs = sig.inputs.iter(); let arg = inputs .next() .ok_or_else(|| syn::Error::new_spanned(&sig.ident, "expected 1 argument"))?; let ty = Self::extract_fn_arg_type(arg)?; Self::assert_no_left_argument(inputs, 1)?; Ok(ty) } fn parse_output_type(sig: &Signature) -> syn::Result<Self::OutputType> { match &sig.output { ReturnType::Default => {} ReturnType::Type(_, ty) => { return Err(syn::Error::new_spanned( ty, "reactor agents cannot return any value", )) } } Ok(()) } } pub fn reactor_impl(name: AgentName, mut agent_fn: AgentFn<ReactorFn>) -> syn::Result<TokenStream> { agent_fn.merge_agent_name(name)?; if !agent_fn.is_async { return Err(syn::Error::new_spanned( &agent_fn.name, "reactor agents must be asynchronous", )); } let struct_attrs = agent_fn.filter_attrs_for_agent_struct(); let reactor_impl_attrs = agent_fn.filter_attrs_for_agent_impl(); let phantom_generics = agent_fn.phantom_generics(); let reactor_name = agent_fn.agent_name(); let fn_name = agent_fn.inner_fn_ident(); let inner_fn = agent_fn.print_inner_fn(); let AgentFn { recv_type, generics, vis, .. } = agent_fn; let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let fn_generics = ty_generics.as_turbofish(); let scope_ident = Ident::new("_scope", Span::mixed_site()); let fn_call = quote! { #fn_name #fn_generics (#scope_ident).await }; let crate_name = quote! { yew_agent }; let quoted = quote! { #(#struct_attrs)* #[allow(unused_parens)] #vis struct #reactor_name #generics #where_clause { inner: ::std::pin::Pin<::std::boxed::Box<dyn ::std::future::Future<Output = ()>>>, _marker: ::std::marker::PhantomData<(#phantom_generics)>, } // we cannot disable any lints here because it will be applied to the function body // as well. #(#reactor_impl_attrs)* impl #impl_generics ::#crate_name::reactor::Reactor for #reactor_name #ty_generics #where_clause { type Scope = #recv_type; fn create(#scope_ident: Self::Scope) -> Self { #inner_fn Self { inner: ::std::boxed::Box::pin( async move { #fn_call } ), _marker: ::std::marker::PhantomData, } } } impl #impl_generics ::std::future::Future for #reactor_name #ty_generics #where_clause { type Output = (); fn poll(mut self: ::std::pin::Pin<&mut Self>, cx: &mut ::std::task::Context<'_>) -> ::std::task::Poll<Self::Output> { ::std::future::Future::poll(::std::pin::Pin::new(&mut self.inner), cx) } } impl #impl_generics ::#crate_name::Registrable for #reactor_name #ty_generics #where_clause { type Registrar = ::#crate_name::reactor::ReactorRegistrar<Self>; fn registrar() -> Self::Registrar { ::#crate_name::reactor::ReactorRegistrar::<Self>::new() } } impl #impl_generics ::#crate_name::Spawnable for #reactor_name #ty_generics #where_clause { type Spawner = ::#crate_name::reactor::ReactorSpawner<Self>; fn spawner() -> Self::Spawner { ::#crate_name::reactor::ReactorSpawner::<Self>::new() } } }; Ok(quoted) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/use_transitive_state.rs
packages/yew-macro/src/use_transitive_state.rs
use proc_macro2::TokenStream; use quote::quote; use syn::parse::{Parse, ParseStream}; use syn::{Expr, ExprClosure, ReturnType, Token, Type}; #[derive(Debug)] pub struct TransitiveState { closure: ExprClosure, return_type: Type, deps: Expr, } impl Parse for TransitiveState { fn parse(input: ParseStream) -> syn::Result<Self> { // Reads the deps. let deps = input.parse()?; input.parse::<Token![,]>().map_err(|e| { syn::Error::new( e.span(), "this hook takes 2 arguments but 1 argument was supplied", ) })?; // Reads a closure. let expr: Expr = input.parse()?; let closure = match expr { Expr::Closure(m) => m, other => return Err(syn::Error::new_spanned(other, "expected closure")), }; let return_type = match &closure.output { ReturnType::Default => { return Err(syn::Error::new_spanned( &closure, "You must specify a return type for this closure. This is used when the \ closure is omitted from the client side rendering bundle.", )) } ReturnType::Type(_rarrow, ty) => *ty.to_owned(), }; if !input.is_empty() { let maybe_trailing_comma = input.lookahead1(); if !maybe_trailing_comma.peek(Token![,]) { return Err(maybe_trailing_comma.error()); } } Ok(Self { closure, return_type, deps, }) } } impl TransitiveState { pub fn to_token_stream_with_closure(&self) -> TokenStream { let deps = &self.deps; let rt = &self.return_type; let closure = &self.closure; quote! { ::yew::functional::use_transitive_state::<#rt, _, _>(#deps, #closure) } } // Expose a hook for the client side. // // The closure is stripped from the client side. pub fn to_token_stream_without_closure(&self) -> TokenStream { let deps = &self.deps; let rt = &self.return_type; quote! { ::yew::functional::use_transitive_state::<#rt, _>(#deps) } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/lib.rs
packages/yew-macro/src/lib.rs
//! This crate provides Yew's procedural macro `html!` which allows using JSX-like syntax //! for generating html and the `Properties` derive macro for deriving the `Properties` trait //! for components. //! //! ``` //! use yew::prelude::*; //! //! struct Component; //! //! #[derive(Properties, PartialEq)] //! struct Props { //! prop: String, //! } //! //! # enum Msg { Submit } //! # //! # impl yew::Component for Component { //! # type Message = Msg; //! # type Properties = Props; //! # fn create(_ctx: &Context<Self>) -> Self { //! # unimplemented!() //! # } //! # //! # //! # fn view(&self, ctx: &Context<Self>) -> Html { //! # //! // ... //! //! html! { //! <div> //! <button onclick={ctx.link().callback(|_| Msg::Submit)}> //! { "Submit" } //! </button> //! <> //! <Component prop="first" /> //! <Component prop="second" /> //! </> //! </div> //! } //! # //! # } //! # } //! # //! # fn main() {} //! ``` //! //! Please refer to [https://github.com/yewstack/yew](https://github.com/yewstack/yew) for how to set this up. mod classes; mod derive_props; mod function_component; mod hook; mod html_tree; mod props; mod stringify; mod use_prepared_state; mod use_transitive_state; use derive_props::DerivePropsInput; use function_component::{function_component_impl, FunctionComponent, FunctionComponentName}; use hook::{hook_impl, HookFn}; use html_tree::{HtmlRoot, HtmlRootVNode}; use proc_macro::TokenStream; use quote::ToTokens; use syn::buffer::Cursor; use syn::parse_macro_input; use use_prepared_state::PreparedState; use use_transitive_state::TransitiveState; trait Peek<'a, T> { fn peek(cursor: Cursor<'a>) -> Option<(T, Cursor<'a>)>; } trait PeekValue<T> { fn peek(cursor: Cursor) -> Option<T>; } fn non_capitalized_ascii(string: &str) -> bool { if !string.is_ascii() { false } else if let Some(c) = string.bytes().next() { c.is_ascii_lowercase() } else { false } } /// Combine multiple `syn` errors into a single one. /// Returns `Result::Ok` if the given iterator is empty fn join_errors(mut it: impl Iterator<Item = syn::Error>) -> syn::Result<()> { it.next().map_or(Ok(()), |mut err| { for other in it { err.combine(other); } Err(err) }) } fn is_ide_completion() -> bool { match std::env::var_os("RUST_IDE_PROC_MACRO_COMPLETION_DUMMY_IDENTIFIER") { None => false, Some(dummy_identifier) => !dummy_identifier.is_empty(), } } #[proc_macro_derive(Properties, attributes(prop_or, prop_or_else, prop_or_default))] pub fn derive_props(input: TokenStream) -> TokenStream { let mut input = parse_macro_input!(input as DerivePropsInput); input.normalise(); TokenStream::from(input.into_token_stream()) } #[proc_macro_error::proc_macro_error] #[proc_macro] pub fn html_nested(input: TokenStream) -> TokenStream { let root = parse_macro_input!(input as HtmlRoot); TokenStream::from(root.into_token_stream()) } #[proc_macro_error::proc_macro_error] #[proc_macro] pub fn html(input: TokenStream) -> TokenStream { let root = parse_macro_input!(input as HtmlRootVNode); TokenStream::from(root.into_token_stream()) } #[proc_macro] pub fn props(input: TokenStream) -> TokenStream { let props = parse_macro_input!(input as props::PropsMacroInput); TokenStream::from(props.into_token_stream()) } #[proc_macro] pub fn classes(input: TokenStream) -> TokenStream { let classes = parse_macro_input!(input as classes::Classes); TokenStream::from(classes.into_token_stream()) } #[proc_macro_error::proc_macro_error] #[proc_macro_attribute] pub fn function_component(attr: TokenStream, item: TokenStream) -> TokenStream { let item = parse_macro_input!(item as FunctionComponent); let attr = parse_macro_input!(attr as FunctionComponentName); function_component_impl(attr, item) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro_error::proc_macro_error] #[proc_macro_attribute] pub fn hook(attr: TokenStream, item: TokenStream) -> TokenStream { let item = parse_macro_input!(item as HookFn); if let Some(m) = proc_macro2::TokenStream::from(attr).into_iter().next() { return syn::Error::new_spanned(m, "hook attribute does not accept any arguments") .into_compile_error() .into(); } hook_impl(item) .unwrap_or_else(|err| err.to_compile_error()) .into() } #[proc_macro] pub fn use_prepared_state_with_closure(input: TokenStream) -> TokenStream { let prepared_state = parse_macro_input!(input as PreparedState); prepared_state.to_token_stream_with_closure().into() } #[proc_macro] pub fn use_prepared_state_without_closure(input: TokenStream) -> TokenStream { let prepared_state = parse_macro_input!(input as PreparedState); prepared_state.to_token_stream_without_closure().into() } #[proc_macro] pub fn use_transitive_state_with_closure(input: TokenStream) -> TokenStream { let transitive_state = parse_macro_input!(input as TransitiveState); transitive_state.to_token_stream_with_closure().into() } #[proc_macro] pub fn use_transitive_state_without_closure(input: TokenStream) -> TokenStream { let transitive_state = parse_macro_input!(input as TransitiveState); transitive_state.to_token_stream_without_closure().into() }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/use_prepared_state.rs
packages/yew-macro/src/use_prepared_state.rs
use proc_macro2::TokenStream; use quote::quote; use syn::parse::{Parse, ParseStream}; use syn::{Expr, ExprClosure, ReturnType, Token, Type}; #[derive(Debug)] pub struct PreparedState { closure: ExprClosure, return_type: Type, deps: Expr, } impl Parse for PreparedState { fn parse(input: ParseStream) -> syn::Result<Self> { // Reads the deps. let deps = input.parse()?; input.parse::<Token![,]>().map_err(|e| { syn::Error::new( e.span(), "this hook takes 2 arguments but 1 argument was supplied", ) })?; // Reads a closure. let expr: Expr = input.parse()?; let closure = match expr { Expr::Closure(m) => m, other => return Err(syn::Error::new_spanned(other, "expected closure")), }; let return_type = match &closure.output { ReturnType::Default => { return Err(syn::Error::new_spanned( &closure, "You must specify a return type for this closure. This is used when the \ closure is omitted from the client side rendering bundle.", )) } ReturnType::Type(_rarrow, ty) => *ty.to_owned(), }; if !input.is_empty() { let maybe_trailing_comma = input.lookahead1(); if !maybe_trailing_comma.peek(Token![,]) { return Err(maybe_trailing_comma.error()); } } Ok(Self { closure, return_type, deps, }) } } impl PreparedState { // Async closure was not stable, so we rewrite it to closure + async block #[rustversion::before(1.85)] pub fn rewrite_to_closure_with_async_block(&self) -> ExprClosure { use proc_macro2::Span; use syn::parse_quote; let async_token = match &self.closure.asyncness { Some(m) => m, None => return self.closure.clone(), }; // The async block always need to be move so input can be moved into it. let move_token = self .closure .capture .unwrap_or_else(|| Token![move](Span::call_site())); let body = &self.closure.body; let inner = parse_quote! { #async_token #move_token { #body } }; let mut closure = self.closure.clone(); closure.asyncness = None; // We omit the output type as it's an opaque future type. closure.output = ReturnType::Default; closure.body = inner; closure.attrs.push(parse_quote! { #[allow(unused_braces)] }); closure } #[rustversion::since(1.85)] pub fn rewrite_to_closure_with_async_block(&self) -> ExprClosure { self.closure.clone() } pub fn to_token_stream_with_closure(&self) -> TokenStream { let deps = &self.deps; let rt = &self.return_type; let closure = self.rewrite_to_closure_with_async_block(); match &self.closure.asyncness { Some(_) => quote! { ::yew::functional::use_prepared_state_with_suspension::<#rt, _, _, _>(#deps, #closure) }, None => quote! { ::yew::functional::use_prepared_state::<#rt, _, _>(#deps, #closure) }, } } // Expose a hook for the client side. // // The closure is stripped from the client side. pub fn to_token_stream_without_closure(&self) -> TokenStream { let deps = &self.deps; let rt = &self.return_type; quote! { ::yew::functional::use_prepared_state::<#rt, _>(#deps) } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/function_component.rs
packages/yew-macro/src/function_component.rs
use proc_macro2::{Span, TokenStream}; use quote::{quote, ToTokens}; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::token::{Comma, Fn}; use syn::{ parse_quote, parse_quote_spanned, visit_mut, Attribute, Block, FnArg, Generics, Ident, Item, ItemFn, LitStr, ReturnType, Type, Visibility, }; use crate::hook::BodyRewriter; #[derive(Clone)] pub struct FunctionComponent { block: Box<Block>, props_type: Box<Type>, arg: FnArg, generics: Generics, vis: Visibility, attrs: Vec<Attribute>, name: Ident, return_type: Box<Type>, fn_token: Fn, component_name: Option<Ident>, } impl Parse for FunctionComponent { fn parse(input: ParseStream) -> syn::Result<Self> { let parsed: Item = input.parse()?; let func = match parsed { Item::Fn(m) => m, item => { return Err(syn::Error::new_spanned( item, "`component` attribute can only be applied to functions", )) } }; let ItemFn { attrs, vis, sig, block, } = func; if sig.generics.lifetimes().next().is_some() { return Err(syn::Error::new_spanned( sig.generics, "function components can't have generic lifetime parameters", )); } if sig.asyncness.is_some() { return Err(syn::Error::new_spanned( sig.asyncness, "function components can't be async", )); } if sig.constness.is_some() { return Err(syn::Error::new_spanned( sig.constness, "const functions can't be function components", )); } if sig.abi.is_some() { return Err(syn::Error::new_spanned( sig.abi, "extern functions can't be function components", )); } let return_type = match sig.output { ReturnType::Default => { return Err(syn::Error::new_spanned( sig, "function components must return `yew::Html` or `yew::HtmlResult`", )) } ReturnType::Type(_, ty) => ty, }; let mut inputs = sig.inputs.into_iter(); let arg = inputs .next() .unwrap_or_else(|| syn::parse_quote! { _: &() }); let ty = match &arg { FnArg::Typed(arg) => match &*arg.ty { Type::Reference(ty) => { if ty.lifetime.is_some() { return Err(syn::Error::new_spanned( &ty.lifetime, "reference must not have a lifetime", )); } if ty.mutability.is_some() { return Err(syn::Error::new_spanned( ty.mutability, "reference must not be mutable", )); } ty.elem.clone() } ty => { let msg = format!( "expected a reference to a `Properties` type (try: `&{}`)", ty.to_token_stream() ); return Err(syn::Error::new_spanned(ty, msg)); } }, FnArg::Receiver(_) => { return Err(syn::Error::new_spanned( arg, "function components can't accept a receiver", )); } }; // Checking after param parsing may make it a little inefficient // but that's a requirement for better error messages in case of receivers // `>0` because first one is already consumed. if inputs.len() > 0 { let params: TokenStream = inputs.map(|it| it.to_token_stream()).collect(); return Err(syn::Error::new_spanned( params, "function components can accept at most one parameter for the props", )); } Ok(Self { props_type: ty, block, arg, generics: sig.generics, vis, attrs, name: sig.ident, return_type, fn_token: sig.fn_token, component_name: None, }) } } impl FunctionComponent { /// Filters attributes that should be copied to component definition. fn filter_attrs_for_component_struct(&self) -> Vec<Attribute> { self.attrs .iter() .filter_map(|m| { m.path() .get_ident() .and_then(|ident| match ident.to_string().as_str() { "doc" | "allow" => Some(m.clone()), _ => None, }) }) .collect() } /// Filters attributes that should be copied to the component impl block. fn filter_attrs_for_component_impl(&self) -> Vec<Attribute> { self.attrs .iter() .filter_map(|m| { m.path() .get_ident() .and_then(|ident| match ident.to_string().as_str() { "allow" => Some(m.clone()), _ => None, }) }) .collect() } fn phantom_generics(&self) -> Punctuated<Ident, Comma> { self.generics .type_params() .map(|ty_param| ty_param.ident.clone()) // create a new Punctuated sequence without any type bounds .collect::<Punctuated<_, Comma>>() } fn merge_component_name(&mut self, name: FunctionComponentName) -> syn::Result<()> { if let Some(ref m) = name.component_name { if m == &self.name { return Err(syn::Error::new_spanned( m, "the component must not have the same name as the function", )); } } self.component_name = name.component_name; Ok(()) } fn inner_fn_ident(&self) -> Ident { if self.component_name.is_some() { self.name.clone() } else { Ident::new("inner", Span::mixed_site()) } } fn component_name(&self) -> Ident { self.component_name .clone() .unwrap_or_else(|| self.name.clone()) } // We need to cast 'static on all generics for base component. fn create_static_component_generics(&self) -> Generics { let mut generics = self.generics.clone(); let where_clause = generics.make_where_clause(); for ty_generic in self.generics.type_params() { let ident = &ty_generic.ident; let bound = parse_quote_spanned! { ident.span() => #ident: 'static }; where_clause.predicates.push(bound); } where_clause.predicates.push(parse_quote! { Self: 'static }); generics } /// Prints the impl fn. fn print_inner_fn(&self) -> TokenStream { let name = self.inner_fn_ident(); let FunctionComponent { ref fn_token, ref attrs, ref block, ref return_type, ref generics, ref arg, .. } = self; let mut block = *block.clone(); let (impl_generics, _ty_generics, where_clause) = generics.split_for_impl(); // We use _ctx here so if the component does not use any hooks, the usused_vars lint will // not be triggered. let ctx_ident = Ident::new("_ctx", Span::mixed_site()); let mut body_rewriter = BodyRewriter::new(ctx_ident.clone()); visit_mut::visit_block_mut(&mut body_rewriter, &mut block); quote! { #(#attrs)* #fn_token #name #impl_generics (#ctx_ident: &mut ::yew::functional::HookContext, #arg) -> #return_type #where_clause { #block } } } fn print_base_component_impl(&self) -> TokenStream { let component_name = self.component_name(); let props_type = &self.props_type; let static_comp_generics = self.create_static_component_generics(); let (impl_generics, ty_generics, where_clause) = static_comp_generics.split_for_impl(); // TODO: replace with blanket implementation when specialisation becomes stable. quote! { #[automatically_derived] impl #impl_generics ::yew::html::BaseComponent for #component_name #ty_generics #where_clause { type Message = (); type Properties = #props_type; #[inline] fn create(ctx: &::yew::html::Context<Self>) -> Self { Self { _marker: ::std::marker::PhantomData, function_component: ::yew::functional::FunctionComponent::<Self>::new(ctx), } } #[inline] fn update(&mut self, _ctx: &::yew::html::Context<Self>, _msg: Self::Message) -> ::std::primitive::bool { true } #[inline] fn changed(&mut self, _ctx: &::yew::html::Context<Self>, _old_props: &Self::Properties) -> ::std::primitive::bool { true } #[inline] fn view(&self, ctx: &::yew::html::Context<Self>) -> ::yew::html::HtmlResult { ::yew::functional::FunctionComponent::<Self>::render( &self.function_component, ::yew::html::Context::<Self>::props(ctx) ) } #[inline] fn rendered(&mut self, _ctx: &::yew::html::Context<Self>, _first_render: ::std::primitive::bool) { ::yew::functional::FunctionComponent::<Self>::rendered(&self.function_component) } #[inline] fn destroy(&mut self, _ctx: &::yew::html::Context<Self>) { ::yew::functional::FunctionComponent::<Self>::destroy(&self.function_component) } #[inline] fn prepare_state(&self) -> ::std::option::Option<::std::string::String> { ::yew::functional::FunctionComponent::<Self>::prepare_state(&self.function_component) } } } } fn print_debug_impl(&self) -> TokenStream { let component_name = self.component_name(); let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl(); let component_name_lit = LitStr::new(&format!("{component_name}<_>"), Span::mixed_site()); quote! { #[automatically_derived] impl #impl_generics ::std::fmt::Debug for #component_name #ty_generics #where_clause { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::std::write!(f, #component_name_lit) } } } } fn print_fn_provider_impl(&self) -> TokenStream { let func = self.print_inner_fn(); let component_impl_attrs = self.filter_attrs_for_component_impl(); let component_name = self.component_name(); let fn_name = self.inner_fn_ident(); let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl(); let props_type = &self.props_type; let fn_generics = ty_generics.as_turbofish(); let component_props = Ident::new("props", Span::mixed_site()); let ctx_ident = Ident::new("ctx", Span::mixed_site()); quote! { // we cannot disable any lints here because it will be applied to the function body // as well. #(#component_impl_attrs)* impl #impl_generics ::yew::functional::FunctionProvider for #component_name #ty_generics #where_clause { type Properties = #props_type; fn run(#ctx_ident: &mut ::yew::functional::HookContext, #component_props: &Self::Properties) -> ::yew::html::HtmlResult { #func ::yew::html::IntoHtmlResult::into_html_result(#fn_name #fn_generics (#ctx_ident, #component_props)) } } } } fn print_struct_def(&self) -> TokenStream { let component_attrs = self.filter_attrs_for_component_struct(); let component_name = self.component_name(); let generics = &self.generics; let (_impl_generics, _ty_generics, where_clause) = self.generics.split_for_impl(); let phantom_generics = self.phantom_generics(); let vis = &self.vis; quote! { #(#component_attrs)* #[allow(unused_parens)] #vis struct #component_name #generics #where_clause { _marker: ::std::marker::PhantomData<(#phantom_generics)>, function_component: ::yew::functional::FunctionComponent<Self>, } } } } pub struct FunctionComponentName { component_name: Option<Ident>, } impl Parse for FunctionComponentName { fn parse(input: ParseStream) -> syn::Result<Self> { if input.is_empty() { return Ok(Self { component_name: None, }); } let component_name = input.parse()?; Ok(Self { component_name: Some(component_name), }) } } pub fn function_component_impl( name: FunctionComponentName, mut component: FunctionComponent, ) -> syn::Result<TokenStream> { component.merge_component_name(name)?; let base_comp_impl = component.print_base_component_impl(); let debug_impl = component.print_debug_impl(); let provider_fn_impl = component.print_fn_provider_impl(); let struct_def = component.print_struct_def(); let quoted = quote! { #struct_def #provider_fn_impl #debug_impl #base_comp_impl }; Ok(quoted) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/stringify.rs
packages/yew-macro/src/stringify.rs
use std::borrow::Cow; use std::mem::size_of; use proc_macro2::{Span, TokenStream}; use quote::{quote_spanned, ToTokens}; use syn::spanned::Spanned; use syn::{Expr, Lit, LitStr}; /// Stringify a value at runtime. fn stringify_at_runtime(src: impl ToTokens) -> TokenStream { quote_spanned! {src.span().resolved_at(Span::call_site())=> ::std::convert::Into::<::yew::virtual_dom::AttrValue>::into(#src) } } /// Create `AttrValue` construction calls. /// /// This is deliberately not implemented for strings to preserve spans. pub trait Stringify { /// Try to turn the value into a string literal. fn try_into_lit(&self) -> Option<LitStr>; /// Create `AttrValue` however possible. fn stringify(&self) -> TokenStream; /// Optimize literals to `&'static str`, otherwise keep the value as is. fn optimize_literals(&self) -> TokenStream where Self: ToTokens, { self.optimize_literals_tagged().to_token_stream() } /// Like `optimize_literals` but tags static or dynamic strings with [Value] fn optimize_literals_tagged(&self) -> Value where Self: ToTokens, { if let Some(lit) = self.try_into_lit() { Value::Static(lit.to_token_stream()) } else { Value::Dynamic(self.to_token_stream()) } } } impl<T: Stringify + ?Sized> Stringify for &T { fn try_into_lit(&self) -> Option<LitStr> { (*self).try_into_lit() } fn stringify(&self) -> TokenStream { (*self).stringify() } } /// A stringified value that can be either static (known at compile time) or dynamic (known only at /// runtime) pub enum Value { Static(TokenStream), Dynamic(TokenStream), } impl ToTokens for Value { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.extend(match self { Value::Static(tt) | Value::Dynamic(tt) => tt.clone(), }); } } impl Stringify for LitStr { fn try_into_lit(&self) -> Option<LitStr> { Some(self.clone()) } fn stringify(&self) -> TokenStream { quote_spanned! {self.span()=> ::yew::virtual_dom::AttrValue::Static(#self) } } } impl Stringify for Lit { fn try_into_lit(&self) -> Option<LitStr> { let mut buf = [0; size_of::<char>()]; let s: Cow<'_, str> = match self { Lit::Str(v) => return v.try_into_lit(), Lit::Char(v) => (&*v.value().encode_utf8(&mut buf)).into(), Lit::Int(v) => v.base10_digits().into(), Lit::Float(v) => v.base10_digits().into(), Lit::Bool(v) => if v.value() { "true" } else { "false" }.into(), Lit::Byte(v) => v.value().to_string().into(), Lit::Verbatim(_) | Lit::ByteStr(_) => return None, _ => unreachable!("unknown Lit {:?}", self), }; Some(LitStr::new(&s, self.span())) } fn stringify(&self) -> TokenStream { self.try_into_lit() .as_ref() .map_or_else(|| stringify_at_runtime(self), Stringify::stringify) } } impl Stringify for Expr { fn try_into_lit(&self) -> Option<LitStr> { if let Expr::Lit(v) = self { v.lit.try_into_lit() } else { None } } fn stringify(&self) -> TokenStream { self.try_into_lit() .as_ref() .map_or_else(|| stringify_at_runtime(self), Stringify::stringify) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/hook/lifetime.rs
packages/yew-macro/src/hook/lifetime.rs
use std::sync::{Arc, Mutex}; use proc_macro2::Span; use syn::visit_mut::{self, VisitMut}; use syn::{ GenericArgument, Lifetime, ParenthesizedGenericArguments, Receiver, TypeBareFn, TypeImplTrait, TypeParamBound, TypeReference, TypeTraitObject, }; // borrowed from the awesome async-trait crate. pub struct CollectLifetimes { pub elided: Vec<Lifetime>, pub name: &'static str, pub default_span: Span, pub type_trait_obj_lock: Arc<Mutex<()>>, pub impl_trait_lock: Arc<Mutex<()>>, pub impl_fn_lock: Arc<Mutex<()>>, } impl CollectLifetimes { pub fn new(name: &'static str, default_span: Span) -> Self { CollectLifetimes { elided: Vec::new(), name, default_span, impl_trait_lock: Arc::default(), type_trait_obj_lock: Arc::default(), impl_fn_lock: Arc::default(), } } fn is_impl_trait(&self) -> bool { self.impl_trait_lock.try_lock().is_err() } fn is_type_trait_obj(&self) -> bool { self.type_trait_obj_lock.try_lock().is_err() } fn is_impl_fn(&self) -> bool { self.impl_fn_lock.try_lock().is_err() } fn visit_opt_lifetime(&mut self, lifetime: &mut Option<Lifetime>) { match lifetime { None => *lifetime = Some(self.next_lifetime(None)), Some(lifetime) => self.visit_lifetime(lifetime), } } fn visit_lifetime(&mut self, lifetime: &mut Lifetime) { if lifetime.ident == "_" { *lifetime = self.next_lifetime(lifetime.span()); } } fn next_lifetime<S: Into<Option<Span>>>(&mut self, span: S) -> Lifetime { let name = format!("{}{}", self.name, self.elided.len()); let span = span.into().unwrap_or(self.default_span); let life = Lifetime::new(&name, span); self.elided.push(life.clone()); life } } impl VisitMut for CollectLifetimes { fn visit_receiver_mut(&mut self, arg: &mut Receiver) { if let Some((_, lifetime)) = &mut arg.reference { self.visit_opt_lifetime(lifetime); } } fn visit_type_reference_mut(&mut self, ty: &mut TypeReference) { // We don't rewrite references in the impl FnOnce(&arg) or fn(&arg) if self.is_impl_fn() { return; } self.visit_opt_lifetime(&mut ty.lifetime); visit_mut::visit_type_reference_mut(self, ty); } fn visit_generic_argument_mut(&mut self, gen: &mut GenericArgument) { // We don't rewrite types in the impl FnOnce(&arg) -> Type<'_> if self.is_impl_fn() { return; } if let GenericArgument::Lifetime(lifetime) = gen { self.visit_lifetime(lifetime); } visit_mut::visit_generic_argument_mut(self, gen); } fn visit_type_impl_trait_mut(&mut self, impl_trait: &mut TypeImplTrait) { let impl_trait_lock = self.impl_trait_lock.clone(); let _locked = impl_trait_lock.try_lock(); impl_trait .bounds .insert(0, TypeParamBound::Lifetime(self.next_lifetime(None))); visit_mut::visit_type_impl_trait_mut(self, impl_trait); } fn visit_type_trait_object_mut(&mut self, type_trait_obj: &mut TypeTraitObject) { let type_trait_obj_lock = self.type_trait_obj_lock.clone(); let _locked = type_trait_obj_lock.try_lock(); visit_mut::visit_type_trait_object_mut(self, type_trait_obj); } fn visit_parenthesized_generic_arguments_mut( &mut self, generic_args: &mut ParenthesizedGenericArguments, ) { let impl_fn_lock = self.impl_fn_lock.clone(); let _maybe_locked = (self.is_impl_trait() || self.is_type_trait_obj()).then(|| impl_fn_lock.try_lock()); visit_mut::visit_parenthesized_generic_arguments_mut(self, generic_args); } fn visit_type_bare_fn_mut(&mut self, i: &mut TypeBareFn) { let impl_fn_lock = self.impl_fn_lock.clone(); let _locked = impl_fn_lock.try_lock(); visit_mut::visit_type_bare_fn_mut(self, i); } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/hook/signature.rs
packages/yew-macro/src/hook/signature.rs
use std::iter::once; use std::mem::take; use proc_macro2::{Span, TokenStream}; use proc_macro_error::emit_error; use quote::{quote, ToTokens}; use syn::punctuated::{Pair, Punctuated}; use syn::spanned::Spanned; use syn::visit_mut::VisitMut; use syn::{ parse_quote, parse_quote_spanned, visit_mut, FnArg, GenericParam, Ident, Lifetime, LifetimeParam, Pat, Receiver, ReturnType, Signature, Type, TypeImplTrait, TypeParam, TypeParamBound, TypeReference, WherePredicate, }; use super::lifetime; fn type_is_generic(ty: &Type, param: &TypeParam) -> bool { match ty { Type::Path(path) => path.path.is_ident(&param.ident), _ => false, } } #[derive(Default)] pub struct CollectArgs { needs_boxing: bool, } impl CollectArgs { pub fn new() -> Self { Self::default() } } impl VisitMut for CollectArgs { fn visit_type_impl_trait_mut(&mut self, impl_trait: &mut TypeImplTrait) { self.needs_boxing = true; visit_mut::visit_type_impl_trait_mut(self, impl_trait); } fn visit_receiver_mut(&mut self, recv: &mut Receiver) { emit_error!(recv, "methods cannot be hooks"); visit_mut::visit_receiver_mut(self, recv); } } pub struct HookSignature { pub hook_lifetime: Lifetime, pub sig: Signature, pub output_type: Type, pub needs_boxing: bool, } impl HookSignature { fn rewrite_return_type(hook_lifetime: &Lifetime, rt_type: &ReturnType) -> (ReturnType, Type) { let bound = quote! { #hook_lifetime + }; match rt_type { ReturnType::Default => ( parse_quote! { -> impl #bound ::yew::functional::Hook<Output = ()> }, parse_quote! { () }, ), ReturnType::Type(arrow, ref return_type) => { if let Type::Reference(ref m) = &**return_type { if m.lifetime.is_none() { let mut return_type_ref = m.clone(); return_type_ref.lifetime = parse_quote!('hook); let return_type_ref = Type::Reference(return_type_ref); return ( parse_quote_spanned! { return_type.span() => #arrow impl #bound ::yew::functional::Hook<Output = #return_type_ref> }, return_type_ref, ); } } ( parse_quote_spanned! { return_type.span() => #arrow impl #bound ::yew::functional::Hook<Output = #return_type> }, *return_type.clone(), ) } } } /// Rewrites a Hook Signature and extracts information. pub fn rewrite(sig: &Signature) -> Self { let mut sig = sig.clone(); let mut arg_info = CollectArgs::new(); arg_info.visit_signature_mut(&mut sig); let mut lifetimes = lifetime::CollectLifetimes::new("'arg", sig.ident.span()); for arg in sig.inputs.iter_mut() { match arg { FnArg::Receiver(arg) => lifetimes.visit_receiver_mut(arg), FnArg::Typed(arg) => lifetimes.visit_type_mut(&mut arg.ty), } } let Signature { ref mut generics, output: ref return_type, .. } = sig; let hook_lifetime = Lifetime::new("'hook", Span::mixed_site()); let mut params: Punctuated<_, _> = once(hook_lifetime.clone()) .chain(lifetimes.elided) .map(|lifetime| { GenericParam::Lifetime(LifetimeParam { attrs: vec![], lifetime, colon_token: None, bounds: Default::default(), }) }) .map(|param| Pair::new(param, Some(Default::default()))) .chain(take(&mut generics.params).into_pairs()) .collect(); for type_param in params.iter_mut().skip(1) { match type_param { GenericParam::Lifetime(param) => { if let Some(predicate) = generics .where_clause .iter_mut() .flat_map(|c| &mut c.predicates) .find_map(|predicate| match predicate { WherePredicate::Lifetime(p) if p.lifetime == param.lifetime => Some(p), _ => None, }) { predicate.bounds.push(hook_lifetime.clone()); } else { param.colon_token = Some(param.colon_token.unwrap_or_default()); param.bounds.push(hook_lifetime.clone()); } } GenericParam::Type(param) => { if let Some(predicate) = generics .where_clause .iter_mut() .flat_map(|c| &mut c.predicates) .find_map(|predicate| match predicate { WherePredicate::Type(p) if type_is_generic(&p.bounded_ty, param) => { Some(p) } _ => None, }) { predicate .bounds .push(TypeParamBound::Lifetime(hook_lifetime.clone())); } else { param.colon_token = Some(param.colon_token.unwrap_or_default()); param .bounds .push(TypeParamBound::Lifetime(hook_lifetime.clone())); } } GenericParam::Const(_) => {} } } generics.params = params; let (output, output_type) = Self::rewrite_return_type(&hook_lifetime, return_type); sig.output = output; Self { hook_lifetime, sig, output_type, needs_boxing: arg_info.needs_boxing, } } pub fn phantom_types(&self) -> Vec<Ident> { self.sig .generics .type_params() .map(|ty_param| ty_param.ident.clone()) .collect() } pub fn phantom_lifetimes(&self) -> Vec<TypeReference> { self.sig .generics .lifetimes() .map(|life| TypeReference { and_token: Default::default(), lifetime: Some(life.lifetime.clone()), mutability: None, elem: Box::new(Type::Tuple(syn::TypeTuple { paren_token: Default::default(), elems: Default::default(), })), }) .collect() } pub fn input_args(&self) -> Vec<Ident> { self.sig .inputs .iter() .filter_map(|m| { if let FnArg::Typed(m) = m { if let Pat::Ident(ref m) = *m.pat { return Some(m.ident.clone()); } } None }) .collect() } pub fn input_types(&self) -> Vec<Type> { self.sig .inputs .iter() .filter_map(|m| { if let FnArg::Typed(m) = m { return Some(*m.ty.clone()); } None }) .collect() } pub fn call_generics(&self) -> TokenStream { let mut generics = self.sig.generics.clone(); // We need to filter out lifetimes. generics.params = generics .params .into_iter() .filter(|m| !matches!(m, GenericParam::Lifetime(_))) .collect(); let (_impl_generics, ty_generics, _where_clause) = generics.split_for_impl(); ty_generics.as_turbofish().to_token_stream() } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/hook/mod.rs
packages/yew-macro/src/hook/mod.rs
use proc_macro2::{Span, TokenStream}; use proc_macro_error::emit_error; use quote::quote; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; use syn::{ visit_mut, AttrStyle, Attribute, Block, Expr, ExprPath, File, Ident, Item, ItemFn, LitStr, Meta, MetaNameValue, ReturnType, Signature, Stmt, Token, Type, }; mod body; mod lifetime; mod signature; pub use body::BodyRewriter; use signature::HookSignature; #[derive(Clone)] pub struct HookFn { inner: ItemFn, } impl Parse for HookFn { fn parse(input: ParseStream) -> syn::Result<Self> { let func: ItemFn = input.parse()?; let sig = func.sig.clone(); if sig.asyncness.is_some() { emit_error!(sig.asyncness, "async functions can't be hooks"); } if sig.constness.is_some() { emit_error!(sig.constness, "const functions can't be hooks"); } if sig.abi.is_some() { emit_error!(sig.abi, "extern functions can't be hooks"); } if sig.unsafety.is_some() { emit_error!(sig.unsafety, "unsafe functions can't be hooks"); } if !sig.ident.to_string().starts_with("use_") { emit_error!(sig.ident, "hooks must have a name starting with `use_`"); } Ok(Self { inner: func }) } } impl HookFn { fn doc_attr(&self) -> Attribute { let span = self.inner.span(); let sig_formatted = prettyplease::unparse(&File { shebang: None, attrs: vec![], items: vec![Item::Fn(ItemFn { block: Box::new(Block { brace_token: Default::default(), stmts: vec![Stmt::Expr( Expr::Path(ExprPath { attrs: vec![], qself: None, path: Ident::new("__yew_macro_dummy_function_body__", span).into(), }), None, )], }), ..self.inner.clone() })], }); let literal = LitStr::new( &format!( r#" # Note When used in function components and hooks, this hook is equivalent to: ``` {} ``` "#, sig_formatted.replace( "__yew_macro_dummy_function_body__", "/* implementation omitted */" ) ), span, ); Attribute { pound_token: Default::default(), style: AttrStyle::Outer, bracket_token: Default::default(), meta: Meta::NameValue(MetaNameValue { path: Ident::new("doc", span).into(), eq_token: Token![=](span), value: Expr::Lit(syn::ExprLit { attrs: vec![], lit: literal.into(), }), }), } } } pub fn hook_impl(hook: HookFn) -> syn::Result<TokenStream> { let doc_attr = hook.doc_attr(); let HookFn { inner: original_fn } = hook; let ItemFn { ref vis, ref sig, ref block, ref attrs, } = original_fn; let mut block = *block.clone(); let hook_sig = HookSignature::rewrite(sig); let Signature { ref fn_token, ref ident, ref inputs, output: ref hook_return_type, ref generics, .. } = hook_sig.sig; let output_type = &hook_sig.output_type; let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let call_generics = hook_sig.call_generics(); // We use _ctx so that if a hook does not use other hooks, it will not trigger unused_vars. let ctx_ident = Ident::new("_ctx", Span::mixed_site()); let mut body_rewriter = BodyRewriter::new(ctx_ident.clone()); visit_mut::visit_block_mut(&mut body_rewriter, &mut block); let inner_fn_ident = Ident::new("inner_fn", Span::mixed_site()); let input_args = hook_sig.input_args(); // there might be some overridden lifetimes in the return type. let inner_fn_rt = match &sig.output { ReturnType::Default => None, ReturnType::Type(rarrow, _) => Some(quote! { #rarrow #output_type }), }; let inner_fn = quote! { fn #inner_fn_ident #generics (#ctx_ident: &mut ::yew::functional::HookContext, #inputs) #inner_fn_rt #where_clause #block }; let inner_type_impl = if hook_sig.needs_boxing { let with_output = !matches!(hook_sig.output_type, Type::ImplTrait(_),); let inner_fn_rt = with_output.then_some(&inner_fn_rt); let output_type = with_output.then_some(&output_type); let hook_lifetime = &hook_sig.hook_lifetime; let hook_lifetime_plus = quote! { #hook_lifetime + }; let boxed_inner_ident = Ident::new("boxed_inner", Span::mixed_site()); let boxed_fn_type = quote! { ::std::boxed::Box<dyn #hook_lifetime_plus ::std::ops::FnOnce(&mut ::yew::functional::HookContext) #inner_fn_rt> }; let as_boxed_fn = with_output.then(|| quote! { as #boxed_fn_type }); let generic_types = generics.type_params().map(|t| &t.ident); // We need boxing implementation for `impl Trait` arguments. quote! { let #boxed_inner_ident = ::std::boxed::Box::new( move |#ctx_ident: &mut ::yew::functional::HookContext| #inner_fn_rt { #inner_fn_ident :: <#(#generic_types,)*> (#ctx_ident, #(#input_args,)*) } ) #as_boxed_fn; ::yew::functional::BoxedHook::<#hook_lifetime, #output_type>::new(#boxed_inner_ident) } } else { let input_types = hook_sig.input_types(); let args_ident = Ident::new("args", Span::mixed_site()); let hook_struct_name = Ident::new("HookProvider", Span::mixed_site()); let phantom_types = hook_sig.phantom_types(); let phantom_lifetimes = hook_sig.phantom_lifetimes(); quote! { struct #hook_struct_name #generics #where_clause { _marker: ::std::marker::PhantomData<( #(#phantom_types,)* #(#phantom_lifetimes,)* )>, #args_ident: (#(#input_types,)*), } #[automatically_derived] impl #impl_generics ::yew::functional::Hook for #hook_struct_name #ty_generics #where_clause { type Output = #output_type; fn run(mut self, #ctx_ident: &mut ::yew::functional::HookContext) -> Self::Output { let (#(#input_args,)*) = self.#args_ident; #inner_fn_ident #call_generics (#ctx_ident, #(#input_args,)*) } } #[automatically_derived] impl #impl_generics #hook_struct_name #ty_generics #where_clause { fn new(#inputs) -> Self { #hook_struct_name { _marker: ::std::marker::PhantomData, #args_ident: (#(#input_args,)*), } } } #hook_struct_name #call_generics ::new(#(#input_args,)*) } }; // There're some weird issues with doc tests that it cannot detect return types properly. // So we print original implementation instead. let output = quote! { #[cfg(not(doctest))] #(#attrs)* #doc_attr #vis #fn_token #ident #generics (#inputs) #hook_return_type #where_clause { #inner_fn #inner_type_impl } #[cfg(doctest)] #original_fn }; Ok(output) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/hook/body.rs
packages/yew-macro/src/hook/body.rs
use std::sync::{Arc, Mutex}; use proc_macro_error::emit_error; use syn::spanned::Spanned; use syn::visit_mut::VisitMut; use syn::{ parse_quote_spanned, visit_mut, Expr, ExprCall, ExprClosure, ExprForLoop, ExprIf, ExprLoop, ExprMatch, ExprWhile, Ident, Item, }; #[derive(Debug)] pub struct BodyRewriter { branch_lock: Arc<Mutex<()>>, ctx_ident: Ident, } impl BodyRewriter { pub fn new(ctx_ident: Ident) -> Self { Self { branch_lock: Arc::default(), ctx_ident, } } fn is_branched(&self) -> bool { self.branch_lock.try_lock().is_err() } fn with_branch<F, O>(&mut self, f: F) -> O where F: FnOnce(&mut BodyRewriter) -> O, { let branch_lock = self.branch_lock.clone(); let _branched = branch_lock.try_lock(); f(self) } } impl VisitMut for BodyRewriter { fn visit_expr_call_mut(&mut self, i: &mut ExprCall) { let ctx_ident = &self.ctx_ident; // Only rewrite hook calls. if let Expr::Path(ref m) = &*i.func { if let Some(m) = m.path.segments.last().as_ref().map(|m| &m.ident) { if m.to_string().starts_with("use_") { if self.is_branched() { emit_error!( m, "hooks cannot be called at this position."; help = "move hooks to the top-level of your function."; note = "see: https://yew.rs/docs/next/concepts/function-components/hooks" ); } else { *i = parse_quote_spanned! { i.span() => ::yew::functional::Hook::run(#i, #ctx_ident) }; } return; } } } visit_mut::visit_expr_call_mut(self, i); } fn visit_expr_mut(&mut self, i: &mut Expr) { let ctx_ident = &self.ctx_ident; match &mut *i { Expr::Macro(m) => { if let Some(ident) = m.mac.path.segments.last().as_ref().map(|m| &m.ident) { if ident.to_string().starts_with("use_") { if self.is_branched() { emit_error!( ident, "hooks cannot be called at this position."; help = "move hooks to the top-level of your function."; note = "see: https://yew.rs/docs/next/concepts/function-components/hooks" ); } else { *i = parse_quote_spanned! { i.span() => ::yew::functional::Hook::run(#i, #ctx_ident) }; } } else { visit_mut::visit_expr_macro_mut(self, m); } } } _ => visit_mut::visit_expr_mut(self, i), } } fn visit_expr_closure_mut(&mut self, i: &mut ExprClosure) { self.with_branch(move |m| visit_mut::visit_expr_closure_mut(m, i)) } fn visit_expr_if_mut(&mut self, i: &mut ExprIf) { for it in &mut i.attrs { visit_mut::visit_attribute_mut(self, it); } visit_mut::visit_expr_mut(self, &mut i.cond); self.with_branch(|m| visit_mut::visit_block_mut(m, &mut i.then_branch)); if let Some(it) = &mut i.else_branch { self.with_branch(|m| visit_mut::visit_expr_mut(m, &mut (it).1)); } } fn visit_expr_loop_mut(&mut self, i: &mut ExprLoop) { self.with_branch(|m| visit_mut::visit_expr_loop_mut(m, i)); } fn visit_expr_for_loop_mut(&mut self, i: &mut ExprForLoop) { for it in &mut i.attrs { visit_mut::visit_attribute_mut(self, it); } if let Some(it) = &mut i.label { visit_mut::visit_label_mut(self, it); } visit_mut::visit_pat_mut(self, &mut i.pat); visit_mut::visit_expr_mut(self, &mut i.expr); self.with_branch(|m| visit_mut::visit_block_mut(m, &mut i.body)); } fn visit_expr_match_mut(&mut self, i: &mut ExprMatch) { for it in &mut i.attrs { visit_mut::visit_attribute_mut(self, it); } visit_mut::visit_expr_mut(self, &mut i.expr); self.with_branch(|m| { for it in &mut i.arms { visit_mut::visit_arm_mut(m, it); } }); } fn visit_expr_while_mut(&mut self, i: &mut ExprWhile) { for it in &mut i.attrs { visit_mut::visit_attribute_mut(self, it); } if let Some(it) = &mut i.label { visit_mut::visit_label_mut(self, it); } self.with_branch(|m| visit_mut::visit_expr_mut(m, &mut i.cond)); self.with_branch(|m| visit_mut::visit_block_mut(m, &mut i.body)); } fn visit_item_mut(&mut self, _i: &mut Item) { // We don't do anything for items. // for components / hooks in other components / hooks, apply the attribute again. } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/html_tree/html_dashed_name.rs
packages/yew-macro/src/html_tree/html_dashed_name.rs
use std::fmt; use proc_macro2::{Ident, Span, TokenStream}; use quote::{quote, ToTokens}; use syn::buffer::Cursor; use syn::ext::IdentExt; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; use syn::{LitStr, Token}; use crate::stringify::Stringify; use crate::{non_capitalized_ascii, Peek}; #[derive(Clone, PartialEq, Eq)] pub struct HtmlDashedName { pub name: Ident, pub extended: Vec<(Token![-], Ident)>, } impl HtmlDashedName { /// Checks if this name is equal to the provided item (which can be anything implementing /// `Into<String>`). pub fn eq_ignore_ascii_case<S>(&self, other: S) -> bool where S: Into<String>, { let mut s = other.into(); s.make_ascii_lowercase(); s == self.to_ascii_lowercase_string() } pub fn to_ascii_lowercase_string(&self) -> String { let mut s = self.to_string(); s.make_ascii_lowercase(); s } pub fn to_lit_str(&self) -> LitStr { LitStr::new(&self.to_string(), self.span()) } } impl fmt::Display for HtmlDashedName { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.name)?; for (_, ident) in &self.extended { write!(f, "-{ident}")?; } Ok(()) } } impl Peek<'_, Self> for HtmlDashedName { fn peek(cursor: Cursor) -> Option<(Self, Cursor)> { let (name, cursor) = cursor.ident()?; if !non_capitalized_ascii(&name.to_string()) { return None; } let mut extended = Vec::new(); let mut cursor = cursor; loop { if let Some((punct, p_cursor)) = cursor.punct() { if punct.as_char() == '-' { let (ident, i_cursor) = p_cursor.ident()?; cursor = i_cursor; extended.push((Token![-](Span::mixed_site()), ident)); continue; } } break; } Some((HtmlDashedName { name, extended }, cursor)) } } impl Parse for HtmlDashedName { fn parse(input: ParseStream) -> syn::Result<Self> { let name = input.call(Ident::parse_any)?; let mut extended = Vec::new(); while input.peek(Token![-]) { extended.push((input.parse::<Token![-]>()?, input.call(Ident::parse_any)?)); } Ok(HtmlDashedName { name, extended }) } } impl ToTokens for HtmlDashedName { fn to_tokens(&self, tokens: &mut TokenStream) { let HtmlDashedName { name, extended } = self; let dashes = extended.iter().map(|(dash, _)| quote! {#dash}); let idents = extended.iter().map(|(_, ident)| quote! {#ident}); let extended = quote! { #(#dashes #idents)* }; tokens.extend(quote! { #name #extended }); } } impl Stringify for HtmlDashedName { fn try_into_lit(&self) -> Option<LitStr> { Some(self.to_lit_str()) } fn stringify(&self) -> TokenStream { self.to_lit_str().stringify() } } impl From<Ident> for HtmlDashedName { fn from(name: Ident) -> Self { HtmlDashedName { name, extended: vec![], } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/html_tree/html_for.rs
packages/yew-macro/src/html_tree/html_for.rs
use proc_macro2::{Ident, TokenStream}; use quote::{quote, ToTokens}; use syn::buffer::Cursor; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; use syn::token::{For, In}; use syn::{braced, Expr, Pat}; use super::{HtmlChildrenTree, ToNodeIterator}; use crate::html_tree::HtmlTree; use crate::PeekValue; /// Determines if an expression is guaranteed to always return the same value anywhere. fn is_contextless_pure(expr: &Expr) -> bool { match expr { Expr::Lit(_) => true, Expr::Path(path) => path.path.get_ident().is_none(), _ => false, } } pub struct HtmlFor { pat: Pat, iter: Expr, body: HtmlChildrenTree, } impl PeekValue<()> for HtmlFor { fn peek(cursor: Cursor) -> Option<()> { let (ident, _) = cursor.ident()?; (ident == "for").then_some(()) } } impl Parse for HtmlFor { fn parse(input: ParseStream) -> syn::Result<Self> { For::parse(input)?; let pat = Pat::parse_single(input)?; In::parse(input)?; let iter = Expr::parse_without_eager_brace(input)?; let body_stream; braced!(body_stream in input); let body = HtmlChildrenTree::parse_delimited(&body_stream)?; // TODO: more concise code by using if-let guards once MSRV is raised for child in body.0.iter() { let HtmlTree::Element(element) = child else { continue; }; let Some(key) = &element.props.special.key else { continue; }; if is_contextless_pure(&key.value) { return Err(syn::Error::new( key.value.span(), "duplicate key for a node in a `for`-loop\nthis will create elements with \ duplicate keys if the loop iterates more than once", )); } } Ok(Self { pat, iter, body }) } } impl ToTokens for HtmlFor { fn to_tokens(&self, tokens: &mut TokenStream) { let Self { pat, iter, body } = self; let acc = Ident::new("__yew_v", iter.span()); let alloc_opt = body .size_hint() .filter(|&size| size > 1) // explicitly reserving space for 1 more element is redundant .map(|size| quote!( #acc.reserve(#size) )); let vlist_gen = match body.fully_keyed() { Some(true) => quote! { ::yew::virtual_dom::VList::__macro_new( #acc, ::std::option::Option::None, ::yew::virtual_dom::FullyKeyedState::KnownFullyKeyed ) }, Some(false) => quote! { ::yew::virtual_dom::VList::__macro_new( #acc, ::std::option::Option::None, ::yew::virtual_dom::FullyKeyedState::KnownMissingKeys ) }, None => quote! { ::yew::virtual_dom::VList::with_children(#acc, ::std::option::Option::None) }, }; let body = body.0.iter().map(|child| { if let Some(child) = child.to_node_iterator_stream() { quote!( #acc.extend(#child) ) } else { quote!( #acc.push(::std::convert::Into::into(#child)) ) } }); tokens.extend(quote!({ let mut #acc = ::std::vec::Vec::<::yew::virtual_dom::VNode>::new(); ::std::iter::Iterator::for_each( ::std::iter::IntoIterator::into_iter(#iter), |#pat| { #alloc_opt; #(#body);* } ); #vlist_gen })) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/html_tree/html_component.rs
packages/yew-macro/src/html_tree/html_component.rs
use proc_macro2::Span; use quote::{quote, quote_spanned, ToTokens}; use syn::parse::discouraged::Speculative; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; use syn::{Token, Type}; use super::{HtmlChildrenTree, TagTokens}; use crate::is_ide_completion; use crate::props::ComponentProps; pub struct HtmlComponent { ty: Type, pub props: ComponentProps, children: HtmlChildrenTree, close: Option<HtmlComponentClose>, } impl Parse for HtmlComponent { fn parse(input: ParseStream) -> syn::Result<Self> { // check if the next tokens are </ let trying_to_close = || { let lt = input.peek(Token![<]); let div = input.peek2(Token![/]); lt && div }; if trying_to_close() { let close = input.parse::<HtmlComponentClose>(); if !is_ide_completion() { return match close { Ok(close) => Err(syn::Error::new_spanned( close.to_spanned(), "this closing tag has no corresponding opening tag", )), Err(err) => Err(err), }; } } let open = input.parse::<HtmlComponentOpen>()?; // Return early if it's a self-closing tag if open.is_self_closing() { return Ok(HtmlComponent { ty: open.ty, props: open.props, children: HtmlChildrenTree::new(), close: None, }); } let mut children = HtmlChildrenTree::new(); let close = loop { if input.is_empty() { if is_ide_completion() { break None; } return Err(syn::Error::new_spanned( open.to_spanned(), "this opening tag has no corresponding closing tag", )); } if trying_to_close() { fn format_token_stream(ts: impl ToTokens) -> String { let string = ts.to_token_stream().to_string(); // remove unnecessary spaces string.replace(' ', "") } let fork = input.fork(); let close = TagTokens::parse_end_content(&fork, |i_fork, tag| { let ty = i_fork.parse().map_err(|e| { syn::Error::new( e.span(), format!( "expected a valid closing tag for component\nnote: found opening \ tag `{lt}{0}{gt}`\nhelp: try `{lt}/{0}{gt}`", format_token_stream(&open.ty), lt = open.tag.lt.to_token_stream(), gt = open.tag.gt.to_token_stream(), ), ) })?; if ty != open.ty && !is_ide_completion() { let open_ty = &open.ty; Err(syn::Error::new_spanned( quote!(#open_ty #ty), format!( "mismatched closing tags: expected `{}`, found `{}`", format_token_stream(open_ty), format_token_stream(ty) ), )) } else { let close = HtmlComponentClose { tag, ty }; input.advance_to(&fork); Ok(close) } })?; break Some(close); } children.parse_child(input)?; }; if !children.is_empty() { if let Some(children_prop) = open.props.children() { return Err(syn::Error::new_spanned( &children_prop.label, "cannot specify the `children` prop when the component already has children", )); } } Ok(HtmlComponent { ty: open.ty, props: open.props, children, close, }) } } impl ToTokens for HtmlComponent { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let Self { ty, props, children, close, } = self; let ty_span = ty.span().resolved_at(Span::call_site()); let props_ty = quote_spanned!(ty_span=> <#ty as ::yew::html::BaseComponent>::Properties); let children_renderer = children.to_children_renderer_tokens(); let build_props = props.build_properties_tokens(&props_ty, children_renderer); let key = props.special().wrap_key_attr(); let use_close_tag = close .as_ref() .map(|close| { let close_ty = &close.ty; quote_spanned! {close_ty.span()=> let _ = |_:#close_ty| {}; } }) .unwrap_or_default(); tokens.extend(quote_spanned! {ty_span=> { #use_close_tag #[allow(clippy::let_unit_value)] let __yew_props = #build_props; ::yew::virtual_dom::VChild::<#ty>::new(__yew_props, #key) } }); } } struct HtmlComponentOpen { tag: TagTokens, ty: Type, props: ComponentProps, } impl HtmlComponentOpen { fn is_self_closing(&self) -> bool { self.tag.div.is_some() } fn to_spanned(&self) -> impl ToTokens { self.tag.to_spanned() } } impl Parse for HtmlComponentOpen { fn parse(input: ParseStream) -> syn::Result<Self> { TagTokens::parse_start_content(input, |input, tag| { let ty = input.parse()?; let props: ComponentProps = input.parse()?; if let Some(ref node_ref) = props.special().node_ref { return Err(syn::Error::new_spanned( &node_ref.label, "cannot use `ref` with components. If you want to specify a property, use \ `r#ref` here instead.", )); } Ok(Self { tag, ty, props }) }) } } struct HtmlComponentClose { tag: TagTokens, ty: Type, } impl HtmlComponentClose { fn to_spanned(&self) -> impl ToTokens { self.tag.to_spanned() } } impl Parse for HtmlComponentClose { fn parse(input: ParseStream) -> syn::Result<Self> { TagTokens::parse_end_content(input, |input, tag| { let ty = input.parse()?; Ok(Self { tag, ty }) }) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/html_tree/html_list.rs
packages/yew-macro/src/html_tree/html_list.rs
use quote::{quote, quote_spanned, ToTokens}; use syn::buffer::Cursor; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; use syn::Expr; use super::html_dashed_name::HtmlDashedName; use super::{HtmlChildrenTree, TagTokens}; use crate::props::Prop; use crate::{Peek, PeekValue}; pub struct HtmlList { pub open: HtmlListOpen, pub children: HtmlChildrenTree, close: HtmlListClose, } impl PeekValue<()> for HtmlList { fn peek(cursor: Cursor) -> Option<()> { HtmlListOpen::peek(cursor) .or_else(|| HtmlListClose::peek(cursor)) .map(|_| ()) } } impl Parse for HtmlList { fn parse(input: ParseStream) -> syn::Result<Self> { if HtmlListClose::peek(input.cursor()).is_some() { return match input.parse::<HtmlListClose>() { Ok(close) => Err(syn::Error::new_spanned( close.to_spanned(), "this closing fragment has no corresponding opening fragment", )), Err(err) => Err(err), }; } let open = input.parse::<HtmlListOpen>()?; let mut children = HtmlChildrenTree::new(); while HtmlListClose::peek(input.cursor()).is_none() { children.parse_child(input)?; if input.is_empty() { return Err(syn::Error::new_spanned( open.to_spanned(), "this opening fragment has no corresponding closing fragment", )); } } let close = input.parse::<HtmlListClose>()?; Ok(Self { open, children, close, }) } } impl ToTokens for HtmlList { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let Self { open, children, close, } = &self; let key = if let Some(key) = &open.props.key { quote_spanned! {key.span()=> ::std::option::Option::Some(::std::convert::Into::<::yew::virtual_dom::Key>::into(#key))} } else { quote! { ::std::option::Option::None } }; let span = { let open = open.to_spanned(); let close = close.to_spanned(); quote! { #open #close } } .span(); tokens.extend(match children.fully_keyed() { Some(true) => quote_spanned!{span=> ::yew::virtual_dom::VList::__macro_new(#children, #key, ::yew::virtual_dom::FullyKeyedState::KnownFullyKeyed) }, Some(false) => quote_spanned!{span=> ::yew::virtual_dom::VList::__macro_new(#children, #key, ::yew::virtual_dom::FullyKeyedState::KnownMissingKeys) }, None => quote_spanned!{span=> ::yew::virtual_dom::VList::with_children(#children, #key) } }); } } pub struct HtmlListOpen { tag: TagTokens, pub props: HtmlListProps, } impl HtmlListOpen { fn to_spanned(&self) -> impl ToTokens { self.tag.to_spanned() } } impl PeekValue<()> for HtmlListOpen { fn peek(cursor: Cursor) -> Option<()> { let (punct, cursor) = cursor.punct()?; if punct.as_char() != '<' { return None; } // make sure it's either a property (key=value) or it's immediately closed if let Some((_, cursor)) = HtmlDashedName::peek(cursor) { let (punct, _) = cursor.punct()?; (punct.as_char() == '=' || punct.as_char() == '?').then_some(()) } else { let (punct, _) = cursor.punct()?; (punct.as_char() == '>').then_some(()) } } } impl Parse for HtmlListOpen { fn parse(input: ParseStream) -> syn::Result<Self> { TagTokens::parse_start_content(input, |input, tag| { let props = input.parse()?; Ok(Self { tag, props }) }) } } pub struct HtmlListProps { pub key: Option<Expr>, } impl Parse for HtmlListProps { fn parse(input: ParseStream) -> syn::Result<Self> { let key = if input.is_empty() { None } else { let prop: Prop = input.parse()?; if !input.is_empty() { return Err(input.error("only a single `key` prop is allowed on a fragment")); } if prop.label.to_ascii_lowercase_string() != "key" { return Err(syn::Error::new_spanned( prop.label, "fragments only accept the `key` prop", )); } Some(prop.value) }; Ok(Self { key }) } } struct HtmlListClose(TagTokens); impl HtmlListClose { fn to_spanned(&self) -> impl ToTokens { self.0.to_spanned() } } impl PeekValue<()> for HtmlListClose { fn peek(cursor: Cursor) -> Option<()> { let (punct, cursor) = cursor.punct()?; if punct.as_char() != '<' { return None; } let (punct, cursor) = cursor.punct()?; if punct.as_char() != '/' { return None; } let (punct, _) = cursor.punct()?; (punct.as_char() == '>').then_some(()) } } impl Parse for HtmlListClose { fn parse(input: ParseStream) -> syn::Result<Self> { TagTokens::parse_end_content(input, |input, tag| { if !input.is_empty() { Err(input.error("unexpected content in list close")) } else { Ok(Self(tag)) } }) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/html_tree/html_iterable.rs
packages/yew-macro/src/html_tree/html_iterable.rs
use proc_macro2::TokenStream; use quote::{quote_spanned, ToTokens}; use syn::buffer::Cursor; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; use syn::{Expr, Token}; use super::ToNodeIterator; use crate::PeekValue; pub struct HtmlIterable(Expr); impl PeekValue<()> for HtmlIterable { fn peek(cursor: Cursor) -> Option<()> { let (ident, _) = cursor.ident()?; (ident == "for").then_some(()) } } impl Parse for HtmlIterable { fn parse(input: ParseStream) -> syn::Result<Self> { let for_token = input.parse::<Token![for]>()?; match input.parse() { Ok(expr) => Ok(HtmlIterable(expr)), Err(err) => { if err.to_string().starts_with("unexpected end of input") { Err(syn::Error::new_spanned( for_token, "expected an expression after the keyword `for`", )) } else { Err(err) } } } } } impl ToTokens for HtmlIterable { fn to_tokens(&self, tokens: &mut TokenStream) { let expr = &self.0; let new_tokens = quote_spanned! {expr.span()=> #[allow(unused_braces)] ::std::iter::Iterator::collect::<::yew::virtual_dom::VNode>(::std::iter::IntoIterator::into_iter(#expr)) }; tokens.extend(new_tokens); } } impl ToNodeIterator for HtmlIterable { fn to_node_iterator_stream(&self) -> Option<TokenStream> { let Self(expr) = self; // #expr can return anything that implements IntoIterator<Item=Into<T>> // We use a util method to avoid clippy warnings and reduce generated code size Some(quote_spanned! {expr.span()=> ::yew::utils::into_node_iter(#expr) }) } fn is_singular(&self) -> bool { false } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/html_tree/mod.rs
packages/yew-macro/src/html_tree/mod.rs
use proc_macro2::{Delimiter, Ident, Span, TokenStream}; use quote::{quote, quote_spanned, ToTokens}; use syn::buffer::Cursor; use syn::ext::IdentExt; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; use syn::{braced, token, Token}; use crate::{is_ide_completion, PeekValue}; mod html_block; mod html_component; mod html_dashed_name; mod html_element; mod html_for; mod html_if; mod html_iterable; mod html_list; mod html_node; mod lint; mod tag; use html_block::HtmlBlock; use html_component::HtmlComponent; pub use html_dashed_name::HtmlDashedName; use html_element::HtmlElement; use html_if::HtmlIf; use html_iterable::HtmlIterable; use html_list::HtmlList; use html_node::HtmlNode; use tag::TagTokens; use self::html_block::BlockContent; use self::html_for::HtmlFor; pub enum HtmlType { Block, Component, List, Element, If, For, Empty, } pub enum HtmlTree { Block(Box<HtmlBlock>), Component(Box<HtmlComponent>), List(Box<HtmlList>), Element(Box<HtmlElement>), If(Box<HtmlIf>), For(Box<HtmlFor>), Empty, } impl Parse for HtmlTree { fn parse(input: ParseStream) -> syn::Result<Self> { let html_type = Self::peek_html_type(input) .ok_or_else(|| input.error("expected a valid html element"))?; Ok(match html_type { HtmlType::Empty => Self::Empty, HtmlType::Component => Self::Component(Box::new(input.parse()?)), HtmlType::Element => Self::Element(Box::new(input.parse()?)), HtmlType::Block => Self::Block(Box::new(input.parse()?)), HtmlType::List => Self::List(Box::new(input.parse()?)), HtmlType::If => Self::If(Box::new(input.parse()?)), HtmlType::For => Self::For(Box::new(input.parse()?)), }) } } impl HtmlTree { /// Determine the [`HtmlType`] before actually parsing it. /// Even though this method accepts a [`ParseStream`], it is forked and the original stream is /// not modified. Once a certain `HtmlType` can be deduced for certain, the function eagerly /// returns with the appropriate type. If invalid html tag, returns `None`. fn peek_html_type(input: ParseStream) -> Option<HtmlType> { let input = input.fork(); // do not modify original ParseStream let cursor = input.cursor(); if input.is_empty() { Some(HtmlType::Empty) } else if HtmlBlock::peek(cursor).is_some() { Some(HtmlType::Block) } else if HtmlIf::peek(cursor).is_some() { Some(HtmlType::If) } else if HtmlFor::peek(cursor).is_some() { Some(HtmlType::For) } else if input.peek(Token![<]) { let _lt: Token![<] = input.parse().ok()?; // eat '/' character for unmatched closing tag let _slash: Option<Token![/]> = input.parse().ok(); if input.peek(Token![>]) { Some(HtmlType::List) } else if input.peek(Token![@]) { Some(HtmlType::Element) // dynamic element } else if input.peek(Token![::]) { Some(HtmlType::Component) } else if input.peek(Ident::peek_any) { let ident = Ident::parse_any(&input).ok()?; let ident_str = ident.to_string(); if input.peek(Token![=]) || (input.peek(Token![?]) && input.peek2(Token![=])) { Some(HtmlType::List) } else if ident_str.chars().next().unwrap().is_ascii_uppercase() || input.peek(Token![::]) || is_ide_completion() && ident_str.chars().any(|c| c.is_ascii_uppercase()) { Some(HtmlType::Component) } else { Some(HtmlType::Element) } } else { None } } else { None } } } impl ToTokens for HtmlTree { fn to_tokens(&self, tokens: &mut TokenStream) { lint::lint_all(self); match self { Self::Empty => tokens.extend(quote! { <::yew::virtual_dom::VNode as ::std::default::Default>::default() }), Self::Component(comp) => comp.to_tokens(tokens), Self::Element(tag) => tag.to_tokens(tokens), Self::List(list) => list.to_tokens(tokens), Self::Block(block) => block.to_tokens(tokens), Self::If(block) => block.to_tokens(tokens), Self::For(block) => block.to_tokens(tokens), } } } pub enum HtmlRoot { Tree(HtmlTree), Node(Box<HtmlNode>), } impl Parse for HtmlRoot { fn parse(input: ParseStream) -> syn::Result<Self> { let html_root = if HtmlTree::peek_html_type(input).is_some() { Self::Tree(input.parse()?) } else { Self::Node(Box::new(input.parse()?)) }; if !input.is_empty() { let stream: TokenStream = input.parse()?; Err(syn::Error::new_spanned( stream, "only one root html element is allowed (hint: you can wrap multiple html elements \ in a fragment `<></>`)", )) } else { Ok(html_root) } } } impl ToTokens for HtmlRoot { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::Tree(tree) => tree.to_tokens(tokens), Self::Node(node) => node.to_tokens(tokens), } } } /// Same as HtmlRoot but always returns a VNode. pub struct HtmlRootVNode(HtmlRoot); impl Parse for HtmlRootVNode { fn parse(input: ParseStream) -> syn::Result<Self> { input.parse().map(Self) } } impl ToTokens for HtmlRootVNode { fn to_tokens(&self, tokens: &mut TokenStream) { let new_tokens = self.0.to_token_stream(); tokens.extend( quote_spanned! {self.0.span().resolved_at(Span::mixed_site())=> { #[allow(clippy::useless_conversion)] <::yew::virtual_dom::VNode as ::std::convert::From<_>>::from(#new_tokens) }}, ); } } /// This trait represents a type that can be unfolded into multiple html nodes. pub trait ToNodeIterator { /// Generate a token stream which produces a value that implements IntoIterator<Item=T> where T /// is inferred by the compiler. The easiest way to achieve this is to call `.into()` on /// each element. If the resulting iterator only ever yields a single item this function /// should return None instead. fn to_node_iterator_stream(&self) -> Option<TokenStream>; /// Returns a boolean indicating whether the node can only ever unfold into 1 node /// Same as calling `.to_node_iterator_stream().is_none()`, /// but doesn't actually construct any token stream fn is_singular(&self) -> bool; } impl ToNodeIterator for HtmlTree { fn to_node_iterator_stream(&self) -> Option<TokenStream> { match self { Self::Block(block) => block.to_node_iterator_stream(), // everything else is just a single node. _ => None, } } fn is_singular(&self) -> bool { match self { Self::Block(block) => block.is_singular(), _ => true, } } } pub struct HtmlChildrenTree(pub Vec<HtmlTree>); impl HtmlChildrenTree { pub fn new() -> Self { Self(Vec::new()) } pub fn parse_child(&mut self, input: ParseStream) -> syn::Result<()> { self.0.push(input.parse()?); Ok(()) } pub fn is_empty(&self) -> bool { self.0.is_empty() } // Check if each child represents a single node. // This is the case when no expressions are used. fn only_single_node_children(&self) -> bool { self.0.iter().all(HtmlTree::is_singular) } pub fn to_build_vec_token_stream(&self) -> TokenStream { let Self(children) = self; if self.only_single_node_children() { // optimize for the common case where all children are single nodes (only using literal // html). let children_into = children .iter() .map(|child| quote_spanned! {child.span()=> ::std::convert::Into::into(#child) }); return quote! { [#(#children_into),*].to_vec() }; } let vec_ident = Ident::new("__yew_v", Span::mixed_site()); let add_children_streams = children.iter().map(|child| { if let Some(node_iterator_stream) = child.to_node_iterator_stream() { quote! { ::std::iter::Extend::extend(&mut #vec_ident, #node_iterator_stream); } } else { quote_spanned! {child.span()=> #vec_ident.push(::std::convert::Into::into(#child)); } } }); quote! { { let mut #vec_ident = ::std::vec::Vec::new(); #(#add_children_streams)* #vec_ident } } } fn parse_delimited(input: ParseStream) -> syn::Result<Self> { let mut children = HtmlChildrenTree::new(); while !input.is_empty() { children.parse_child(input)?; } Ok(children) } pub fn to_children_renderer_tokens(&self) -> Option<TokenStream> { match self.0[..] { [] => None, [HtmlTree::Component(ref children)] => Some(quote! { #children }), [HtmlTree::Element(ref children)] => Some(quote! { #children }), [HtmlTree::Block(ref m)] => { // We only want to process `{vnode}` and not `{for vnodes}`. // This should be converted into a if let guard once https://github.com/rust-lang/rust/issues/51114 is stable. // Or further nested once deref pattern (https://github.com/rust-lang/rust/issues/87121) is stable. if let HtmlBlock { content: BlockContent::Node(children), .. } = m.as_ref() { Some(quote! { #children }) } else { Some(quote! { ::yew::html::ChildrenRenderer::new(#self) }) } } _ => Some(quote! { ::yew::html::ChildrenRenderer::new(#self) }), } } pub fn to_vnode_tokens(&self) -> TokenStream { match self.0[..] { [] => quote! {::std::default::Default::default() }, [HtmlTree::Component(ref children)] => { quote! { ::yew::html::IntoPropValue::<::yew::virtual_dom::VNode>::into_prop_value(#children) } } [HtmlTree::Element(ref children)] => { quote! { ::yew::html::IntoPropValue::<::yew::virtual_dom::VNode>::into_prop_value(#children) } } [HtmlTree::Block(ref m)] => { // We only want to process `{vnode}` and not `{for vnodes}`. // This should be converted into a if let guard once https://github.com/rust-lang/rust/issues/51114 is stable. // Or further nested once deref pattern (https://github.com/rust-lang/rust/issues/87121) is stable. if let HtmlBlock { content: BlockContent::Node(children), .. } = m.as_ref() { quote! { ::yew::html::IntoPropValue::<::yew::virtual_dom::VNode>::into_prop_value(#children) } } else { quote! { ::yew::html::IntoPropValue::<::yew::virtual_dom::VNode>::into_prop_value( ::yew::html::ChildrenRenderer::new(#self) ) } } } _ => quote! { ::yew::html::IntoPropValue::<::yew::virtual_dom::VNode>::into_prop_value( ::yew::html::ChildrenRenderer::new(#self) ) }, } } pub fn size_hint(&self) -> Option<usize> { self.only_single_node_children().then_some(self.0.len()) } pub fn fully_keyed(&self) -> Option<bool> { for child in self.0.iter() { match child { HtmlTree::Block(block) => { return if let BlockContent::Node(node) = &block.content { matches!(&**node, HtmlNode::Literal(_)).then_some(false) } else { None } } HtmlTree::Component(comp) => { if comp.props.props.special.key.is_none() { return Some(false); } } HtmlTree::List(list) => { if list.open.props.key.is_none() { return Some(false); } } HtmlTree::Element(element) => { if element.props.special.key.is_none() { return Some(false); } } HtmlTree::If(_) | HtmlTree::For(_) | HtmlTree::Empty => return Some(false), } } Some(true) } } impl ToTokens for HtmlChildrenTree { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.extend(self.to_build_vec_token_stream()); } } pub struct HtmlRootBraced { brace: token::Brace, children: HtmlChildrenTree, } impl PeekValue<()> for HtmlRootBraced { fn peek(cursor: Cursor) -> Option<()> { cursor.group(Delimiter::Brace).map(|_| ()) } } impl Parse for HtmlRootBraced { fn parse(input: ParseStream) -> syn::Result<Self> { let content; let brace = braced!(content in input); let children = HtmlChildrenTree::parse_delimited(&content)?; Ok(HtmlRootBraced { brace, children }) } } impl ToTokens for HtmlRootBraced { fn to_tokens(&self, tokens: &mut TokenStream) { let Self { brace, children } = self; tokens.extend(quote_spanned! {brace.span.span()=> { ::yew::virtual_dom::VNode::VList(::std::rc::Rc::new( ::yew::virtual_dom::VList::with_children(#children, ::std::option::Option::None) )) } }); } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/html_tree/html_if.rs
packages/yew-macro/src/html_tree/html_if.rs
use proc_macro2::TokenStream; use quote::{quote_spanned, ToTokens}; use syn::buffer::Cursor; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; use syn::{parse_quote, Expr, Token}; use super::HtmlRootBraced; use crate::PeekValue; pub struct HtmlIf { if_token: Token![if], cond: Box<Expr>, then_branch: HtmlRootBraced, else_branch: Option<(Token![else], Box<HtmlRootBracedOrIf>)>, } impl PeekValue<()> for HtmlIf { fn peek(cursor: Cursor) -> Option<()> { let (ident, _) = cursor.ident()?; (ident == "if").then_some(()) } } impl Parse for HtmlIf { fn parse(input: ParseStream) -> syn::Result<Self> { let if_token = input.parse()?; let cond = Box::new(input.call(Expr::parse_without_eager_brace)?); match &*cond { Expr::Block(syn::ExprBlock { block, .. }) if block.stmts.is_empty() => { return Err(syn::Error::new( cond.span(), "missing condition for `if` expression", )) } _ => {} } if input.is_empty() { return Err(syn::Error::new( cond.span(), "this `if` expression has a condition, but no block", )); } let then_branch = input.parse()?; let else_branch = input .parse::<Token![else]>() .ok() .map(|else_token| { if input.is_empty() { return Err(syn::Error::new( else_token.span(), "expected block or `if` after `else`", )); } input.parse().map(|branch| (else_token, branch)) }) .transpose()?; Ok(HtmlIf { if_token, cond, then_branch, else_branch, }) } } impl ToTokens for HtmlIf { fn to_tokens(&self, tokens: &mut TokenStream) { let Self { if_token, cond, then_branch, else_branch, } = self; let default_else_branch = parse_quote! { {} }; let else_branch = else_branch .as_ref() .map(|(_, branch)| branch) .unwrap_or(&default_else_branch); let new_tokens = quote_spanned! {if_token.span()=> if #cond #then_branch else #else_branch }; tokens.extend(new_tokens); } } pub enum HtmlRootBracedOrIf { Branch(HtmlRootBraced), If(HtmlIf), } impl PeekValue<()> for HtmlRootBracedOrIf { fn peek(cursor: Cursor) -> Option<()> { HtmlRootBraced::peek(cursor).or_else(|| HtmlIf::peek(cursor)) } } impl Parse for HtmlRootBracedOrIf { fn parse(input: ParseStream) -> syn::Result<Self> { if HtmlRootBraced::peek(input.cursor()).is_some() { input.parse().map(Self::Branch) } else { input.parse().map(Self::If) } } } impl ToTokens for HtmlRootBracedOrIf { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::Branch(x) => x.to_tokens(tokens), Self::If(x) => x.to_tokens(tokens), } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/html_tree/html_block.rs
packages/yew-macro/src/html_tree/html_block.rs
use proc_macro2::Delimiter; use quote::{quote, quote_spanned, ToTokens}; use syn::buffer::Cursor; use syn::parse::{Parse, ParseStream}; use syn::{braced, token}; use super::{HtmlIterable, HtmlNode, ToNodeIterator}; use crate::PeekValue; pub struct HtmlBlock { pub content: BlockContent, brace: token::Brace, } pub enum BlockContent { Node(Box<HtmlNode>), Iterable(Box<HtmlIterable>), } impl PeekValue<()> for HtmlBlock { fn peek(cursor: Cursor) -> Option<()> { cursor.group(Delimiter::Brace).map(|_| ()) } } impl Parse for HtmlBlock { fn parse(input: ParseStream) -> syn::Result<Self> { let content; let brace = braced!(content in input); let content = if HtmlIterable::peek(content.cursor()).is_some() { BlockContent::Iterable(Box::new(content.parse()?)) } else { BlockContent::Node(Box::new(content.parse()?)) }; Ok(HtmlBlock { content, brace }) } } impl ToTokens for HtmlBlock { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let HtmlBlock { content, .. } = self; let new_tokens = match content { BlockContent::Iterable(html_iterable) => quote! {#html_iterable}, BlockContent::Node(html_node) => quote! {#html_node}, }; tokens.extend(quote! {#new_tokens}); } } impl ToNodeIterator for HtmlBlock { fn to_node_iterator_stream(&self) -> Option<proc_macro2::TokenStream> { let HtmlBlock { content, brace } = self; let new_tokens = match content { BlockContent::Iterable(iterable) => iterable.to_node_iterator_stream(), BlockContent::Node(node) => node.to_node_iterator_stream(), }?; Some(quote_spanned! {brace.span=> #new_tokens}) } fn is_singular(&self) -> bool { match &self.content { BlockContent::Node(node) => node.is_singular(), BlockContent::Iterable(_) => false, } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/html_tree/html_element.rs
packages/yew-macro/src/html_tree/html_element.rs
use proc_macro2::{Delimiter, Group, Span, TokenStream}; use proc_macro_error::emit_warning; use quote::{quote, quote_spanned, ToTokens}; use syn::buffer::Cursor; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; use syn::{Expr, Ident, Lit, LitStr, Token}; use super::{HtmlChildrenTree, HtmlDashedName, TagTokens}; use crate::props::{ElementProps, Prop, PropDirective}; use crate::stringify::{Stringify, Value}; use crate::{is_ide_completion, non_capitalized_ascii, Peek, PeekValue}; fn is_normalised_element_name(name: &str) -> bool { match name { "animateMotion" | "animateTransform" | "clipPath" | "feBlend" | "feColorMatrix" | "feComponentTransfer" | "feComposite" | "feConvolveMatrix" | "feDiffuseLighting" | "feDisplacementMap" | "feDistantLight" | "feDropShadow" | "feFlood" | "feFuncA" | "feFuncB" | "feFuncG" | "feFuncR" | "feGaussianBlur" | "feImage" | "feMerge" | "feMergeNode" | "feMorphology" | "feOffset" | "fePointLight" | "feSpecularLighting" | "feSpotLight" | "feTile" | "feTurbulence" | "foreignObject" | "glyphRef" | "linearGradient" | "radialGradient" | "textPath" => true, _ => !name.chars().any(|c| c.is_ascii_uppercase()), } } pub struct HtmlElement { pub name: TagName, pub props: ElementProps, pub children: HtmlChildrenTree, } impl PeekValue<()> for HtmlElement { fn peek(cursor: Cursor) -> Option<()> { HtmlElementOpen::peek(cursor) .or_else(|| HtmlElementClose::peek(cursor)) .map(|_| ()) } } impl Parse for HtmlElement { fn parse(input: ParseStream) -> syn::Result<Self> { if HtmlElementClose::peek(input.cursor()).is_some() { return match input.parse::<HtmlElementClose>() { Ok(close) => Err(syn::Error::new_spanned( close.to_spanned(), "this closing tag has no corresponding opening tag", )), Err(err) => Err(err), }; } let open = input.parse::<HtmlElementOpen>()?; // Return early if it's a self-closing tag if open.is_self_closing() { return Ok(HtmlElement { name: open.name, props: open.props, children: HtmlChildrenTree::new(), }); } if let TagName::Lit(name) = &open.name { // Void elements should not have children. // See https://html.spec.whatwg.org/multipage/syntax.html#void-elements // // For dynamic tags this is done at runtime! match name.to_ascii_lowercase_string().as_str() { "textarea" => { return Err(syn::Error::new_spanned( open.to_spanned(), "the tag `<textarea>` is a void element and cannot have children (hint: \ to provide value to it, rewrite it as `<textarea value={x} />`. If you \ wish to set the default value, rewrite it as `<textarea defaultvalue={x} \ />`)", )) } "area" | "base" | "br" | "col" | "embed" | "hr" | "img" | "input" | "link" | "meta" | "param" | "source" | "track" | "wbr" => { return Err(syn::Error::new_spanned( open.to_spanned(), format!( "the tag `<{name}>` is a void element and cannot have children (hint: \ rewrite this as `<{name} />`)", ), )) } _ => {} } } let open_key = open.name.get_key(); let mut children = HtmlChildrenTree::new(); loop { if input.is_empty() { if is_ide_completion() { break; } return Err(syn::Error::new_spanned( open.to_spanned(), "this opening tag has no corresponding closing tag", )); } if let Some(close_key) = HtmlElementClose::peek(input.cursor()) { if open_key == close_key { break; } } children.parse_child(input)?; } if !input.is_empty() || !is_ide_completion() { input.parse::<HtmlElementClose>()?; } Ok(Self { name: open.name, props: open.props, children, }) } } impl ToTokens for HtmlElement { #[allow(clippy::cognitive_complexity)] fn to_tokens(&self, tokens: &mut TokenStream) { let Self { name, props, children, } = self; let ElementProps { classes, attributes, booleans, value, checked, listeners, special, defaultvalue, } = &props; // attributes with special treatment let node_ref = special.wrap_node_ref_attr(); let key = special.wrap_key_attr(); let value = || { value .as_ref() .map(|prop| wrap_attr_value(prop.value.optimize_literals())) .unwrap_or(quote! { ::std::option::Option::None }) }; let checked = || { checked .as_ref() .map(|attr| { let value = &attr.value; quote! { ::std::option::Option::Some( #value ) } }) .unwrap_or(quote! { ::std::option::Option::None }) }; let defaultvalue = || { defaultvalue .as_ref() .map(|prop| wrap_attr_value(prop.value.optimize_literals())) .unwrap_or(quote! { ::std::option::Option::None }) }; // other attributes let attributes = { let normal_attrs = attributes.iter().map( |Prop { label, value, directive, .. }| { ( label.to_lit_str(), value.optimize_literals_tagged(), *directive, ) }, ); let boolean_attrs = booleans.iter().filter_map( |Prop { label, value, directive, .. }| { let key = label.to_lit_str(); Some(( key.clone(), match value { Expr::Lit(e) => match &e.lit { Lit::Bool(b) => Value::Static(if b.value { quote! { #key } } else { return None; }), _ => Value::Dynamic(quote_spanned! {value.span()=> { ::yew::utils::__ensure_type::<::std::primitive::bool>(#value); #key }}), }, expr => Value::Dynamic( quote_spanned! {expr.span().resolved_at(Span::call_site())=> if #expr { ::std::option::Option::Some( ::yew::virtual_dom::AttrValue::Static(#key) ) } else { ::std::option::Option::None } }, ), }, *directive, )) }, ); let class_attr = classes .as_ref() .and_then(|classes| match classes.value.try_into_lit() { Some(lit) => { if lit.value().is_empty() { None } else { Some(( LitStr::new("class", lit.span()), Value::Static(quote! { #lit }), None, )) } } None => { let expr = &classes.value; Some(( LitStr::new("class", classes.label.span()), Value::Dynamic(quote! { ::std::convert::Into::<::yew::html::Classes>::into(#expr) }), None, )) } }); /// Try to turn attribute list into a `::yew::virtual_dom::Attributes::Static` fn try_into_static( src: &[(LitStr, Value, Option<PropDirective>)], ) -> Option<TokenStream> { if src .iter() .any(|(_, _, d)| matches!(d, Some(PropDirective::ApplyAsProperty(_)))) { // don't try to make a static attribute list if there are any properties to // assign return None; } let mut kv = Vec::with_capacity(src.len()); for (k, v, directive) in src.iter() { let v = match v { Value::Static(v) => quote! { #v }, Value::Dynamic(_) => return None, }; let v = match directive { Some(PropDirective::ApplyAsProperty(token)) => { quote_spanned!(token.span()=> ::yew::virtual_dom::AttributeOrProperty::Property( ::std::convert::Into::into(#v) )) } None => quote!(::yew::virtual_dom::AttributeOrProperty::Static( #v )), }; kv.push(quote! { ( #k, #v) }); } Some(quote! { ::yew::virtual_dom::Attributes::Static(&[#(#kv),*]) }) } let attrs = normal_attrs .chain(boolean_attrs) .chain(class_attr) .collect::<Vec<(LitStr, Value, Option<PropDirective>)>>(); try_into_static(&attrs).unwrap_or_else(|| { let keys = attrs.iter().map(|(k, ..)| quote! { #k }); let values = attrs.iter().map(|(_, v, directive)| { let value = match directive { Some(PropDirective::ApplyAsProperty(token)) => { quote_spanned!(token.span()=> ::std::option::Option::Some( ::yew::virtual_dom::AttributeOrProperty::Property( ::std::convert::Into::into(#v) )) ) } None => { let value = wrap_attr_value(v); quote! { ::std::option::Option::map(#value, ::yew::virtual_dom::AttributeOrProperty::Attribute) } }, }; quote! { #value } }); quote! { ::yew::virtual_dom::Attributes::Dynamic{ keys: &[#(#keys),*], values: ::std::boxed::Box::new([#(#values),*]), } } }) }; let listeners = if listeners.is_empty() { quote! { ::yew::virtual_dom::listeners::Listeners::None } } else { let listeners_it = listeners.iter().map(|Prop { label, value, .. }| { let name = &label.name; quote! { ::yew::html::#name::Wrapper::__macro_new(#value) } }); quote! { ::yew::virtual_dom::listeners::Listeners::Pending( ::std::boxed::Box::new([#(#listeners_it),*]) ) } }; // TODO: if none of the children have possibly None expressions or literals as keys, we can // compute `VList.fully_keyed` at compile time. let children = children.to_vnode_tokens(); tokens.extend(match &name { TagName::Lit(dashedname) => { let name_span = dashedname.span(); let name = dashedname.to_string(); let lowercase_name = dashedname.to_ascii_lowercase_string(); if !is_normalised_element_name(&dashedname.to_string()) { emit_warning!( name_span.clone(), format!( "The tag '{dashedname}' is not matching its normalized form '{lowercase_name}' \ and is not a recognized SVG or MathML element. If you want to keep this name, \ you can use the dynamic tag `@{{\"{dashedname}\"}}` to silence this warning." ) ) } // Use lowercase for compile-time checks but preserve original casing in output let node = match &*lowercase_name { "input" => { let value = value(); let checked = checked(); quote! { ::std::convert::Into::<::yew::virtual_dom::VNode>::into( ::yew::virtual_dom::VTag::__new_input( #value, #checked, #node_ref, #key, #attributes, #listeners, ), ) } } "textarea" => { let value = value(); let defaultvalue = defaultvalue(); quote! { ::std::convert::Into::<::yew::virtual_dom::VNode>::into( ::yew::virtual_dom::VTag::__new_textarea( #value, #defaultvalue, #node_ref, #key, #attributes, #listeners, ), ) } } _ => { quote! { ::std::convert::Into::<::yew::virtual_dom::VNode>::into( ::yew::virtual_dom::VTag::__new_other( ::yew::virtual_dom::AttrValue::Static(#name), #node_ref, #key, #attributes, #listeners, #children, ), ) } } }; // the return value can be inlined without the braces when this is stable: // https://github.com/rust-lang/rust/issues/15701 quote_spanned!{ name_span => { #[allow(clippy::redundant_clone, unused_braces)] let node = #node; node } } } TagName::Expr(name) => { let vtag = Ident::new("__yew_vtag", name.span()); let expr = name.expr.as_ref().map(Group::stream); let vtag_name = Ident::new("__yew_vtag_name", expr.span()); let void_children = Ident::new("__yew_void_children", Span::mixed_site()); // handle special attribute value let handle_value_attr = props.value.as_ref().map(|prop| { let v = prop.value.optimize_literals(); quote_spanned! {v.span()=> { __yew_vtag.__macro_push_attr("value", #v); }} }); #[rustversion::since(1.88)] fn derive_debug_tag(vtag: &Ident) -> String { let span = vtag.span().unwrap(); // the file, line, column methods are stable since 1.88 format!("[{}:{}:{}] ", span.file(), span.line(), span.column()) } #[rustversion::before(1.88)] fn derive_debug_tag(_: &Ident) -> &'static str { "" } let invalid_void_tag_msg_start = derive_debug_tag(&vtag); let value = value(); let checked = checked(); let defaultvalue = defaultvalue(); // this way we get a nice error message (with the correct span) when the expression // doesn't return a valid value quote_spanned! {expr.span()=> { let mut #vtag_name = ::std::convert::Into::< ::yew::virtual_dom::AttrValue >::into(#expr); ::std::debug_assert!( #vtag_name.is_ascii(), "a dynamic tag returned a tag name containing non ASCII characters: `{}`", #vtag_name, ); #[allow(clippy::redundant_clone, unused_braces, clippy::let_and_return)] let mut #vtag = match () { _ if "input".eq_ignore_ascii_case(::std::convert::AsRef::<::std::primitive::str>::as_ref(&#vtag_name)) => { ::yew::virtual_dom::VTag::__new_input( #value, #checked, #node_ref, #key, #attributes, #listeners, ) } _ if "textarea".eq_ignore_ascii_case(::std::convert::AsRef::<::std::primitive::str>::as_ref(&#vtag_name)) => { ::yew::virtual_dom::VTag::__new_textarea( #value, #defaultvalue, #node_ref, #key, #attributes, #listeners, ) } _ => { let mut __yew_vtag = ::yew::virtual_dom::VTag::__new_other( #vtag_name, #node_ref, #key, #attributes, #listeners, #children, ); #handle_value_attr __yew_vtag } }; // These are the runtime-checks exclusive to dynamic tags. // For literal tags this is already done at compile-time. // // check void element if ::yew::virtual_dom::VTag::children(&#vtag).is_some() && !::std::matches!( ::yew::virtual_dom::VTag::children(&#vtag), ::std::option::Option::Some(::yew::virtual_dom::VNode::VList(ref #void_children)) if ::std::vec::Vec::is_empty(#void_children) ) { ::std::debug_assert!( !::std::matches!(#vtag.tag().to_ascii_lowercase().as_str(), "area" | "base" | "br" | "col" | "embed" | "hr" | "img" | "input" | "link" | "meta" | "param" | "source" | "track" | "wbr" | "textarea" ), concat!(#invalid_void_tag_msg_start, "a dynamic tag tried to create a `<{0}>` tag with children. `<{0}>` is a void element which can't have any children."), #vtag.tag(), ); } ::std::convert::Into::<::yew::virtual_dom::VNode>::into(#vtag) }} } }); } } fn wrap_attr_value<T: ToTokens>(value: T) -> TokenStream { quote_spanned! {value.span()=> ::yew::html::IntoPropValue::< ::std::option::Option< ::yew::virtual_dom::AttrValue > > ::into_prop_value(#value) } } pub struct DynamicName { at: Token![@], expr: Option<Group>, } impl Peek<'_, ()> for DynamicName { fn peek(cursor: Cursor) -> Option<((), Cursor)> { let (punct, cursor) = cursor.punct()?; if punct.as_char() != '@' { return None; } // move cursor past block if there is one let cursor = cursor .group(Delimiter::Brace) .map(|(_, _, cursor)| cursor) .unwrap_or(cursor); Some(((), cursor)) } } impl Parse for DynamicName { fn parse(input: ParseStream) -> syn::Result<Self> { let at = input.parse()?; // the expression block is optional, closing tags don't have it. let expr = input.parse().ok(); Ok(Self { at, expr }) } } impl ToTokens for DynamicName { fn to_tokens(&self, tokens: &mut TokenStream) { let Self { at, expr } = self; tokens.extend(quote! {#at #expr}); } } #[derive(PartialEq)] enum TagKey { Lit(HtmlDashedName), Expr, } pub enum TagName { Lit(HtmlDashedName), Expr(DynamicName), } impl TagName { fn get_key(&self) -> TagKey { match self { TagName::Lit(name) => TagKey::Lit(name.clone()), TagName::Expr(_) => TagKey::Expr, } } } impl Peek<'_, TagKey> for TagName { fn peek(cursor: Cursor) -> Option<(TagKey, Cursor)> { if let Some((_, cursor)) = DynamicName::peek(cursor) { Some((TagKey::Expr, cursor)) } else { HtmlDashedName::peek(cursor).map(|(name, cursor)| (TagKey::Lit(name), cursor)) } } } impl Parse for TagName { fn parse(input: ParseStream) -> syn::Result<Self> { if DynamicName::peek(input.cursor()).is_some() { DynamicName::parse(input).map(Self::Expr) } else { HtmlDashedName::parse(input).map(Self::Lit) } } } impl ToTokens for TagName { fn to_tokens(&self, tokens: &mut TokenStream) { match self { TagName::Lit(name) => name.to_tokens(tokens), TagName::Expr(name) => name.to_tokens(tokens), } } } struct HtmlElementOpen { tag: TagTokens, name: TagName, props: ElementProps, } impl HtmlElementOpen { fn is_self_closing(&self) -> bool { self.tag.div.is_some() } fn to_spanned(&self) -> impl ToTokens { self.tag.to_spanned() } } impl PeekValue<TagKey> for HtmlElementOpen { fn peek(cursor: Cursor) -> Option<TagKey> { let (punct, cursor) = cursor.punct()?; if punct.as_char() != '<' { return None; } let (tag_key, cursor) = TagName::peek(cursor)?; if let TagKey::Lit(name) = &tag_key { // Avoid parsing `<key=[...]>` as an element. It needs to be parsed as an `HtmlList`. if name.to_string() == "key" { let (punct, _) = cursor.punct()?; // ... unless it isn't followed by a '='. `<key></key>` is a valid element! if punct.as_char() == '=' { return None; } } else if !non_capitalized_ascii(&name.to_string()) { return None; } } Some(tag_key) } } impl Parse for HtmlElementOpen { fn parse(input: ParseStream) -> syn::Result<Self> { TagTokens::parse_start_content(input, |input, tag| { let name = input.parse::<TagName>()?; let mut props = input.parse::<ElementProps>()?; match &name { TagName::Lit(name) => { // Don't treat value as special for non input / textarea fields // For dynamic tags this is done at runtime! match name.to_ascii_lowercase_string().as_str() { "input" | "textarea" => {} _ => { if let Some(attr) = props.value.take() { props.attributes.push(attr); } if let Some(attr) = props.checked.take() { props.attributes.push(attr); } } } } TagName::Expr(name) => { if name.expr.is_none() { return Err(syn::Error::new_spanned( name, "this dynamic tag is missing an expression block defining its value", )); } } } Ok(Self { tag, name, props }) }) } } struct HtmlElementClose { tag: TagTokens, _name: TagName, } impl HtmlElementClose { fn to_spanned(&self) -> impl ToTokens { self.tag.to_spanned() } } impl PeekValue<TagKey> for HtmlElementClose { fn peek(cursor: Cursor) -> Option<TagKey> { let (punct, cursor) = cursor.punct()?; if punct.as_char() != '<' { return None; } let (punct, cursor) = cursor.punct()?; if punct.as_char() != '/' { return None; } let (tag_key, cursor) = TagName::peek(cursor)?; if matches!(&tag_key, TagKey::Lit(name) if !non_capitalized_ascii(&name.to_string())) { return None; } let (punct, _) = cursor.punct()?; (punct.as_char() == '>').then_some(tag_key) } } impl Parse for HtmlElementClose { fn parse(input: ParseStream) -> syn::Result<Self> { TagTokens::parse_end_content(input, |input, tag| { let name = input.parse()?; if let TagName::Expr(name) = &name { if let Some(expr) = &name.expr { return Err(syn::Error::new_spanned( expr, "dynamic closing tags must not have a body (hint: replace it with just \ `</@>`)", )); } } Ok(Self { tag, _name: name }) }) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/html_tree/tag.rs
packages/yew-macro/src/html_tree/tag.rs
use proc_macro2::{Span, TokenStream, TokenTree}; use quote::{quote, ToTokens}; use syn::parse::{ParseStream, Parser}; use syn::Token; /// Check whether two spans are equal. /// The implementation is really silly but I couldn't find another way to do it on stable. /// This check isn't required to be fully accurate so it's not the end of the world if it breaks. fn span_eq_hack(a: &Span, b: &Span) -> bool { format!("{a:?}") == format!("{b:?}") } /// Change all occurrences of span `from` to `to` in the given error. fn error_replace_span(err: syn::Error, from: Span, to: impl ToTokens) -> syn::Error { let err_it = err.into_iter().map(|err| { if span_eq_hack(&err.span(), &from) { syn::Error::new_spanned(&to, err.to_string()) } else { err } }); // SAFETY: all errors have at least one message crate::join_errors(err_it).unwrap_err() } /// Helper type for parsing HTML tags. /// The struct only stores the associated tokens, not the content of the tag. /// This is meant to mirror the design of delimiters in `syn`. pub struct TagTokens { pub lt: Token![<], pub div: Option<Token![/]>, pub gt: Token![>], } impl TagTokens { /// Parse the content of a start tag. /// The given parse function is called with a `ParseStream` /// containing only the contents of the tag and surrounding `TagTokens`. pub fn parse_start_content<T>( input: ParseStream, parse: impl FnOnce(ParseStream, Self) -> syn::Result<T>, ) -> syn::Result<T> { Self::parse_content(Self::parse_start(input)?, parse) } /// Same as `parse_start_content` but for end tags. pub fn parse_end_content<T>( input: ParseStream, parse: impl FnOnce(ParseStream, Self) -> syn::Result<T>, ) -> syn::Result<T> { Self::parse_content(Self::parse_end(input)?, parse) } fn parse_content<T>( (tag, content): (Self, TokenStream), parse: impl FnOnce(ParseStream, Self) -> syn::Result<T>, ) -> syn::Result<T> { let scope_spanned = tag.to_spanned(); let content_parser = |input: ParseStream| { parse(input, tag).map_err(|err| { // we can't modify the scope span used by `ParseStream`. It just uses the call site // by default. The scope span is used when an error can't be // attributed to a token tree (ex. when the input is empty). // We rewrite all spans to point at the tag which at least narrows down the correct // location. It's not ideal, but it'll have to do until `syn` gives // us more access. error_replace_span(err, Span::call_site(), &scope_spanned) }) }; content_parser.parse2(content) } /// Parse a start tag fn parse_start(input: ParseStream) -> syn::Result<(Self, TokenStream)> { let lt = input.parse()?; let (content, div, gt) = Self::parse_until_end(input)?; Ok((Self { lt, div, gt }, content)) } /// Parse an end tag. /// `div` will always be `Some` for end tags. fn parse_end(input: ParseStream) -> syn::Result<(Self, TokenStream)> { let lt = input.parse()?; let div = Some(input.parse()?); let (content, end_div, gt) = Self::parse_until_end(input)?; if end_div.is_some() { return Err(syn::Error::new_spanned( end_div, "unexpected `/` in this end tag", )); } Ok((Self { lt, div, gt }, content)) } fn parse_until_end( input: ParseStream, ) -> syn::Result<(TokenStream, Option<Token![/]>, Token![>])> { let mut inner_trees = Vec::new(); let mut angle_count: usize = 1; let mut div: Option<Token![/]> = None; let gt: Token![>]; loop { let next = input.parse()?; if let TokenTree::Punct(punct) = &next { match punct.as_char() { '/' => { if angle_count == 1 && input.peek(Token![>]) { div = Some(syn::token::Slash { spans: [punct.span()], }); gt = input.parse()?; break; } } '>' => { angle_count = angle_count.checked_sub(1).ok_or_else(|| { syn::Error::new_spanned( punct, "this tag close has no corresponding tag open", ) })?; if angle_count == 0 { gt = syn::token::Gt { spans: [punct.span()], }; break; } } '<' => angle_count += 1, _ => {} }; } inner_trees.push(next); } Ok((inner_trees.into_iter().collect(), div, gt)) } /// Generate tokens which can be used in `syn::Error::new_spanned` to span the entire tag. /// This is to work around the limitation of being unable to manually join spans on stable. pub fn to_spanned(&self) -> impl ToTokens { let Self { lt, gt, .. } = self; quote! {#lt #gt} } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/html_tree/html_node.rs
packages/yew-macro/src/html_tree/html_node.rs
use proc_macro2::{Span, TokenStream}; use quote::{quote, quote_spanned, ToTokens}; use syn::buffer::Cursor; use syn::parse::{Parse, ParseStream, Result}; use syn::spanned::Spanned; use syn::Lit; use super::ToNodeIterator; use crate::stringify::Stringify; use crate::PeekValue; pub enum HtmlNode { Literal(Box<Lit>), Expression(Box<TokenStream>), } impl Parse for HtmlNode { fn parse(input: ParseStream) -> Result<Self> { let node = if HtmlNode::peek(input.cursor()).is_some() { let lit = input.parse()?; match lit { Lit::ByteStr(lit) => { return Err(syn::Error::new( lit.span(), "byte-strings can't be converted to HTML text note: remove the `b` prefix or convert this to a `String`", )) } Lit::Verbatim(lit) => { return Err(syn::Error::new(lit.span(), "unsupported literal")) } _ => (), } HtmlNode::Literal(Box::new(lit)) } else { HtmlNode::Expression(Box::new(input.parse()?)) }; Ok(node) } } impl PeekValue<()> for HtmlNode { fn peek(cursor: Cursor) -> Option<()> { cursor.literal().map(|_| ()).or_else(|| { let (ident, _) = cursor.ident()?; match ident.to_string().as_str() { "true" | "false" => Some(()), _ => None, } }) } } impl ToTokens for HtmlNode { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.extend(match &self { HtmlNode::Literal(lit) => { let sr = lit.stringify(); quote_spanned! {lit.span()=> ::yew::virtual_dom::VText::new(#sr) } } HtmlNode::Expression(expr) => quote! {#expr}, }); } } impl ToNodeIterator for HtmlNode { fn to_node_iterator_stream(&self) -> Option<TokenStream> { match self { Self::Literal(_) => None, Self::Expression(expr) => { // NodeSeq turns both Into<T> and Vec<Into<T>> into IntoIterator<Item = T> Some(quote_spanned! {expr.span().resolved_at(Span::call_site())=> ::std::convert::Into::<::yew::utils::NodeSeq<_, _>>::into(#expr) }) } } } fn is_singular(&self) -> bool { match self { Self::Literal(_) => true, Self::Expression(_) => false, } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/html_tree/lint/mod.rs
packages/yew-macro/src/html_tree/lint/mod.rs
//! Lints to catch possible misuse of the `html!` macro use. At the moment these are mostly focused //! on accessibility. use proc_macro_error::emit_warning; use syn::spanned::Spanned; use super::html_element::{HtmlElement, TagName}; use super::HtmlTree; use crate::props::{ElementProps, Prop}; /// Lints HTML elements to check if they are well formed. If the element is not well-formed, then /// use `proc-macro-error` (and the `emit_warning!` macro) to produce a warning. At present, these /// are only emitted on nightly. pub trait Lint { #[cfg_attr(not(yew_lints), allow(dead_code))] fn lint(element: &HtmlElement); } /// Applies all the lints to the HTML tree. pub fn lint_all(tree: &HtmlTree) { lint::<AHrefLint>(tree); lint::<ImgAltLint>(tree); } /// Applies a specific lint to the HTML tree. pub fn lint<L>(tree: &HtmlTree) where L: Lint, { let _ = L::lint; #[cfg(not(yew_lints))] let _ = tree; #[cfg(yew_lints)] match tree { HtmlTree::List(list) => { for child in &list.children.0 { lint::<L>(child) } } HtmlTree::Element(el) => L::lint(el), _ => {} } } /// Retrieves an attribute from an element and returns a reference valid for the lifetime of the /// element (if that attribute can be found on the prop). /// /// Attribute names are lowercased before being compared (so pass "href" for `name` and not "HREF"). fn get_attribute<'a>(props: &'a ElementProps, name: &str) -> Option<&'a Prop> { props .attributes .iter() .find(|item| item.label.eq_ignore_ascii_case(name)) } /// Lints to check if anchor (`<a>`) tags have valid `href` attributes defined. pub struct AHrefLint; impl Lint for AHrefLint { fn lint(element: &HtmlElement) { if let TagName::Lit(ref tag_name) = element.name { if !tag_name.eq_ignore_ascii_case("a") { return; }; if let Some(prop) = get_attribute(&element.props, "href") { if let syn::Expr::Lit(lit) = &prop.value { if let syn::Lit::Str(href) = &lit.lit { let href_value = href.value(); match href_value.as_ref() { "#" | "javascript:void(0)" => emit_warning!( lit.span(), format!("'{href_value}' is not a suitable value for the `href` attribute. \ Without a meaningful attribute assistive technologies \ will struggle to understand your webpage. \ https://developer.mozilla.org/en-US/docs/Learn/Accessibility/HTML#onclick_events" )), _ => {} } } }; } else { emit_warning!( quote::quote! {#tag_name}.span(), "All `<a>` elements should have a `href` attribute. This makes it possible \ for assistive technologies to correctly interpret what your links point to. \ https://developer.mozilla.org/en-US/docs/Learn/Accessibility/HTML#more_on_links" ) } } } } /// Checks to make sure that images have `alt` attributes defined. pub struct ImgAltLint; impl Lint for ImgAltLint { fn lint(element: &HtmlElement) { if let super::html_element::TagName::Lit(ref tag_name) = element.name { if !tag_name.eq_ignore_ascii_case("img") { return; }; if get_attribute(&element.props, "alt").is_none() { emit_warning!( quote::quote! {#tag_name}.span(), "All `<img>` tags should have an `alt` attribute which provides a \ human-readable description " ) } } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/derive_props/field.rs
packages/yew-macro/src/derive_props/field.rs
use std::cmp::{Ord, Ordering, PartialEq, PartialOrd}; use std::convert::TryFrom; use proc_macro2::{Ident, Span}; use quote::{format_ident, quote, quote_spanned}; use syn::parse::Result; use syn::spanned::Spanned; use syn::{parse_quote, Attribute, Error, Expr, Field, GenericParam, Generics, Type, Visibility}; use super::should_preserve_attr; use crate::derive_props::generics::push_type_param; #[allow(clippy::large_enum_variant)] #[derive(PartialEq, Eq)] pub enum PropAttr { Required { wrapped_name: Ident }, PropOr(Expr), PropOrElse(Expr), PropOrDefault, } #[derive(Eq)] pub struct PropField { pub ty: Type, name: Ident, pub attr: PropAttr, extra_attrs: Vec<Attribute>, } impl PropField { /// All required property fields are wrapped in an `Option` pub fn is_required(&self) -> bool { matches!(self.attr, PropAttr::Required { .. }) } /// This check name is descriptive to help a developer realize they missed a required prop fn to_check_name(&self, props_name: &Ident) -> Ident { format_ident!("Has{}{}", props_name, self.name, span = Span::mixed_site()) } /// This check name is descriptive to help a developer realize they missed a required prop fn to_check_arg_name(&self, props_name: &Ident) -> GenericParam { let ident = format_ident!("How{}{}", props_name, self.name, span = Span::mixed_site()); GenericParam::Type(ident.into()) } /// Ident of the wrapped field name fn wrapped_name(&self) -> &Ident { match &self.attr { PropAttr::Required { wrapped_name } => wrapped_name, _ => &self.name, } } pub fn to_field_check<'a>( &'a self, props_name: &'a Ident, vis: &'a Visibility, token: &'a GenericParam, ) -> PropFieldCheck<'a> { let check_struct = self.to_check_name(props_name); let check_arg = self.to_check_arg_name(props_name); PropFieldCheck { this: self, vis, token, check_struct, check_arg, } } /// Used to transform the `PropWrapper` struct into `Properties` pub fn to_field_setter(&self) -> proc_macro2::TokenStream { let name = &self.name; let setter = match &self.attr { PropAttr::Required { wrapped_name } => { quote! { #name: ::std::option::Option::unwrap(this.wrapped.#wrapped_name), } } PropAttr::PropOr(value) => { quote_spanned! {value.span()=> #name: ::std::option::Option::unwrap_or(this.wrapped.#name, #value), } } PropAttr::PropOrElse(func) => { quote_spanned! {func.span()=> #name: ::std::option::Option::unwrap_or_else(this.wrapped.#name, #func), } } PropAttr::PropOrDefault => { quote! { #name: ::std::option::Option::unwrap_or_default(this.wrapped.#name), } } }; let extra_attrs = &self.extra_attrs; quote! { #( #extra_attrs )* #setter } } /// Wrap all required props in `Option` pub fn to_field_def(&self) -> proc_macro2::TokenStream { let ty = &self.ty; let extra_attrs = &self.extra_attrs; let wrapped_name = self.wrapped_name(); quote! { #( #extra_attrs )* #wrapped_name: ::std::option::Option<#ty>, } } /// All optional props must implement the `Default` trait pub fn to_default_setter(&self) -> proc_macro2::TokenStream { let wrapped_name = self.wrapped_name(); let extra_attrs = &self.extra_attrs; quote! { #( #extra_attrs )* #wrapped_name: ::std::option::Option::None, } } /// Each field is set using a builder method pub fn to_build_step_fn( &self, vis: &Visibility, props_name: &Ident, ) -> proc_macro2::TokenStream { let Self { name, ty, attr, .. } = self; let token_ty = Ident::new("__YewTokenTy", Span::mixed_site()); let build_fn = match attr { PropAttr::Required { wrapped_name } => { let check_struct = self.to_check_name(props_name); quote! { #[doc(hidden)] #vis fn #name<#token_ty>( &mut self, token: #token_ty, value: impl ::yew::html::IntoPropValue<#ty>, ) -> #check_struct< #token_ty > { self.wrapped.#wrapped_name = ::std::option::Option::Some(value.into_prop_value()); #check_struct ( ::std::marker::PhantomData ) } } } _ => { quote! { #[doc(hidden)] #vis fn #name<#token_ty>( &mut self, token: #token_ty, value: impl ::yew::html::IntoPropValue<#ty>, ) -> #token_ty { self.wrapped.#name = ::std::option::Option::Some(value.into_prop_value()); token } } } }; let extra_attrs = &self.extra_attrs; quote! { #( #extra_attrs )* #build_fn } } // Detect Properties 2.0 attributes fn attribute(named_field: &Field) -> Result<PropAttr> { let attr = named_field.attrs.iter().find(|attr| { attr.path().is_ident("prop_or") || attr.path().is_ident("prop_or_else") || attr.path().is_ident("prop_or_default") }); if let Some(attr) = attr { if attr.path().is_ident("prop_or") { Ok(PropAttr::PropOr(attr.parse_args()?)) } else if attr.path().is_ident("prop_or_else") { Ok(PropAttr::PropOrElse(attr.parse_args()?)) } else if attr.path().is_ident("prop_or_default") { Ok(PropAttr::PropOrDefault) } else { unreachable!() } } else { let ident = named_field.ident.as_ref().unwrap(); let wrapped_name = format_ident!("{}_wrapper", ident, span = Span::mixed_site()); Ok(PropAttr::Required { wrapped_name }) } } } pub struct PropFieldCheck<'a> { this: &'a PropField, vis: &'a Visibility, token: &'a GenericParam, check_struct: Ident, check_arg: GenericParam, } impl PropFieldCheck<'_> { pub fn to_fake_prop_decl(&self) -> proc_macro2::TokenStream { let Self { this, .. } = self; if !this.is_required() { return Default::default(); } let mut prop_check_name = this.name.clone(); prop_check_name.set_span(Span::mixed_site()); quote! { #[allow(non_camel_case_types)] pub struct #prop_check_name; } } pub fn to_stream( &self, type_generics: &mut Generics, check_args: &mut Vec<GenericParam>, prop_name_mod: &Ident, ) -> proc_macro2::TokenStream { let Self { this, vis, token, check_struct, check_arg, } = self; if !this.is_required() { return Default::default(); } let mut prop_check_name = this.name.clone(); prop_check_name.set_span(Span::mixed_site()); check_args.push(check_arg.clone()); push_type_param(type_generics, check_arg.clone()); let where_clause = type_generics.make_where_clause(); where_clause.predicates.push(parse_quote! { #token: ::yew::html::HasProp< #prop_name_mod :: #prop_check_name, #check_arg > }); quote! { #[doc(hidden)] #[allow(non_camel_case_types)] #vis struct #check_struct<How>(::std::marker::PhantomData<How>); #[automatically_derived] #[diagnostic::do_not_recommend] impl<B> ::yew::html::HasProp< #prop_name_mod :: #prop_check_name, #check_struct<B>> for #check_struct<B> {} #[automatically_derived] #[diagnostic::do_not_recommend] impl<B, P, How> ::yew::html::HasProp<P, &dyn ::yew::html::HasProp<P, How>> for #check_struct<B> where B: ::yew::html::HasProp<P, How> {} } } } impl TryFrom<Field> for PropField { type Error = Error; fn try_from(field: Field) -> Result<Self> { let extra_attrs = field .attrs .iter() .filter(|a| should_preserve_attr(a)) .cloned() .collect(); Ok(PropField { attr: Self::attribute(&field)?, extra_attrs, ty: field.ty, name: field.ident.unwrap(), }) } } impl PartialOrd for PropField { fn partial_cmp(&self, other: &PropField) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for PropField { fn cmp(&self, other: &PropField) -> Ordering { if self.name == other.name { Ordering::Equal } else if self.name == "children" { Ordering::Greater } else if other.name == "children" { Ordering::Less } else { self.name.cmp(&other.name) } } } impl PartialEq for PropField { fn eq(&self, other: &Self) -> bool { self.name == other.name } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/derive_props/builder.rs
packages/yew-macro/src/derive_props/builder.rs
//! The `PropsBuilder` constructs props in alphabetical order and enforces that required props have //! been set before allowing the build to complete. Each property has a corresponding method in the //! builder. Required property builder methods advance the builder to the next step, optional //! properties can be added or skipped with no effect on the build step. Once all of required //! properties have been set, the builder moves to the final build step which implements the //! `build()` method. use proc_macro2::{Ident, Span}; use quote::{format_ident, quote, ToTokens}; use syn::{parse_quote_spanned, Attribute, GenericParam}; use super::generics::to_arguments; use super::DerivePropsInput; use crate::derive_props::generics::push_type_param; pub struct PropsBuilder<'a> { builder_name: &'a Ident, props: &'a DerivePropsInput, wrapper_name: &'a Ident, check_all_props_name: &'a Ident, extra_attrs: &'a [Attribute], } impl ToTokens for PropsBuilder<'_> { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let Self { builder_name, props, wrapper_name, .. } = self; let DerivePropsInput { vis, generics, .. } = props; let assert_all_props = self.impl_assert_props(); let (_, ty_generics, where_clause) = generics.split_for_impl(); let builder = quote! { #[doc(hidden)] #vis struct #builder_name #generics #where_clause { wrapped: ::std::boxed::Box<#wrapper_name #ty_generics>, } #assert_all_props }; tokens.extend(builder); } } impl<'a> PropsBuilder<'_> { pub fn new( name: &'a Ident, props: &'a DerivePropsInput, wrapper_name: &'a Ident, check_all_props_name: &'a Ident, extra_attrs: &'a [Attribute], ) -> PropsBuilder<'a> { PropsBuilder { builder_name: name, props, wrapper_name, check_all_props_name, extra_attrs, } } } impl PropsBuilder<'_> { fn set_fields(&self) -> impl Iterator<Item = impl ToTokens + '_> { self.props.prop_fields.iter().map(|pf| pf.to_field_setter()) } fn impl_assert_props(&self) -> proc_macro2::TokenStream { let Self { builder_name, check_all_props_name, extra_attrs, .. } = self; let DerivePropsInput { vis, generics, props_name, prop_fields, .. } = self.props; let set_fields = self.set_fields(); let prop_fns = prop_fields .iter() .map(|pf| pf.to_build_step_fn(vis, props_name)); let (builder_impl_generics, ty_generics, builder_where_clause) = generics.split_for_impl(); let turbofish_generics = ty_generics.as_turbofish(); let generic_args = to_arguments(generics); let mut assert_impl_generics = generics.clone(); let token_arg: GenericParam = parse_quote_spanned! {Span::mixed_site()=> __YewToken }; push_type_param(&mut assert_impl_generics, token_arg.clone()); let assert_impl_generics = assert_impl_generics; let (impl_generics, _, where_clause) = assert_impl_generics.split_for_impl(); let props_mod_name = format_ident!("_{}", props_name, span = Span::mixed_site()); let mut check_impl_generics = assert_impl_generics.clone(); let mut check_args = vec![]; let mut check_props = proc_macro2::TokenStream::new(); let prop_field_decls = prop_fields .iter() .map(|pf| pf.to_field_check(props_name, vis, &token_arg)) .collect::<Vec<_>>(); let prop_name_decls = prop_field_decls.iter().map(|pf| pf.to_fake_prop_decl()); for pf in prop_field_decls.iter() { check_props.extend(pf.to_stream( &mut check_impl_generics, &mut check_args, &props_mod_name, )); } let (check_impl_generics, _, check_where_clause) = check_impl_generics.split_for_impl(); quote! { #[automatically_derived] #( #extra_attrs )* impl #builder_impl_generics #builder_name<#generic_args> #builder_where_clause { #( #prop_fns )* } #[doc(hidden)] #[allow(non_snake_case)] #vis mod #props_mod_name { #( #prop_name_decls )* } #check_props #[doc(hidden)] #vis struct #check_all_props_name<How>(::std::marker::PhantomData<How>); #[automatically_derived] #[diagnostic::do_not_recommend] impl<B, P, How> ::yew::html::HasProp<P, &dyn ::yew::html::HasProp<P, How>> for #check_all_props_name<B> where B: ::yew::html::HasProp<P, How> {} #[automatically_derived] #[diagnostic::do_not_recommend] impl #check_impl_generics ::yew::html::HasAllProps< #props_name #ty_generics , ( #( #check_args , )* ), > for #check_all_props_name< #token_arg > #check_where_clause { } #[automatically_derived] impl #impl_generics ::yew::html::Buildable< #token_arg > for #builder_name<#generic_args> #where_clause { type Output = #props_name #ty_generics; type WrappedToken = #check_all_props_name< #token_arg >; fn build(this: Self) -> Self::Output { #props_name #turbofish_generics { #(#set_fields)* } } } } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/derive_props/generics.rs
packages/yew-macro/src/derive_props/generics.rs
use proc_macro2::Ident; use syn::punctuated::Punctuated; use syn::{GenericArgument, GenericParam, Generics, Path, Token, Type, TypePath}; /// Alias for a comma-separated list of `GenericArgument` pub type GenericArguments = Punctuated<GenericArgument, Token![,]>; /// Finds the index of the first generic param with a default value or a const generic. fn first_default_or_const_param_position(generics: &Generics) -> Option<usize> { generics.params.iter().position(|param| match param { GenericParam::Type(param) => param.default.is_some(), GenericParam::Const(_) => true, _ => false, }) } /// Push a type GenericParam into a Generics pub fn push_type_param(generics: &mut Generics, type_param: GenericParam) { if let Some(idx) = first_default_or_const_param_position(generics) { generics.params.insert(idx, type_param) } else { generics.params.push(type_param) } } /// Converts `GenericParams` into `GenericArguments`. pub fn to_arguments(generics: &Generics) -> GenericArguments { let mut args: GenericArguments = Punctuated::new(); args.extend(generics.params.iter().map(|param| match param { GenericParam::Type(type_param) => new_generic_type_arg(type_param.ident.clone()), GenericParam::Lifetime(lifetime_param) => { GenericArgument::Lifetime(lifetime_param.lifetime.clone()) } GenericParam::Const(const_param) => new_generic_type_arg(const_param.ident.clone()), })); args } // Creates a `GenericArgument` from an `Ident` fn new_generic_type_arg(ident: Ident) -> GenericArgument { GenericArgument::Type(Type::Path(TypePath { path: Path::from(ident), qself: None, })) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/derive_props/wrapper.rs
packages/yew-macro/src/derive_props/wrapper.rs
use proc_macro2::Ident; use quote::{quote, ToTokens}; use syn::{Attribute, Generics}; use super::PropField; pub struct PropsWrapper<'a> { wrapper_name: &'a Ident, generics: &'a Generics, prop_fields: &'a [PropField], extra_attrs: &'a [Attribute], } impl ToTokens for PropsWrapper<'_> { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let Self { generics, wrapper_name, extra_attrs, .. } = self; let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let turbofish_generics = ty_generics.as_turbofish(); let wrapper_field_defs = self.field_defs(); let wrapper_default_setters = self.default_setters(); let wrapper = quote! { #[doc(hidden)] #(#extra_attrs)* struct #wrapper_name #generics #where_clause { #(#wrapper_field_defs)* } #[automatically_derived] impl #impl_generics ::std::default::Default for #wrapper_name #ty_generics #where_clause { fn default() -> Self { #wrapper_name #turbofish_generics { #(#wrapper_default_setters)* } } } }; wrapper.to_tokens(tokens); } } impl<'a> PropsWrapper<'a> { pub fn new( name: &'a Ident, generics: &'a Generics, prop_fields: &'a [PropField], extra_attrs: &'a [Attribute], ) -> Self { PropsWrapper { wrapper_name: name, generics, prop_fields, extra_attrs, } } fn field_defs(&self) -> impl Iterator<Item = impl ToTokens + '_> { self.prop_fields.iter().map(|pf| pf.to_field_def()) } fn default_setters(&self) -> impl Iterator<Item = impl ToTokens + '_> { self.prop_fields.iter().map(|pf| pf.to_default_setter()) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/derive_props/mod.rs
packages/yew-macro/src/derive_props/mod.rs
mod builder; mod field; mod generics; mod wrapper; use std::convert::TryInto; use builder::PropsBuilder; use field::PropField; use proc_macro2::{Ident, Span}; use quote::{format_ident, quote, ToTokens}; use syn::parse::{Parse, ParseStream, Result}; use syn::punctuated::Pair; use syn::visit_mut::VisitMut; use syn::{ AngleBracketedGenericArguments, Attribute, ConstParam, DeriveInput, GenericArgument, GenericParam, Generics, Path, PathArguments, PathSegment, Type, TypeParam, TypePath, Visibility, }; use wrapper::PropsWrapper; use self::field::PropAttr; use self::generics::to_arguments; pub struct DerivePropsInput { vis: Visibility, generics: Generics, props_name: Ident, prop_fields: Vec<PropField>, preserved_attrs: Vec<Attribute>, } /// AST visitor that replaces all occurences of the keyword `Self` with `new_self` struct Normaliser<'ast> { new_self: &'ast Ident, generics: &'ast Generics, /// `Option` for one-time initialisation new_self_full: Option<PathSegment>, } impl<'ast> Normaliser<'ast> { pub fn new(new_self: &'ast Ident, generics: &'ast Generics) -> Self { Self { new_self, generics, new_self_full: None, } } fn get_new_self(&mut self) -> PathSegment { self.new_self_full .get_or_insert_with(|| { PathSegment { ident: self.new_self.clone(), arguments: if self.generics.lt_token.is_some() { PathArguments::AngleBracketed(AngleBracketedGenericArguments { colon2_token: Some(Default::default()), lt_token: Default::default(), args: self .generics .params .pairs() .map(|pair| { let (value, punct) = pair.cloned().into_tuple(); let value = match value { GenericParam::Lifetime(param) => { GenericArgument::Lifetime(param.lifetime) } GenericParam::Type(TypeParam { ident, .. }) | GenericParam::Const(ConstParam { ident, .. }) => { GenericArgument::Type(Type::Path(TypePath { qself: None, path: ident.into(), })) } }; Pair::new(value, punct) }) .collect(), gt_token: Default::default(), }) } else { // if no generics were defined for the struct PathArguments::None }, } }) .clone() } } impl VisitMut for Normaliser<'_> { fn visit_path_mut(&mut self, path: &mut Path) { if let Some(first) = path.segments.first_mut() { if first.ident == "Self" { *first = self.get_new_self(); } syn::visit_mut::visit_path_mut(self, path) } } } /// Some attributes on the original struct are to be preserved and added to the builder struct, /// in order to avoid warnings (sometimes reported as errors) in the output. fn should_preserve_attr(attr: &Attribute) -> bool { // #[cfg(...)]: does not usually appear in macro inputs, but rust-analyzer seems to generate it // sometimes. If not preserved, results in "no-such-field" errors generating // the field setter for `build` #[allow(...)]: silences warnings from clippy, such as // dead_code etc. #[deny(...)]: enable additional warnings from clippy let path = attr.path(); path.is_ident("allow") || path.is_ident("deny") || path.is_ident("cfg") } impl Parse for DerivePropsInput { fn parse(input: ParseStream) -> Result<Self> { let input: DeriveInput = input.parse()?; let prop_fields = match input.data { syn::Data::Struct(data) => match data.fields { syn::Fields::Named(fields) => { let mut prop_fields: Vec<PropField> = fields .named .into_iter() .map(|f| f.try_into()) .collect::<Result<Vec<PropField>>>()?; // Alphabetize prop_fields.sort(); prop_fields } syn::Fields::Unit => Vec::new(), _ => unimplemented!("only structs are supported"), }, _ => unimplemented!("only structs are supported"), }; let preserved_attrs = input .attrs .iter() .filter(|a| should_preserve_attr(a)) .cloned() .collect(); Ok(Self { vis: input.vis, props_name: input.ident, generics: input.generics, prop_fields, preserved_attrs, }) } } impl DerivePropsInput { /// Replaces all occurences of `Self` in the struct with the actual name of the struct. /// Must be called before tokenising the struct. pub fn normalise(&mut self) { let mut normaliser = Normaliser::new(&self.props_name, &self.generics); for field in &mut self.prop_fields { normaliser.visit_type_mut(&mut field.ty); if let PropAttr::PropOr(expr) | PropAttr::PropOrElse(expr) = &mut field.attr { normaliser.visit_expr_mut(expr) } } } } impl ToTokens for DerivePropsInput { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let Self { generics, props_name, prop_fields, preserved_attrs, .. } = self; // The wrapper is a new struct which wraps required props in `Option` let wrapper_name = format_ident!("{}Wrapper", props_name, span = Span::mixed_site()); let wrapper = PropsWrapper::new(&wrapper_name, generics, prop_fields, preserved_attrs); tokens.extend(wrapper.into_token_stream()); // The builder will only build if all required props have been set let builder_name = format_ident!("{}Builder", props_name, span = Span::mixed_site()); let check_all_props_name = format_ident!("Check{}All", props_name, span = Span::mixed_site()); let builder = PropsBuilder::new( &builder_name, self, &wrapper_name, &check_all_props_name, preserved_attrs, ); let generic_args = to_arguments(generics); tokens.extend(builder.into_token_stream()); // The properties trait has a `builder` method which creates the props builder let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let properties = quote! { impl #impl_generics ::yew::html::Properties for #props_name #ty_generics #where_clause { type Builder = #builder_name<#generic_args>; fn builder() -> Self::Builder { #builder_name { wrapped: ::std::boxed::Box::new(::std::default::Default::default()), } } } }; tokens.extend(properties); } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/props/element.rs
packages/yew-macro/src/props/element.rs
use std::collections::HashSet; use once_cell::sync::Lazy; use syn::parse::{Parse, ParseStream}; use super::{Prop, Props, SpecialProps}; pub struct ElementProps { pub attributes: Vec<Prop>, pub listeners: Vec<Prop>, pub classes: Option<Prop>, pub booleans: Vec<Prop>, pub value: Option<Prop>, pub defaultvalue: Option<Prop>, pub checked: Option<Prop>, pub special: SpecialProps, } impl Parse for ElementProps { fn parse(input: ParseStream) -> syn::Result<Self> { let mut props = input.parse::<Props>()?; let listeners = props.drain_filter(|prop| LISTENER_SET.contains(prop.label.to_string().as_str())); // Multiple listener attributes are allowed, but no others props.check_no_duplicates()?; let booleans = props.drain_filter(|prop| BOOLEAN_SET.contains(prop.label.to_string().as_str())); let classes = props.pop("class"); let value = props.pop("value"); let checked = props.pop("checked"); let defaultvalue = props.pop("defaultvalue"); let special = props.special; Ok(Self { attributes: props.prop_list.into_vec(), classes, listeners: listeners.into_vec(), checked, booleans: booleans.into_vec(), value, special, defaultvalue, }) } } static BOOLEAN_SET: Lazy<HashSet<&'static str>> = Lazy::new(|| { [ // Living Standard // From: https://html.spec.whatwg.org/#attributes-3 // where `Value` = Boolean attribute // Note: `checked` is uniquely handled in the html! macro. "allowfullscreen", "async", "autofocus", "autoplay", "controls", "default", "defer", "disabled", "formnovalidate", "hidden", "inert", "ismap", "itemscope", "loop", "multiple", "muted", "nomodule", "novalidate", "open", "playsinline", "readonly", "required", "reversed", "selected", "truespeed", // Not-yet-standardized "webkitdirectory", ] .into() }); static LISTENER_SET: Lazy<HashSet<&'static str>> = Lazy::new(|| { [ // Living Standard // From: https://html.spec.whatwg.org/multipage/webappapis.html#globaleventhandlers "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 not in standard but added due to browser support // see issue 1896: https://github.com/yewstack/yew/issues/1896 "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", // Standard HTML Document and Element // From: https://html.spec.whatwg.org/multipage/webappapis.html#documentandelementeventhandlers "oncopy", "oncut", "onpaste", // Others // From: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers "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", ] .into() });
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/props/prop.rs
packages/yew-macro/src/props/prop.rs
use std::convert::TryFrom; use std::ops::{Deref, DerefMut}; use proc_macro2::{Spacing, Span, TokenStream, TokenTree}; use quote::{quote, quote_spanned}; use syn::parse::{Parse, ParseBuffer, ParseStream}; use syn::spanned::Spanned; use syn::token::Brace; use syn::{braced, Block, Expr, ExprBlock, ExprMacro, ExprPath, ExprRange, Stmt, Token}; use crate::html_tree::HtmlDashedName; use crate::stringify::Stringify; #[derive(Copy, Clone)] pub enum PropDirective { ApplyAsProperty(Token![~]), } pub struct Prop { pub directive: Option<PropDirective>, pub label: HtmlDashedName, /// Punctuation between `label` and `value`. pub value: Expr, } impl Parse for Prop { fn parse(input: ParseStream) -> syn::Result<Self> { let directive = input .parse::<Token![~]>() .map(PropDirective::ApplyAsProperty) .ok(); if input.peek(Brace) { Self::parse_shorthand_prop_assignment(input, directive) } else { Self::parse_prop_assignment(input, directive) } } } /// Helpers for parsing props impl Prop { /// Parse a prop using the shorthand syntax `{value}`, short for `value={value}` /// This only allows for labels with no hyphens, as it would otherwise create /// an ambiguity in the syntax fn parse_shorthand_prop_assignment( input: ParseStream, directive: Option<PropDirective>, ) -> syn::Result<Self> { let value; let _brace = braced!(value in input); let expr = value.parse::<Expr>()?; let label = if let Expr::Path(ExprPath { ref attrs, qself: None, ref path, }) = expr { if let (Some(ident), true) = (path.get_ident(), attrs.is_empty()) { Ok(HtmlDashedName::from(ident.clone())) } else { Err(syn::Error::new_spanned( path, "only simple identifiers are allowed in the shorthand property syntax", )) } } else { return Err(syn::Error::new_spanned( expr, "missing label for property value. If trying to use the shorthand property \ syntax, only identifiers may be used", )); }?; Ok(Self { label, value: expr, directive, }) } /// Parse a prop of the form `label={value}` fn parse_prop_assignment( input: ParseStream, directive: Option<PropDirective>, ) -> syn::Result<Self> { let label = input.parse::<HtmlDashedName>()?; let equals = input.parse::<Token![=]>().map_err(|_| { syn::Error::new_spanned( &label, format!( "`{label}` doesn't have a value. (hint: set the value to `true` or `false` \ for boolean attributes)" ), ) })?; if input.is_empty() { return Err(syn::Error::new_spanned( equals, "expected an expression following this equals sign", )); } let value = parse_prop_value(input)?; Ok(Self { label, value, directive, }) } } fn parse_prop_value(input: &ParseBuffer) -> syn::Result<Expr> { if input.peek(Brace) { strip_braces(input.parse()?) } else { let expr = if let Some(ExprRange { start: Some(start), .. }) = range_expression_peek(input) { // If a range expression is seen, treat the left-side expression as the value // and leave the right-side expression to be parsed as a base expression advance_until_next_dot2(input)?; *start } else { input.parse()? }; match &expr { Expr::Lit(_) => Ok(expr), ref exp => Err(syn::Error::new_spanned( &expr, format!( "the property value must be either a literal or enclosed in braces. Consider \ adding braces around your expression.: {exp:#?}" ), )), } } } fn strip_braces(block: ExprBlock) -> syn::Result<Expr> { match block { ExprBlock { block: Block { mut stmts, .. }, .. } if stmts.len() == 1 => { let stmt = stmts.remove(0); match stmt { Stmt::Expr(expr, None) => Ok(expr), Stmt::Macro(mac) => Ok(Expr::Macro(ExprMacro { attrs: vec![], mac: mac.mac, })), // See issue #2267, we want to parse macro invocations as expressions Stmt::Item(syn::Item::Macro(mac)) if mac.ident.is_none() && mac.semi_token.is_none() => { Ok(Expr::Macro(syn::ExprMacro { attrs: mac.attrs, mac: mac.mac, })) } Stmt::Expr(_, Some(semi)) => Err(syn::Error::new_spanned( semi, "only an expression may be assigned as a property. Consider removing this \ semicolon", )), _ => Err(syn::Error::new_spanned( stmt, "only an expression may be assigned as a property", )), } } block => Ok(Expr::Block(block)), } } // Without advancing cursor, returns the range expression at the current cursor position if any fn range_expression_peek(input: &ParseBuffer) -> Option<ExprRange> { match input.fork().parse::<Expr>().ok()? { Expr::Range(range) => Some(range), _ => None, } } fn advance_until_next_dot2(input: &ParseBuffer) -> syn::Result<()> { input.step(|cursor| { let mut rest = *cursor; let mut first_dot = None; while let Some((tt, next)) = rest.token_tree() { match &tt { TokenTree::Punct(punct) if punct.as_char() == '.' => { if let Some(first_dot) = first_dot { return Ok(((), first_dot)); } else { // Only consider dot as potential first if there is no spacing after it first_dot = if punct.spacing() == Spacing::Joint { Some(rest) } else { None }; } } _ => { first_dot = None; } } rest = next; } Err(cursor.error("no `..` found in expression")) }) } /// List of props sorted in alphabetical order*. /// /// \*The "children" prop always comes last to match the behaviour of the `Properties` derive macro. /// /// The list may contain multiple props with the same label. /// Use `check_no_duplicates` to ensure that there are no duplicates. pub struct PropList(Vec<Prop>); impl PropList { /// Create a new `SortedPropList` from a vector of props. /// The given `props` doesn't need to be sorted. pub fn new(props: Vec<Prop>) -> Self { Self(props) } fn position(&self, key: &str) -> Option<usize> { self.0.iter().position(|it| it.label.to_string() == key) } /// Get the first prop with the given key. pub fn get_by_label(&self, key: &str) -> Option<&Prop> { self.0.iter().find(|it| it.label.to_string() == key) } /// Pop the first prop with the given key. pub fn pop(&mut self, key: &str) -> Option<Prop> { self.position(key).map(|i| self.0.remove(i)) } /// Pop the prop with the given key and error if there are multiple ones. pub fn pop_unique(&mut self, key: &str) -> syn::Result<Option<Prop>> { let prop = self.pop(key); if prop.is_some() { if let Some(other_prop) = self.get_by_label(key) { return Err(syn::Error::new_spanned( &other_prop.label, format!("`{key}` can only be specified once"), )); } } Ok(prop) } /// Turn the props into a vector of `Prop`. pub fn into_vec(self) -> Vec<Prop> { self.0 } /// Iterate over all duplicate props in order of appearance. fn iter_duplicates(&self) -> impl Iterator<Item = &Prop> { self.0.windows(2).filter_map(|pair| { let (a, b) = (&pair[0], &pair[1]); if a.label == b.label { Some(b) } else { None } }) } /// Remove and return all props for which `filter` returns `true`. pub fn drain_filter(&mut self, filter: impl FnMut(&Prop) -> bool) -> Self { let (drained, others) = self.0.drain(..).partition(filter); self.0 = others; Self(drained) } /// Run the given function for all props and aggregate the errors. /// If there's at least one error, the result will be `Result::Err`. pub fn check_all(&self, f: impl FnMut(&Prop) -> syn::Result<()>) -> syn::Result<()> { crate::join_errors(self.0.iter().map(f).filter_map(Result::err)) } /// Return an error for all duplicate props. pub fn check_no_duplicates(&self) -> syn::Result<()> { crate::join_errors(self.iter_duplicates().map(|prop| { syn::Error::new_spanned( &prop.label, format!( "`{}` can only be specified once but is given here again", prop.label ), ) })) } } impl Parse for PropList { fn parse(input: ParseStream) -> syn::Result<Self> { let mut props: Vec<Prop> = Vec::new(); // Stop parsing props if a base expression preceded by `..` is reached while !input.is_empty() && !input.peek(Token![..]) { props.push(input.parse()?); } Ok(Self::new(props)) } } impl Deref for PropList { type Target = [Prop]; fn deref(&self) -> &Self::Target { &self.0 } } #[derive(Default)] pub struct SpecialProps { pub node_ref: Option<Prop>, pub key: Option<Prop>, } impl SpecialProps { const KEY_LABEL: &'static str = "key"; const REF_LABEL: &'static str = "ref"; fn pop_from(props: &mut PropList) -> syn::Result<Self> { let node_ref = props.pop_unique(Self::REF_LABEL)?; let key = props.pop_unique(Self::KEY_LABEL)?; Ok(Self { node_ref, key }) } fn iter(&self) -> impl Iterator<Item = &Prop> { self.node_ref.as_ref().into_iter().chain(self.key.as_ref()) } /// Run the given function for all props and aggregate the errors. /// If there's at least one error, the result will be `Result::Err`. pub fn check_all(&self, f: impl FnMut(&Prop) -> syn::Result<()>) -> syn::Result<()> { crate::join_errors(self.iter().map(f).filter_map(Result::err)) } pub fn wrap_node_ref_attr(&self) -> TokenStream { self.node_ref .as_ref() .map(|attr| { let value = &attr.value; quote_spanned! {value.span().resolved_at(Span::call_site())=> ::yew::html::IntoPropValue::<::yew::html::NodeRef> ::into_prop_value(#value) } }) .unwrap_or(quote! { ::std::default::Default::default() }) } pub fn wrap_key_attr(&self) -> TokenStream { self.key .as_ref() .map(|attr| { let value = attr.value.optimize_literals(); quote_spanned! {value.span().resolved_at(Span::call_site())=> ::std::option::Option::Some( ::std::convert::Into::<::yew::virtual_dom::Key>::into(#value) ) } }) .unwrap_or(quote! { ::std::option::Option::None }) } } pub struct Props { pub special: SpecialProps, pub prop_list: PropList, } impl Parse for Props { fn parse(input: ParseStream) -> syn::Result<Self> { Self::try_from(input.parse::<PropList>()?) } } impl Deref for Props { type Target = PropList; fn deref(&self) -> &Self::Target { &self.prop_list } } impl DerefMut for Props { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.prop_list } } impl TryFrom<PropList> for Props { type Error = syn::Error; fn try_from(mut prop_list: PropList) -> Result<Self, Self::Error> { let special = SpecialProps::pop_from(&mut prop_list)?; Ok(Self { special, prop_list }) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/props/mod.rs
packages/yew-macro/src/props/mod.rs
mod component; mod element; mod prop; mod prop_macro; pub use component::*; pub use element::*; pub use prop::*; pub use prop_macro::PropsMacroInput; const CHILDREN_LABEL: &str = "children";
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/props/prop_macro.rs
packages/yew-macro/src/props/prop_macro.rs
use std::convert::TryInto; use proc_macro2::TokenStream; use quote::{quote_spanned, ToTokens}; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::token::Brace; use syn::{Expr, Token, TypePath}; use super::{ComponentProps, Prop, PropList, Props}; use crate::html_tree::HtmlDashedName; /// Pop from `Punctuated` without leaving it in a state where it has trailing punctuation. fn pop_last_punctuated<T, P>(punctuated: &mut Punctuated<T, P>) -> Option<T> { let value = punctuated.pop().map(|pair| pair.into_value()); // remove the 2nd last value and push it right back to remove the trailing punctuation if let Some(pair) = punctuated.pop() { punctuated.push_value(pair.into_value()); } value } /// Check if the given type path looks like an associated `Properties` type. fn is_associated_properties(ty: &TypePath) -> bool { let mut segments_it = ty.path.segments.iter(); if let Some(seg) = segments_it.next_back() { // if the last segment is `Properties` ... if seg.ident == "Properties" { if let Some(seg) = segments_it.next_back() { // ... and we can be reasonably sure that the previous segment is a component ... if !crate::non_capitalized_ascii(&seg.ident.to_string()) { // ... then we assume that this is an associated type like // `Component::Properties` return true; } } } } false } struct PropValue { label: HtmlDashedName, value: Expr, } impl Parse for PropValue { fn parse(input: ParseStream) -> syn::Result<Self> { let label = input.parse()?; let value = if input.peek(Token![:]) { let _colon_token: Token![:] = input.parse()?; input.parse()? } else { syn::parse_quote!(#label) }; Ok(Self { label, value }) } } impl From<PropValue> for Prop { fn from(prop_value: PropValue) -> Prop { let PropValue { label, value } = prop_value; Prop { label, value, directive: None, } } } struct PropsExpr { ty: TypePath, _brace_token: Brace, fields: Punctuated<PropValue, Token![,]>, } impl Parse for PropsExpr { fn parse(input: ParseStream) -> syn::Result<Self> { let mut ty: TypePath = input.parse()?; // if the type isn't already qualified (`<x as y>`) and it's an associated type // (`MyComp::Properties`) ... if ty.qself.is_none() && is_associated_properties(&ty) { pop_last_punctuated(&mut ty.path.segments); // .. transform it into a "qualified-self" type ty = syn::parse2(quote_spanned! {ty.span()=> <#ty as ::yew::html::Component>::Properties })?; } let content; let brace_token = syn::braced!(content in input); let fields = content.parse_terminated(PropValue::parse, Token![,])?; Ok(Self { ty, _brace_token: brace_token, fields, }) } } pub struct PropsMacroInput { ty: TypePath, props: ComponentProps, } impl Parse for PropsMacroInput { fn parse(input: ParseStream) -> syn::Result<Self> { let PropsExpr { ty, fields, .. } = input.parse()?; let prop_list = PropList::new(fields.into_iter().map(Into::into).collect()); let props: Props = prop_list.try_into()?; props.special.check_all(|prop| { let label = &prop.label; Err(syn::Error::new_spanned( label, "special props cannot be specified in the `props!` macro", )) })?; Ok(Self { ty, props: props.try_into()?, }) } } impl ToTokens for PropsMacroInput { fn to_tokens(&self, tokens: &mut TokenStream) { let Self { ty, props } = self; tokens.extend(props.build_properties_tokens(ty, None::<TokenStream>)) } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/props/component.rs
packages/yew-macro/src/props/component.rs
use std::convert::TryFrom; use proc_macro2::{Ident, Span, TokenStream}; use quote::{quote, quote_spanned, ToTokens}; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; use syn::token::DotDot; use syn::Expr; use super::{Prop, Props, SpecialProps, CHILDREN_LABEL}; struct BaseExpr { pub dot_dot: DotDot, pub expr: Expr, } impl Parse for BaseExpr { fn parse(input: ParseStream) -> syn::Result<Self> { let dot_dot = input.parse()?; let expr = input.parse().map_err(|expr_error| { let mut error = syn::Error::new_spanned(dot_dot, "expected base props expression after `..`"); error.combine(expr_error); error })?; Ok(Self { dot_dot, expr }) } } impl ToTokens for BaseExpr { fn to_tokens(&self, tokens: &mut TokenStream) { let BaseExpr { dot_dot, expr } = self; tokens.extend(quote! { #dot_dot #expr }); } } pub struct ComponentProps { pub props: Props, base_expr: Option<Expr>, } impl ComponentProps { /// Get the special props supported by both variants pub fn special(&self) -> &SpecialProps { &self.props.special } // check if the `children` prop is given explicitly pub fn children(&self) -> Option<&Prop> { self.props.get_by_label(CHILDREN_LABEL) } fn prop_validation_tokens(&self, props_ty: impl ToTokens, has_children: bool) -> TokenStream { let props_ident = Ident::new("__yew_props", props_ty.span()); let check_children = if has_children { Some(quote_spanned! {props_ty.span()=> let _ = #props_ident.children; }) } else { None }; let check_props: TokenStream = self .props .iter() .map(|Prop { label, .. }| { quote_spanned! {Span::call_site().located_at(label.span())=> let _ = &#props_ident.#label; } }) .collect(); quote_spanned! {props_ty.span()=> #[allow(clippy::no_effect)] if false { let _ = |#props_ident: #props_ty| { #check_children #check_props }; }; } } pub fn build_properties_tokens<CR: ToTokens>( &self, props_ty: impl ToTokens, children_renderer: Option<CR>, ) -> TokenStream { let has_children = children_renderer.is_some(); let validate_props = self.prop_validation_tokens(&props_ty, has_children); let build_props = match &self.base_expr { None => { let builder_ident = Ident::new("__yew_props", props_ty.span()); let token_ident = Ident::new( "__yew_required_props_token", props_ty.span().resolved_at(Span::mixed_site()), ); let init_builder = quote_spanned! {props_ty.span()=> let mut #builder_ident = <#props_ty as ::yew::html::Properties>::builder(); let #token_ident = ::yew::html::AssertAllProps; }; let set_props = self.props.iter().map(|Prop { label, value, .. }| { quote_spanned! {value.span()=> let #token_ident = #builder_ident.#label(#token_ident, #value); } }); let set_children = children_renderer.map(|children| { quote_spanned! {props_ty.span()=> let #token_ident = #builder_ident.children(#token_ident, #children); } }); let build_builder = quote_spanned! {props_ty.span()=> ::yew::html::Buildable::prepare_build(#builder_ident, &#token_ident).build() }; quote! { #init_builder #( #set_props )* #set_children #build_builder } } // Builder pattern is unnecessary in this case, since the base expression guarantees // all values are initialized Some(expr) => { let ident = Ident::new("__yew_props", props_ty.span()); let set_props = self.props.iter().map(|Prop { label, value, .. }| { quote_spanned! {value.span().resolved_at(Span::call_site())=> #ident.#label = ::yew::html::IntoPropValue::into_prop_value(#value); } }); let set_children = children_renderer.map(|children| { quote_spanned! {props_ty.span()=> #ident.children = ::yew::html::IntoPropValue::into_prop_value(#children); } }); let init_base = quote_spanned! {expr.span().resolved_at(Span::call_site())=> let mut #ident: #props_ty = #expr; }; quote! { #init_base #(#set_props)* #set_children #ident } } }; quote! { { #validate_props #build_props } } } } impl Parse for ComponentProps { fn parse(input: ParseStream) -> syn::Result<Self> { let props = validate(input.parse()?)?; let base_expr = if input.is_empty() { None } else { Some(input.parse::<BaseExpr>()?) }; if input.is_empty() { let base_expr = base_expr.map(|base| base.expr); Ok(Self { props, base_expr }) } else { Err(syn::Error::new_spanned( base_expr, "base props expression must appear last in list of props", )) } } } impl TryFrom<Props> for ComponentProps { type Error = syn::Error; fn try_from(props: Props) -> Result<Self, Self::Error> { Ok(Self { props: validate(props)?, base_expr: None, }) } } fn validate(props: Props) -> Result<Props, syn::Error> { props.check_no_duplicates()?; props.check_all(|prop| { if !prop.label.extended.is_empty() { Err(syn::Error::new_spanned( &prop.label, "expected a valid Rust identifier", )) } else { Ok(()) } })?; Ok(props) }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/src/classes/mod.rs
packages/yew-macro/src/classes/mod.rs
use proc_macro2::TokenStream; use quote::{quote, quote_spanned, ToTokens}; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{Expr, ExprLit, Lit, LitStr, Token}; /// List of HTML classes. pub struct Classes(Punctuated<ClassExpr, Token![,]>); impl Parse for Classes { fn parse(input: ParseStream) -> syn::Result<Self> { input .parse_terminated(ClassExpr::parse, Token![,]) .map(Self) } } impl ToTokens for Classes { fn to_tokens(&self, tokens: &mut TokenStream) { let n = self.0.len(); let push_classes = self.0.iter().map(|x| match x { ClassExpr::Lit(class) => quote! { unsafe { __yew_classes.unchecked_push(#class) }; }, ClassExpr::Expr(class) => quote_spanned! {class.span()=> __yew_classes.push(#class); }, }); tokens.extend(quote! { { let mut __yew_classes = ::yew::html::Classes::with_capacity(#n); #(#push_classes)* __yew_classes } }); } } enum ClassExpr { Lit(LitStr), Expr(Box<Expr>), } impl Parse for ClassExpr { fn parse(input: ParseStream) -> syn::Result<Self> { match input.parse()? { Expr::Lit(ExprLit { lit: Lit::Str(lit_str), .. }) => { let value = lit_str.value(); let classes = value.split_whitespace().collect::<Vec<_>>(); if classes.len() > 1 { let fix = classes .into_iter() .map(|class| format!("\"{class}\"")) .collect::<Vec<_>>() .join(", "); let msg = format!( "string literals must not contain more than one class (hint: use `{fix}`)" ); Err(syn::Error::new(lit_str.span(), msg)) } else { Ok(Self::Lit(lit_str)) } } expr => Ok(Self::Expr(Box::new(expr))), } } }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/derive_props_test.rs
packages/yew-macro/tests/derive_props_test.rs
#[allow(dead_code)] #[rustversion::attr(stable(1.84.0), test)] fn derive_props() { let t = trybuild::TestCases::new(); t.pass("tests/derive_props/pass.rs"); t.compile_fail("tests/derive_props/fail.rs"); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/props_macro_test.rs
packages/yew-macro/tests/props_macro_test.rs
#[allow(dead_code)] #[rustversion::attr(stable(1.84.0), test)] fn props_macro() { let t = trybuild::TestCases::new(); t.pass("tests/props_macro/*-pass.rs"); t.compile_fail("tests/props_macro/*-fail.rs"); } #[test] fn props_order() { #[derive(yew::Properties, PartialEq)] struct Props { first: usize, second: usize, last: usize, } let mut g = 1..=3; let props = yew::props!(Props { first: g.next().unwrap(), second: g.next().unwrap(), last: g.next().unwrap() }); assert_eq!(props.first, 1); assert_eq!(props.second, 2); assert_eq!(props.last, 3); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_lints_test.rs
packages/yew-macro/tests/html_lints_test.rs
#[allow(dead_code)] #[cfg(yew_lints)] #[rustversion::attr(nightly, test)] fn test_html_lints() { let t = trybuild::TestCases::new(); t.compile_fail("tests/html_lints/fail.rs"); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/classes_macro_test.rs
packages/yew-macro/tests/classes_macro_test.rs
#[allow(dead_code)] #[rustversion::attr(stable(1.84.0), test)] fn classes_macro() { let t = trybuild::TestCases::new(); t.pass("tests/classes_macro/*-pass.rs"); t.compile_fail("tests/classes_macro/*-fail.rs"); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/hook_macro_test.rs
packages/yew-macro/tests/hook_macro_test.rs
#[allow(dead_code)] #[rustversion::attr(stable(1.84.0), test)] fn tests() { let t = trybuild::TestCases::new(); t.pass("tests/hook_macro/*-pass.rs"); t.compile_fail("tests/hook_macro/*-fail.rs"); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_attr_test.rs
packages/yew-macro/tests/function_attr_test.rs
#[allow(dead_code)] #[rustversion::attr(stable(1.84.0), test)] fn tests() { let t = trybuild::TestCases::new(); t.pass("tests/function_component_attr/*-pass.rs"); t.compile_fail("tests/function_component_attr/*-fail.rs"); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/html_macro_test.rs
packages/yew-macro/tests/html_macro_test.rs
use yew::{html, html_nested}; #[allow(dead_code)] #[rustversion::attr(stable(1.84.0), test)] fn html_macro() { let t = trybuild::TestCases::new(); t.pass("tests/html_macro/*-pass.rs"); t.compile_fail("tests/html_macro/*-fail.rs"); } #[test] #[should_panic( expected = "a dynamic tag tried to create a `<br>` tag with children. `<br>` is a void \ element which can't have any children." )] fn dynamic_tags_catch_void_elements() { let _ = html! { <@{"br"}> <span>{ "No children allowed" }</span> </@> }; } #[test] #[should_panic(expected = "a dynamic tag returned a tag name containing non ASCII characters: `❤`")] fn dynamic_tags_catch_non_ascii() { let _ = html! { <@{"❤"}/> }; } /// test that compilation on html elements pass /// fixes: https://github.com/yewstack/yew/issues/2268 #[test] fn html_nested_macro_on_html_element() { let _node = html_nested! { <feBlend/> }; let _node = html_nested! { <input/> }; }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/hook_attr_test.rs
packages/yew-macro/tests/hook_attr_test.rs
#[allow(dead_code)] #[rustversion::attr(stable(1.84.0), test)] fn tests() { let t = trybuild::TestCases::new(); t.pass("tests/hook_attr/*-pass.rs"); t.compile_fail("tests/hook_attr/*-fail.rs"); }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/props_macro/props-pass.rs
packages/yew-macro/tests/props_macro/props-pass.rs
// Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; #[derive(::std::clone::Clone, ::yew::Properties, ::std::cmp::PartialEq)] struct Props { a: ::std::primitive::usize, #[prop_or_default] b: ::std::primitive::usize, } fn pass_simple_props() { ::yew::props!(Props { a: 5 }); let (a, b) = (3, 5); ::yew::props!(Props { a, b }); } #[derive(::yew::Properties, ::std::cmp::PartialEq)] pub struct RawIdentProps { r#true: ::std::primitive::usize, #[prop_or_default] r#pointless_raw_name: ::std::primitive::usize, } #[derive(::yew::Properties)] pub struct SelfRefProps<'a, T> { x: ::std::boxed::Box<T>, y: ::std::boxed::Box<Self>, z: &'a Self, a: ::std::marker::PhantomData<(&'a Self, Self)>, b: ::std::marker::PhantomData<::std::boxed::Box<Self>>, c: fn(&Self) -> Self, } impl<T> ::std::cmp::PartialEq for SelfRefProps<'_, T> { fn eq(&self, _: &Self) -> ::std::primitive::bool { ::std::unimplemented!() } } fn pass_raw_idents() { ::yew::props!(RawIdentProps { r#true: 5 }); let (r#true, r#pointless_raw_name) = (3, 5); ::yew::props!(RawIdentProps { r#true, r#pointless_raw_name }); } #[derive(::std::clone::Clone, ::yew::Properties, ::std::cmp::PartialEq)] struct BuildProp { build: ::std::primitive::usize, } fn pass_build_prop() { ::yew::props!(BuildProp { build: 5 }); } #[derive(::yew::Properties, ::std::cmp::PartialEq)] struct GenericProps<T: ::std::cmp::PartialEq> { item: T, } fn pass_generic_props<T: ::std::cmp::PartialEq>(the_item: T) { ::yew::props!(GenericProps<T> { item: the_item }); } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/props_macro/props-fail.rs
packages/yew-macro/tests/props_macro/props-fail.rs
use yew::prelude::*; #[derive(Clone, Properties, PartialEq)] struct Props { a: usize, } fn compile_fail() { yew::props!(Props { ref: NodeRef::default(), key: "key" }); yew::props!(Props { a: 5, fail: 10 }); let props = yew::props!(Props { a: 1 }); yew::props!(Props { a: 1, ..props }); yew::props!(Props { does_not_exist }); } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/props_macro/resolve-prop-pass.rs
packages/yew-macro/tests/props_macro/resolve-prop-pass.rs
// Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; #[derive(::std::clone::Clone, ::yew::Properties, ::std::cmp::PartialEq)] struct Props { n: ::std::primitive::i32, } struct MyComp; impl ::yew::Component for MyComp { type Message = (); type Properties = Props; fn create(_ctx: &::yew::Context<Self>) -> Self { ::std::unimplemented!() } fn view(&self, _ctx: &::yew::Context<Self>) -> ::yew::Html { ::std::unimplemented!() } } fn compile_pass() { ::yew::props!(Props { n: 1 }); ::yew::props!(self::Props { n: 1 }); ::yew::props!(MyComp::Properties { n: 2 }); ::yew::props!(self::MyComp::Properties { n: 3 }); ::yew::props!(<MyComp as ::yew::Component>::Properties { n: 5}); } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/props_macro/resolve-prop-fail.rs
packages/yew-macro/tests/props_macro/resolve-prop-fail.rs
use yew::prelude::*; #[derive(Clone, Properties)] struct Props {} struct MyComp; impl Component for MyComp { type Message = (); type Properties = Props; fn create(_ctx: &Context<Self>) -> Self { unimplemented!() } fn view(&self, _ctx: &Context<Self>) -> Html { unimplemented!() } } trait NotAComponent { type Properties; } struct MyNotAComponent; impl NotAComponent for MyNotAComponent { type Properties = (); } fn compile_fail() { yew::props!(Vec<_> {}); yew::props!(MyComp {}); yew::props!(MyNotAComponent::Properties {}); } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/extern-fail.rs
packages/yew-macro/tests/function_component_attr/extern-fail.rs
use yew::prelude::*; #[derive(Clone, Properties, PartialEq)] struct Props { a: usize, } #[component(Comp)] extern "C" fn comp(props: &Props) -> Html { html! { <p> { props.a } </p> } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/const-fail.rs
packages/yew-macro/tests/function_component_attr/const-fail.rs
use yew::prelude::*; #[derive(Clone, Properties, PartialEq)] struct Props { a: usize, } #[component(Comp)] const fn comp(props: &Props) -> Html { html! { <p> { props.a } </p> } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/generic-props-fail.rs
packages/yew-macro/tests/function_component_attr/generic-props-fail.rs
use yew::prelude::*; #[derive(Clone, Properties, PartialEq)] struct Props { a: usize, } #[component(Comp)] fn comp<P>(_props: &P) -> Html where P: Properties + PartialEq, { html! { <p></p> } } struct MissingTypeBounds; fn compile_fail() { // missing prop 'a' html! { <Comp<Props> /> }; // invalid type parameter html! { <Comp<INVALID> /> }; // parameter doesn't match bounds html! { <Comp<MissingTypeBounds> /> }; // missing type param html! { <Comp /> }; } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/no-name-default-pass.rs
packages/yew-macro/tests/function_component_attr/no-name-default-pass.rs
#[derive(::yew::prelude::Properties, ::std::prelude::rust_2021::PartialEq,)] struct Props { a: usize, } #[::yew::prelude::component] fn Comp(props: &Props) -> ::yew::prelude::Html { ::yew::prelude::html! { <p> { props.a } </p> } } fn main() { let _ = ::yew::prelude::html! { <Comp a={0} /> }; }
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/without-props-pass.rs
packages/yew-macro/tests/function_component_attr/without-props-pass.rs
#![no_implicit_prelude] // Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; #[::yew::component(Comp)] fn comp() -> ::yew::Html { ::yew::html! { <p> { "Test" } </p> } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/mut-ref-props-param-fail.rs
packages/yew-macro/tests/function_component_attr/mut-ref-props-param-fail.rs
use yew::prelude::*; #[derive(Clone, Properties, PartialEq)] struct Props { a: usize, } #[component(Comp)] fn comp(props: &mut Props) -> Html { html! { <p> { props.a } </p> } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/with-defaulted-type-param-pass.rs
packages/yew-macro/tests/function_component_attr/with-defaulted-type-param-pass.rs
#[derive(::yew::prelude::Properties, ::std::fmt::Debug)] pub struct CompProps<A> { #[prop_or_default] _phantom: ::std::marker::PhantomData<A>, } impl<A> ::std::cmp::PartialEq for CompProps<A> { fn eq(&self, _rhs: &Self) -> bool { true } } #[::yew::prelude::component(Comp)] pub fn comp<A = ()>(_props: &CompProps<A>) -> ::yew::prelude::Html { ::std::todo!() } #[::yew::prelude::component(App)] pub fn app() -> ::yew::prelude::Html { ::yew::prelude::html! { <Comp /> } // No generics here. } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/multiple-param-fail.rs
packages/yew-macro/tests/function_component_attr/multiple-param-fail.rs
use yew::prelude::*; #[derive(Clone, Properties, PartialEq)] struct Props { a: usize, } #[component(Comp)] fn comp(props: &Props, invalid: String) -> Html { html! { <p> { props.a } { invalid } </p> } } #[component(Comp)] fn comp3(props: &Props, invalid: String, another_invalid: u32) -> Html { html! { <p> { props.a } { invalid } { another_invalid } </p> } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/with-props-pass.rs
packages/yew-macro/tests/function_component_attr/with-props-pass.rs
// Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; #[derive(Clone, ::yew::Properties, PartialEq)] struct Props { a: ::std::primitive::usize, } #[::yew::component(Comp)] fn comp(props: &Props) -> ::yew::Html { ::yew::html! { <p> { props.a } </p> } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/generic-lifetime-fail.rs
packages/yew-macro/tests/function_component_attr/generic-lifetime-fail.rs
use yew::prelude::*; #[derive(Clone, Properties, PartialEq)] struct Props { a: usize, } #[component(Comp)] fn comp<'a>(props: &'a Props) -> Html { html! { <p> { props.a } </p> } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/generic-pass.rs
packages/yew-macro/tests/function_component_attr/generic-pass.rs
// Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; #[derive(::std::clone::Clone, ::yew::Properties, ::std::cmp::PartialEq)] struct Props { a: ::std::primitive::usize, } #[::yew::component(Comp)] fn comp<P>(_props: &P) -> ::yew::Html where P: ::yew::Properties + ::std::cmp::PartialEq, { ::yew::html! { <p></p> } } #[::yew::component(Comp1)] fn comp1<T1, T2>(_props: &()) -> ::yew::Html { ::yew::html! { <p></p> } } #[::yew::component(ConstGenerics)] fn const_generics<const N: ::std::primitive::i32>() -> ::yew::Html { ::yew::html! { <div> { N } </div> } } fn compile_pass() { let _ = ::yew::html! { <Comp<Props> a=10 /> }; let _ = ::yew::html! { <Comp1<::std::primitive::usize, ::std::primitive::usize> /> }; let _ = ::yew::html! { <ConstGenerics<10> /> }; } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/bad-return-type-fail.rs
packages/yew-macro/tests/function_component_attr/bad-return-type-fail.rs
use yew::prelude::*; #[derive(Clone, Properties, PartialEq)] struct Props { a: usize, } #[component(Comp1)] fn comp_1(_props: &Props) {} #[component(Comp)] fn comp(_props: &Props) -> u32 { 1 } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/with-receiver-fail.rs
packages/yew-macro/tests/function_component_attr/with-receiver-fail.rs
use yew::prelude::*; #[derive(Clone, Properties, PartialEq)] struct Props { a: usize, } struct Test; impl Test { #[component(Comp)] fn comp(self, props: &Props) -> Html { html! { <p> { props.a } </p> } } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/hook_location-fail.rs
packages/yew-macro/tests/function_component_attr/hook_location-fail.rs
use yew::prelude::*; #[derive(Debug, PartialEq, Clone)] struct Ctx; #[component] fn Comp() -> Html { if let Some(_m) = use_context::<Ctx>() { use_context::<Ctx>().unwrap(); todo!() } let _ = || { use_context::<Ctx>().unwrap(); todo!() }; for _ in 0..10 { use_context::<Ctx>().unwrap(); } while let Some(_m) = use_context::<Ctx>() { use_context::<Ctx>().unwrap(); } match use_context::<Ctx>() { Some(_) => use_context::<Ctx>(), None => { todo!() } } loop { use_context::<Ctx>().unwrap(); todo!() } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/hook_location-pass.rs
packages/yew-macro/tests/function_component_attr/hook_location-pass.rs
#[derive( ::std::prelude::rust_2021::Debug, ::std::prelude::rust_2021::PartialEq, ::std::prelude::rust_2021::Clone, )] struct Ctx; #[::yew::prelude::component] fn Comp() -> ::yew::prelude::Html { ::yew::prelude::use_context::<Ctx>().unwrap(); if let ::std::prelude::rust_2021::Some(_m) = ::yew::prelude::use_context::<Ctx>() { ::std::todo!() } let _ctx = { ::yew::prelude::use_context::<Ctx>() }; match ::yew::prelude::use_context::<Ctx>() { ::std::prelude::rust_2021::Some(_) => { ::std::todo!() } ::std::prelude::rust_2021::None => { ::std::todo!() } } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/applied-to-non-fn-fail.rs
packages/yew-macro/tests/function_component_attr/applied-to-non-fn-fail.rs
use yew::prelude::*; #[derive(Clone, Properties, PartialEq)] struct Props { a: usize, } #[component(Comp)] struct Test; fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/async-fail.rs
packages/yew-macro/tests/function_component_attr/async-fail.rs
use yew::prelude::*; #[derive(Clone, Properties, PartialEq)] struct Props { a: usize, } #[component(Comp)] async fn comp(props: &Props) -> Html { html! { <p> { props.a } </p> } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/bad-props-param-fail.rs
packages/yew-macro/tests/function_component_attr/bad-props-param-fail.rs
use yew::prelude::*; #[derive(Clone, Properties, PartialEq)] struct Props { a: usize, } #[component(Comp)] fn comp(props: Props) -> Html { html! { <p> { props.a } </p> } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/bad-name-fail.rs
packages/yew-macro/tests/function_component_attr/bad-name-fail.rs
use yew::prelude::*; #[derive(Clone, Properties, PartialEq)] struct Props { a: usize, } #[component(let)] fn comp(props: &Props) -> Html { html! { <p> { props.a } </p> } } #[component(x, y, z)] fn comp_2(props: &Props) -> Html { html! { <p> { props.a } </p> } } #[component(124)] fn comp_3(props: &Props) -> Html { html! { <p> { props.a } </p> } } #[component(component)] fn component(props: &Props) -> Html { html! { <p> { props.a } </p> } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/function_component_attr/lifetime-props-param-fail.rs
packages/yew-macro/tests/function_component_attr/lifetime-props-param-fail.rs
use yew::prelude::*; #[derive(Clone, Properties, PartialEq)] struct Props { a: usize, } #[component(Comp)] fn comp(props: &'static Props) -> Html { html! { <p> { props.a } </p> } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/hook_attr/hook_macro-fail.rs
packages/yew-macro/tests/hook_attr/hook_macro-fail.rs
use yew::prelude::*; #[hook] pub fn use_some_macro_inner(val: &str) -> String { use_state(|| val.to_owned()).to_string() } macro_rules! use_some_macro { () => { use_some_macro_inner("default str") }; ($t: tt) => { use_some_macro_inner($t) }; } #[component] fn Comp() -> Html { let content = if true { use_some_macro!() } else { use_some_macro!("b") }; html! { <div>{content}</div> } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/hook_attr/hook-lifetime-pass.rs
packages/yew-macro/tests/hook_attr/hook-lifetime-pass.rs
#![no_implicit_prelude] #[::yew::functional::hook] fn use_as_is<'a>(input: &'a ()) -> &'a () { input } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/hook_attr/hook-const-generic-pass.rs
packages/yew-macro/tests/hook_attr/hook-const-generic-pass.rs
#![no_implicit_prelude] #[::yew::prelude::hook] fn use_a_const<const N: u32>() -> u32 { N } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/hook_attr/hook-call-generics-pass.rs
packages/yew-macro/tests/hook_attr/hook-call-generics-pass.rs
use yew::prelude::*; #[hook] fn use_reducer_default_action<T>() -> T::Action where T: Reducible + 'static, T::Action: Default + 'static, { T::Action::default() } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/hook_attr/hook-dynamic-dispatch-pass.rs
packages/yew-macro/tests/hook_attr/hook-dynamic-dispatch-pass.rs
#![no_implicit_prelude] #[::yew::prelude::hook] fn use_boxed_fn(_f: ::std::boxed::Box<dyn::std::ops::Fn(&str) -> &str>) { ::std::todo!() } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/hook_attr/hook-return-ref-pass.rs
packages/yew-macro/tests/hook_attr/hook-return-ref-pass.rs
#![no_implicit_prelude] #[::yew::prelude::hook] fn use_str_ref(f: &::std::primitive::str) -> &::std::primitive::str { f } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/hook_attr/hook_location-fail.rs
packages/yew-macro/tests/hook_attr/hook_location-fail.rs
use yew::prelude::*; #[derive(Debug, PartialEq, Clone)] struct Ctx; #[hook] fn use_some_html() -> Html { if let Some(_m) = use_context::<Ctx>() { use_context::<Ctx>().unwrap(); todo!() } let _ = || { use_context::<Ctx>().unwrap(); todo!() }; for _ in 0..10 { use_context::<Ctx>().unwrap(); } while let Some(_m) = use_context::<Ctx>() { use_context::<Ctx>().unwrap(); } match use_context::<Ctx>() { Some(_) => use_context::<Ctx>(), None => { todo!() } } loop { use_context::<Ctx>().unwrap(); todo!() } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/hook_attr/hook_location-pass.rs
packages/yew-macro/tests/hook_attr/hook_location-pass.rs
#![no_implicit_prelude] #[derive( ::std::prelude::rust_2021::Debug, ::std::prelude::rust_2021::PartialEq, ::std::prelude::rust_2021::Clone, )] struct Ctx; #[::yew::prelude::hook] fn use_some_html() -> ::yew::prelude::Html { ::yew::prelude::use_context::<Ctx>().unwrap(); if let ::std::prelude::rust_2021::Some(_m) = ::yew::prelude::use_context::<Ctx>() { ::std::todo!() } let _ctx = { ::yew::prelude::use_context::<Ctx>() }; match ::yew::prelude::use_context::<Ctx>() { ::std::prelude::rust_2021::Some(_) => { ::std::todo!() } ::std::prelude::rust_2021::None => { ::std::todo!() } } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/hook_attr/hook-return-impl-trait-pass.rs
packages/yew-macro/tests/hook_attr/hook-return-impl-trait-pass.rs
#![no_implicit_prelude] #[::yew::prelude::hook] fn use_deref_as_u32() -> impl ::std::ops::Deref<Target = ::std::primitive::u32> { ::std::rc::Rc::new(0) } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/hook_attr/hook-impl-trait-pass.rs
packages/yew-macro/tests/hook_attr/hook-impl-trait-pass.rs
// we need to re-test the macro hygiene here as it uses a different implementation for impl traits. #![no_implicit_prelude] #[::yew::prelude::hook] fn use_some_string(a: impl ::std::convert::Into<::std::string::String>) -> ::std::string::String { a.into() } #[::yew::prelude::hook] fn use_impl_fn<T, U>(_callback: impl ::std::prelude::rust_2021::Fn(&T) -> &U) {} fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/hook_attr/hook-trait-item-pass.rs
packages/yew-macro/tests/hook_attr/hook-trait-item-pass.rs
use std::marker::PhantomData; pub struct QueryState<T> { p: PhantomData<T> } pub trait MyTrait { type Associated; } #[yew::hook] pub fn use_query_state<Props>( _selector: impl yew::html::IntoPropValue<bool>, ) -> QueryState<Props::Associated> where Props: MyTrait, { QueryState::<Props::Associated> { p: PhantomData::<Props::Associated> } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/hook_attr/hook_macro-pass.rs
packages/yew-macro/tests/hook_attr/hook_macro-pass.rs
#![no_implicit_prelude] #[::yew::functional::hook] pub fn use_some_macro_inner(val: &str) -> ::std::string::String { let state = ::yew::functional::use_state(|| ::std::borrow::ToOwned::to_owned(val)); ::std::string::ToString::to_string(&*state) } macro_rules! use_some_macro { () => { use_some_macro_inner("default str") }; ($t: tt) => { use_some_macro_inner($t) }; } #[::yew::functional::component] fn Comp() -> ::yew::Html { let a = use_some_macro!(); let b = use_some_macro!("b"); ::yew::html! { <div>{a}{b}</div> } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false
yewstack/yew
https://github.com/yewstack/yew/blob/2019f4577cbdcd389b34973fdec3164be3af941a/packages/yew-macro/tests/classes_macro/classes-pass.rs
packages/yew-macro/tests/classes_macro/classes-pass.rs
#![no_implicit_prelude] // Shadow primitives #[allow(non_camel_case_types)] pub struct bool; #[allow(non_camel_case_types)] pub struct char; #[allow(non_camel_case_types)] pub struct f32; #[allow(non_camel_case_types)] pub struct f64; #[allow(non_camel_case_types)] pub struct i128; #[allow(non_camel_case_types)] pub struct i16; #[allow(non_camel_case_types)] pub struct i32; #[allow(non_camel_case_types)] pub struct i64; #[allow(non_camel_case_types)] pub struct i8; #[allow(non_camel_case_types)] pub struct isize; #[allow(non_camel_case_types)] pub struct str; #[allow(non_camel_case_types)] pub struct u128; #[allow(non_camel_case_types)] pub struct u16; #[allow(non_camel_case_types)] pub struct u32; #[allow(non_camel_case_types)] pub struct u64; #[allow(non_camel_case_types)] pub struct u8; #[allow(non_camel_case_types)] pub struct usize; fn compile_pass() { // multiple literals ::yew::classes!("one", "two"); // single literal ::yew::classes!("one"); // empty ::yew::classes!(); // multiple expressions ::yew::classes!(::std::vec!["one"], ::std::vec!["two"]); // single expression ::yew::classes!(::std::vec!["one", "two"]); // single array ::yew::classes!(["one", "two"]); // multiple arrays ::yew::classes!(["one"], ["two"]); // optional classes ::yew::classes!( ::std::option::Option::Some("one"), ::std::option::Option::None::<&'static ::std::primitive::str>, ); // mixed types { use ::std::borrow::ToOwned; ::yew::classes!("one".to_owned(), "two", ::std::vec!["three"], ["four", "five"]); } } fn main() {}
rust
Apache-2.0
2019f4577cbdcd389b34973fdec3164be3af941a
2026-01-04T15:33:05.007302Z
false