Skip to content

Commit 5923586

Browse files
authored
fix: include comments in t macro transform (#12)
Descriptions in i18n comments should also be included in migration to v3
1 parent 86b9e47 commit 5923586

File tree

3 files changed

+38
-16
lines changed

3 files changed

+38
-16
lines changed

transforms/__testfixtures__/v2-to-v3/t.input.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,6 @@ t('my.id')`Some input`
66
const value = 1
77
t('my.id')`Some value (${value})`
88
t('my.id')`Some complex value (${value.toFixed(2)})`
9+
const withComment = /**i18n: a description of the message*/t`Some message`
10+
test`no transform`
11+
test('id')`no transform`

transforms/__testfixtures__/v2-to-v3/t.output.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,9 @@ t({
1515
id: "my.id",
1616
message: `Some complex value (${value.toFixed(2)})`
1717
})
18+
const withComment = t({
19+
message: `Some message`,
20+
comment: "a description of the message"
21+
})
22+
test`no transform`
23+
test('id')`no transform`

transforms/v2-to-v3.ts

Lines changed: 29 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -246,21 +246,34 @@ function removeMacroWrap(root, j: JSCodeshift) {
246246
* eslint.
247247
*/
248248
function tWithIdPropsChanges(root, j: JSCodeshift) {
249+
const objectProperty = (key: string, value) =>
250+
j.property('init', j.identifier(key), value);
251+
249252
return root
250-
.find(j.TaggedTemplateExpression, {
251-
tag: {
252-
callee: {
253-
name: "t"
254-
}
255-
}
256-
})
257-
.replaceWith((nodePath) => {
258-
const id = nodePath.node.tag.arguments[0].value;
259-
return j.callExpression(nodePath.node.tag.callee, [
260-
j.objectExpression([
261-
j.property("init", j.identifier("id"), j.literal(id)),
262-
j.property("init", j.identifier("message"), nodePath.node.quasi)
263-
])
264-
]);
265-
})
253+
.find(j.TaggedTemplateExpression)
254+
.filter(item => {
255+
const hasId = item.get('tag', 'callee', 'name').value === 't'
256+
const hasComments = (item.get('leadingComments', '0', 'value').value || '').startsWith('*i18n:');
257+
return hasId || hasComments;
258+
})
259+
.replaceWith(nodePath => {
260+
const id = nodePath.get('tag', 'arguments', '0', 'value').value;
261+
const message = nodePath.get('quasi').value;
262+
const comment = nodePath.get('leadingComments', '0', 'value').value;
263+
264+
const properties = [objectProperty('message', message)];
265+
266+
if (id) {
267+
properties.unshift(objectProperty('id', j.literal(id)));
268+
}
269+
270+
if (comment) {
271+
properties.push(
272+
objectProperty('comment', j.literal(comment.replace(/^\*i18n:\s?/, '')))
273+
);
274+
}
275+
276+
return j.callExpression(j.identifier('t'), [j.objectExpression(properties)]);
277+
})
278+
.toSource();
266279
}

0 commit comments

Comments
 (0)