Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/add jsx list #1

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
lib

# Logs
logs
*.log
Expand Down Expand Up @@ -102,3 +104,5 @@ dist

# TernJS port file
.tern-port

package-lock.json
8 changes: 8 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions .idea/swc-plugin-transform-jsx-list.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions __tests__/__fixtures__/example/actual.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { createElement } from 'react';

function Foo() {
return (
<View>
<View x-for={array}>hello</View>
<View x-for={item in array}>item: {item}</View>
<View x-for={(item, key) in foo}>key: {key}, item: {item}</View>
<View x-for={(item, key) in exp()}>key: {key}, item: {item}</View>
</View>
)
}
14 changes: 14 additions & 0 deletions __tests__/__fixtures__/example/expected.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { createList as __create_list__ } from "babel-runtime-jsx-plus";
import { createElement } from "react";
function Foo() {
return /*#__PURE__*/ React.createElement(View, null, __create_list__.call(this, array, function() {
return React.createElement(View, null, "hello");
}), __create_list__.call(this, array, function(item) {
return React.createElement(View, null, "item: ", item);
}), __create_list__.call(this, foo, function(item, key) {
return React.createElement(View, null, "key: ", key, ", item: ", item);
}), __create_list__.call(this, exp(), function(item, key) {
return React.createElement(View, null, "key: ", key, ", item: ", item);
}));
}

11 changes: 11 additions & 0 deletions __tests__/__fixtures__/side-effects/actual.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const items = [1, 2, 3, 4];

export default function List() {
return (
<div>
<div x-for={(it, idx) in items}>
<span>{it}</span>
</div>
</div>
);
}
13 changes: 13 additions & 0 deletions __tests__/__fixtures__/side-effects/expected.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { createList as __create_list__ } from "babel-runtime-jsx-plus";
var items = [
1,
2,
3,
4
];
export default function List() {
return /*#__PURE__*/ React.createElement("div", null, __create_list__.call(this, items, function(it, idx) {
return React.createElement("div", null, /*#__PURE__*/ React.createElement("span", null, it));
}));
};

27 changes: 27 additions & 0 deletions __tests__/usage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const swc = require('@swc/core')
const path = require('path')
const fs = require('fs');
const JSXConditionTransformPlugin = require(path.join(__dirname, '../lib/index.js')).default;

describe('', () => {
const fixturesDir = path.join(__dirname, '__fixtures__');
fs.readdirSync(fixturesDir).map((caseName) => {
it(`should ${caseName.split('-').join(' ')}`, () => {
const fixtureDir = path.join(fixturesDir, caseName);
const actualPath = path.join(fixtureDir, 'actual.js');
const actualCode = fs.readFileSync(actualPath, {encoding: 'utf-8'});
const expectedCode = fs.readFileSync(path.join(fixtureDir, 'expected.js'), { encoding: 'utf-8' });

const transformedOutput = swc.transformSync(actualCode, {
jsc: {
parser: {
jsx: true
},
},
plugin: JSXConditionTransformPlugin
});

expect(transformedOutput.code.trim()).toBe(expectedCode.trim());
});
});
});
8 changes: 8 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Sync object
/** @type {import('@jest/types').Config.InitialOptions} */
const config = {
verbose: true,
testMatch: ['!**/__fixtures__/**', '**/__tests__/**/*.js']
};

module.exports = config;
28 changes: 28 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "swc-plugin-transform-jsx-list",
"version": "0.1.0-beta.1",
"description": "Support of transform jsx list directive based on SWC",
"main": "lib/index.js",
"scripts": {
"build": "tsc -d",
"build:watch": "tsc -d --watch",
"test": "jest"
},
"types": "./lib/index.d.ts",
"repository": {
"type": "git",
"url": "git+https://github.com/jsx-plus/swc-plugin-transform-jsx-list.git"
},
"devDependencies": {
"jest": "^24.9.0",
"typescript": "^4.7.3"
},
"dependencies": {
"@swc/core": "^1.2.203"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/jsx-plus/swc-plugin-transform-jsx-list/issues"
},
"homepage": "https://github.com/jsx-plus/swc-plugin-transform-jsx-list#readme"
}
149 changes: 149 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import {
Expression, JSXAttribute, JSXAttrValue,
JSXElement, JSXExpression, JSXText, Program,
} from '@swc/core';
import Visitor from '@swc/core/Visitor';
import {
ExprOrSpread, JSXElementChild, Pattern
} from '@swc/core/types';
import {
buildArrayExpression,
buildArrowFunctionExpression,
buildBooleanLiteral,
buildCallExpression,
buildIdentifier,
buildImportDeclaration,
buildJSXElement,
buildJSXExpressionContainer,
buildJSXText,
buildMemberExpression,
buildNamedImportSpecifier,
buildNullLiteral,
buildStringLiteral, buildThisExpression
} from './utils';

