lib.rs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. quote::quote! {
  188. {
  189. let __line_num = get_line_num();
  190. let __rsx_text_index: RsxContext = cx.consume_context().expect("Hot reload is not avalable on this platform");
  191. // only the insert the rsx text once
  192. if !__rsx_text_index.read().hm.contains_key(&__line_num){
  193. __rsx_text_index.insert(
  194. __line_num.clone(),
  195. #rsx_text.to_string(),
  196. );
  197. }
  198. LazyNodes::new(move |__cx|{
  199. if let Some(__text) = {
  200. let read = __rsx_text_index.read();
  201. // clone prevents deadlock on nested rsx calls
  202. read.hm.get(&__line_num).cloned()
  203. } {
  204. match interpert_rsx(
  205. __cx,
  206. &__text,
  207. #captured
  208. ){
  209. Ok(vnode) => vnode,
  210. Err(err) => {
  211. __rsx_text_index.report_error(err);
  212. __cx.text(format_args!(""))
  213. }
  214. }
  215. }
  216. else {
  217. panic!("rsx: line number {:?} not found in rsx index", __line_num);
  218. }
  219. })
  220. }
  221. }
  222. .into()
  223. }
  224. Err(err) => err.into_compile_error().into(),
  225. }
  226. }
  227. #[cfg(not(feature = "hot_reload"))]
  228. body.to_token_stream().into()
  229. }
  230. }
  231. }
  232. /// Derive props for a component within the component definition.
  233. ///
  234. /// This macro provides a simple transformation from `Scope<{}>` to `Scope<P>`,
  235. /// removing some boilerplate when defining props.
  236. ///
  237. /// You don't *need* to use this macro at all, but it can be helpful in cases where
  238. /// you would be repeating a lot of the usual Rust boilerplate.
  239. ///
  240. /// # Example
  241. /// ```
  242. /// #[inline_props]
  243. /// fn app(cx: Scope, bob: String) -> Element {
  244. /// cx.render(rsx!("hello, {bob}"))
  245. /// }
  246. ///
  247. /// // is equivalent to
  248. ///
  249. /// #[derive(PartialEq, Props)]
  250. /// struct AppProps {
  251. /// bob: String,
  252. /// }
  253. ///
  254. /// fn app(cx: Scope<AppProps>) -> Element {
  255. /// cx.render(rsx!("hello, {bob}"))
  256. /// }
  257. /// ```
  258. #[proc_macro_attribute]
  259. pub fn inline_props(_args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
  260. match syn::parse::<inlineprops::InlinePropsBody>(s) {
  261. Err(e) => e.to_compile_error().into(),
  262. Ok(s) => s.to_token_stream().into(),
  263. }
  264. }