forked from lingui/js-lingui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmacroJsx.ts
More file actions
510 lines (441 loc) · 13.8 KB
/
macroJsx.ts
File metadata and controls
510 lines (441 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
import * as babelTypes from "@babel/types"
import {
ConditionalExpression,
Expression,
JSXAttribute,
JSXElement,
JSXExpressionContainer,
JSXIdentifier,
JSXSpreadAttribute,
Literal,
Node,
StringLiteral,
TemplateLiteral,
SourceLocation,
Identifier,
} from "@babel/types"
import type { NodePath } from "@babel/traverse"
import { ArgToken, ElementToken, TextToken, Token } from "./icu"
import { makeCounter } from "./utils"
import { JsxMacroName, MsgDescriptorPropKey, JsMacroName } from "./constants"
import cleanJSXElementLiteralChild from "./utils/cleanJSXElementLiteralChild"
import { createMessageDescriptorFromTokens } from "./messageDescriptorUtils"
import {
createMacroJsContext,
MacroJsContext,
tokenizeExpression,
} from "./macroJsAst"
import { LinguiConfigNormalized } from "@lingui/conf"
import { PluginPass } from "@babel/core"
const pluralRuleRe = /(_[\d\w]+|zero|one|two|few|many|other)/
const jsx2icuExactChoice = (value: string) =>
value.replace(/_(\d+)/, "=$1").replace(/_(\w+)/, "$1")
type JSXChildPath = NodePath<JSXElement["children"][number]>
function maybeNodeValue(node: Node): { text: string; loc: SourceLocation } {
if (!node) return null
if (node.type === "StringLiteral") return { text: node.value, loc: node.loc }
if (node.type === "JSXAttribute") return maybeNodeValue(node.value)
if (node.type === "JSXExpressionContainer")
return maybeNodeValue(node.expression)
if (node.type === "TemplateLiteral" && node.expressions.length === 0)
return { text: node.quasis[0].value.raw, loc: node.loc }
return null
}
export type MacroJsxContext = MacroJsContext & {
elementIndex: () => number
transImportName: string
elementsTracking: Map<string, JSXElement>
jsxPlaceholderAttribute?: string
jsxPlaceholderDefaults?: Record<string, string>
}
export type MacroJsxOpts = {
stripNonEssentialProps: boolean
stripMessageProp: boolean
transImportName: string
isLinguiIdentifier: (node: Identifier, macro: JsMacroName) => boolean
jsxPlaceholderAttribute?: string
jsxPlaceholderDefaults?: Record<string, string>
}
const choiceComponentAttributesWhitelist = [
"_\\w+",
"_\\d+",
"zero",
"one",
"two",
"few",
"many",
"other",
"value",
"offset",
]
export class MacroJSX {
types: typeof babelTypes
ctx: MacroJsxContext
constructor({ types }: { types: typeof babelTypes }, opts: MacroJsxOpts) {
this.types = types
this.ctx = {
...createMacroJsContext(
opts.isLinguiIdentifier,
opts.stripNonEssentialProps,
opts.stripMessageProp,
),
transImportName: opts.transImportName,
elementIndex: makeCounter(),
elementsTracking: new Map(),
jsxPlaceholderAttribute: opts.jsxPlaceholderAttribute,
jsxPlaceholderDefaults: opts.jsxPlaceholderDefaults,
}
}
replacePath = (path: NodePath): false | Node => {
if (!path.isJSXElement()) {
return false
}
const tokens = this.tokenizeNode(path, true, true)
if (!tokens) {
return false
}
const { attributes, id, comment, context } = this.stripMacroAttributes(
path as NodePath<JSXElement>,
)
if (!tokens.length) {
throw new Error("Incorrect usage of Trans")
}
const messageDescriptor = createMessageDescriptorFromTokens(
tokens,
path.node.loc,
this.ctx.stripNonEssentialProps,
this.ctx.stripMessageProp,
{
id,
context,
comment,
},
)
attributes.push(this.types.jsxSpreadAttribute(messageDescriptor))
const newNode = this.types.jsxElement(
this.types.jsxOpeningElement(
this.types.jsxIdentifier(this.ctx.transImportName),
attributes,
true,
),
null,
[],
true,
)
newNode.loc = path.node.loc
return newNode
}
attrName = (names: string[], exclude = false) => {
const namesRe = new RegExp("^(" + names.join("|") + ")$")
return (attr: JSXAttribute | JSXSpreadAttribute) => {
const name = ((attr as JSXAttribute).name as JSXIdentifier).name
return exclude ? !namesRe.test(name) : namesRe.test(name)
}
}
stripMacroAttributes = (path: NodePath<JSXElement>) => {
const { attributes } = path.node.openingElement
const id = attributes.find(this.attrName([MsgDescriptorPropKey.id]))
const message = attributes.find(
this.attrName([MsgDescriptorPropKey.message]),
)
const comment = attributes.find(
this.attrName([MsgDescriptorPropKey.comment]),
)
const context = attributes.find(
this.attrName([MsgDescriptorPropKey.context]),
)
let reserved: string[] = [
MsgDescriptorPropKey.id,
MsgDescriptorPropKey.message,
MsgDescriptorPropKey.comment,
MsgDescriptorPropKey.context,
]
if (this.isChoiceComponent(path)) {
reserved = [...reserved, ...choiceComponentAttributesWhitelist]
}
return {
id: maybeNodeValue(id),
message: maybeNodeValue(message),
comment: maybeNodeValue(comment),
context: maybeNodeValue(context),
attributes: attributes.filter(this.attrName(reserved, true)),
}
}
tokenizeNode = (
path: NodePath,
ignoreExpression = false,
ignoreElement = false,
): Token[] => {
if (this.isTransComponent(path)) {
// t
return this.tokenizeTrans(path)
}
const componentName = this.isChoiceComponent(path)
if (componentName) {
// plural, select and selectOrdinal
return [
this.tokenizeChoiceComponent(
path as NodePath<JSXElement>,
componentName,
),
]
}
if (path.isJSXElement() && !ignoreElement) {
return [this.tokenizeElement(path)]
}
if (!ignoreExpression) {
return [this.tokenizeExpression(path)]
}
}
tokenizeTrans = (path: NodePath<JSXElement>): Token[] => {
return path
.get("children")
.flatMap((child) => this.tokenizeChildren(child))
.filter(Boolean)
}
tokenizeChildren = (path: JSXChildPath): Token[] => {
if (path.isJSXExpressionContainer()) {
const exp = path.get("expression") as NodePath<Expression>
// Ignore JSX comments like {/* comment */} - they should not affect
// the message or consume expression indices
if (exp.isJSXEmptyExpression()) {
return []
}
if (exp.isStringLiteral()) {
return [this.tokenizeText(exp.node.value)]
}
if (exp.isTemplateLiteral()) {
return this.tokenizeTemplateLiteral(exp)
}
if (exp.isConditionalExpression()) {
return [this.tokenizeConditionalExpression(exp)]
}
if (exp.isJSXElement()) {
return this.tokenizeNode(exp)
}
return [this.tokenizeExpression(exp)]
} else if (path.isJSXElement()) {
return this.tokenizeNode(path)
} else if (path.isJSXSpreadChild()) {
throw new Error(
"Incorrect usage of Trans: Spread could not be used as Trans children",
)
} else if (path.isJSXText()) {
return [this.tokenizeText(cleanJSXElementLiteralChild(path.node.value))]
} else {
// impossible path
// return this.tokenizeText(node.value)
}
}
tokenizeTemplateLiteral(exp: NodePath<TemplateLiteral>): Token[] {
const expressions = exp.get("expressions") as NodePath<Expression>[]
return exp.get("quasis").flatMap(({ node: text }, i) => {
const value = text.value.cooked
let argTokens: Token[] = []
const currExp = expressions[i]
if (currExp) {
argTokens = currExp.isCallExpression()
? this.tokenizeNode(currExp)
: [this.tokenizeExpression(currExp)]
}
return [...(value ? [this.tokenizeText(value)] : []), ...argTokens]
})
}
tokenizeChoiceComponent = (
path: NodePath<JSXElement>,
componentName: JsxMacroName,
): Token => {
const element = path.get("openingElement")
const format = componentName.toLowerCase()
const props = element.get("attributes").filter((attr) => {
return this.attrName(choiceComponentAttributesWhitelist)(attr.node)
})
let token: Token = {
type: "arg",
format,
name: null,
value: undefined,
options: {
offset: undefined,
},
}
for (const _attr of props) {
if (_attr.isJSXSpreadAttribute()) {
continue
}
const attr = _attr as NodePath<JSXAttribute>
if (this.types.isJSXNamespacedName(attr.node.name)) {
continue
}
const name = attr.node.name.name
const value = attr.get("value") as
| NodePath<Literal>
| NodePath<JSXExpressionContainer>
if (name === "value") {
token = {
...token,
...this.tokenizeExpression(
value.isLiteral() ? value : value.get("expression"),
),
}
} else if (format !== "select" && name === "offset") {
// offset is static parameter, so it must be either string or number
token.options.offset =
value.isStringLiteral() || value.isNumericLiteral()
? (value.node.value as string)
: (
(value as NodePath<JSXExpressionContainer>).get(
"expression",
) as NodePath<StringLiteral>
).node.value
} else {
let option: ArgToken["options"][number]
if (value.isStringLiteral()) {
option = (value.node.extra.raw as string).replace(
/(["'])(.*)\1/,
"$2",
)
} else {
option = this.tokenizeChildren(value as JSXChildPath)
}
if (pluralRuleRe.test(name)) {
token.options[jsx2icuExactChoice(name)] = option
} else {
token.options[name] = option
}
}
}
return token
}
tokenizeElement = (path: NodePath<JSXElement>): ElementToken => {
const {
jsxPlaceholderAttribute,
jsxPlaceholderDefaults,
elementsTracking,
} = this.ctx
let node = path.node
let name: string | undefined = undefined
if (jsxPlaceholderAttribute) {
const { attributes } = node.openingElement
const attrIndex = attributes.findIndex(
(attr) =>
attr.type === "JSXAttribute" &&
attr.name.name === jsxPlaceholderAttribute,
)
if (attrIndex !== -1) {
const attr = attributes[attrIndex] as JSXAttribute
if (attr.value && attr.value.type === "StringLiteral") {
name = attr.value.value
}
const newAttributes = [...attributes]
newAttributes.splice(attrIndex, 1)
node = {
...node,
openingElement: {
...node.openingElement,
attributes: newAttributes,
},
}
}
}
if (!name && jsxPlaceholderDefaults) {
const tagName = node.openingElement.name
if (tagName.type === "JSXIdentifier") {
name = jsxPlaceholderDefaults[tagName.name]
}
}
if (!name) {
name = String(this.ctx.elementIndex())
elementsTracking.set(name, node)
} else {
const existingElement = elementsTracking.get(name)
if (existingElement) {
const existingAttrs = existingElement.openingElement.attributes
const openingAttrs = node.openingElement.attributes
if (
existingAttrs.length !== openingAttrs.length ||
!existingAttrs.every((a) =>
openingAttrs.some((b) => this.types.isNodesEquivalent(a, b)),
)
) {
const eg = `(e.g. \`<element ${jsxPlaceholderAttribute || '_t'}="newName" />\`)`
const msg = `Multiple distinct JSX elements with the same placeholder name (\`${name}\`). `
+ (jsxPlaceholderAttribute
? `Differentiate them by adding/modifying the \`${jsxPlaceholderAttribute}\` attribute ${eg}.`
: `Differentiate them by setting \`macro.jsxPlaceholderAttribute\` in the lingui config and then adding the attribute to your JSX elements ${eg}.`
)
throw path.buildCodeFrameError(msg)
}
} else {
elementsTracking.set(name, node)
}
}
return {
type: "element",
name,
value: {
...node,
children: [],
openingElement: {
...node.openingElement,
selfClosing: true,
},
},
children: this.tokenizeTrans(path),
}
}
tokenizeExpression = (path: NodePath<Expression | Node>): ArgToken => {
return tokenizeExpression(path.node, this.ctx)
}
tokenizeConditionalExpression = (
exp: NodePath<ConditionalExpression>,
): ArgToken => {
exp.traverse(
{
JSXElement: (el) => {
if (this.isTransComponent(el) || this.isChoiceComponent(el)) {
this.replacePath(el)
el.skip()
}
},
},
exp.state,
)
return this.tokenizeExpression(exp)
}
tokenizeText = (value: string): TextToken => {
return {
type: "text",
value,
}
}
isLinguiComponent = (
path: NodePath,
name: JsxMacroName,
): path is NodePath<JSXElement> => {
if (!path.isJSXElement()) {
return false
}
const config = (path.context.state as PluginPass).get(
"linguiConfig",
) as LinguiConfigNormalized
const identifier = path.get("openingElement").get("name")
return config.macro.jsxPackage.some((moduleSource) =>
identifier.referencesImport(moduleSource, name),
)
}
isTransComponent = (path: NodePath): path is NodePath<JSXElement> => {
return this.isLinguiComponent(path, JsxMacroName.Trans)
}
isChoiceComponent = (path: NodePath): JsxMacroName => {
if (this.isLinguiComponent(path, JsxMacroName.Plural)) {
return JsxMacroName.Plural
}
if (this.isLinguiComponent(path, JsxMacroName.Select)) {
return JsxMacroName.Select
}
if (this.isLinguiComponent(path, JsxMacroName.SelectOrdinal)) {
return JsxMacroName.SelectOrdinal
}
}
}