Skip to content

Commit

Permalink
feat(macro): support tagged templates in defineMessage + short alias
Browse files Browse the repository at this point in the history
  • Loading branch information
timofei-iatsenko committed Mar 9, 2023
1 parent 3ae3c1e commit 9b92731
Show file tree
Hide file tree
Showing 11 changed files with 251 additions and 113 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,26 @@ exports[`@lingui/babel-plugin-extract-messages should extract all messages from
38,
],
},
{
comment: undefined,
context: Context2,
id: Some ID,
message: undefined,
origin: [
js-with-macros.js,
43,
],
},
{
comment: undefined,
context: undefined,
id: sD7MQ4,
message: TplLiteral,
origin: [
js-with-macros.js,
48,
],
},
]
`;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,41 +1,48 @@
import { t, defineMessage } from "@lingui/macro"
import { t, defineMessage, msg } from "@lingui/macro"

t`Message`

const msg = t`Message`
const msg1 = t`Message`

const withDescription = defineMessage({
message: 'Description',
comment: "description"
message: "Description",
comment: "description",
})

const withId = defineMessage({
id: 'ID',
message: 'Message with id'
id: "ID",
message: "Message with id",
})

const withValues = t`Values ${param}`

const withTId = t({
id: "ID Some",
message: "Message with id some"
message: "Message with id some",
})

const withTIdBacktick = t({
id: `Backtick`
id: `Backtick`,
})

const tWithContextA = t({
id: "Some ID",
context: "Context1"
context: "Context1",
})

const tWithContextB = t({
id: "Some other ID",
context: "Context1"
context: "Context1",
})

const defineMessageWithContext = defineMessage({
id: "Some ID",
context: "Context2"
context: "Context2",
})

const defineMessageAlias = msg({
id: "Some ID",
context: "Context2",
})

const defineMessageAlias2 = msg`TplLiteral`
11 changes: 11 additions & 0 deletions packages/macro/__typetests__/index.test-d.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { MessageDescriptor, I18n } from "@lingui/core"
import {
t,
defineMessage,
msg,
plural,
selectOrdinal,
select,
Expand Down Expand Up @@ -76,6 +77,16 @@ expectType<MessageDescriptor>(
message: "Hello world",
})
)
expectType<MessageDescriptor>(
msg({
id: "custom.id",
comment: "Hello",
context: "context",
message: "Hello world",
})
)
expectType<MessageDescriptor>(defineMessage`Message`)
expectType<MessageDescriptor>(msg`Message`)

// @ts-expect-error id or message should be presented
expectType<MessageDescriptor>(defineMessage({}))
Expand Down
8 changes: 6 additions & 2 deletions packages/macro/__typetests__/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
{
"compilerOptions": {
"jsx": "react",
"esModuleInterop": true
"esModuleInterop": true,
"strict": true
},
"paths": {}
"paths": {},
"include": [
"./**.tsx"
]
}
23 changes: 23 additions & 0 deletions packages/macro/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,29 @@ export function defineMessage(
descriptor: MacroMessageDescriptor
): MessageDescriptor

/**
* Define a message for later use
*
* @example
* ```
* import { defineMessage, msg } from "@lingui/macro";
* const message = defineMessage`Hello ${name}`;
*
* // or using shorter version
* const message = msg`Hello ${name}`;
* ```
*/
export function defineMessage(
literals: TemplateStringsArray,
...placeholders: any[]
): string

/**
* Define a message for later use
* Alias for {@see defineMessage}
*/
export const msg: typeof defineMessage

