element.rs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. use super::*;
  2. use proc_macro2::{Span, TokenStream as TokenStream2};
  3. use quote::{quote, ToTokens, TokenStreamExt};
  4. use syn::{
  5. parse::{Parse, ParseBuffer, ParseStream},
  6. Error, Expr, Ident, LitStr, Result, Token,
  7. };
  8. // =======================================
  9. // Parse the VNode::Element type
  10. // =======================================
  11. #[derive(PartialEq, Eq, Clone, Debug, Hash)]
  12. pub struct Element {
  13. pub name: Ident,
  14. pub key: Option<IfmtInput>,
  15. pub attributes: Vec<ElementAttrNamed>,
  16. pub children: Vec<BodyNode>,
  17. pub _is_static: bool,
  18. pub brace: syn::token::Brace,
  19. }
  20. impl Parse for Element {
  21. fn parse(stream: ParseStream) -> Result<Self> {
  22. let el_name = Ident::parse(stream)?;
  23. // parse the guts
  24. let content: ParseBuffer;
  25. let brace = syn::braced!(content in stream);
  26. let mut attributes: 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()?;
  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. if content.parse::<Token![,]>().is_err() {
  58. missing_trailing_comma!(ident.span());
  59. }
  60. continue;
  61. }
  62. if content.peek(Ident) && content.peek2(Token![:]) && !content.peek3(Token![:]) {
  63. let name = content.parse::<Ident>()?;
  64. let ident = name.clone();
  65. let name_str = name.to_string();
  66. content.parse::<Token![:]>()?;
  67. if name_str.starts_with("on") {
  68. attributes.push(ElementAttrNamed {
  69. el_name: el_name.clone(),
  70. attr: ElementAttr::EventTokens {
  71. name,
  72. tokens: content.parse()?,
  73. },
  74. });
  75. } else {
  76. match name_str.as_str() {
  77. "key" => {
  78. key = Some(content.parse()?);
  79. }
  80. "classes" => todo!("custom class list not supported yet"),
  81. // "namespace" => todo!("custom namespace not supported yet"),
  82. "node_ref" => {
  83. _el_ref = Some(content.parse::<Expr>()?);
  84. }
  85. _ => {
  86. if content.peek(LitStr) {
  87. attributes.push(ElementAttrNamed {
  88. el_name: el_name.clone(),
  89. attr: ElementAttr::AttrText {
  90. name,
  91. value: content.parse()?,
  92. },
  93. });
  94. } else {
  95. attributes.push(ElementAttrNamed {
  96. el_name: el_name.clone(),
  97. attr: ElementAttr::AttrExpression {
  98. name,
  99. value: content.parse()?,
  100. },
  101. });
  102. }
  103. }
  104. }
  105. }
  106. if content.is_empty() {
  107. break;
  108. }
  109. // todo: add a message saying you need to include commas between fields
  110. if content.parse::<Token![,]>().is_err() {
  111. missing_trailing_comma!(ident.span());
  112. }
  113. continue;
  114. }
  115. break;
  116. }
  117. while !content.is_empty() {
  118. if (content.peek(LitStr) && content.peek2(Token![:])) && !content.peek3(Token![:]) {
  119. attr_after_element!(content.span());
  120. }
  121. if (content.peek(Ident) && content.peek2(Token![:])) && !content.peek3(Token![:]) {
  122. attr_after_element!(content.span());
  123. }
  124. children.push(content.parse::<BodyNode>()?);
  125. // consume comma if it exists
  126. // we don't actually care if there *are* commas after elements/text
  127. if content.peek(Token![,]) {
  128. let _ = content.parse::<Token![,]>();
  129. }
  130. }
  131. Ok(Self {
  132. key,
  133. name: el_name,
  134. attributes,
  135. children,
  136. brace,
  137. _is_static: false,
  138. })
  139. }
  140. }
  141. impl ToTokens for Element {
  142. fn to_tokens(&self, tokens: &mut TokenStream2) {
  143. let name = &self.name;
  144. let children = &self.children;
  145. let key = match &self.key {
  146. Some(ty) => quote! { Some(#ty) },
  147. None => quote! { None },
  148. };
  149. let listeners = self
  150. .attributes
  151. .iter()
  152. .filter(|f| matches!(f.attr, ElementAttr::EventTokens { .. }));
  153. let attr = self
  154. .attributes
  155. .iter()
  156. .filter(|f| !matches!(f.attr, ElementAttr::EventTokens { .. }));
  157. tokens.append_all(quote! {
  158. __cx.element(
  159. dioxus_elements::#name,
  160. __cx.bump().alloc([ #(#listeners),* ]),
  161. __cx.bump().alloc([ #(#attr),* ]),
  162. __cx.bump().alloc([ #(#children),* ]),
  163. #key,
  164. )
  165. });
  166. }
  167. }
  168. #[derive(PartialEq, Eq, Clone, Debug, Hash)]
  169. pub enum ElementAttr {
  170. /// `attribute: "value"`
  171. AttrText { name: Ident, value: IfmtInput },
  172. /// `attribute: true`
  173. AttrExpression { name: Ident, value: Expr },
  174. /// `"attribute": "value"`
  175. CustomAttrText { name: LitStr, value: IfmtInput },
  176. /// `"attribute": true`
  177. CustomAttrExpression { name: LitStr, value: Expr },
  178. // /// onclick: move |_| {}
  179. // EventClosure { name: Ident, closure: ExprClosure },
  180. /// onclick: {}
  181. EventTokens { name: Ident, tokens: Expr },
  182. }
  183. impl ElementAttr {
  184. pub fn start(&self) -> Span {
  185. match self {
  186. ElementAttr::AttrText { name, .. } => name.span(),
  187. ElementAttr::AttrExpression { name, .. } => name.span(),
  188. ElementAttr::CustomAttrText { name, .. } => name.span(),
  189. ElementAttr::CustomAttrExpression { name, .. } => name.span(),
  190. ElementAttr::EventTokens { name, .. } => name.span(),
  191. }
  192. }
  193. pub fn is_expr(&self) -> bool {
  194. matches!(
  195. self,
  196. ElementAttr::AttrExpression { .. }
  197. | ElementAttr::CustomAttrExpression { .. }
  198. | ElementAttr::EventTokens { .. }
  199. )
  200. }
  201. }
  202. #[derive(PartialEq, Eq, Clone, Debug, Hash)]
  203. pub struct ElementAttrNamed {
  204. pub el_name: Ident,
  205. pub 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. __cx.attr(
  214. dioxus_elements::#el_name::#name.0,
  215. #value,
  216. dioxus_elements::#el_name::#name.1,
  217. dioxus_elements::#el_name::#name.2
  218. )
  219. }
  220. }
  221. ElementAttr::AttrExpression { name, value } => {
  222. quote! {
  223. __cx.attr(
  224. dioxus_elements::#el_name::#name.0,
  225. #value,
  226. dioxus_elements::#el_name::#name.1,
  227. dioxus_elements::#el_name::#name.2
  228. )
  229. }
  230. }
  231. ElementAttr::CustomAttrText { name, value } => {
  232. quote! {
  233. __cx.attr(
  234. #name,
  235. #value,
  236. None,
  237. false
  238. )
  239. }
  240. }
  241. ElementAttr::CustomAttrExpression { name, value } => {
  242. quote! {
  243. __cx.attr(
  244. #name,
  245. #value,
  246. None,
  247. false
  248. )
  249. }
  250. }
  251. ElementAttr::EventTokens { name, tokens } => {
  252. quote! {
  253. dioxus_elements::events::#name(__cx, #tokens)
  254. }
  255. }
  256. });
  257. }
  258. }
  259. // ::dioxus::core::Attribute {
  260. // name: stringify!(#name),
  261. // namespace: None,
  262. // volatile: false,
  263. // mounted_node: Default::default(),
  264. // value: ::dioxus::core::AttributeValue::Text(#value),
  265. // }