Skip to content

Commit

Permalink
(Finally) fix the issue with how JSX handles newlines
Browse files Browse the repository at this point in the history
  • Loading branch information
kbairak committed Jul 26, 2024
1 parent 0dbcce5 commit 176c9c0
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
16 changes: 14 additions & 2 deletions packages/cli/src/api/parsers/babel.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,19 @@ 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;

// Try to mimic how JSX is parsed in runtime React
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'
Expand Down Expand Up @@ -195,7 +207,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;
Expand Down
2 changes: 1 addition & 1 deletion packages/react/src/components/T.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
3 changes: 1 addition & 2 deletions packages/react/src/utils/toStr.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down

0 comments on commit 176c9c0

Please sign in to comment.