element.rs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. use std::fmt::{Display, Formatter};
  2. use super::*;
  3. use proc_macro2::{Span, TokenStream as TokenStream2};
  4. use quote::{quote, ToTokens, TokenStreamExt};
  5. use syn::{
  6. parse::{Parse, ParseBuffer, ParseStream},
  7. punctuated::Punctuated,
  8. spanned::Spanned,
  9. Expr, Ident, LitStr, Result, Token,
  10. };
  11. // =======================================
  12. // Parse the VNode::Element type
  13. // =======================================
  14. #[derive(PartialEq, Eq, Clone, Debug, Hash)]
  15. pub struct Element {
  16. pub name: ElementName,
  17. pub key: Option<IfmtInput>,
  18. pub attributes: Vec<AttributeType>,
  19. pub merged_attributes: Vec<AttributeType>,
  20. pub children: Vec<BodyNode>,
  21. pub brace: syn::token::Brace,
  22. }
  23. impl Parse for Element {
  24. fn parse(stream: ParseStream) -> Result<Self> {
  25. let el_name = ElementName::parse(stream)?;
  26. // parse the guts
  27. let content: ParseBuffer;
  28. let brace = syn::braced!(content in stream);
  29. let mut attributes: Vec<AttributeType> = vec![];
  30. let mut children: Vec<BodyNode> = vec![];
  31. let mut key = None;
  32. // parse fields with commas
  33. // break when we don't get this pattern anymore
  34. // start parsing bodynodes
  35. // "def": 456,
  36. // abc: 123,
  37. loop {
  38. if content.peek(Token![..]) {
  39. content.parse::<Token![..]>()?;
  40. let expr = content.parse::<Expr>()?;
  41. let span = expr.span();
  42. attributes.push(attribute::AttributeType::Spread(expr));
  43. if content.is_empty() {
  44. break;
  45. }
  46. if content.parse::<Token![,]>().is_err() {
  47. missing_trailing_comma!(span);
  48. }
  49. continue;
  50. }
  51. // Parse the raw literal fields
  52. if content.peek(LitStr) && content.peek2(Token![:]) && !content.peek3(Token![:]) {
  53. let name = content.parse::<LitStr>()?;
  54. let ident = name.clone();
  55. content.parse::<Token![:]>()?;
  56. let value = content.parse::<ElementAttrValue>()?;
  57. attributes.push(attribute::AttributeType::Named(ElementAttrNamed {
  58. el_name: el_name.clone(),
  59. attr: ElementAttr {
  60. name: ElementAttrName::Custom(name),
  61. value,
  62. },
  63. }));
  64. if content.is_empty() {
  65. break;
  66. }
  67. if content.parse::<Token![,]>().is_err() {
  68. missing_trailing_comma!(ident.span());
  69. }
  70. continue;
  71. }
  72. if content.peek(Ident) && content.peek2(Token![:]) && !content.peek3(Token![:]) {
  73. let name = content.parse::<Ident>()?;
  74. let name_str = name.to_string();
  75. content.parse::<Token![:]>()?;
  76. // The span of the content to be parsed,
  77. // for example the `hi` part of `class: "hi"`.
  78. let span = content.span();
  79. if name_str.starts_with("on") {
  80. attributes.push(attribute::AttributeType::Named(ElementAttrNamed {
  81. el_name: el_name.clone(),
  82. attr: ElementAttr {
  83. name: ElementAttrName::BuiltIn(name),
  84. value: ElementAttrValue::EventTokens(content.parse()?),
  85. },
  86. }));
  87. } else {
  88. match name_str.as_str() {
  89. "key" => {
  90. key = Some(content.parse()?);
  91. }
  92. _ => {
  93. let value = content.parse::<ElementAttrValue>()?;
  94. attributes.push(attribute::AttributeType::Named(ElementAttrNamed {
  95. el_name: el_name.clone(),
  96. attr: ElementAttr {
  97. name: ElementAttrName::BuiltIn(name),
  98. value,
  99. },
  100. }));
  101. }
  102. }
  103. }
  104. if content.is_empty() {
  105. break;
  106. }
  107. if content.parse::<Token![,]>().is_err() {
  108. missing_trailing_comma!(span);
  109. }
  110. continue;
  111. }
  112. break;
  113. }
  114. // Deduplicate any attributes that can be combined
  115. // For example, if there are two `class` attributes, combine them into one
  116. let mut merged_attributes: Vec<AttributeType> = Vec::new();
  117. for attr in &attributes {
  118. if let Some(old_attr_index) = merged_attributes.iter().position(|a| {
  119. matches!((a, attr), (
  120. AttributeType::Named(ElementAttrNamed {
  121. attr: ElementAttr {
  122. name: ElementAttrName::BuiltIn(old_name),
  123. ..
  124. },
  125. ..
  126. }),
  127. AttributeType::Named(ElementAttrNamed {
  128. attr: ElementAttr {
  129. name: ElementAttrName::BuiltIn(new_name),
  130. ..
  131. },
  132. ..
  133. }),
  134. ) if old_name == new_name)
  135. }) {
  136. let old_attr = &mut merged_attributes[old_attr_index];
  137. if let Some(combined) = old_attr.try_combine(attr) {
  138. *old_attr = combined;
  139. }
  140. } else {
  141. merged_attributes.push(attr.clone());
  142. }
  143. }
  144. while !content.is_empty() {
  145. if (content.peek(LitStr) && content.peek2(Token![:])) && !content.peek3(Token![:]) {
  146. attr_after_element!(content.span());
  147. }
  148. if (content.peek(Ident) && content.peek2(Token![:])) && !content.peek3(Token![:]) {
  149. attr_after_element!(content.span());
  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. merged_attributes,
  163. children,
  164. brace,
  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 key = match &self.key {
  173. Some(ty) => quote! { Some(#ty) },
  174. None => quote! { None },
  175. };
  176. let listeners = self.merged_attributes.iter().filter(|f| {
  177. matches!(
  178. f,
  179. AttributeType::Named(ElementAttrNamed {
  180. attr: ElementAttr {
  181. value: ElementAttrValue::EventTokens { .. },
  182. ..
  183. },
  184. ..
  185. })
  186. )
  187. });
  188. let attr = self.merged_attributes.iter().filter(|f| {
  189. !matches!(
  190. f,
  191. AttributeType::Named(ElementAttrNamed {
  192. attr: ElementAttr {
  193. value: ElementAttrValue::EventTokens { .. },
  194. ..
  195. },
  196. ..
  197. })
  198. )
  199. });
  200. tokens.append_all(quote! {
  201. __cx.element(
  202. #name,
  203. __cx.bump().alloc([ #(#listeners),* ]),
  204. __cx.bump().alloc([ #(#attr),* ]),
  205. __cx.bump().alloc([ #(#children),* ]),
  206. #key,
  207. )
  208. });
  209. }
  210. }
  211. #[derive(PartialEq, Eq, Clone, Debug, Hash)]
  212. pub enum ElementName {
  213. Ident(Ident),
  214. Custom(LitStr),
  215. }
  216. impl ElementName {
  217. pub(crate) fn tag_name(&self) -> TokenStream2 {
  218. match self {
  219. ElementName::Ident(i) => quote! { dioxus_elements::#i::TAG_NAME },
  220. ElementName::Custom(s) => quote! { #s },
  221. }
  222. }
  223. }
  224. impl ElementName {
  225. pub fn span(&self) -> Span {
  226. match self {
  227. ElementName::Ident(i) => i.span(),
  228. ElementName::Custom(s) => s.span(),
  229. }
  230. }
  231. }
  232. impl PartialEq<&str> for ElementName {
  233. fn eq(&self, other: &&str) -> bool {
  234. match self {
  235. ElementName::Ident(i) => i == *other,
  236. ElementName::Custom(s) => s.value() == *other,
  237. }
  238. }
  239. }
  240. impl Display for ElementName {
  241. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  242. match self {
  243. ElementName::Ident(i) => write!(f, "{}", i),
  244. ElementName::Custom(s) => write!(f, "{}", s.value()),
  245. }
  246. }
  247. }
  248. impl Parse for ElementName {
  249. fn parse(stream: ParseStream) -> Result<Self> {
  250. let raw = Punctuated::<Ident, Token![-]>::parse_separated_nonempty(stream)?;
  251. if raw.len() == 1 {
  252. Ok(ElementName::Ident(raw.into_iter().next().unwrap()))
  253. } else {
  254. let span = raw.span();
  255. let tag = raw
  256. .into_iter()
  257. .map(|ident| ident.to_string())
  258. .collect::<Vec<_>>()
  259. .join("-");
  260. let tag = LitStr::new(&tag, span);
  261. Ok(ElementName::Custom(tag))
  262. }
  263. }
  264. }
  265. impl ToTokens for ElementName {
  266. fn to_tokens(&self, tokens: &mut TokenStream2) {
  267. match self {
  268. ElementName::Ident(i) => tokens.append_all(quote! { dioxus_elements::#i }),
  269. ElementName::Custom(s) => tokens.append_all(quote! { #s }),
  270. }
  271. }
  272. }