lib.rs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. use proc_macro::TokenStream;
  2. use quote::ToTokens;
  3. use syn::parse_macro_input;
  4. mod inlineprops;
  5. mod props;
  6. // mod rsx;
  7. use dioxus_rsx as rsx;
  8. #[proc_macro]
  9. pub fn format_args_f(input: TokenStream) -> TokenStream {
  10. use rsx::*;
  11. let item = parse_macro_input!(input as IfmtInput);
  12. format_args_f_impl(item)
  13. .unwrap_or_else(|err| err.to_compile_error())
  14. .into()
  15. }
  16. #[proc_macro_derive(Props, attributes(props))]
  17. pub fn derive_typed_builder(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
  18. let input = parse_macro_input!(input as syn::DeriveInput);
  19. match props::impl_my_derive(&input) {
  20. Ok(output) => output.into(),
  21. Err(error) => error.to_compile_error().into(),
  22. }
  23. }
  24. /// The rsx! macro makes it easy for developers to write jsx-style markup in their components.
  25. ///
  26. /// ## Complete Reference Guide:
  27. /// ```
  28. /// const Example: Component = |cx| {
  29. /// let formatting = "formatting!";
  30. /// let formatting_tuple = ("a", "b");
  31. /// let lazy_fmt = format_args!("lazily formatted text");
  32. /// cx.render(rsx! {
  33. /// div {
  34. /// // Elements
  35. /// div {}
  36. /// h1 {"Some text"}
  37. /// h1 {"Some text with {formatting}"}
  38. /// h1 {"Formatting basic expressions {formatting_tuple.0} and {formatting_tuple.1}"}
  39. /// h2 {
  40. /// "Multiple"
  41. /// "Text"
  42. /// "Blocks"
  43. /// "Use comments as separators in html"
  44. /// }
  45. /// div {
  46. /// h1 {"multiple"}
  47. /// h2 {"nested"}
  48. /// h3 {"elements"}
  49. /// }
  50. /// div {
  51. /// class: "my special div"
  52. /// h1 {"Headers and attributes!"}
  53. /// }
  54. /// div {
  55. /// // pass simple rust expressions in
  56. /// class: lazy_fmt,
  57. /// id: format_args!("attributes can be passed lazily with std::fmt::Arguments"),
  58. /// div {
  59. /// class: {
  60. /// const WORD: &str = "expressions";
  61. /// format_args!("Arguments can be passed in through curly braces for complex {}", WORD)
  62. /// }
  63. /// }
  64. /// }
  65. ///
  66. /// // Expressions can be used in element position too:
  67. /// {rsx!(p { "More templating!" })}
  68. /// {html!(<p>"Even HTML templating!!"</p>)}
  69. ///
  70. /// // Iterators
  71. /// {(0..10).map(|i| rsx!(li { "{i}" }))}
  72. /// {{
  73. /// let data = std::collections::HashMap::<&'static str, &'static str>::new();
  74. /// // Iterators *should* have keys when you can provide them.
  75. /// // Keys make your app run faster. Make sure your keys are stable, unique, and predictable.
  76. /// // Using an "ID" associated with your data is a good idea.
  77. /// data.into_iter().map(|(k, v)| rsx!(li { key: "{k}" "{v}" }))
  78. /// }}
  79. ///
  80. /// // Matching
  81. /// {match true {
  82. /// true => rsx!(h1 {"Top text"}),
  83. /// false => rsx!(h1 {"Bottom text"})
  84. /// }}
  85. ///
  86. /// // Conditional rendering
  87. /// // Dioxus conditional rendering is based around None/Some. We have no special syntax for conditionals.
  88. /// // You can convert a bool condition to rsx! with .then and .or
  89. /// {true.then(|| rsx!(div {}))}
  90. ///
  91. /// // True conditions
  92. /// {if true {
  93. /// rsx!(h1 {"Top text"})
  94. /// } else {
  95. /// rsx!(h1 {"Bottom text"})
  96. /// }}
  97. ///
  98. /// // returning "None" is a bit noisy... but rare in practice
  99. /// {None as Option<()>}
  100. ///
  101. /// // Use the Dioxus type-alias for less noise
  102. /// {NONE_ELEMENT}
  103. ///
  104. /// // can also just use empty fragments
  105. /// Fragment {}
  106. ///
  107. /// // Fragments let you insert groups of nodes without a parent.
  108. /// // This lets you make components that insert elements as siblings without a container.
  109. /// div {"A"}
  110. /// Fragment {
  111. /// div {"B"}
  112. /// div {"C"}
  113. /// Fragment {
  114. /// "D"
  115. /// Fragment {
  116. /// "heavily nested fragments is an antipattern"
  117. /// "they cause Dioxus to do unnecessary work"
  118. /// "don't use them carelessly if you can help it"
  119. /// }
  120. /// }
  121. /// }
  122. ///
  123. /// // Components
  124. /// // Can accept any paths
  125. /// // Notice how you still get syntax highlighting and IDE support :)
  126. /// Baller {}
  127. /// baller::Baller { }
  128. /// crate::baller::Baller {}
  129. ///
  130. /// // Can take properties
  131. /// Taller { a: "asd" }
  132. ///
  133. /// // Can take optional properties
  134. /// Taller { a: "asd" }
  135. ///
  136. /// // Can pass in props directly as an expression
  137. /// {{
  138. /// let props = TallerProps {a: "hello"};
  139. /// rsx!(Taller { ..props })
  140. /// }}
  141. ///
  142. /// // Spreading can also be overridden manually
  143. /// Taller {
  144. /// ..TallerProps { a: "ballin!" }
  145. /// a: "not ballin!"
  146. /// }
  147. ///
  148. /// // Can take children too!
  149. /// Taller { a: "asd", div {"hello world!"} }
  150. /// }
  151. /// })
  152. /// };
  153. ///
  154. /// mod baller {
  155. /// use super::*;
  156. /// pub struct BallerProps {}
  157. ///
  158. /// /// This component totally balls
  159. /// pub fn Baller(cx: Scope) -> DomTree {
  160. /// todo!()
  161. /// }
  162. /// }
  163. ///
  164. /// #[derive(Debug, PartialEq, Props)]
  165. /// pub struct TallerProps {
  166. /// a: &'static str,
  167. /// }
  168. ///
  169. /// /// This component is taller than most :)
  170. /// pub fn Taller(cx: Scope<TallerProps>) -> DomTree {
  171. /// let b = true;
  172. /// todo!()
  173. /// }
  174. /// ```
  175. #[proc_macro]
  176. pub fn rsx(s: TokenStream) -> TokenStream {
  177. #[cfg(feature = "hot_reload")]
  178. let rsx_text = s.to_string();
  179. match syn::parse::<rsx::CallBody>(s) {
  180. Err(err) => err.to_compile_error().into(),
  181. Ok(body) => {
  182. #[cfg(feature = "hot_reload")]
  183. {
  184. use dioxus_rsx_interpreter::captuered_context::CapturedContextBuilder;
  185. match CapturedContextBuilder::from_call_body(body) {
  186. Ok(captured) => {
  187. let lazy = quote::quote! {
  188. LazyNodes::new(move |__cx|{
  189. let captured = #captured;
  190. let line_num = get_line_num();
  191. let text = #rsx_text;
  192. resolve_scope(line_num, text, captured, __cx)
  193. })
  194. };
  195. if let Some(cx) = captured.custom_context {
  196. quote::quote! {
  197. #cx.render(#lazy)
  198. }
  199. .into()
  200. } else {
  201. lazy.into()
  202. }
  203. }
  204. Err(err) => err.into_compile_error().into(),
  205. }
  206. }
  207. #[cfg(not(feature = "hot_reload"))]
  208. body.to_token_stream().into()
  209. }
  210. }
  211. }
  212. /// Derive props for a component within the component definition.
  213. ///
  214. /// This macro provides a simple transformation from `Scope<{}>` to `Scope<P>`,
  215. /// removing some boilerplate when defining props.
  216. ///
  217. /// You don't *need* to use this macro at all, but it can be helpful in cases where
  218. /// you would be repeating a lot of the usual Rust boilerplate.
  219. ///
  220. /// # Example
  221. /// ```
  222. /// #[inline_props]
  223. /// fn app(cx: Scope, bob: String) -> Element {
  224. /// cx.render(rsx!("hello, {bob}"))
  225. /// }
  226. ///
  227. /// // is equivalent to
  228. ///
  229. /// #[derive(PartialEq, Props)]
  230. /// struct AppProps {
  231. /// bob: String,
  232. /// }
  233. ///
  234. /// fn app(cx: Scope<AppProps>) -> Element {
  235. /// cx.render(rsx!("hello, {bob}"))
  236. /// }
  237. /// ```
  238. #[proc_macro_attribute]
  239. pub fn inline_props(_args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
  240. match syn::parse::<inlineprops::InlinePropsBody>(s) {
  241. Err(e) => e.to_compile_error().into(),
  242. Ok(s) => s.to_token_stream().into(),
  243. }
  244. }