Skip to content

Commit

Permalink
Merge pull request #3 from thomaseizinger/main
Browse files Browse the repository at this point in the history
Auto-generate props if there are more than 1 arguments or the one provided does not end in `Props`
  • Loading branch information
Pitasi authored Sep 20, 2023
2 parents 867d6aa + 175763d commit caaf55b
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 3 deletions.
46 changes: 43 additions & 3 deletions rscx-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ use rstml::{
node::{KeyedAttribute, Node, NodeAttribute, NodeElement, NodeName},
Parser, ParserConfig,
};
use syn::{parse::Parse, spanned::Spanned, Expr, ExprLit, ItemStruct};
use syn::punctuated::Punctuated;
use syn::{parse::Parse, parse_quote, spanned::Spanned, Expr, ExprLit, FnArg, ItemStruct, Token};

#[proc_macro]
pub fn html(tokens: TokenStream) -> TokenStream {
Expand Down Expand Up @@ -445,9 +446,48 @@ impl ToTokens for ComponentFn {
let props = item.sig.inputs.first().unwrap();
(quote! {}, props.to_token_stream())
}
// TODO: generate #nameProps here
_ => {
panic!("wrong props")
let field_defs = &item
.sig
.inputs
.clone()
.into_iter()
.map(|i| match i {
FnArg::Receiver(_) => {
panic!("receiver arguments unsupported");
}
FnArg::Typed(mut t) => {
if t.attrs.is_empty() {
t.attrs.push(parse_quote! { #[builder(setter(into))] });
}

t
}
})
.collect::<Punctuated<_, Token![,]>>();
let field_names = item
.sig
.inputs
.iter()
.map(|i| match i {
FnArg::Receiver(_) => {
panic!("receiver arguments unsupported");
}
FnArg::Typed(t) => &t.pat,
})
.collect::<Punctuated<_, Token![,]>>();
let props_name =
syn::Ident::new(&format!("{}Props", name), proc_macro2::Span::call_site());

(
quote! {
#[rscx::props]
pub struct #props_name {
#field_defs
}
},
quote! { #props_name { #field_names }: #props_name },
)
}
};

Expand Down
38 changes: 38 additions & 0 deletions rscx/examples/autogenerated_props.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use rscx::{component, html};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let app = app().await;
println!("{}", app);
Ok(())
}

// simple function returning a String
async fn app() -> String {
let s = "ul { color: red; }";
html! {
<!DOCTYPE html>
<html>
<head>
<style>{s}</style>
</head>
<body>
// call a component with props and children
<Section title="Hello">
<p>"I am a paragraph"</p>
</Section>
</body>
</html>
}
}

#[component]
/// mark functions with #[component] to use them as components inside html! macro
fn Section(title: String, children: String) -> String {
html! {
<div>
<h1>{ title }</h1>
{ children }
</div>
}
}

0 comments on commit caaf55b

Please sign in to comment.