From 5c460aee354452c9dbc55231f76135d8d0140a01 Mon Sep 17 00:00:00 2001 From: ddyo Date: Wed, 6 Mar 2024 03:13:07 +0200 Subject: [PATCH] support transforming member expressions to args --- packages/macro/src/macroJs.ts | 21 +++++++++++++++++++++ packages/macro/src/macroJsx.ts | 31 ++++++++++++++++++++++++++++++- 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/packages/macro/src/macroJs.ts b/packages/macro/src/macroJs.ts index 49bedba1d..fa4df0bdd 100644 --- a/packages/macro/src/macroJs.ts +++ b/packages/macro/src/macroJs.ts @@ -10,6 +10,7 @@ import { SourceLocation, StringLiteral, TemplateLiteral, + MemberExpression, } from "@babel/types" import { NodePath } from "@babel/traverse" @@ -367,11 +368,31 @@ export default class MacroJs { } } + memberExpressionToArgument(exp: MemberExpression): string { + let parts: string[] = [] + + if (this.types.isThisExpression(exp.object)) { + // ignore this + } else { + parts.unshift(this.expressionToArgument(exp.object)) + } + + parts.push( + this.expressionToArgument( + this.types.isPrivateName(exp.property) ? exp.property.id : exp.property + ) + ) + + return parts.join("_") + } + expressionToArgument(exp: Expression): string { if (this.types.isIdentifier(exp)) { return exp.name } else if (this.types.isStringLiteral(exp)) { return exp.value + } else if (this.types.isMemberExpression(exp)) { + return this.memberExpressionToArgument(exp) } else { return String(this._expressionIndex()) } diff --git a/packages/macro/src/macroJsx.ts b/packages/macro/src/macroJsx.ts index 66046967a..4c1c95774 100644 --- a/packages/macro/src/macroJsx.ts +++ b/packages/macro/src/macroJsx.ts @@ -1,6 +1,7 @@ import * as babelTypes from "@babel/types" import { ConditionalExpression, + MemberExpression, Expression, JSXAttribute, JSXElement, @@ -285,6 +286,7 @@ export default class MacroJSX { if (exp.isJSXElement()) { return this.tokenizeNode(exp) } + return [this.tokenizeExpression(exp)] } else if (path.isJSXElement()) { return this.tokenizeNode(path) @@ -464,8 +466,35 @@ export default class MacroJSX { } } + memberExpressionToArgument(path: NodePath): string { + let parts: string[] = [] + + if (this.types.isThisExpression(path.node.object)) { + // ignore this + } else { + parts.unshift(this.expressionToArgument(path.get("object"))) + } + + const propertyPath = path.get("property") + + parts.push( + this.expressionToArgument( + propertyPath.isPrivateName() ? propertyPath.get("id") : propertyPath + ) + ) + return parts.join("_") + } + expressionToArgument(path: NodePath): string { - return path.isIdentifier() ? path.node.name : String(this.expressionIndex()) + if (this.types.isIdentifier(path.node)) { + return path.node.name + } else if (this.types.isStringLiteral(path.node)) { + return path.node.value + } else if (path.isMemberExpression()) { + return this.memberExpressionToArgument(path) + } else { + return String(this.expressionIndex()) + } } /**