From 0ae3414582b62f85ae0916e5b75293dd0746c3e0 Mon Sep 17 00:00:00 2001 From: Konstantinos Bairaktaris Date: Thu, 25 Jul 2024 20:34:39 +0300 Subject: [PATCH] (Finally) fix the issue with how JSX handles newlines --- packages/cli/src/api/parsers/babel.js | 15 +++++++++++++-- packages/react/src/components/T.jsx | 2 +- packages/react/src/utils/toStr.js | 3 +-- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/packages/cli/src/api/parsers/babel.js b/packages/cli/src/api/parsers/babel.js index 3667c202..666cf67f 100644 --- a/packages/cli/src/api/parsers/babel.js +++ b/packages/cli/src/api/parsers/babel.js @@ -73,7 +73,18 @@ function toStr(children, counter = 0) { } } else if (child.type === 'JSXText') { // Child is not a React element, append as-is - const chunk = child.value.trim().replace(/\s+/g, ' '); + let chunk = child.value; + + const [startMatch] = /^[\s\n]*/.exec(child.value); + if (startMatch.includes('\n')) { + chunk = chunk.substring(startMatch.length); + } + + const [endMatch] = /[\s\n]*$/.exec(child.value); + if (endMatch.includes('\n')) { + chunk = chunk.substring(0, chunk.length - endMatch.length); + } + if (chunk) { result.push(chunk); } } else if ( child.type === 'JSXExpressionContainer' @@ -195,7 +206,7 @@ function babelExtractPhrases(HASHES, source, relativeFile, options) { if (!string && elem.name.name === 'T' && node.children && node.children.length) { const [result] = toStr(node.children); - string = result.join(' ').trim(); + string = result.join('').trim(); } if (!string) return; diff --git a/packages/react/src/components/T.jsx b/packages/react/src/components/T.jsx index 140f8244..bac7abd0 100644 --- a/packages/react/src/components/T.jsx +++ b/packages/react/src/components/T.jsx @@ -49,7 +49,7 @@ export default function T({ _str, children, ...props }) { if (!children) { return t(_str, props); } const [templateArray, propsContainer] = toStr(children); - const templateString = templateArray.join(' ').trim(); + const templateString = templateArray.join('').trim(); const translation = t(templateString, props); const result = toElement(translation, propsContainer); diff --git a/packages/react/src/utils/toStr.js b/packages/react/src/utils/toStr.js index 7da07fd9..861f827d 100644 --- a/packages/react/src/utils/toStr.js +++ b/packages/react/src/utils/toStr.js @@ -64,8 +64,7 @@ export function toStr(children, counter = 0) { // Child is not a React element, append as-is /* eslint-disable no-lonely-if */ if (typeof child === 'string' || child instanceof String) { - const chunk = child.trim().replace(/\s+/g, ' '); - if (chunk) { result.push(chunk); } + if (child) { result.push(child); } } else { result.push(child); }