type CommonProps = {
id?: string
comment?: string
Expand Down
1 change: 1 addition & 0 deletions packages/macro/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export type LinguiMacroOpts = {

const jsMacroTags = new Set([
"defineMessage",
"msg",
"arg",
"t",
"plural",
Expand Down
131 changes: 62 additions & 69 deletions packages/macro/src/macroJs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import ICUMessageFormat, {
ParsedResult,
TextToken,
Token,
Tokens,
} from "./icu"
import { makeCounter } from "./utils"
import { COMMENT, CONTEXT, EXTRACT_MARK, ID, MESSAGE } from "./constants"
Expand All @@ -30,6 +31,13 @@ function normalizeWhitespace(text: string): string {
return text.replace(keepSpaceRe, " ").replace(keepNewLineRe, "\n").trim()
}

function buildICUFromTokens(tokens: Tokens) {
const messageFormat = new ICUMessageFormat()
const { message, values } = messageFormat.fromTokens(tokens)

return { message: normalizeWhitespace(message), values }
}

export type MacroJsOpts = {
i18nImportName: string
stripNonEssentialProps: boolean
Expand Down Expand Up @@ -62,24 +70,11 @@ export default class MacroJs {

replacePathWithMessage = (
path: NodePath,
{
message,
values,
}: { message: ParsedResult["message"]; values: ParsedResult["values"] },
tokens: Tokens,
linguiInstance?: babelTypes.Expression
) => {
const properties: ObjectProperty[] = [
this.createIdProperty(message),
this.createObjectProperty(MESSAGE, this.types.stringLiteral(message)),
this.createValuesProperty(values),
]

const newNode = this.createI18nCall(
this.createMessageDescriptor(
properties,
// preserve line numbers for extractor
path.node.loc
),
this.createMessageDescriptorFromTokens(tokens, path.node.loc),
linguiInstance
)

Expand All @@ -91,9 +86,29 @@ export default class MacroJs {
// reset the expression counter
this._expressionIndex = makeCounter()

if (this.isDefineMessage(path.node)) {
this.replaceDefineMessage(path as NodePath<CallExpression>)
return true
// defineMessage({ message: "Message", context: "My" }) -> {id: <hash + context>, message: "Message"}
if (
this.types.isCallExpression(path.node) &&
this.isDefineMessage(path.node.callee)
) {
let descriptor = this.processDescriptor(path.node.arguments[0])
path.replaceWith(descriptor)
return false
}

// defineMessage`Message` -> {id: <hash>, message: "Message"}
if (
this.types.isTaggedTemplateExpression(path.node) &&
this.isDefineMessage(path.node.tag)
) {
const tokens = this.tokenizeTemplateLiteral(path.node.quasi)
const descriptor = this.createMessageDescriptorFromTokens(
tokens,
path.node.loc
)

path.replaceWith(descriptor)
return false
}

// t(i18nInstance)`Message` -> i18nInstance._(messageDescriptor)
Expand All @@ -107,15 +122,7 @@ export default class MacroJs {
const i18nInstance = path.node.arguments[0]
const tokens = this.tokenizeNode(path.parentPath.node)

const messageFormat = new ICUMessageFormat()
const { message: messageRaw, values } = messageFormat.fromTokens(tokens)
const message = normalizeWhitespace(messageRaw)

this.replacePathWithMessage(
path.parentPath,
{ message, values },
i18nInstance
)
this.replacePathWithMessage(path.parentPath, tokens, i18nInstance)
return false
}

Expand All @@ -135,6 +142,7 @@ export default class MacroJs {
return false
}

// t({...})
if (
this.types.isCallExpression(path.node) &&
this.isLinguiIdentifier(path.node.callee, "t")
Expand All @@ -145,45 +153,11 @@ export default class MacroJs {

const tokens = this.tokenizeNode(path.node)

const messageFormat = new ICUMessageFormat()
const { message: messageRaw, values } = messageFormat.fromTokens(tokens)
const message = normalizeWhitespace(messageRaw)

this.replacePathWithMessage(path, { message, values })
this.replacePathWithMessage(path, tokens)

return true
}

/**
* macro `defineMessage` is called with MessageDescriptor. The only
* thing that happens is that any macros used in `message` property
* are replaced with formatted message.
*
* import { defineMessage, plural } from '@lingui/macro';
* const message = defineMessage({
* id: "msg.id",
* comment: "Description",
* message: plural(value, { one: "book", other: "books" })
* })
*
* ↓ ↓ ↓ ↓ ↓ ↓
*
* const message = {
* id: "msg.id",
* comment: "Description",
* message: "{value, plural, one {book} other {books}}"
* }
*
*/
replaceDefineMessage = (path: NodePath<CallExpression>) => {
// reset the expression counter
this._expressionIndex = makeCounter()

let descriptor = this.processDescriptor(path.node.arguments[0])

path.replaceWith(descriptor)
}

/**
* macro `t` is called with MessageDescriptor, after that
* we create a new node to append it to i18n._
Expand All @@ -209,7 +183,8 @@ export default class MacroJs {
*
* {
* comment: "Description",
* id: "{value, plural, one {book} other {books}}"
* id: <hash>
* message: "{value, plural, one {book} other {books}}"
* }
*
*/
Expand Down Expand Up @@ -237,9 +212,7 @@ export default class MacroJs {
let messageNode = messageProperty.value as StringLiteral

if (tokens) {
const messageFormat = new ICUMessageFormat()
const { message: messageRaw, values } = messageFormat.fromTokens(tokens)
const message = normalizeWhitespace(messageRaw)
const { message, values } = buildICUFromTokens(tokens)
messageNode = this.types.stringLiteral(message)

properties.push(this.createValuesProperty(values))
Expand Down Expand Up @@ -435,6 +408,26 @@ export default class MacroJs {
)
}

createMessageDescriptorFromTokens(tokens: Tokens, oldLoc?: SourceLocation) {
const { message, values } = buildICUFromTokens(tokens)

const properties: ObjectProperty[] = [
this.createIdProperty(message),

!this.stripNonEssentialProps
? this.createObjectProperty(MESSAGE, this.types.stringLiteral(message))
: null,

this.createValuesProperty(values),
]

return this.createMessageDescriptor(
properties,
// preserve line numbers for extractor
oldLoc
)
}

createMessageDescriptor(
properties: ObjectProperty[],
oldLoc?: SourceLocation
Expand Down Expand Up @@ -473,10 +466,10 @@ export default class MacroJs {
})
}

isDefineMessage(node: Node): boolean {
isDefineMessage(node: Node | Expression): boolean {
return (
this.types.isCallExpression(node) &&
this.isLinguiIdentifier(node.callee, "defineMessage")
this.isLinguiIdentifier(node, "defineMessage") ||
this.isLinguiIdentifier(node, "msg")
)
}

Expand Down
Loading

0 comments on commit 9b92731

Please sign in to comment.