function JSXListToStandard(n: JSXElement) {
let openingAttributes = n.opening.attributes;

if (openingAttributes) {
openingAttributes = openingAttributes.filter((attribute) => {
if (attribute.type === 'JSXAttribute' && attribute.name.type === 'Identifier' && attribute.name.value === 'x-for') {
return false;
}
return true;
});
}
return buildJSXElement({
...n.opening,
attributes: openingAttributes
}, n.children, n.closing)
}

function transformJSXList(n: JSXElement, currentList: JSXElementChild[], currentIndex: number): JSXElement | JSXText {
n.children = n.children.map((c, i) => {
if (c.type === 'JSXElement' && isJSXList(c)) {
return transformJSXList(c, n.children, i);
}
return c;
});

if (isJSXList(n)) {
let attrValue = getJSXList(n);
if (!attrValue || attrValue.type !== 'JSXExpressionContainer') {
console.warn('ignore x-for due to stynax error.');
return n;
}

// @ts-ignore
if (n.__listHandled) return n;
// @ts-ignore
n.__listHandled = true;

let { expression } = attrValue;
let params: Pattern[] = [];
let iterValue: Expression;

if (expression.type === 'BinaryExpression' && expression.operator === 'in') {
// x-for={(item, index) in value}
const { left, right } = expression;
iterValue = right;

if (left.type === 'ParenthesisExpression' && left.expression.type === 'SequenceExpression') {
// x-for={(item, key) in value}
params = left.expression.expressions;
} else if (left.type === 'Identifier') {
// x-for={item in value}
params.push(buildIdentifier(left.value));
} else {
// x-for={??? in value}
throw new Error('Stynax error of x-for.');
}
} else {
// x-for={value}, x-for={callExp()}, ...
iterValue = expression;
}

let callee = buildMemberExpression(buildIdentifier('__create_list__'), buildIdentifier('call'));
let body = buildCallExpression(callee, [
{
expression: buildThisExpression()
},
{
expression: iterValue
},
{
expression: buildArrowFunctionExpression(params, JSXListToStandard(n))
}
]) as any;

return buildJSXExpressionContainer(body) as any;
}

return n;
}

function getJSXList(n: JSXElement): JSXAttrValue | undefined {
let opening = n.opening;
let openingAttributes = opening.attributes;

if (openingAttributes) {
for (let attribute of openingAttributes) {
if (attribute.type === 'JSXAttribute' && attribute.name.type === 'Identifier' && attribute.name.value === 'x-for') {
return attribute.value;
}
}
}
}

function isJSXList(n: JSXElement): boolean {
let opening = n.opening;
let openingAttributes = opening.attributes;

if (openingAttributes) {
for (let attribute of openingAttributes) {
if (attribute.type === 'JSXAttribute' && attribute.name.type === 'Identifier' && attribute.name.value === 'x-for') {
return true;
}
}
}
return false;
}

class JSXListTransformer extends Visitor {
visitJSXElement(n: JSXElement): JSXElement {
return transformJSXList(n, [], -1) as JSXElement;
}
}

export default function JSXConditionTransformPlugin(m: Program): Program {
let result = new JSXListTransformer().visitProgram(m);
let babelImport = buildImportDeclaration([
buildNamedImportSpecifier(
buildIdentifier('__create_list__', false),
buildIdentifier('createList', false)
)
], buildStringLiteral('babel-runtime-jsx-plus'));
result.body.unshift(babelImport as any);

return result;
}
Loading