element.rs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. use super::*;
  2. use proc_macro2::TokenStream as TokenStream2;
  3. use quote::{quote, ToTokens, TokenStreamExt};
  4. use syn::{
  5. parse::{Parse, ParseBuffer, ParseStream},
  6. Expr, Ident, LitStr, Result, Token,
  7. };
  8. // =======================================
  9. // Parse the VNode::Element type
  10. // =======================================
  11. pub struct Element {
  12. name: Ident,
  13. key: Option<LitStr>,
  14. attributes: Vec<ElementAttrNamed>,
  15. listeners: Vec<ElementAttrNamed>,
  16. children: Vec<BodyNode>,
  17. _is_static: bool,
  18. }
  19. impl Parse for Element {
  20. fn parse(stream: ParseStream) -> Result<Self> {
  21. let el_name = Ident::parse(stream)?;
  22. // parse the guts
  23. let content: ParseBuffer;
  24. syn::braced!(content in stream);
  25. let mut attributes: Vec<ElementAttrNamed> = vec![];
  26. let mut listeners: Vec<ElementAttrNamed> = vec![];
  27. let mut children: Vec<BodyNode> = vec![];
  28. let mut key = None;
  29. let mut _el_ref = None;
  30. // parse fields with commas
  31. // break when we don't get this pattern anymore
  32. // start parsing bodynodes
  33. // "def": 456,
  34. // abc: 123,
  35. loop {
  36. // Parse the raw literal fields
  37. if content.peek(LitStr) && content.peek2(Token![:]) && !content.peek3(Token![:]) {
  38. let name = content.parse::<LitStr>()?;
  39. let ident = name.clone();
  40. content.parse::<Token![:]>()?;
  41. if content.peek(LitStr) {
  42. let value = content.parse::<LitStr>()?;
  43. attributes.push(ElementAttrNamed {
  44. el_name: el_name.clone(),
  45. attr: ElementAttr::CustomAttrText { name, value },
  46. });
  47. } else {
  48. let value = content.parse::<Expr>()?;
  49. attributes.push(ElementAttrNamed {
  50. el_name: el_name.clone(),
  51. attr: ElementAttr::CustomAttrExpression { name, value },
  52. });
  53. }
  54. if content.is_empty() {
  55. break;
  56. }
  57. // todo: add a message saying you need to include commas between fields
  58. if content.parse::<Token![,]>().is_err() {
  59. proc_macro_error::emit_error!(
  60. ident,
  61. "This attribute is misisng a trailing comma"
  62. )
  63. }
  64. continue;
  65. }
  66. if content.peek(Ident) && content.peek2(Token![:]) && !content.peek3(Token![:]) {
  67. let name = content.parse::<Ident>()?;
  68. let ident = name.clone();
  69. let name_str = name.to_string();
  70. content.parse::<Token![:]>()?;
  71. if name_str.starts_with("on") {
  72. listeners.push(ElementAttrNamed {
  73. el_name: el_name.clone(),
  74. attr: ElementAttr::EventTokens {
  75. name,
  76. tokens: content.parse()?,
  77. },
  78. });
  79. } else {
  80. match name_str.as_str() {
  81. "key" => {
  82. key = Some(content.parse()?);
  83. }
  84. "classes" => todo!("custom class list not supported yet"),
  85. // "namespace" => todo!("custom namespace not supported yet"),
  86. "node_ref" => {
  87. _el_ref = Some(content.parse::<Expr>()?);
  88. }
  89. _ => {
  90. if content.peek(LitStr) {
  91. attributes.push(ElementAttrNamed {
  92. el_name: el_name.clone(),
  93. attr: ElementAttr::AttrText {
  94. name,
  95. value: content.parse()?,
  96. },
  97. });
  98. } else {
  99. attributes.push(ElementAttrNamed {
  100. el_name: el_name.clone(),
  101. attr: ElementAttr::AttrExpression {
  102. name,
  103. value: content.parse()?,
  104. },
  105. });
  106. }
  107. }
  108. }
  109. }
  110. if content.is_empty() {
  111. break;
  112. }
  113. // todo: add a message saying you need to include commas between fields
  114. if content.parse::<Token![,]>().is_err() {
  115. proc_macro_error::emit_error!(
  116. ident,
  117. "This attribute is misisng a trailing comma"
  118. )
  119. }
  120. continue;
  121. }
  122. break;
  123. }
  124. while !content.is_empty() {
  125. if (content.peek(LitStr) && content.peek2(Token![:])) && !content.peek3(Token![:]) {
  126. let ident = content.parse::<LitStr>().unwrap();
  127. let name = ident.value();
  128. proc_macro_error::emit_error!(
  129. ident, "This attribute `{}` is in the wrong place.", name;
  130. help =
  131. "All attribute fields must be placed above children elements.
  132. div {
  133. attr: \"...\", <---- attribute is above children
  134. div { } <---- children are below attributes
  135. }";
  136. )
  137. }
  138. if (content.peek(Ident) && content.peek2(Token![:])) && !content.peek3(Token![:]) {
  139. let ident = content.parse::<Ident>().unwrap();
  140. let name = ident.to_string();
  141. proc_macro_error::emit_error!(
  142. ident, "This attribute `{}` is in the wrong place.", name;
  143. help =
  144. "All attribute fields must be placed above children elements.
  145. div {
  146. attr: \"...\", <---- attribute is above children
  147. div { } <---- children are below attributes
  148. }";
  149. )
  150. }
  151. children.push(content.parse::<BodyNode>()?);
  152. // consume comma if it exists
  153. // we don't actually care if there *are* commas after elements/text
  154. if content.peek(Token![,]) {
  155. let _ = content.parse::<Token![,]>();
  156. }
  157. }
  158. Ok(Self {
  159. key,
  160. name: el_name,
  161. attributes,
  162. children,
  163. listeners,
  164. _is_static: false,
  165. })
  166. }
  167. }
  168. impl ToTokens for Element {
  169. fn to_tokens(&self, tokens: &mut TokenStream2) {
  170. let name = &self.name;
  171. let children = &self.children;
  172. let listeners = &self.listeners;
  173. let attr = &self.attributes;
  174. let key = match &self.key {
  175. Some(ty) => quote! { Some(format_args_f!(#ty)) },
  176. None => quote! { None },
  177. };
  178. tokens.append_all(quote! {
  179. __cx.element(
  180. dioxus_elements::#name,
  181. __cx.bump().alloc([ #(#listeners),* ]),
  182. __cx.bump().alloc([ #(#attr),* ]),
  183. __cx.bump().alloc([ #(#children),* ]),
  184. #key,
  185. )
  186. });
  187. }
  188. }
  189. enum ElementAttr {
  190. // attribute: "valuee {}"
  191. AttrText { name: Ident, value: LitStr },
  192. // attribute: true,
  193. AttrExpression { name: Ident, value: Expr },
  194. // "attribute": "value {}"
  195. CustomAttrText { name: LitStr, value: LitStr },
  196. // "attribute": true,
  197. CustomAttrExpression { name: LitStr, value: Expr },
  198. // // onclick: move |_| {}
  199. // EventClosure { name: Ident, closure: ExprClosure },
  200. // onclick: {}
  201. EventTokens { name: Ident, tokens: Expr },
  202. }
  203. struct ElementAttrNamed {
  204. el_name: Ident,
  205. attr: ElementAttr,
  206. }
  207. impl ToTokens for ElementAttrNamed {
  208. fn to_tokens(&self, tokens: &mut TokenStream2) {
  209. let ElementAttrNamed { el_name, attr } = self;
  210. tokens.append_all(match attr {
  211. ElementAttr::AttrText { name, value } => {
  212. quote! {
  213. dioxus_elements::#el_name.#name(__cx, format_args_f!(#value))
  214. }
  215. }
  216. ElementAttr::AttrExpression { name, value } => {
  217. quote! {
  218. dioxus_elements::#el_name.#name(__cx, #value)
  219. }
  220. }
  221. ElementAttr::CustomAttrText { name, value } => {
  222. quote! {
  223. __cx.attr( #name, format_args_f!(#value), None, false )
  224. }
  225. }
  226. ElementAttr::CustomAttrExpression { name, value } => {
  227. quote! {
  228. __cx.attr( #name, format_args_f!(#value), None, false )
  229. }
  230. }
  231. // ElementAttr::EventClosure { name, closure } => {
  232. // quote! {
  233. // dioxus_elements::on::#name(__cx, #closure)
  234. // }
  235. // }
  236. ElementAttr::EventTokens { name, tokens } => {
  237. quote! {
  238. dioxus_elements::on::#name(__cx, #tokens)
  239. }
  240. }
  241. });
  242. }
  243. }