From 206c828a568d07fde66d201d651fc978d5d14921 Mon Sep 17 00:00:00 2001 From: Sebastian McKenzie Date: Sat, 15 Nov 2014 11:00:32 +1100 Subject: [PATCH] more react compliant whitespace - #165 --- lib/6to5/transformation/transformers/react.js | 41 +++++++++++++++++-- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/lib/6to5/transformation/transformers/react.js b/lib/6to5/transformation/transformers/react.js index 5a70e20968..094dbf4a0b 100644 --- a/lib/6to5/transformation/transformers/react.js +++ b/lib/6to5/transformation/transformers/react.js @@ -106,11 +106,44 @@ exports.XJSElement = { exit: function (node) { var callExpr = node.openingElement; - var childrenToRender = node.children.filter(function(child) { - return !(t.isLiteral(child) && _.isString(child.value) && child.value.match(/^[ \t]*[\r\n][ \t\r\n]*$/)); - }); + _.each(node.children, function (child) { + if (t.isLiteral(child)) { + var lines = child.value.split(/\r\n|\n|\r/); + + var lastNonEmptyLine = 0; + + _.each(lines, function (line, i) { + if (line.match(/[^ \t]/)) { + lastNonEmptyLine = i; + } + }); + + _.each(lines, function (line, i) { + var isFirstLine = i === 0; + var isLastLine = i === lines.length - 1; + var isLastNonEmptyLine = i === lastNonEmptyLine; + + // replace rendered whitespace tabs with spaces + var trimmedLine = line.replace(/\t/g, ' '); + + // trim whitespace touching a newline + if (!isFirstLine) { + trimmedLine = trimmedLine.replace(/^[ ]+/, ''); + } + + // trim whitespace touching an endline + if (!isLastLine) { + trimmedLine = trimmedLine.replace(/[ ]+$/, ''); + } + + if (trimmedLine || isLastNonEmptyLine) { + callExpr.arguments.push(t.literal(trimmedLine)); + } + }); + + return; + } - _.each(childrenToRender, function (child) { callExpr.arguments.push(child); });