element.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. // check for any duplicate event listeners
  81. if attributes.iter().any(|f| {
  82. if let AttributeType::Named(ElementAttrNamed {
  83. attr:
  84. ElementAttr {
  85. name: ElementAttrName::BuiltIn(n),
  86. value: ElementAttrValue::EventTokens(_),
  87. },
  88. ..
  89. }) = f
  90. {
  91. n == &name_str
  92. } else {
  93. false
  94. }
  95. }) {
  96. return Err(syn::Error::new(
  97. name.span(),
  98. format!("Duplicate event listener `{}`", name),
  99. ));
  100. }
  101. attributes.push(attribute::AttributeType::Named(ElementAttrNamed {
  102. el_name: el_name.clone(),
  103. attr: ElementAttr {
  104. name: ElementAttrName::BuiltIn(name),
  105. value: ElementAttrValue::EventTokens(content.parse()?),
  106. },
  107. }));
  108. } else {
  109. match name_str.as_str() {
  110. "key" => {
  111. key = Some(content.parse()?);
  112. }
  113. _ => {
  114. let value = content.parse::<ElementAttrValue>()?;
  115. attributes.push(attribute::AttributeType::Named(ElementAttrNamed {
  116. el_name: el_name.clone(),
  117. attr: ElementAttr {
  118. name: ElementAttrName::BuiltIn(name),
  119. value,
  120. },
  121. }));
  122. }
  123. }
  124. }
  125. if content.is_empty() {
  126. break;
  127. }
  128. if content.parse::<Token![,]>().is_err() {
  129. missing_trailing_comma!(span);
  130. }
  131. continue;
  132. }
  133. break;
  134. }
  135. // Deduplicate any attributes that can be combined
  136. // For example, if there are two `class` attributes, combine them into one
  137. let mut merged_attributes: Vec<AttributeType> = Vec::new();
  138. for attr in &attributes {
  139. if let Some(old_attr_index) = merged_attributes.iter().position(|a| {
  140. matches!((a, attr), (
  141. AttributeType::Named(ElementAttrNamed {
  142. attr: ElementAttr {
  143. name: ElementAttrName::BuiltIn(old_name),
  144. ..
  145. },
  146. ..
  147. }),
  148. AttributeType::Named(ElementAttrNamed {
  149. attr: ElementAttr {
  150. name: ElementAttrName::BuiltIn(new_name),
  151. ..
  152. },
  153. ..
  154. }),
  155. ) if old_name == new_name)
  156. }) {
  157. let old_attr = &mut merged_attributes[old_attr_index];
  158. if let Some(combined) = old_attr.try_combine(attr) {
  159. *old_attr = combined;
  160. }
  161. } else {
  162. merged_attributes.push(attr.clone());
  163. }
  164. }
  165. while !content.is_empty() {
  166. if (content.peek(LitStr) && content.peek2(Token![:])) && !content.peek3(Token![:]) {
  167. attr_after_element!(content.span());
  168. }
  169. if (content.peek(Ident) && content.peek2(Token![:])) && !content.peek3(Token![:]) {
  170. attr_after_element!(content.span());
  171. }
  172. children.push(content.parse::<BodyNode>()?);
  173. // consume comma if it exists
  174. // we don't actually care if there *are* commas after elements/text
  175. if content.peek(Token![,]) {
  176. let _ = content.parse::<Token![,]>();
  177. }
  178. }
  179. Ok(Self {
  180. key,
  181. name: el_name,
  182. attributes,
  183. merged_attributes,
  184. children,
  185. brace,
  186. })
  187. }
  188. }
  189. impl ToTokens for Element {
  190. fn to_tokens(&self, tokens: &mut TokenStream2) {
  191. let name = &self.name;
  192. let children = &self.children;
  193. let key = match &self.key {
  194. Some(ty) => quote! { Some(#ty) },
  195. None => quote! { None },
  196. };
  197. let listeners = self.merged_attributes.iter().filter(|f| {
  198. matches!(
  199. f,
  200. AttributeType::Named(ElementAttrNamed {
  201. attr: ElementAttr {
  202. value: ElementAttrValue::EventTokens { .. },
  203. ..
  204. },
  205. ..
  206. })
  207. )
  208. });
  209. let attr = self.merged_attributes.iter().filter(|f| {
  210. !matches!(
  211. f,
  212. AttributeType::Named(ElementAttrNamed {
  213. attr: ElementAttr {
  214. value: ElementAttrValue::EventTokens { .. },
  215. ..
  216. },
  217. ..
  218. })
  219. )
  220. });
  221. tokens.append_all(quote! {
  222. __cx.element(
  223. #name,
  224. __cx.bump().alloc([ #(#listeners),* ]),
  225. __cx.bump().alloc([ #(#attr),* ]),
  226. __cx.bump().alloc([ #(#children),* ]),
  227. #key,
  228. )
  229. });
  230. }
  231. }
  232. #[derive(PartialEq, Eq, Clone, Debug, Hash)]
  233. pub enum ElementName {
  234. Ident(Ident),
  235. Custom(LitStr),
  236. }
  237. impl ElementName {
  238. pub(crate) fn tag_name(&self) -> TokenStream2 {
  239. match self {
  240. ElementName::Ident(i) => quote! { dioxus_elements::#i::TAG_NAME },
  241. ElementName::Custom(s) => quote! { #s },
  242. }
  243. }
  244. }
  245. impl ElementName {
  246. pub fn span(&self) -> Span {
  247. match self {
  248. ElementName::Ident(i) => i.span(),
  249. ElementName::Custom(s) => s.span(),
  250. }
  251. }
  252. }
  253. impl PartialEq<&str> for ElementName {
  254. fn eq(&self, other: &&str) -> bool {
  255. match self {
  256. ElementName::Ident(i) => i == *other,
  257. ElementName::Custom(s) => s.value() == *other,
  258. }
  259. }
  260. }
  261. impl Display for ElementName {
  262. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
  263. match self {
  264. ElementName::Ident(i) => write!(f, "{}", i),
  265. ElementName::Custom(s) => write!(f, "{}", s.value()),
  266. }
  267. }
  268. }
  269. impl Parse for ElementName {
  270. fn parse(stream: ParseStream) -> Result<Self> {
  271. let raw = Punctuated::<Ident, Token![-]>::parse_separated_nonempty(stream)?;
  272. if raw.len() == 1 {
  273. Ok(ElementName::Ident(raw.into_iter().next().unwrap()))
  274. } else {
  275. let span = raw.span();
  276. let tag = raw
  277. .into_iter()
  278. .map(|ident| ident.to_string())
  279. .collect::<Vec<_>>()
  280. .join("-");
  281. let tag = LitStr::new(&tag, span);
  282. Ok(ElementName::Custom(tag))
  283. }
  284. }
  285. }
  286. impl ToTokens for ElementName {
  287. fn to_tokens(&self, tokens: &mut TokenStream2) {
  288. match self {
  289. ElementName::Ident(i) => tokens.append_all(quote! { dioxus_elements::#i }),
  290. ElementName::Custom(s) => tokens.append_all(quote! { #s }),
  291. }
  292. }
  293. }