fix: add support for jsx expression

This commit is contained in:
wukidy 2022-10-25 15:41:56 +08:00 committed by LeoYuan 袁力皓
parent e0e537a5a3
commit 453e0699ec
4 changed files with 87 additions and 2 deletions

View File

@ -161,7 +161,11 @@ export function parseExpressionGetKeywords(expr: string | null | undefined): str
try {
const keywordVars = new OrderedSet<string>();
const ast = parser.parse(`!(${expr});`);
const ast = parser.parse(`!(${expr});`, {
plugins: [
'jsx',
],
});
const addIdentifierIfNeeded = (x: Record<string, unknown> | number | null | undefined) => {
if (typeof x === 'object' && isIdentifier(x) && JS_KEYWORDS.includes(x.name)) {

View File

@ -8,7 +8,12 @@ import { transformExpressionLocalRef, ParseError } from './expressionParser';
function parseFunction(content: string): t.FunctionExpression | null {
try {
const ast = parser.parse(`(${content});`);
const ast = parser.parse(`(${content});`, {
plugins: [
'jsx',
],
});
let resultNode: t.FunctionExpression | null = null;
traverse(ast, {
FunctionExpression(path) {

View File

@ -0,0 +1,45 @@
import { generateFunction } from '../../../src/utils/jsExpression';
const marcoFactory = () => {
const cases: any[] = [];
const marco = (
value: { type: string; value: string },
config: Record<string, string | boolean>,
expected: any,
) => {
cases.push([value, config, expected]);
};
const start = () => {
test.each(cases)(`after convert this to context "${1}" should be "${3}"`, (a, b, expected) => {
expect(generateFunction(a, b)).toEqual(expected);
});
};
return { marco, start };
};
const { marco: testMarco, start: startMarco } = marcoFactory();
// 支持普通函数
testMarco(
{
type: 'JSFunction',
value: 'function isDisabled(row, rowIndex) { \n \n}',
},
{ isArrow: true },
'(row, rowIndex) => {}',
);
// 支持 jsx 表达式
testMarco(
{
type: 'JSFunction',
value: 'function content() { \n return <div>我是自定义在div内容123</div> \n}',
},
{ isArrow: true },
'() => {\n return <div>我是自定义在div内容123</div>;\n}',
);
startMarco();

View File

@ -0,0 +1,31 @@
import { parseExpressionGetKeywords } from '../../../src/utils/expressionParser';
const marcoFactory = () => {
const cases: any[] = [];
const marco = (input: string | null, expected: any) => {
cases.push([input, expected]);
};
const start = () => {
test.each(cases)(
`after convert this to context "${1}" should be "${2}"`,
(a, expected) => {
expect(parseExpressionGetKeywords(a)).toEqual(expected);
},
);
};
return { marco, start };
};
const { marco: testMarco, start: startMarco } = marcoFactory();
// 支持普通函数
testMarco('function isDisabled(row) {}', []);
testMarco('function content() { \n return "hello world"\n}', []);
// 支持 jsx 表达式
testMarco('function content() { \n return <div>自定义在div内容123</div> \n}', []);
startMarco();