Skip to content

Commit

Permalink
feature(macro): support JSX macro inside conditional expressions
Browse files Browse the repository at this point in the history
fixes: #1175
  • Loading branch information
timofei-iatsenko committed Feb 14, 2023
1 parent a129adf commit 2555690
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
24 changes: 24 additions & 0 deletions packages/macro/src/macroJsx.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as babelTypes from "@babel/types"
import {
ConditionalExpression,
Expression,
JSXAttribute,
JSXElement,
Expand Down Expand Up @@ -283,6 +284,10 @@ export default class MacroJSX {
]
})
}
if (exp.isConditionalExpression()) {
return [this.tokenizeConditionalExpression(exp)]
}

if (exp.isJSXElement()) {
return this.tokenizeNode(exp)
}
Expand Down Expand Up @@ -411,6 +416,25 @@ export default class MacroJSX {
}
}

tokenizeConditionalExpression = (
exp: NodePath<ConditionalExpression>
): ArgToken => {
exp.traverse({
JSXElement: (el) => {
if (this.isI18nComponent(el) || this.isChoiceComponent(el)) {
this.replacePath(el)
el.skip()
}
},
})

return {
type: "arg",
name: this.expressionToArgument(exp),
value: exp.node,
}
}

tokenizeText = (value: string): TextToken => {
return {
type: "text",
Expand Down
44 changes: 44 additions & 0 deletions packages/macro/test/jsx-trans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,50 @@ const cases: TestCase[] = [
}} />;
`,
},
{
name: "JSX Macro inside JSX conditional expressions",
input: `
import { Trans } from '@lingui/macro'
;<Trans>Hello, {props.world ? <Trans>world</Trans> : <Trans>guys</Trans>}</Trans>
`,
expected: `
import { Trans } from '@lingui/react'
;<Trans
id={"Hello, {0}"}
values={{
0: props.world ? <Trans id={'world'} /> : <Trans id={'guys'} />
}}
/>
`,
},
{
name: "JSX Macro inside JSX multiple nested conditional expressions",
input: `
import { Trans } from '@lingui/macro'
;<Trans>Hello, {props.world ? <Trans>world</Trans> : (
props.b
? <Trans>nested</Trans>
: <Trans>guys</Trans>
)
}</Trans>
`,
expected: `
import { Trans } from "@lingui/react";
<Trans
id={"Hello, {0}"}
values={{
0: props.world ? (
<Trans id={"world"} />
) : props.b ? (
<Trans id={"nested"} />
) : (
<Trans id={"guys"} />
),
}}
/>;
`,
},
{
name: "Elements are replaced with placeholders",
input: `
Expand Down

0 comments on commit 2555690

Please sign in to comment.