Skip to content

Commit

Permalink
Merge pull request #701 from ggalletty/ns-from-type-arg
Browse files Browse the repository at this point in the history
feat: parse namespace from `t` type arguments
  • Loading branch information
karellm committed Jan 16, 2023
2 parents eb38095 + 597e3d0 commit d6a956e
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/lexers/javascript-lexer.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ export default class JavascriptLexer extends BaseLexer {

parseCommentNode(keys, node, content)

if (
node.kind === ts.SyntaxKind.ArrowFunction ||
node.kind === ts.SyntaxKind.FunctionDeclaration
) {
this.functionParamExtractor.call(this, node)
}

if (node.kind === ts.SyntaxKind.TaggedTemplateExpression) {
entry = this.taggedTemplateExpressionExtractor.call(this, node)
}
Expand All @@ -99,6 +106,32 @@ export default class JavascriptLexer extends BaseLexer {
return this.setNamespaces(keys)
}

/** @param {ts.FunctionLikeDeclaration} node */
functionParamExtractor(node) {
const tFunctionParam =
node.parameters &&
node.parameters.find(
(param) =>
param.name &&
param.name.kind === ts.SyntaxKind.Identifier &&
this.functions.includes(param.name.text)
)

if (
tFunctionParam &&
tFunctionParam.type &&
tFunctionParam.type.typeName.text === 'TFunction'
) {
const { typeArguments } = tFunctionParam.type
if (
typeArguments.length &&
typeArguments[0].kind === ts.SyntaxKind.LiteralType
) {
this.defaultNamespace = typeArguments[0].literal.text
}
}
}

taggedTemplateExpressionExtractor(node) {
const entry = {}

Expand Down
11 changes: 11 additions & 0 deletions test/lexers/javascript-lexer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,17 @@ describe('JavascriptLexer', () => {
done()
})

it('parses namespace from `t` type argument', (done) => {
const Lexer = new JavascriptLexer()
const content = `
const content = (t: TFunction<"foo">) => ({
title: t("bar"),
})
`
assert.deepEqual(Lexer.extract(content), [{ key: 'bar', namespace: 'foo' }])
done()
})

it("does not parse text with `doesn't` or isolated `t` in it", (done) => {
const Lexer = new JavascriptLexer()
const js =
Expand Down

0 comments on commit d6a956e

Please sign in to comment.