element.rs 9.5 KB

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