element.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. use crate::Writer;
  2. use dioxus_rsx::*;
  3. use proc_macro2::Span;
  4. use std::{
  5. fmt::Result,
  6. fmt::{self, Write},
  7. };
  8. use syn::{spanned::Spanned, token::Brace, Expr};
  9. #[derive(Debug)]
  10. enum ShortOptimization {
  11. /// Special because we want to print the closing bracket immediately
  12. ///
  13. /// IE
  14. /// `div {}` instead of `div { }`
  15. Empty,
  16. /// Special optimization to put everything on the same line and add some buffer spaces
  17. ///
  18. /// IE
  19. ///
  20. /// `div { "asdasd" }` instead of a multiline variant
  21. Oneliner,
  22. /// Optimization where children flow but props remain fixed on top
  23. PropsOnTop,
  24. /// The noisiest optimization where everything flows
  25. NoOpt,
  26. }
  27. /*
  28. // whitespace
  29. div {
  30. // some whitespace
  31. class: "asdasd"
  32. // whjiot
  33. asdasd // whitespace
  34. }
  35. */
  36. impl Writer<'_> {
  37. pub fn write_element(&mut self, el: &Element) -> Result {
  38. let Element {
  39. name,
  40. key,
  41. attributes,
  42. children,
  43. _is_static,
  44. brace,
  45. } = el;
  46. /*
  47. 1. Write the tag
  48. 2. Write the key
  49. 3. Write the attributes
  50. 4. Write the children
  51. */
  52. write!(self.out, "{name} {{")?;
  53. // decide if we have any special optimizations
  54. // Default with none, opt the cases in one-by-one
  55. let mut opt_level = ShortOptimization::NoOpt;
  56. // check if we have a lot of attributes
  57. let attr_len = self.is_short_attrs(attributes);
  58. let is_short_attr_list = (attr_len + self.out.indent * 4) < 80;
  59. let children_len = self.is_short_children(children);
  60. let is_small_children = children_len.is_some();
  61. // if we have few attributes and a lot of children, place the attrs on top
  62. if is_short_attr_list && !is_small_children {
  63. opt_level = ShortOptimization::PropsOnTop;
  64. }
  65. // even if the attr is long, it should be put on one line
  66. if !is_short_attr_list && attributes.len() <= 1 {
  67. if children.is_empty() {
  68. opt_level = ShortOptimization::Oneliner;
  69. } else {
  70. opt_level = ShortOptimization::PropsOnTop;
  71. }
  72. }
  73. // if we have few children and few attributes, make it a one-liner
  74. if is_short_attr_list && is_small_children {
  75. if children_len.unwrap() + attr_len + self.out.indent * 4 < 100 {
  76. opt_level = ShortOptimization::Oneliner;
  77. } else {
  78. opt_level = ShortOptimization::PropsOnTop;
  79. }
  80. }
  81. // If there's nothing at all, empty optimization
  82. if attributes.is_empty() && children.is_empty() && key.is_none() {
  83. opt_level = ShortOptimization::Empty;
  84. // Write comments if they exist
  85. self.write_todo_body(brace)?;
  86. }
  87. // multiline handlers bump everything down
  88. if attr_len > 1000 {
  89. opt_level = ShortOptimization::NoOpt;
  90. }
  91. match opt_level {
  92. ShortOptimization::Empty => {}
  93. ShortOptimization::Oneliner => {
  94. write!(self.out, " ")?;
  95. self.write_attributes(attributes, key, true)?;
  96. if !children.is_empty() && (!attributes.is_empty() || key.is_some()) {
  97. write!(self.out, ", ")?;
  98. }
  99. for (id, child) in children.iter().enumerate() {
  100. self.write_ident(child)?;
  101. if id != children.len() - 1 && children.len() > 1 {
  102. write!(self.out, ", ")?;
  103. }
  104. }
  105. write!(self.out, " ")?;
  106. }
  107. ShortOptimization::PropsOnTop => {
  108. if !attributes.is_empty() || key.is_some() {
  109. write!(self.out, " ")?;
  110. }
  111. self.write_attributes(attributes, key, true)?;
  112. if !children.is_empty() && (!attributes.is_empty() || key.is_some()) {
  113. write!(self.out, ",")?;
  114. }
  115. if !children.is_empty() {
  116. self.write_body_indented(children)?;
  117. }
  118. self.out.tabbed_line()?;
  119. }
  120. ShortOptimization::NoOpt => {
  121. self.write_attributes(attributes, key, false)?;
  122. if !children.is_empty() && (!attributes.is_empty() || key.is_some()) {
  123. write!(self.out, ",")?;
  124. }
  125. if !children.is_empty() {
  126. self.write_body_indented(children)?;
  127. }
  128. self.out.tabbed_line()?;
  129. }
  130. }
  131. write!(self.out, "}}")?;
  132. Ok(())
  133. }
  134. fn write_attributes(
  135. &mut self,
  136. attributes: &[ElementAttrNamed],
  137. key: &Option<IfmtInput>,
  138. sameline: bool,
  139. ) -> Result {
  140. let mut attr_iter = attributes.iter().peekable();
  141. if let Some(key) = key {
  142. if !sameline {
  143. self.out.indented_tabbed_line()?;
  144. }
  145. write!(
  146. self.out,
  147. "key: \"{}\"",
  148. key.source.as_ref().unwrap().value()
  149. )?;
  150. if !attributes.is_empty() {
  151. write!(self.out, ",")?;
  152. if sameline {
  153. write!(self.out, " ")?;
  154. }
  155. }
  156. }
  157. while let Some(attr) = attr_iter.next() {
  158. self.out.indent += 1;
  159. if !sameline {
  160. self.write_comments(attr.attr.start())?;
  161. }
  162. self.out.indent -= 1;
  163. if !sameline {
  164. self.out.indented_tabbed_line()?;
  165. }
  166. self.write_attribute(attr)?;
  167. if attr_iter.peek().is_some() {
  168. write!(self.out, ",")?;
  169. if sameline {
  170. write!(self.out, " ")?;
  171. }
  172. }
  173. }
  174. Ok(())
  175. }
  176. fn write_attribute(&mut self, attr: &ElementAttrNamed) -> Result {
  177. match &attr.attr {
  178. ElementAttr::AttrText { name, value } => {
  179. write!(
  180. self.out,
  181. "{name}: \"{value}\"",
  182. value = value.source.as_ref().unwrap().value()
  183. )?;
  184. }
  185. ElementAttr::AttrExpression { name, value } => {
  186. let out = prettyplease::unparse_expr(value);
  187. write!(self.out, "{name}: {out}")?;
  188. }
  189. ElementAttr::CustomAttrText { name, value } => {
  190. write!(
  191. self.out,
  192. "\"{name}\": \"{value}\"",
  193. name = name.value(),
  194. value = value.source.as_ref().unwrap().value()
  195. )?;
  196. }
  197. ElementAttr::CustomAttrExpression { name, value } => {
  198. let out = prettyplease::unparse_expr(value);
  199. write!(self.out, "\"{}\": {}", name.value(), out)?;
  200. }
  201. ElementAttr::EventTokens { name, tokens } => {
  202. let out = self.retrieve_formatted_expr(tokens).to_string();
  203. let mut lines = out.split('\n').peekable();
  204. let first = lines.next().unwrap();
  205. // a one-liner for whatever reason
  206. // Does not need a new line
  207. if lines.peek().is_none() {
  208. write!(self.out, "{name}: {first}")?;
  209. } else {
  210. writeln!(self.out, "{name}: {first}")?;
  211. while let Some(line) = lines.next() {
  212. self.out.indented_tab()?;
  213. write!(self.out, "{line}")?;
  214. if lines.peek().is_none() {
  215. write!(self.out, "")?;
  216. } else {
  217. writeln!(self.out)?;
  218. }
  219. }
  220. }
  221. }
  222. }
  223. Ok(())
  224. }
  225. // make sure the comments are actually relevant to this element.
  226. // test by making sure this element is the primary element on this line
  227. pub fn current_span_is_primary(&self, location: Span) -> bool {
  228. let start = location.start();
  229. let line_start = start.line - 1;
  230. let beginning = self
  231. .src
  232. .get(line_start)
  233. .filter(|this_line| this_line.len() > start.column)
  234. .map(|this_line| this_line[..start.column].trim())
  235. .unwrap_or_default();
  236. beginning.is_empty()
  237. }
  238. // check if the children are short enough to be on the same line
  239. // We don't have the notion of current line depth - each line tries to be < 80 total
  240. // returns the total line length if it's short
  241. // returns none if the length exceeds the limit
  242. // I think this eventually becomes quadratic :(
  243. pub fn is_short_children(&mut self, children: &[BodyNode]) -> Option<usize> {
  244. if children.is_empty() {
  245. // todo: allow elements with comments but no children
  246. // like div { /* comment */ }
  247. // or
  248. // div {
  249. // // some helpful
  250. // }
  251. return Some(0);
  252. }
  253. for child in children {
  254. if self.current_span_is_primary(child.span()) {
  255. 'line: for line in self.src[..child.span().start().line - 1].iter().rev() {
  256. match (line.trim().starts_with("//"), line.is_empty()) {
  257. (true, _) => return None,
  258. (_, true) => continue 'line,
  259. _ => break 'line,
  260. }
  261. }
  262. }
  263. }
  264. match children {
  265. [BodyNode::Text(ref text)] => Some(text.source.as_ref().unwrap().value().len()),
  266. [BodyNode::Component(ref comp)] => {
  267. let attr_len = self.field_len(&comp.fields, &comp.manual_props);
  268. if attr_len > 80 {
  269. None
  270. } else if comp.children.is_empty() {
  271. Some(attr_len)
  272. } else {
  273. None
  274. }
  275. }
  276. // TODO: let rawexprs to be inlined
  277. [BodyNode::RawExpr(ref expr)] => get_expr_length(expr),
  278. [BodyNode::Element(ref el)] => {
  279. let attr_len = self.is_short_attrs(&el.attributes);
  280. if el.children.is_empty() && attr_len < 80 {
  281. return Some(el.name.to_string().len());
  282. }
  283. if el.children.len() == 1 {
  284. if let BodyNode::Text(ref text) = el.children[0] {
  285. let value = text.source.as_ref().unwrap().value();
  286. if value.len() + el.name.to_string().len() + attr_len < 80 {
  287. return Some(value.len() + el.name.to_string().len() + attr_len);
  288. }
  289. }
  290. }
  291. None
  292. }
  293. // todo, allow non-elements to be on the same line
  294. items => {
  295. let mut total_count = 0;
  296. for item in items {
  297. match item {
  298. BodyNode::Component(_) | BodyNode::Element(_) => return None,
  299. BodyNode::Text(text) => {
  300. total_count += text.source.as_ref().unwrap().value().len()
  301. }
  302. BodyNode::RawExpr(expr) => match get_expr_length(expr) {
  303. Some(len) => total_count += len,
  304. None => return None,
  305. },
  306. BodyNode::ForLoop(_forloop) => return None,
  307. BodyNode::IfChain(_chain) => return None,
  308. }
  309. }
  310. Some(total_count)
  311. }
  312. }
  313. }
  314. /// empty everything except for some comments
  315. fn write_todo_body(&mut self, brace: &Brace) -> fmt::Result {
  316. let span = brace.span.span();
  317. let start = span.start();
  318. let end = span.end();
  319. if start.line == end.line {
  320. return Ok(());
  321. }
  322. writeln!(self.out)?;
  323. for idx in start.line..end.line {
  324. let line = &self.src[idx];
  325. if line.trim().starts_with("//") {
  326. for _ in 0..self.out.indent + 1 {
  327. write!(self.out, " ")?
  328. }
  329. writeln!(self.out, "{}", line.trim()).unwrap();
  330. }
  331. }
  332. for _ in 0..self.out.indent {
  333. write!(self.out, " ")?
  334. }
  335. Ok(())
  336. }
  337. }
  338. fn get_expr_length(expr: &Expr) -> Option<usize> {
  339. let span = expr.span();
  340. let (start, end) = (span.start(), span.end());
  341. if start.line == end.line {
  342. Some(end.column - start.column)
  343. } else {
  344. None
  345. }
  346. }