Skip to content

Commit

Permalink
fix(v2): i18n translation extractor should handle JSX formatting edge…
Browse files Browse the repository at this point in the history
… cases better (#3920)

* translation extractor should work despite weirdly formatted JSX  or empty text nodes around the content to translate

* fix TS
  • Loading branch information
slorber authored Dec 14, 2020
1 parent aff6561 commit 1db0277
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,16 @@ export default function MyComponent() {
<Translate
id={prefix + "codeId comp"}
description={prefix + "code description"}
>{prefix + "code message"}</Translate>
>
{prefix + "code message"}
</Translate>
<Translate>
{
prefix + \`Static template literal with unusual formatting!\`
}
</Translate>
</div>
);
}
Expand All @@ -183,6 +192,9 @@ export default function MyComponent() {
message: 'prefix code message',
description: 'prefix code description',
},
'prefix Static template literal with unusual formatting!': {
message: 'prefix Static template literal with unusual formatting!',
},
},
warnings: [],
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,14 +189,22 @@ function extractSourceCodeAstTranslations(
path.node.openingElement.name.type === 'JSXIdentifier' &&
path.node.openingElement.name.name === 'Translate'
) {
// TODO support multiple childrens here?
if (
path.node.children.length === 1 &&
t.isJSXText(path.node.children[0])
) {
const message = path.node.children[0].value
.trim()
.replace(/\s+/g, ' ');
// We only handle the optimistic case where we have a single non-empty content
const singleChildren: NodePath | undefined = path
.get('children')
// Remove empty/useless text nodes that might be around our translation!
// Makes the translation system more reliable to JSX formatting issues
.filter(
(childrenPath: NodePath) =>
!(
t.isJSXText(childrenPath.node) &&
childrenPath.node.value.replace('\n', '').trim() === ''
),
)
.pop();

if (singleChildren && t.isJSXText(singleChildren.node)) {
const message = singleChildren.node.value.trim().replace(/\s+/g, ' ');

const id = evaluateJSXProp('id');
const description = evaluateJSXProp('description');
Expand All @@ -206,12 +214,12 @@ function extractSourceCodeAstTranslations(
...(description && {description}),
};
} else if (
path.node.children.length === 1 &&
t.isJSXExpressionContainer(path.node.children[0]) &&
(path.get('children.0.expression') as NodePath).evaluate().confident
singleChildren &&
t.isJSXExpressionContainer(singleChildren) &&
(singleChildren.get('expression') as NodePath).evaluate().confident
) {
const message = (path.get(
'children.0.expression',
const message = (singleChildren.get(
'expression',
) as NodePath).evaluate().value;

const id = evaluateJSXProp('id');
Expand Down

0 comments on commit 1db0277

Please sign in to comment.