From 3a1fd1918f65c0a751a872d66e2d5bb01c64830c Mon Sep 17 00:00:00 2001 From: Titus Wormer Date: Mon, 3 Oct 2022 17:34:52 +0200 Subject: Add support for creating a component, using layout --- tests/test_utils/to_swc.rs | 53 ++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) (limited to 'tests/test_utils/to_swc.rs') diff --git a/tests/test_utils/to_swc.rs b/tests/test_utils/to_swc.rs index 1d25f47..59d60ee 100644 --- a/tests/test_utils/to_swc.rs +++ b/tests/test_utils/to_swc.rs @@ -345,11 +345,44 @@ fn transform_root( node: &hast::Node, _root: &hast::Root, ) -> Result, String> { - let children = all(context, node)?; + let mut children = all(context, node)?; + let mut queue = vec![]; + let mut nodes = vec![]; + let mut seen = false; + + children.reverse(); + + // Remove initial/final whitespace. + while let Some(child) = children.pop() { + let mut stash = false; + + if let swc_ecma_ast::JSXElementChild::JSXExprContainer(container) = &child { + if let swc_ecma_ast::JSXExpr::Expr(expr) = &container.expr { + if let swc_ecma_ast::Expr::Lit(swc_ecma_ast::Lit::Str(str)) = (*expr).as_ref() { + if inter_element_whitespace(str.value.as_ref()) { + stash = true; + } + } + } + } + + if stash { + if seen { + queue.push(child); + } + } else { + if !queue.is_empty() { + nodes.append(&mut queue); + } + nodes.push(child); + seen = true; + } + } + // To do: remove whitespace? // To do: return a single child if there is one? Ok(Some(swc_ecma_ast::JSXElementChild::JSXFragment( - create_fragment(children, node), + create_fragment(nodes, node), ))) } @@ -493,6 +526,22 @@ fn position_to_span(position: Option<&Position>) -> swc_common::Span { }) } +fn inter_element_whitespace(value: &str) -> bool { + let bytes = value.as_bytes(); + let mut index = 0; + + while index < bytes.len() { + match bytes[index] { + // To do: form feed. + b'\t' | b'\r' | b'\n' | b' ' => {} + _ => return false, + } + index += 1; + } + + true +} + /// Different kinds of JSX names. enum JsxName<'a> { // `a.b.c` -- cgit