element.rs 10 KB

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