mirror of
https://github.com/alibaba/lowcode-engine.git
synced 2026-01-13 09:41:57 +00:00
Merge branch 'feat/for-merge' into feat/rax-code-generator
This commit is contained in:
commit
a4cf3ccc63
13473
packages/code-generator/demo/assets.json
Normal file
13473
packages/code-generator/demo/assets.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -4,20 +4,20 @@ const CodeGenerator = require('../lib').default;
|
||||
|
||||
function flatFiles(rootName, dir) {
|
||||
const dirRoot = rootName ? `${rootName}/${dir.name}` : dir.name;
|
||||
const files = dir.files.map(file => ({
|
||||
const files = dir.files.map((file) => ({
|
||||
name: `${dirRoot}/${file.name}.${file.ext}`,
|
||||
content: file.content,
|
||||
ext: '',
|
||||
}));
|
||||
const filesInSub = dir.dirs.map(subDir => flatFiles(`${dirRoot}`, subDir));
|
||||
const result = files.concat.apply(files, filesInSub);
|
||||
const filesInSub = dir.dirs.map((subDir) => flatFiles(`${dirRoot}`, subDir));
|
||||
const result = files.concat(...filesInSub);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function displayResultInConsole(root, fileName) {
|
||||
const files = flatFiles('.', root);
|
||||
files.forEach(file => {
|
||||
files.forEach((file) => {
|
||||
if (!fileName || fileName === file.name) {
|
||||
console.log(`========== ${file.name} Start ==========`);
|
||||
console.log(file.content);
|
||||
@ -37,20 +37,62 @@ async function writeResultToDisk(root, path) {
|
||||
});
|
||||
}
|
||||
|
||||
function getComponentsMap() {
|
||||
const assetJson = fs.readFileSync('./demo/assets.json', { encoding: 'utf8' });
|
||||
const assets = JSON.parse(assetJson);
|
||||
const { components } = assets;
|
||||
|
||||
const componentsMap = components
|
||||
.filter((c) => !!c.npm)
|
||||
.map((c) => ({
|
||||
componentName: c.componentName,
|
||||
...(c.npm || {}),
|
||||
}));
|
||||
|
||||
return componentsMap;
|
||||
}
|
||||
|
||||
function main() {
|
||||
const schemaJson = fs.readFileSync('./demo/sampleSchema.json', { encoding: 'utf8' });
|
||||
const createIceJsProjectBuilder = CodeGenerator.solutions.icejs;
|
||||
const builder = createIceJsProjectBuilder();
|
||||
|
||||
builder.generateProject(schemaJson).then(result => {
|
||||
builder.generateProject(schemaJson).then((result) => {
|
||||
displayResultInConsole(result);
|
||||
writeResultToDisk(result, 'output/lowcodeDemo').then(response =>
|
||||
writeResultToDisk(result, 'output/lowcodeDemo').then((response) =>
|
||||
console.log('Write to disk: ', JSON.stringify(response)),
|
||||
);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
function demo() {
|
||||
const schemaJson = fs.readFileSync('./demo/schema.json', { encoding: 'utf8' });
|
||||
const createIceJsProjectBuilder = CodeGenerator.solutions.icejs;
|
||||
const builder = createIceJsProjectBuilder();
|
||||
|
||||
const componentsMap = getComponentsMap();
|
||||
const root = JSON.parse(schemaJson);
|
||||
|
||||
const fullSchema = {
|
||||
version: '1.0.0',
|
||||
config: {
|
||||
historyMode: 'hash',
|
||||
targetRootID: 'J_Container',
|
||||
},
|
||||
meta: {
|
||||
name: 'demoproject',
|
||||
},
|
||||
componentsTree: [root],
|
||||
componentsMap,
|
||||
};
|
||||
|
||||
builder.generateProject(fullSchema).then((result) => {
|
||||
displayResultInConsole(result);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
function exportModule() {
|
||||
const schemaJson = fs.readFileSync('./demo/shenmaSample.json', { encoding: 'utf8' });
|
||||
const moduleBuilder = CodeGenerator.createModuleBuilder({
|
||||
@ -66,13 +108,11 @@ function exportModule() {
|
||||
CodeGenerator.plugins.react.jsx(),
|
||||
CodeGenerator.plugins.style.css(),
|
||||
],
|
||||
postProcessors: [
|
||||
CodeGenerator.postprocessor.prettier(),
|
||||
],
|
||||
postProcessors: [CodeGenerator.postprocessor.prettier()],
|
||||
mainFileName: 'index',
|
||||
});
|
||||
|
||||
moduleBuilder.generateModuleCode(schemaJson).then(result => {
|
||||
moduleBuilder.generateModuleCode(schemaJson).then((result) => {
|
||||
displayResultInConsole(result);
|
||||
return result;
|
||||
});
|
||||
@ -81,7 +121,7 @@ function exportModule() {
|
||||
function exportProject() {
|
||||
const schemaJson = fs.readFileSync('./demo/sampleSchema.json', { encoding: 'utf8' });
|
||||
|
||||
const builder = CodeGenerator.createProjectBuilder({
|
||||
const builder = CodeGenerator.createProjectBuilder({
|
||||
template: CodeGenerator.solutionParts.icejs.template,
|
||||
plugins: {
|
||||
components: [
|
||||
@ -108,41 +148,21 @@ function exportProject() {
|
||||
CodeGenerator.plugins.react.jsx(),
|
||||
CodeGenerator.plugins.style.css(),
|
||||
],
|
||||
router: [
|
||||
CodeGenerator.plugins.common.esmodule(),
|
||||
CodeGenerator.solutionParts.icejs.plugins.router(),
|
||||
],
|
||||
entry: [
|
||||
CodeGenerator.solutionParts.icejs.plugins.entry(),
|
||||
],
|
||||
constants: [
|
||||
CodeGenerator.plugins.project.constants(),
|
||||
],
|
||||
utils: [
|
||||
CodeGenerator.plugins.common.esmodule(),
|
||||
CodeGenerator.plugins.project.utils(),
|
||||
],
|
||||
i18n: [
|
||||
CodeGenerator.plugins.project.i18n(),
|
||||
],
|
||||
globalStyle: [
|
||||
CodeGenerator.solutionParts.icejs.plugins.globalStyle(),
|
||||
],
|
||||
htmlEntry: [
|
||||
CodeGenerator.solutionParts.icejs.plugins.entryHtml(),
|
||||
],
|
||||
packageJSON: [
|
||||
CodeGenerator.solutionParts.icejs.plugins.packageJSON(),
|
||||
],
|
||||
router: [CodeGenerator.plugins.common.esmodule(), CodeGenerator.solutionParts.icejs.plugins.router()],
|
||||
entry: [CodeGenerator.solutionParts.icejs.plugins.entry()],
|
||||
constants: [CodeGenerator.plugins.project.constants()],
|
||||
utils: [CodeGenerator.plugins.common.esmodule(), CodeGenerator.plugins.project.utils()],
|
||||
i18n: [CodeGenerator.plugins.project.i18n()],
|
||||
globalStyle: [CodeGenerator.solutionParts.icejs.plugins.globalStyle()],
|
||||
htmlEntry: [CodeGenerator.solutionParts.icejs.plugins.entryHtml()],
|
||||
packageJSON: [CodeGenerator.solutionParts.icejs.plugins.packageJSON()],
|
||||
},
|
||||
postProcessors: [
|
||||
CodeGenerator.postprocessor.prettier(),
|
||||
],
|
||||
postProcessors: [CodeGenerator.postprocessor.prettier()],
|
||||
});
|
||||
|
||||
builder.generateProject(schemaJson).then(result => {
|
||||
builder.generateProject(schemaJson).then((result) => {
|
||||
displayResultInConsole(result);
|
||||
writeResultToDisk(result, 'output/lowcodeDemo').then(response =>
|
||||
writeResultToDisk(result, 'output/lowcodeDemo').then((response) =>
|
||||
console.log('Write to disk: ', JSON.stringify(response)),
|
||||
);
|
||||
return result;
|
||||
@ -151,4 +171,5 @@ function exportProject() {
|
||||
|
||||
// main();
|
||||
// exportModule();
|
||||
exportProject();
|
||||
// exportProject();
|
||||
demo();
|
||||
|
||||
420
packages/code-generator/demo/schema.json
Normal file
420
packages/code-generator/demo/schema.json
Normal file
@ -0,0 +1,420 @@
|
||||
{
|
||||
"componentName": "Page",
|
||||
"id": "node_dockcviv8fo1",
|
||||
"props": {
|
||||
"ref": "outterView",
|
||||
"autoLoading": true,
|
||||
"style": {
|
||||
"padding": "0 5px 0 5px"
|
||||
}
|
||||
},
|
||||
"fileName": "test",
|
||||
"dataSource": {
|
||||
"list": []
|
||||
},
|
||||
"state": {
|
||||
"text": "outter",
|
||||
"isShowDialog": false
|
||||
},
|
||||
"css": "body {font-size: 12px;} .botton{width:100px;color:#ff00ff}",
|
||||
"lifeCycles": {
|
||||
"componentDidMount": {
|
||||
"type": "JSFunction",
|
||||
"value": "function() {\n console.log('did mount');\n }"
|
||||
},
|
||||
"componentWillUnmount": {
|
||||
"type": "JSFunction",
|
||||
"value": "function() {\n console.log('will umount');\n }"
|
||||
}
|
||||
},
|
||||
"methods": {
|
||||
"testFunc": {
|
||||
"type": "JSFunction",
|
||||
"value": "function() {\n console.log('test func');\n }"
|
||||
},
|
||||
"onClick": {
|
||||
"type": "JSFunction",
|
||||
"value": "function(){\n this.setState({\n isShowDialog:true\n })\n\t}"
|
||||
}
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Box",
|
||||
"id": "node_dockcy8n9xed",
|
||||
"props": {
|
||||
"style": {
|
||||
"backgroundColor": "rgba(31,56,88,0.1)",
|
||||
"padding": "12px 12px 12px 12px"
|
||||
}
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Box",
|
||||
"id": "node_dockcy8n9xee",
|
||||
"props": {
|
||||
"style": {
|
||||
"padding": "12px 12px 12px 12px",
|
||||
"backgroundColor": "#ffffff"
|
||||
}
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Breadcrumb",
|
||||
"id": "node_dockcy8n9xef",
|
||||
"props": {
|
||||
"prefix": "next-",
|
||||
"maxNode": 100,
|
||||
"component": "nav"
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Breadcrumb.Item",
|
||||
"id": "node_dockcy8n9xeg",
|
||||
"props": {
|
||||
"prefix": "next-"
|
||||
},
|
||||
"children": ["首页"]
|
||||
}, {
|
||||
"componentName": "Breadcrumb.Item",
|
||||
"id": "node_dockcy8n9xei",
|
||||
"props": {
|
||||
"prefix": "next-"
|
||||
},
|
||||
"children": ["品质中台"]
|
||||
}, {
|
||||
"componentName": "Breadcrumb.Item",
|
||||
"id": "node_dockcy8n9xek",
|
||||
"props": {
|
||||
"prefix": "next-"
|
||||
},
|
||||
"children": ["商家品质页面管理"]
|
||||
}, {
|
||||
"componentName": "Breadcrumb.Item",
|
||||
"id": "node_dockcy8n9xem",
|
||||
"props": {
|
||||
"prefix": "next-"
|
||||
},
|
||||
"children": ["质检知识条配置"]
|
||||
}]
|
||||
}]
|
||||
}, {
|
||||
"componentName": "Box",
|
||||
"id": "node_dockcy8n9xeo",
|
||||
"props": {
|
||||
"style": {
|
||||
"marginTop": "12px",
|
||||
"backgroundColor": "#ffffff"
|
||||
}
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Form",
|
||||
"id": "node_dockcy8n9xep",
|
||||
"props": {
|
||||
"inline": true,
|
||||
"style": {
|
||||
"marginTop": "12px",
|
||||
"marginRight": "12px",
|
||||
"marginLeft": "12px"
|
||||
},
|
||||
"__events": []
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Form.Item",
|
||||
"id": "node_dockcy8n9xeq",
|
||||
"props": {
|
||||
"style": {
|
||||
"marginBottom": "0"
|
||||
},
|
||||
"label": "类目名:"
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Select",
|
||||
"id": "node_dockcy8n9xer",
|
||||
"props": {
|
||||
"mode": "single",
|
||||
"hasArrow": true,
|
||||
"cacheValue": true,
|
||||
"style": {
|
||||
"width": "150px"
|
||||
}
|
||||
}
|
||||
}]
|
||||
}, {
|
||||
"componentName": "Form.Item",
|
||||
"id": "node_dockcy8n9xes",
|
||||
"props": {
|
||||
"style": {
|
||||
"marginBottom": "0"
|
||||
},
|
||||
"label": "项目类型:"
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Select",
|
||||
"id": "node_dockcy8n9xet",
|
||||
"props": {
|
||||
"mode": "single",
|
||||
"hasArrow": true,
|
||||
"cacheValue": true,
|
||||
"style": {
|
||||
"width": "200px"
|
||||
}
|
||||
}
|
||||
}]
|
||||
}, {
|
||||
"componentName": "Form.Item",
|
||||
"id": "node_dockcy8n9xeu",
|
||||
"props": {
|
||||
"style": {
|
||||
"marginBottom": "0"
|
||||
},
|
||||
"label": "项目 ID:"
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Input",
|
||||
"id": "node_dockcy8n9xev",
|
||||
"props": {
|
||||
"hasBorder": true,
|
||||
"size": "medium",
|
||||
"autoComplete": "off",
|
||||
"style": {
|
||||
"width": "200px"
|
||||
}
|
||||
}
|
||||
}]
|
||||
}, {
|
||||
"componentName": "Button.Group",
|
||||
"id": "node_dockcy8n9xew",
|
||||
"props": {},
|
||||
"children": [{
|
||||
"componentName": "Button",
|
||||
"id": "node_dockcy8n9xex",
|
||||
"props": {
|
||||
"type": "primary",
|
||||
"style": {
|
||||
"margin": "0 5px 0 5px"
|
||||
},
|
||||
"htmlType": "submit"
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Icon",
|
||||
"id": "node_dockcy8n9xey",
|
||||
"props": {
|
||||
"type": "success"
|
||||
}
|
||||
}, "搜索"]
|
||||
}, {
|
||||
"componentName": "Button",
|
||||
"id": "node_dockcy8n9xe10",
|
||||
"props": {
|
||||
"type": "normal",
|
||||
"style": {
|
||||
"margin": "0 5px 0 5px"
|
||||
},
|
||||
"htmlType": "reset"
|
||||
},
|
||||
"children": ["清空"]
|
||||
}]
|
||||
}]
|
||||
}]
|
||||
}, {
|
||||
"componentName": "Box",
|
||||
"id": "node_dockcy8n9xe12",
|
||||
"props": {
|
||||
"style": {
|
||||
"justifyContent": "flex-end",
|
||||
"display": "flex",
|
||||
"backgroundColor": "#ffffff",
|
||||
"flexDirection": "row",
|
||||
"paddingRight": "24px"
|
||||
}
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Button",
|
||||
"id": "node_dockcy8n9xe13",
|
||||
"props": {
|
||||
"prefix": "next-",
|
||||
"type": "primary",
|
||||
"size": "medium",
|
||||
"htmlType": "button",
|
||||
"component": "button",
|
||||
"style": {
|
||||
"width": "100px"
|
||||
},
|
||||
"events": {
|
||||
"onClick": {
|
||||
"type": "JSFunction",
|
||||
"value": "function(){ this.onClick() }",
|
||||
"__eventData": {
|
||||
"type": "componentEvent",
|
||||
"name": "onClick",
|
||||
"relatedEventName": "onClick"
|
||||
}
|
||||
}
|
||||
},
|
||||
"__events": [{
|
||||
"type": "componentEvent",
|
||||
"name": "onClick",
|
||||
"relatedEventName": "onClick"
|
||||
}],
|
||||
"onClick": {
|
||||
"type": "JSFunction",
|
||||
"value": "function(){ this.onClick() }"
|
||||
}
|
||||
},
|
||||
"children": ["新建配置"]
|
||||
}]
|
||||
}, {
|
||||
"componentName": "Box",
|
||||
"id": "node_dockcy8n9xe15",
|
||||
"props": {
|
||||
"style": {
|
||||
"backgroundColor": "#ffffff"
|
||||
}
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Table",
|
||||
"id": "node_dockcy8n9xe16",
|
||||
"props": {
|
||||
"dataSource": [{
|
||||
"firstCategory": "其他",
|
||||
"secondCategory": "新品预览",
|
||||
"leafCategory": "",
|
||||
"projectType": "标识判断",
|
||||
"projectId": "",
|
||||
"title": "其他类目->新品预览类目类型知识库",
|
||||
"url": "其他",
|
||||
"operation": "编辑"
|
||||
}, {
|
||||
"firstCategory": "其他",
|
||||
"secondCategory": "新品预览",
|
||||
"leafCategory": "",
|
||||
"projectType": "",
|
||||
"projectId": "1",
|
||||
"title": "其他类目->新品预览项目Id知识库",
|
||||
"url": "其他",
|
||||
"operation": "编辑"
|
||||
}],
|
||||
"size": "medium",
|
||||
"prefix": "next-",
|
||||
"hasBorder": true,
|
||||
"hasHeader": true,
|
||||
"isZebra": false,
|
||||
"loading": false,
|
||||
"expandedIndexSimulate": false,
|
||||
"primaryKey": "id",
|
||||
"locale": "zhCN.Table",
|
||||
"crossline": false,
|
||||
"style": {
|
||||
"margin": "24px 12px 24px 12px"
|
||||
}
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Table.Column",
|
||||
"id": "node_dockcy8n9xe17",
|
||||
"props": {
|
||||
"title": "一级类目",
|
||||
"dataIndex": "firstCategory"
|
||||
}
|
||||
}, {
|
||||
"componentName": "Table.Column",
|
||||
"id": "node_dockcy8n9xe18",
|
||||
"props": {
|
||||
"title": "二级类目",
|
||||
"dataIndex": "secondCategory"
|
||||
}
|
||||
}, {
|
||||
"componentName": "Table.Column",
|
||||
"id": "node_dockcy8n9xe19",
|
||||
"props": {
|
||||
"title": "叶子类目",
|
||||
"dataIndex": "leafCategory"
|
||||
}
|
||||
}, {
|
||||
"componentName": "Table.Column",
|
||||
"id": "node_dockcy8n9xe1a",
|
||||
"props": {
|
||||
"title": "项目类型",
|
||||
"dataIndex": "projectType"
|
||||
}
|
||||
}, {
|
||||
"componentName": "Table.Column",
|
||||
"id": "node_dockcy8n9xe1b",
|
||||
"props": {
|
||||
"title": "项目 ID",
|
||||
"dataIndex": "projectId"
|
||||
}
|
||||
}, {
|
||||
"componentName": "Table.Column",
|
||||
"id": "node_dockcy8n9xe1c",
|
||||
"props": {
|
||||
"title": "知识条标题",
|
||||
"dataIndex": "title"
|
||||
}
|
||||
}, {
|
||||
"componentName": "Table.Column",
|
||||
"id": "node_dockcy8n9xe1d",
|
||||
"props": {
|
||||
"title": "知识条链接",
|
||||
"dataIndex": "url"
|
||||
}
|
||||
}, {
|
||||
"componentName": "Table.Column",
|
||||
"id": "node_dockcy8n9xe1e",
|
||||
"props": {
|
||||
"title": "操作",
|
||||
"dataIndex": "operation"
|
||||
}
|
||||
}]
|
||||
}]
|
||||
}, {
|
||||
"componentName": "Box",
|
||||
"id": "node_dockcy8n9xe1f",
|
||||
"props": {
|
||||
"style": {
|
||||
"backgroundColor": "#ffffff",
|
||||
"paddingBottom": "24px"
|
||||
}
|
||||
},
|
||||
"children": [{
|
||||
"componentName": "Pagination",
|
||||
"id": "node_dockcy8n9xe1g",
|
||||
"props": {
|
||||
"prefix": "next-",
|
||||
"type": "normal",
|
||||
"shape": "normal",
|
||||
"size": "medium",
|
||||
"defaultCurrent": 1,
|
||||
"total": 100,
|
||||
"pageShowCount": 5,
|
||||
"pageSize": 10,
|
||||
"pageSizePosition": "start",
|
||||
"showJump": true,
|
||||
"style": {
|
||||
"display": "flex",
|
||||
"justifyContent": "flex-end"
|
||||
}
|
||||
}
|
||||
}]
|
||||
}]
|
||||
}, {
|
||||
"componentName": "Dialog",
|
||||
"id": "node_dockcy8n9xe1h",
|
||||
"props": {
|
||||
"prefix": "next-",
|
||||
"footerAlign": "right",
|
||||
"footerActions": ["ok", "cancel"],
|
||||
"closeable": "esc,close",
|
||||
"hasMask": true,
|
||||
"align": "cc cc",
|
||||
"minMargin": 40,
|
||||
"visible": {
|
||||
"type": "JSExpression",
|
||||
"value": "this.state.isShowDialog"
|
||||
},
|
||||
"children": {
|
||||
"type": "JSSlot"
|
||||
},
|
||||
"title": "标题",
|
||||
"footer": {
|
||||
"type": "JSSlot"
|
||||
},
|
||||
"events": []
|
||||
}
|
||||
}]
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
export const NATIVE_ELE_PKG: string = 'native';
|
||||
export const NATIVE_ELE_PKG = 'native';
|
||||
|
||||
export const CONTAINER_TYPE = {
|
||||
COMPONENT: 'Component',
|
||||
|
||||
@ -1,28 +1,18 @@
|
||||
import {
|
||||
BuilderComponentPlugin,
|
||||
IChunkBuilder,
|
||||
ICodeChunk,
|
||||
ICodeStruct,
|
||||
} from '../types';
|
||||
import { BuilderComponentPlugin, IChunkBuilder, ICodeChunk, ICodeStruct } from '../types';
|
||||
|
||||
import { COMMON_SUB_MODULE_NAME } from '../const/generator';
|
||||
|
||||
export const groupChunks = (chunks: ICodeChunk[]): ICodeChunk[][] => {
|
||||
const col = chunks.reduce(
|
||||
(chunksSet: Record<string, ICodeChunk[]>, chunk) => {
|
||||
const fileKey = `${chunk.subModule || COMMON_SUB_MODULE_NAME}.${
|
||||
chunk.fileType
|
||||
}`;
|
||||
if (!chunksSet[fileKey]) {
|
||||
chunksSet[fileKey] = [];
|
||||
}
|
||||
chunksSet[fileKey].push(chunk);
|
||||
return chunksSet;
|
||||
},
|
||||
{},
|
||||
);
|
||||
const col = chunks.reduce((chunksSet: Record<string, ICodeChunk[]>, chunk) => {
|
||||
const fileKey = `${chunk.subModule || COMMON_SUB_MODULE_NAME}.${chunk.fileType}`;
|
||||
if (!chunksSet[fileKey]) {
|
||||
chunksSet[fileKey] = [];
|
||||
}
|
||||
chunksSet[fileKey].push(chunk);
|
||||
return chunksSet;
|
||||
}, {});
|
||||
|
||||
return Object.keys(col).map(key => col[key]);
|
||||
return Object.keys(col).map((key) => col[key]);
|
||||
};
|
||||
|
||||
/**
|
||||
@ -39,7 +29,7 @@ export default class ChunkBuilder implements IChunkBuilder {
|
||||
this.plugins = plugins;
|
||||
}
|
||||
|
||||
public async run(
|
||||
async run(
|
||||
ir: unknown,
|
||||
initialStructure: ICodeStruct = {
|
||||
ir,
|
||||
@ -64,11 +54,11 @@ export default class ChunkBuilder implements IChunkBuilder {
|
||||
};
|
||||
}
|
||||
|
||||
public getPlugins() {
|
||||
getPlugins() {
|
||||
return this.plugins;
|
||||
}
|
||||
|
||||
public addPlugin(plugin: BuilderComponentPlugin) {
|
||||
addPlugin(plugin: BuilderComponentPlugin) {
|
||||
this.plugins.push(plugin);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,11 +1,4 @@
|
||||
import {
|
||||
ChunkContent,
|
||||
ChunkType,
|
||||
CodeGeneratorError,
|
||||
CodeGeneratorFunction,
|
||||
ICodeBuilder,
|
||||
ICodeChunk,
|
||||
} from '../types';
|
||||
import { ChunkContent, ChunkType, CodeGeneratorError, CodeGeneratorFunction, ICodeBuilder, ICodeChunk } from '../types';
|
||||
|
||||
export default class Builder implements ICodeBuilder {
|
||||
private chunkDefinitions: ICodeChunk[] = [];
|
||||
@ -23,13 +16,13 @@ export default class Builder implements ICodeBuilder {
|
||||
* Links all chunks together based on their requirements. Returns an array
|
||||
* of ordered chunk names which need to be compiled and glued together.
|
||||
*/
|
||||
public link(chunkDefinitions: ICodeChunk[] = []): string {
|
||||
link(chunkDefinitions: ICodeChunk[] = []): string {
|
||||
const chunks = chunkDefinitions || this.chunkDefinitions;
|
||||
if (chunks.length <= 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const unprocessedChunks = chunks.map(chunk => {
|
||||
const unprocessedChunks = chunks.map((chunk) => {
|
||||
return {
|
||||
name: chunk.name,
|
||||
type: chunk.type,
|
||||
@ -50,9 +43,7 @@ export default class Builder implements ICodeBuilder {
|
||||
}
|
||||
|
||||
if (unprocessedChunks[indexToRemove].linkAfter.length > 0) {
|
||||
throw new CodeGeneratorError(
|
||||
'Operation aborted. Reason: cyclic dependency between chunks.',
|
||||
);
|
||||
throw new CodeGeneratorError('Operation aborted. Reason: cyclic dependency between chunks.');
|
||||
}
|
||||
|
||||
const { type, content, name } = unprocessedChunks[indexToRemove];
|
||||
@ -62,10 +53,10 @@ export default class Builder implements ICodeBuilder {
|
||||
}
|
||||
|
||||
unprocessedChunks.splice(indexToRemove, 1);
|
||||
if (!unprocessedChunks.some(ch => ch.name === name)) {
|
||||
if (!unprocessedChunks.some((ch) => ch.name === name)) {
|
||||
unprocessedChunks.forEach(
|
||||
// remove the processed chunk from all the linkAfter arrays from the remaining chunks
|
||||
ch => (ch.linkAfter = ch.linkAfter.filter(after => after !== name)),
|
||||
(ch) => (ch.linkAfter = ch.linkAfter.filter((after) => after !== name)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -73,14 +64,12 @@ export default class Builder implements ICodeBuilder {
|
||||
return resultingString.join('\n');
|
||||
}
|
||||
|
||||
public generateByType(type: string, content: unknown): string {
|
||||
generateByType(type: string, content: unknown): string {
|
||||
if (!content) {
|
||||
return '';
|
||||
}
|
||||
if (Array.isArray(content)) {
|
||||
return content
|
||||
.map(contentItem => this.generateByType(type, contentItem))
|
||||
.join('\n');
|
||||
return content.map((contentItem) => this.generateByType(type, contentItem)).join('\n');
|
||||
}
|
||||
|
||||
if (!this.generators[type]) {
|
||||
@ -95,8 +84,6 @@ export default class Builder implements ICodeBuilder {
|
||||
// remove invalid chunks (which did not end up being created) from the linkAfter fields
|
||||
// one use-case is when you want to remove the import plugin
|
||||
private cleanupInvalidChunks(linkAfter: string[], chunks: ICodeChunk[]) {
|
||||
return linkAfter.filter(chunkName =>
|
||||
chunks.some(chunk => chunk.name === chunkName),
|
||||
);
|
||||
return linkAfter.filter((chunkName) => chunks.some((chunk) => chunk.name === chunkName));
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,13 +1,12 @@
|
||||
import { ProjectSchema, ResultFile, ResultDir } from '@ali/lowcode-types';
|
||||
|
||||
import {
|
||||
BuilderComponentPlugin,
|
||||
CodeGeneratorError,
|
||||
IBasicSchema,
|
||||
ICodeChunk,
|
||||
ICompiledModule,
|
||||
IModuleBuilder,
|
||||
IParseResult,
|
||||
IResultDir,
|
||||
IResultFile,
|
||||
ISchemaParser,
|
||||
PostProcessor,
|
||||
} from '../types';
|
||||
@ -17,9 +16,7 @@ import { COMMON_SUB_MODULE_NAME } from '../const/generator';
|
||||
import SchemaParser from '../parser/SchemaParser';
|
||||
import ChunkBuilder from './ChunkBuilder';
|
||||
import CodeBuilder from './CodeBuilder';
|
||||
|
||||
import ResultDir from '../model/ResultDir';
|
||||
import ResultFile from '../model/ResultFile';
|
||||
import { createResultFile, createResultDir, addFile } from '../utils/resultHelper';
|
||||
|
||||
export function createModuleBuilder(
|
||||
options: {
|
||||
@ -37,33 +34,27 @@ export function createModuleBuilder(
|
||||
const generateModule = async (input: unknown): Promise<ICompiledModule> => {
|
||||
const moduleMainName = options.mainFileName || COMMON_SUB_MODULE_NAME;
|
||||
if (chunkGenerator.getPlugins().length <= 0) {
|
||||
throw new CodeGeneratorError(
|
||||
'No plugins found. Component generation cannot work without any plugins!',
|
||||
);
|
||||
throw new CodeGeneratorError('No plugins found. Component generation cannot work without any plugins!');
|
||||
}
|
||||
|
||||
let files: IResultFile[] = [];
|
||||
let files: ResultFile[] = [];
|
||||
|
||||
const { chunks } = await chunkGenerator.run(input);
|
||||
chunks.forEach(fileChunkList => {
|
||||
chunks.forEach((fileChunkList) => {
|
||||
const content = linker.link(fileChunkList);
|
||||
const file = new ResultFile(
|
||||
fileChunkList[0].subModule || moduleMainName,
|
||||
fileChunkList[0].fileType,
|
||||
content,
|
||||
);
|
||||
const file = createResultFile(fileChunkList[0].subModule || moduleMainName, fileChunkList[0].fileType, content);
|
||||
files.push(file);
|
||||
});
|
||||
|
||||
if (options.postProcessors.length > 0) {
|
||||
files = files.map(file => {
|
||||
files = files.map((file) => {
|
||||
let content = file.content;
|
||||
const type = file.ext;
|
||||
options.postProcessors.forEach(processer => {
|
||||
options.postProcessors.forEach((processer) => {
|
||||
content = processer(content, type);
|
||||
});
|
||||
|
||||
return new ResultFile(file.name, type, content);
|
||||
return createResultFile(file.name, type, content);
|
||||
});
|
||||
}
|
||||
|
||||
@ -72,7 +63,7 @@ export function createModuleBuilder(
|
||||
};
|
||||
};
|
||||
|
||||
const generateModuleCode = async (schema: IBasicSchema | string): Promise<IResultDir> => {
|
||||
const generateModuleCode = async (schema: ProjectSchema | string): Promise<ResultDir> => {
|
||||
// Init
|
||||
const schemaParser: ISchemaParser = new SchemaParser();
|
||||
const parseResult: IParseResult = schemaParser.parse(schema);
|
||||
@ -80,26 +71,19 @@ export function createModuleBuilder(
|
||||
const containerInfo = parseResult.containers[0];
|
||||
const { files } = await generateModule(containerInfo);
|
||||
|
||||
const dir = new ResultDir(containerInfo.moduleName);
|
||||
files.forEach(file => dir.addFile(file));
|
||||
const dir = createResultDir(containerInfo.moduleName);
|
||||
files.forEach((file) => addFile(dir, file));
|
||||
|
||||
return dir;
|
||||
}
|
||||
};
|
||||
|
||||
const linkCodeChunks = (
|
||||
chunks: Record<string, ICodeChunk[]>,
|
||||
fileName: string,
|
||||
) => {
|
||||
const files: IResultFile[] = [];
|
||||
const linkCodeChunks = (chunks: Record<string, ICodeChunk[]>, fileName: string) => {
|
||||
const files: ResultFile[] = [];
|
||||
|
||||
Object.keys(chunks).forEach(fileKey => {
|
||||
Object.keys(chunks).forEach((fileKey) => {
|
||||
const fileChunkList = chunks[fileKey];
|
||||
const content = linker.link(fileChunkList);
|
||||
const file = new ResultFile(
|
||||
fileChunkList[0].subModule || fileName,
|
||||
fileChunkList[0].fileType,
|
||||
content,
|
||||
);
|
||||
const file = createResultFile(fileChunkList[0].subModule || fileName, fileChunkList[0].fileType, content);
|
||||
files.push(file);
|
||||
});
|
||||
|
||||
|
||||
@ -1,36 +1,35 @@
|
||||
import { ResultDir, ResultFile, ProjectSchema } from '@ali/lowcode-types';
|
||||
|
||||
import {
|
||||
IModuleBuilder,
|
||||
IParseResult,
|
||||
IProjectBuilder,
|
||||
IProjectPlugins,
|
||||
IProjectSchema,
|
||||
IProjectTemplate,
|
||||
IResultDir,
|
||||
IResultFile,
|
||||
ISchemaParser,
|
||||
PostProcessor,
|
||||
} from '../types';
|
||||
|
||||
import ResultDir from '../model/ResultDir';
|
||||
import SchemaParser from '../parser/SchemaParser';
|
||||
import { createResultDir, addDirectory, addFile } from '../utils/resultHelper';
|
||||
|
||||
import { createModuleBuilder } from '../generator/ModuleBuilder';
|
||||
|
||||
interface IModuleInfo {
|
||||
moduleName?: string;
|
||||
path: string[];
|
||||
files: IResultFile[];
|
||||
files: ResultFile[];
|
||||
}
|
||||
|
||||
function getDirFromRoot(root: IResultDir, path: string[]): IResultDir {
|
||||
let current: IResultDir = root;
|
||||
path.forEach(p => {
|
||||
const exist = current.dirs.find(d => d.name === p);
|
||||
function getDirFromRoot(root: ResultDir, path: string[]): ResultDir {
|
||||
let current: ResultDir = root;
|
||||
path.forEach((p) => {
|
||||
const exist = current.dirs.find((d) => d.name === p);
|
||||
if (exist) {
|
||||
current = exist;
|
||||
} else {
|
||||
const newDir = new ResultDir(p);
|
||||
current.addDirectory(newDir);
|
||||
const newDir = createResultDir(p);
|
||||
addDirectory(current, newDir);
|
||||
current = newDir;
|
||||
}
|
||||
});
|
||||
@ -57,7 +56,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
this.postProcessors = postProcessors;
|
||||
}
|
||||
|
||||
public async generateProject(schema: IProjectSchema | string): Promise<IResultDir> {
|
||||
async generateProject(schema: ProjectSchema | string): Promise<ResultDir> {
|
||||
// Init
|
||||
const schemaParser: ISchemaParser = new SchemaParser();
|
||||
const builders = this.createModuleBuilders();
|
||||
@ -76,7 +75,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
// components
|
||||
// pages
|
||||
const containerBuildResult: IModuleInfo[] = await Promise.all<IModuleInfo>(
|
||||
parseResult.containers.map(async containerInfo => {
|
||||
parseResult.containers.map(async (containerInfo) => {
|
||||
let builder: IModuleBuilder;
|
||||
let path: string[];
|
||||
if (containerInfo.containerType === 'Page') {
|
||||
@ -100,9 +99,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
|
||||
// router
|
||||
if (parseResult.globalRouter && builders.router) {
|
||||
const { files } = await builders.router.generateModule(
|
||||
parseResult.globalRouter,
|
||||
);
|
||||
const { files } = await builders.router.generateModule(parseResult.globalRouter);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.router.path,
|
||||
@ -112,9 +109,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
|
||||
// entry
|
||||
if (parseResult.project && builders.entry) {
|
||||
const { files } = await builders.entry.generateModule(
|
||||
parseResult.project,
|
||||
);
|
||||
const { files } = await builders.entry.generateModule(parseResult.project);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.entry.path,
|
||||
@ -124,9 +119,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
|
||||
// appConfig
|
||||
if (parseResult.project && builders.appConfig) {
|
||||
const { files } = await builders.appConfig.generateModule(
|
||||
parseResult.project,
|
||||
);
|
||||
const { files } = await builders.appConfig.generateModule(parseResult.project);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.appConfig.path,
|
||||
@ -135,14 +128,8 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
}
|
||||
|
||||
// constants?
|
||||
if (
|
||||
parseResult.project &&
|
||||
builders.constants &&
|
||||
this.template.slots.constants
|
||||
) {
|
||||
const { files } = await builders.constants.generateModule(
|
||||
parseResult.project,
|
||||
);
|
||||
if (parseResult.project && builders.constants && this.template.slots.constants) {
|
||||
const { files } = await builders.constants.generateModule(parseResult.project);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.constants.path,
|
||||
@ -151,14 +138,8 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
}
|
||||
|
||||
// utils?
|
||||
if (
|
||||
parseResult.globalUtils &&
|
||||
builders.utils &&
|
||||
this.template.slots.utils
|
||||
) {
|
||||
const { files } = await builders.utils.generateModule(
|
||||
parseResult.globalUtils,
|
||||
);
|
||||
if (parseResult.globalUtils && builders.utils && this.template.slots.utils) {
|
||||
const { files } = await builders.utils.generateModule(parseResult.globalUtils);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.utils.path,
|
||||
@ -168,9 +149,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
|
||||
// i18n?
|
||||
if (parseResult.globalI18n && builders.i18n && this.template.slots.i18n) {
|
||||
const { files } = await builders.i18n.generateModule(
|
||||
parseResult.globalI18n,
|
||||
);
|
||||
const { files } = await builders.i18n.generateModule(parseResult.globalI18n);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.i18n.path,
|
||||
@ -180,9 +159,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
|
||||
// globalStyle
|
||||
if (parseResult.project && builders.globalStyle) {
|
||||
const { files } = await builders.globalStyle.generateModule(
|
||||
parseResult.project,
|
||||
);
|
||||
const { files } = await builders.globalStyle.generateModule(parseResult.project);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.globalStyle.path,
|
||||
@ -192,9 +169,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
|
||||
// htmlEntry
|
||||
if (parseResult.project && builders.htmlEntry) {
|
||||
const { files } = await builders.htmlEntry.generateModule(
|
||||
parseResult.project,
|
||||
);
|
||||
const { files } = await builders.htmlEntry.generateModule(parseResult.project);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.htmlEntry.path,
|
||||
@ -204,9 +179,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
|
||||
// packageJSON
|
||||
if (parseResult.project && builders.packageJSON) {
|
||||
const { files } = await builders.packageJSON.generateModule(
|
||||
parseResult.project,
|
||||
);
|
||||
const { files } = await builders.packageJSON.generateModule(parseResult.project);
|
||||
|
||||
buildResult.push({
|
||||
path: this.template.slots.packageJSON.path,
|
||||
@ -217,14 +190,14 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
// Post Process
|
||||
|
||||
// Combine Modules
|
||||
buildResult.forEach(moduleInfo => {
|
||||
buildResult.forEach((moduleInfo) => {
|
||||
let targetDir = getDirFromRoot(projectRoot, moduleInfo.path);
|
||||
if (moduleInfo.moduleName) {
|
||||
const dir = new ResultDir(moduleInfo.moduleName);
|
||||
targetDir.addDirectory(dir);
|
||||
const dir = createResultDir(moduleInfo.moduleName);
|
||||
addDirectory(targetDir, dir);
|
||||
targetDir = dir;
|
||||
}
|
||||
moduleInfo.files.forEach(file => targetDir.addFile(file));
|
||||
moduleInfo.files.forEach((file) => addFile(targetDir, file));
|
||||
});
|
||||
|
||||
return projectRoot;
|
||||
@ -233,7 +206,7 @@ export class ProjectBuilder implements IProjectBuilder {
|
||||
private createModuleBuilders(): Record<string, IModuleBuilder> {
|
||||
const builders: Record<string, IModuleBuilder> = {};
|
||||
|
||||
Object.keys(this.plugins).forEach(pluginName => {
|
||||
Object.keys(this.plugins).forEach((pluginName) => {
|
||||
if (this.plugins[pluginName].length > 0) {
|
||||
const options: { mainFileName?: string } = {};
|
||||
if (this.template.slots[pluginName] && this.template.slots[pluginName].fileName) {
|
||||
|
||||
@ -11,11 +11,7 @@ import { createZipPublisher } from './publisher/zip';
|
||||
|
||||
// 引入说明
|
||||
import { REACT_CHUNK_NAME } from './plugins/component/react/const';
|
||||
import {
|
||||
COMMON_CHUNK_NAME,
|
||||
CLASS_DEFINE_CHUNK_NAME,
|
||||
DEFAULT_LINK_AFTER,
|
||||
} from './const/generator';
|
||||
import { COMMON_CHUNK_NAME, CLASS_DEFINE_CHUNK_NAME, DEFAULT_LINK_AFTER } from './const/generator';
|
||||
|
||||
// 引入通用插件组
|
||||
import esmodule from './plugins/common/esmodule';
|
||||
@ -38,8 +34,11 @@ import prettier from './postprocessor/prettier';
|
||||
import * as utilsCommon from './utils/common';
|
||||
import * as utilsCompositeType from './utils/compositeType';
|
||||
import * as utilsJsExpression from './utils/jsExpression';
|
||||
import * as utilsJsSlot from './utils/jsSlot';
|
||||
import * as utilsNodeToJSX from './utils/nodeToJSX';
|
||||
import * as utilsResultHelper from './utils/resultHelper';
|
||||
import * as utilsTemplateHelper from './utils/templateHelper';
|
||||
import * as utilsValidate from './utils/validate';
|
||||
|
||||
// 引入内置解决方案模块
|
||||
import icejs from './plugins/project/framework/icejs';
|
||||
@ -91,8 +90,11 @@ export default {
|
||||
common: utilsCommon,
|
||||
compositeType: utilsCompositeType,
|
||||
jsExpression: utilsJsExpression,
|
||||
jsSlot: utilsJsSlot,
|
||||
nodeToJSX: utilsNodeToJSX,
|
||||
resultHelper: utilsResultHelper,
|
||||
templateHelper: utilsTemplateHelper,
|
||||
validate: utilsValidate,
|
||||
},
|
||||
chunkNames: {
|
||||
COMMON_CHUNK_NAME,
|
||||
|
||||
@ -1,31 +0,0 @@
|
||||
import { CodeGeneratorError, IResultDir, IResultFile } from '../types';
|
||||
|
||||
export default class ResultDir implements IResultDir {
|
||||
public name: string;
|
||||
public dirs: IResultDir[];
|
||||
public files: IResultFile[];
|
||||
|
||||
constructor(name: string) {
|
||||
this.name = name;
|
||||
this.dirs = [];
|
||||
this.files = [];
|
||||
}
|
||||
|
||||
public addDirectory(dir: IResultDir): void {
|
||||
if (this.dirs.findIndex(d => d.name === dir.name) < 0) {
|
||||
this.dirs.push(dir);
|
||||
} else {
|
||||
throw new CodeGeneratorError(`Adding same directory to one directory: ${dir.name} -> ${this.name}`);
|
||||
}
|
||||
}
|
||||
|
||||
public addFile(file: IResultFile): void {
|
||||
if (
|
||||
this.files.findIndex(f => f.name === file.name && f.ext === file.ext) < 0
|
||||
) {
|
||||
this.files.push(file);
|
||||
} else {
|
||||
throw new CodeGeneratorError(`Adding same file to one directory: ${file.name} -> ${this.name}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,13 +0,0 @@
|
||||
import { IResultFile } from '../types';
|
||||
|
||||
export default class ResultFile implements IResultFile {
|
||||
public name: string;
|
||||
public ext: string;
|
||||
public content: string;
|
||||
|
||||
constructor(name: string, ext: string = 'jsx', content: string = '') {
|
||||
this.name = name;
|
||||
this.ext = ext;
|
||||
this.content = content;
|
||||
}
|
||||
}
|
||||
@ -3,28 +3,25 @@
|
||||
* 本解析器面向的是标准 schema 协议。
|
||||
*/
|
||||
import changeCase from 'change-case';
|
||||
import { UtilItem, NodeDataType, NodeSchema, ContainerSchema, ProjectSchema, PropsMap } from '@ali/lowcode-types';
|
||||
|
||||
import { SUPPORT_SCHEMA_VERSION_LIST } from '../const';
|
||||
|
||||
import { handleChildren } from '../utils/nodeToJSX';
|
||||
import { handleSubNodes } from '../utils/nodeToJSX';
|
||||
import { uniqueArray } from '../utils/common';
|
||||
|
||||
import {
|
||||
NodeData,
|
||||
CodeGeneratorError,
|
||||
CompatibilityError,
|
||||
DependencyType,
|
||||
IBasicSchema,
|
||||
NodeSchema,
|
||||
IContainerInfo,
|
||||
IContainerNodeItem,
|
||||
IDependency,
|
||||
IExternalDependency,
|
||||
IInternalDependency,
|
||||
InternalDependencyType,
|
||||
IPageMeta,
|
||||
IParseResult,
|
||||
IProjectSchema,
|
||||
ISchemaParser,
|
||||
UtilItem,
|
||||
INpmPackage,
|
||||
} from '../types';
|
||||
|
||||
const defaultContainer: IContainerInfo = {
|
||||
@ -37,7 +34,7 @@ const defaultContainer: IContainerInfo = {
|
||||
};
|
||||
|
||||
class SchemaParser implements ISchemaParser {
|
||||
public validate(schema: IBasicSchema): boolean {
|
||||
validate(schema: ProjectSchema): boolean {
|
||||
if (SUPPORT_SCHEMA_VERSION_LIST.indexOf(schema.version) < 0) {
|
||||
throw new CompatibilityError(`Not support schema with version [${schema.version}]`);
|
||||
}
|
||||
@ -45,13 +42,13 @@ class SchemaParser implements ISchemaParser {
|
||||
return true;
|
||||
}
|
||||
|
||||
public parse(schemaSrc: IProjectSchema | string): IParseResult {
|
||||
parse(schemaSrc: ProjectSchema | string): IParseResult {
|
||||
// TODO: collect utils depends in JSExpression
|
||||
const compDeps: Record<string, IExternalDependency> = {};
|
||||
const internalDeps: Record<string, IInternalDependency> = {};
|
||||
let utilsDeps: IExternalDependency[] = [];
|
||||
|
||||
let schema: IProjectSchema;
|
||||
let schema: ProjectSchema;
|
||||
if (typeof schemaSrc === 'string') {
|
||||
try {
|
||||
schema = JSON.parse(schemaSrc);
|
||||
@ -68,7 +65,7 @@ class SchemaParser implements ISchemaParser {
|
||||
compDeps[info.componentName] = {
|
||||
...info,
|
||||
dependencyType: DependencyType.External,
|
||||
importName: info.componentName,
|
||||
componentName: info.componentName,
|
||||
exportName: info.exportName ?? info.componentName,
|
||||
version: info.version || '*',
|
||||
destructuring: info.destructuring ?? false,
|
||||
@ -79,7 +76,7 @@ class SchemaParser implements ISchemaParser {
|
||||
let containers: IContainerInfo[];
|
||||
// Test if this is a lowcode component without container
|
||||
if (schema.componentsTree.length > 0) {
|
||||
const firstRoot: IContainerNodeItem = schema.componentsTree[0] as IContainerNodeItem;
|
||||
const firstRoot: ContainerSchema = schema.componentsTree[0] as ContainerSchema;
|
||||
|
||||
if (!('fileName' in firstRoot) || !firstRoot.fileName) {
|
||||
// 整个 schema 描述一个容器,且无根节点定义
|
||||
@ -91,7 +88,7 @@ class SchemaParser implements ISchemaParser {
|
||||
} else {
|
||||
// 普通带 1 到多个容器的 schema
|
||||
containers = schema.componentsTree.map((n) => {
|
||||
const subRoot = n;
|
||||
const subRoot = n as ContainerSchema;
|
||||
const container: IContainerInfo = {
|
||||
...subRoot,
|
||||
containerType: subRoot.componentName,
|
||||
@ -130,34 +127,62 @@ class SchemaParser implements ISchemaParser {
|
||||
internalDeps[dep.moduleName] = dep;
|
||||
});
|
||||
|
||||
// 分析容器内部组件依赖
|
||||
const containersDeps = ([] as IDependency[]).concat(...containers.map((c) => c.deps || []));
|
||||
// TODO: 不应该在出码部分解决?
|
||||
// 处理 children 写在了 props 里的情况
|
||||
containers.forEach((container) => {
|
||||
if (container.children) {
|
||||
// const depNames = this.getComponentNames(container.children);
|
||||
// container.deps = uniqueArray<string>(depNames)
|
||||
// .map(depName => internalDeps[depName] || compDeps[depName])
|
||||
// .filter(dep => !!dep);
|
||||
container.deps = Object.keys(compDeps).map((depName) => compDeps[depName]);
|
||||
handleSubNodes<string>(
|
||||
container.children,
|
||||
{
|
||||
node: (i: NodeSchema) => {
|
||||
if (i.props) {
|
||||
if (Array.isArray(i.props)) {
|
||||
// FIXME: is array type props description
|
||||
} else {
|
||||
const nodeProps = i.props as PropsMap;
|
||||
if (nodeProps.children && !i.children) {
|
||||
i.children = nodeProps.children as NodeDataType;
|
||||
}
|
||||
}
|
||||
}
|
||||
return [''];
|
||||
},
|
||||
},
|
||||
{
|
||||
rerun: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const containersDeps = ([] as IDependency[]).concat(...containers.map((c) => c.deps || []));
|
||||
// 分析容器内部组件依赖
|
||||
containers.forEach((container) => {
|
||||
if (container.children) {
|
||||
const depNames = this.getComponentNames(container.children);
|
||||
container.deps = uniqueArray<string>(depNames, (i: string) => i)
|
||||
.map((depName) => internalDeps[depName] || compDeps[depName])
|
||||
.filter((dep) => !!dep);
|
||||
// container.deps = Object.keys(compDeps).map((depName) => compDeps[depName]);
|
||||
}
|
||||
});
|
||||
|
||||
// 分析路由配置
|
||||
// TODO: 低代码规范里面的路由是咋弄的?
|
||||
const routes = containers
|
||||
.filter((container) => container.containerType === 'Page')
|
||||
.map((page) => {
|
||||
const meta = (page as { meta?: IPageMeta }).meta as IPageMeta;
|
||||
if (meta) {
|
||||
return {
|
||||
path: meta.router,
|
||||
componentName: page.moduleName,
|
||||
};
|
||||
let router = '';
|
||||
if (page.meta) {
|
||||
router = (page.meta as any)?.router || '';
|
||||
}
|
||||
|
||||
if (!router) {
|
||||
router = `/${page.fileName}`;
|
||||
}
|
||||
|
||||
return {
|
||||
path: '',
|
||||
path: router,
|
||||
componentName: page.moduleName,
|
||||
};
|
||||
});
|
||||
@ -175,6 +200,16 @@ class SchemaParser implements ISchemaParser {
|
||||
utils = [];
|
||||
}
|
||||
|
||||
// 分析项目 npm 依赖
|
||||
let npms: INpmPackage[] = [];
|
||||
containers.forEach((con) => {
|
||||
const p = (con.deps || [])
|
||||
.map((dep) => (dep.dependencyType === DependencyType.External ? dep : null))
|
||||
.filter((dep) => dep !== null);
|
||||
npms.push(...((p as unknown) as INpmPackage[]));
|
||||
});
|
||||
npms = uniqueArray<INpmPackage>(npms, (i) => i.package);
|
||||
|
||||
return {
|
||||
containers,
|
||||
globalUtils: {
|
||||
@ -187,21 +222,26 @@ class SchemaParser implements ISchemaParser {
|
||||
deps: routerDeps,
|
||||
},
|
||||
project: {
|
||||
meta: schema.meta,
|
||||
config: schema.config,
|
||||
css: schema.css,
|
||||
constants: schema.constants,
|
||||
i18n: schema.i18n,
|
||||
containersDeps,
|
||||
utilsDeps,
|
||||
packages: npms,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
public getComponentNames(children: NodeData | NodeData[]): string[] {
|
||||
return handleChildren(children, {
|
||||
node: (i: NodeSchema) => [i.componentName],
|
||||
});
|
||||
getComponentNames(children: NodeDataType): string[] {
|
||||
return handleSubNodes<string>(
|
||||
children,
|
||||
{
|
||||
node: (i: NodeSchema) => [i.componentName],
|
||||
},
|
||||
{
|
||||
rerun: true,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -15,6 +15,8 @@ import {
|
||||
IWithDependency,
|
||||
} from '../../types';
|
||||
|
||||
import { isValidIdentifier } from '../../utils/validate';
|
||||
|
||||
function groupDepsByPack(deps: IDependency[]): Record<string, IDependency[]> {
|
||||
const depMap: Record<string, IDependency[]> = {};
|
||||
|
||||
@ -25,11 +27,23 @@ function groupDepsByPack(deps: IDependency[]): Record<string, IDependency[]> {
|
||||
depMap[pkg].push(dep);
|
||||
};
|
||||
|
||||
// TODO: main 这个信息到底怎么用,是不是外部包不需要使用?
|
||||
// deps.forEach(dep => {
|
||||
// if (dep.dependencyType === DependencyType.Internal) {
|
||||
// addDep(
|
||||
// `${(dep as IInternalDependency).moduleName}${`/${dep.main}` || ''}`,
|
||||
// dep,
|
||||
// );
|
||||
// } else {
|
||||
// addDep(`${(dep as IExternalDependency).package}${`/${dep.main}` || ''}`, dep);
|
||||
// }
|
||||
// });
|
||||
|
||||
deps.forEach((dep) => {
|
||||
if (dep.dependencyType === DependencyType.Internal) {
|
||||
addDep(`${(dep as IInternalDependency).moduleName}${dep.main || ''}`, dep);
|
||||
addDep(`${(dep as IInternalDependency).moduleName}`, dep);
|
||||
} else {
|
||||
addDep(`${(dep as IExternalDependency).package}${dep.main || ''}`, dep);
|
||||
addDep(`${(dep as IExternalDependency).package}`, dep);
|
||||
}
|
||||
});
|
||||
|
||||
@ -38,16 +52,13 @@ function groupDepsByPack(deps: IDependency[]): Record<string, IDependency[]> {
|
||||
|
||||
function buildPackageImport(pkg: string, deps: IDependency[], targetFileType: string): ICodeChunk[] {
|
||||
const chunks: ICodeChunk[] = [];
|
||||
let defaultImport: string = '';
|
||||
let defaultImportAs: string = '';
|
||||
let defaultImport = '';
|
||||
let defaultImportAs = '';
|
||||
const imports: Record<string, string> = {};
|
||||
|
||||
deps.forEach((dep) => {
|
||||
const srcName = dep.exportName;
|
||||
let targetName = dep.importName || dep.exportName;
|
||||
if (dep.subName) {
|
||||
return;
|
||||
}
|
||||
let targetName = dep.componentName || dep.exportName;
|
||||
|
||||
if (dep.subName) {
|
||||
chunks.push({
|
||||
@ -63,6 +74,20 @@ function buildPackageImport(pkg: string, deps: IDependency[], targetFileType: st
|
||||
},
|
||||
});
|
||||
|
||||
if (targetName !== `${srcName}.${dep.subName}`) {
|
||||
if (!isValidIdentifier(targetName)) {
|
||||
throw new CodeGeneratorError(`Invalid Identifier [${targetName}]`);
|
||||
}
|
||||
|
||||
chunks.push({
|
||||
type: ChunkType.STRING,
|
||||
fileType: targetFileType,
|
||||
name: COMMON_CHUNK_NAME.FileVarDefine,
|
||||
content: `const ${targetName} = ${srcName}.${dep.subName};`,
|
||||
linkAfter: [COMMON_CHUNK_NAME.ExternalDepsImport, COMMON_CHUNK_NAME.InternalDepsImport],
|
||||
});
|
||||
}
|
||||
|
||||
targetName = srcName;
|
||||
}
|
||||
|
||||
|
||||
@ -1,12 +1,6 @@
|
||||
import { COMMON_CHUNK_NAME } from '../../const/generator';
|
||||
|
||||
import {
|
||||
BuilderComponentPlugin,
|
||||
BuilderComponentPluginFactory,
|
||||
ChunkType,
|
||||
FileType,
|
||||
ICodeStruct,
|
||||
} from '../../types';
|
||||
import { BuilderComponentPlugin, BuilderComponentPluginFactory, ChunkType, FileType, ICodeStruct } from '../../types';
|
||||
|
||||
// TODO: How to merge this logic to common deps
|
||||
const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
|
||||
@ -6,7 +6,6 @@ import {
|
||||
ChunkType,
|
||||
FileType,
|
||||
ICodeStruct,
|
||||
IContainerInfo,
|
||||
} from '../../../types';
|
||||
|
||||
const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
import { isJSExpression, isJSFunction, JSExpression, JSFunction, NpmInfo } from '@ali/lowcode-types';
|
||||
|
||||
import {
|
||||
BuilderComponentPlugin,
|
||||
BuilderComponentPluginFactory,
|
||||
@ -6,11 +8,6 @@ import {
|
||||
ICodeChunk,
|
||||
ICodeStruct,
|
||||
IContainerInfo,
|
||||
isJSExpression,
|
||||
isJSFunction,
|
||||
JSExpression,
|
||||
JSFunction,
|
||||
NpmInfo,
|
||||
} from '../../../types';
|
||||
|
||||
import { RAX_CHUNK_NAME } from './const';
|
||||
@ -73,9 +70,9 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
||||
},
|
||||
[generateReactCtrlLine],
|
||||
{
|
||||
expression: (input) => (isJSExpression(input) ? handlers.expression(input) : ''),
|
||||
function: (input) => (isJSFunction(input) ? handlers.function(input) : ''),
|
||||
loopDataExpr: (input) => (typeof input === 'string' ? transformers.transformLoopExpr(input) : ''),
|
||||
expression: (input: JSExpression) => (isJSExpression(input) ? handlers.expression(input) : ''),
|
||||
function: (input: JSFunction) => (isJSFunction(input) ? handlers.function(input) : ''),
|
||||
loopDataExpr: (input: string) => (typeof input === 'string' ? transformers.transformLoopExpr(input) : ''),
|
||||
tagName: mapComponentNameToAliasOrKeepIt,
|
||||
},
|
||||
);
|
||||
|
||||
@ -60,10 +60,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
fileType: FileType.JSX,
|
||||
name: CLASS_DEFINE_CHUNK_NAME.ConstructorEnd,
|
||||
content: '}',
|
||||
linkAfter: [
|
||||
CLASS_DEFINE_CHUNK_NAME.ConstructorStart,
|
||||
CLASS_DEFINE_CHUNK_NAME.ConstructorContent,
|
||||
],
|
||||
linkAfter: [CLASS_DEFINE_CHUNK_NAME.ConstructorStart, CLASS_DEFINE_CHUNK_NAME.ConstructorContent],
|
||||
});
|
||||
|
||||
next.chunks.push({
|
||||
@ -83,11 +80,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
fileType: FileType.JSX,
|
||||
name: REACT_CHUNK_NAME.ClassRenderEnd,
|
||||
content: '}',
|
||||
linkAfter: [
|
||||
REACT_CHUNK_NAME.ClassRenderStart,
|
||||
REACT_CHUNK_NAME.ClassRenderPre,
|
||||
REACT_CHUNK_NAME.ClassRenderJSX,
|
||||
],
|
||||
linkAfter: [REACT_CHUNK_NAME.ClassRenderStart, REACT_CHUNK_NAME.ClassRenderPre, REACT_CHUNK_NAME.ClassRenderJSX],
|
||||
});
|
||||
|
||||
next.chunks.push({
|
||||
|
||||
@ -13,7 +13,7 @@ import {
|
||||
|
||||
type PluginConfig = {
|
||||
fileType: string;
|
||||
}
|
||||
};
|
||||
|
||||
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
|
||||
const cfg: PluginConfig = {
|
||||
@ -30,9 +30,9 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
||||
|
||||
if (ir.state) {
|
||||
const state = ir.state;
|
||||
const fields = Object.keys(state).map<string>(stateName => {
|
||||
const [isString, value] = generateCompositeType(state[stateName]);
|
||||
return `${stateName}: ${isString ? `'${value}'` : value},`;
|
||||
const fields = Object.keys(state).map<string>((stateName) => {
|
||||
const value = generateCompositeType(state[stateName]);
|
||||
return `${stateName}: ${value},`;
|
||||
});
|
||||
|
||||
next.chunks.push({
|
||||
|
||||
@ -14,7 +14,7 @@ import {
|
||||
type PluginConfig = {
|
||||
fileType: string;
|
||||
implementType: 'inConstructor' | 'insMember' | 'hooks';
|
||||
}
|
||||
};
|
||||
|
||||
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
|
||||
const cfg: PluginConfig = {
|
||||
@ -32,9 +32,9 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
||||
|
||||
if (ir.state) {
|
||||
const state = ir.state;
|
||||
const fields = Object.keys(state).map<string>(stateName => {
|
||||
const [isString, value] = generateCompositeType(state[stateName]);
|
||||
return `${stateName}: ${isString ? `'${value}'` : value},`;
|
||||
const fields = Object.keys(state).map<string>((stateName) => {
|
||||
const value = generateCompositeType(state[stateName]);
|
||||
return `${stateName}: ${value},`;
|
||||
});
|
||||
|
||||
if (cfg.implementType === 'inConstructor') {
|
||||
|
||||
@ -1,18 +1,16 @@
|
||||
import { CLASS_DEFINE_CHUNK_NAME, DEFAULT_LINK_AFTER } from '../../../const/generator';
|
||||
import { REACT_CHUNK_NAME } from './const';
|
||||
|
||||
import { getFuncExprBody, transformFuncExpr2MethodMember } from '../../../utils/jsExpression';
|
||||
import { generateFunction } from '../../../utils/jsExpression';
|
||||
|
||||
import {
|
||||
BuilderComponentPlugin,
|
||||
BuilderComponentPluginFactory,
|
||||
ChunkType,
|
||||
CodeGeneratorError,
|
||||
FileType,
|
||||
ICodeChunk,
|
||||
ICodeStruct,
|
||||
IContainerInfo,
|
||||
JSExpression,
|
||||
} from '../../../types';
|
||||
|
||||
type PluginConfig = {
|
||||
@ -46,7 +44,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
||||
type: ChunkType.STRING,
|
||||
fileType: cfg.fileType,
|
||||
name: CLASS_DEFINE_CHUNK_NAME.ConstructorContent,
|
||||
content: getFuncExprBody((lifeCycles[lifeCycleName] as JSExpression).value),
|
||||
content: generateFunction(lifeCycles[lifeCycleName], { isBlock: true }),
|
||||
linkAfter: [...DEFAULT_LINK_AFTER[CLASS_DEFINE_CHUNK_NAME.ConstructorStart]],
|
||||
};
|
||||
}
|
||||
@ -55,7 +53,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
||||
type: ChunkType.STRING,
|
||||
fileType: cfg.fileType,
|
||||
name: REACT_CHUNK_NAME.ClassRenderPre,
|
||||
content: getFuncExprBody((lifeCycles[lifeCycleName] as JSExpression).value),
|
||||
content: generateFunction(lifeCycles[lifeCycleName], { isBlock: true }),
|
||||
linkAfter: [REACT_CHUNK_NAME.ClassRenderStart],
|
||||
};
|
||||
}
|
||||
@ -64,12 +62,12 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
||||
type: ChunkType.STRING,
|
||||
fileType: cfg.fileType,
|
||||
name: CLASS_DEFINE_CHUNK_NAME.InsMethod,
|
||||
content: transformFuncExpr2MethodMember(exportName, (lifeCycles[lifeCycleName] as JSExpression).value),
|
||||
content: generateFunction(lifeCycles[lifeCycleName], { name: exportName, isMember: true }),
|
||||
linkAfter: [...DEFAULT_LINK_AFTER[CLASS_DEFINE_CHUNK_NAME.InsMethod]],
|
||||
};
|
||||
});
|
||||
|
||||
next.chunks.push.apply(next.chunks, chunks);
|
||||
next.chunks.push(...chunks);
|
||||
}
|
||||
|
||||
return next;
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { CLASS_DEFINE_CHUNK_NAME, DEFAULT_LINK_AFTER } from '../../../const/generator';
|
||||
|
||||
import { transformFuncExpr2MethodMember } from '../../../utils/jsExpression';
|
||||
import { generateFunction } from '../../../utils/jsExpression';
|
||||
|
||||
import {
|
||||
BuilderComponentPlugin,
|
||||
@ -10,7 +10,6 @@ import {
|
||||
ICodeChunk,
|
||||
ICodeStruct,
|
||||
IContainerInfo,
|
||||
JSExpression,
|
||||
} from '../../../types';
|
||||
|
||||
type PluginConfig = {
|
||||
@ -36,11 +35,11 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
||||
type: ChunkType.STRING,
|
||||
fileType: cfg.fileType,
|
||||
name: CLASS_DEFINE_CHUNK_NAME.InsMethod,
|
||||
content: transformFuncExpr2MethodMember(methodName, (methods[methodName] as JSExpression).value),
|
||||
content: generateFunction(methods[methodName], { name: methodName, isMember: true }),
|
||||
linkAfter: [...DEFAULT_LINK_AFTER[CLASS_DEFINE_CHUNK_NAME.InsMethod]],
|
||||
}));
|
||||
|
||||
next.chunks.push.apply(next.chunks, chunks);
|
||||
next.chunks.push(...chunks);
|
||||
}
|
||||
|
||||
return next;
|
||||
|
||||
@ -12,16 +12,18 @@ import { REACT_CHUNK_NAME } from './const';
|
||||
import { createReactNodeGenerator } from '../../../utils/nodeToJSX';
|
||||
|
||||
type PluginConfig = {
|
||||
fileType: string;
|
||||
}
|
||||
fileType?: string;
|
||||
nodeTypeMapping?: Record<string, string>;
|
||||
};
|
||||
|
||||
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
|
||||
const cfg: PluginConfig = {
|
||||
const cfg = {
|
||||
fileType: FileType.JSX,
|
||||
nodeTypeMapping: {},
|
||||
...config,
|
||||
};
|
||||
|
||||
const generator = createReactNodeGenerator();
|
||||
const generator = createReactNodeGenerator({ nodeTypeMapping: cfg.nodeTypeMapping });
|
||||
|
||||
const plugin: BuilderComponentPlugin = async (pre: ICodeStruct) => {
|
||||
const next: ICodeStruct = {
|
||||
@ -36,10 +38,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
||||
fileType: cfg.fileType,
|
||||
name: REACT_CHUNK_NAME.ClassRenderJSX,
|
||||
content: `return ${jsxContent};`,
|
||||
linkAfter: [
|
||||
REACT_CHUNK_NAME.ClassRenderStart,
|
||||
REACT_CHUNK_NAME.ClassRenderPre,
|
||||
],
|
||||
linkAfter: [REACT_CHUNK_NAME.ClassRenderStart, REACT_CHUNK_NAME.ClassRenderPre],
|
||||
});
|
||||
|
||||
return next;
|
||||
|
||||
@ -1,3 +0,0 @@
|
||||
export const RECORE_CHUNK_NAME = {
|
||||
|
||||
};
|
||||
@ -1,3 +1,5 @@
|
||||
import { JSExpression, CompositeValue } from '@ali/lowcode-types';
|
||||
|
||||
import { CLASS_DEFINE_CHUNK_NAME, DEFAULT_LINK_AFTER } from '../../../const/generator';
|
||||
|
||||
import {
|
||||
@ -7,15 +9,14 @@ import {
|
||||
FileType,
|
||||
ICodeStruct,
|
||||
IContainerInfo,
|
||||
CompositeValue,
|
||||
JSExpression,
|
||||
} from '../../../types';
|
||||
|
||||
import { generateCompositeType, handleStringValueDefault } from '../../../utils/compositeType';
|
||||
import { generateCompositeType } from '../../../utils/compositeType';
|
||||
import { generateExpression } from '../../../utils/jsExpression';
|
||||
|
||||
function packJsExpression(exp: JSExpression): string {
|
||||
const funcStr = generateExpression(exp);
|
||||
function packJsExpression(exp: unknown): string {
|
||||
const expression = exp as JSExpression;
|
||||
const funcStr = generateExpression(expression);
|
||||
return `function() { return (${funcStr}); }`;
|
||||
}
|
||||
|
||||
@ -40,11 +41,11 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
|
||||
attrs = [...attrs, ...extConfigs];
|
||||
|
||||
const listProp = handleStringValueDefault(
|
||||
generateCompositeType((list as unknown) as CompositeValue, {
|
||||
const listProp = generateCompositeType((list as unknown) as CompositeValue, {
|
||||
handlers: {
|
||||
expression: packJsExpression,
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
attrs.push(`list: ${listProp}`);
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
type: ChunkType.STRING,
|
||||
fileType: FileType.TS,
|
||||
name: CLASS_DEFINE_CHUNK_NAME.StaticVar,
|
||||
content: `static cssText = '${ir.css.replace(/\'/g, '\\\'')}';`,
|
||||
content: `static cssText = '${ir.css.replace(/'/g, "\\'")}';`,
|
||||
linkAfter: [...DEFAULT_LINK_AFTER[CLASS_DEFINE_CHUNK_NAME.StaticVar]],
|
||||
});
|
||||
}
|
||||
|
||||
@ -1,20 +1,22 @@
|
||||
import { NodeSchema } from '@ali/lowcode-types';
|
||||
|
||||
import {
|
||||
BuilderComponentPlugin,
|
||||
BuilderComponentPluginFactory,
|
||||
ChunkType,
|
||||
ICodeStruct,
|
||||
IContainerInfo,
|
||||
NodeSchema,
|
||||
INodeGeneratorContext,
|
||||
CodePiece,
|
||||
PIECE_TYPE,
|
||||
} from '../../../types';
|
||||
import { COMMON_CHUNK_NAME, DEFAULT_LINK_AFTER } from '../../../const/generator';
|
||||
import { COMMON_CHUNK_NAME } from '../../../const/generator';
|
||||
|
||||
import { createNodeGenerator, generateString } from '../../../utils/nodeToJSX';
|
||||
import { generateExpression } from '../../../utils/jsExpression';
|
||||
import { generateCompositeType, handleStringValueDefault } from '../../../utils/compositeType';
|
||||
import { generateCompositeType } from '../../../utils/compositeType';
|
||||
|
||||
const generateGlobalProps = (nodeItem: NodeSchema): CodePiece[] => {
|
||||
const generateGlobalProps = (ctx: INodeGeneratorContext, nodeItem: NodeSchema): CodePiece[] => {
|
||||
return [
|
||||
{
|
||||
value: `{...globalProps.${nodeItem.componentName}}`,
|
||||
@ -23,11 +25,11 @@ const generateGlobalProps = (nodeItem: NodeSchema): CodePiece[] => {
|
||||
];
|
||||
};
|
||||
|
||||
const generateCtrlLine = (nodeItem: NodeSchema): CodePiece[] => {
|
||||
const generateCtrlLine = (ctx: INodeGeneratorContext, nodeItem: NodeSchema): CodePiece[] => {
|
||||
const pieces: CodePiece[] = [];
|
||||
|
||||
if (nodeItem.loop && nodeItem.loopArgs) {
|
||||
const loopDataExp = handleStringValueDefault(generateCompositeType(nodeItem.loop));
|
||||
const loopDataExp = generateCompositeType(nodeItem.loop);
|
||||
pieces.push({
|
||||
type: PIECE_TYPE.ATTR,
|
||||
value: `x-for={${loopDataExp}}`,
|
||||
@ -40,7 +42,7 @@ const generateCtrlLine = (nodeItem: NodeSchema): CodePiece[] => {
|
||||
}
|
||||
|
||||
if (nodeItem.condition) {
|
||||
const conditionExp = handleStringValueDefault(generateCompositeType(nodeItem.condition));
|
||||
const conditionExp = generateCompositeType(nodeItem.condition);
|
||||
pieces.push({
|
||||
type: PIECE_TYPE.ATTR,
|
||||
value: `x-if={${conditionExp}}`,
|
||||
|
||||
@ -1,11 +1,6 @@
|
||||
import { COMMON_CHUNK_NAME } from '../../../const/generator';
|
||||
|
||||
import {
|
||||
BuilderComponentPlugin,
|
||||
BuilderComponentPluginFactory,
|
||||
ChunkType,
|
||||
ICodeStruct,
|
||||
} from '../../../types';
|
||||
import { BuilderComponentPlugin, BuilderComponentPluginFactory, ChunkType, ICodeStruct } from '../../../types';
|
||||
|
||||
const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
const plugin: BuilderComponentPlugin = async (pre: ICodeStruct) => {
|
||||
|
||||
@ -12,7 +12,7 @@ import {
|
||||
type PluginConfig = {
|
||||
fileType: string;
|
||||
moduleFileType: string;
|
||||
}
|
||||
};
|
||||
|
||||
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
|
||||
const cfg: PluginConfig = {
|
||||
|
||||
@ -17,7 +17,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
|
||||
const ir = next.ir as IProjectInfo;
|
||||
if (ir.constants) {
|
||||
const [, constantStr] = generateCompositeType(ir.constants);
|
||||
const constantStr = generateCompositeType(ir.constants);
|
||||
|
||||
next.chunks.push({
|
||||
type: ChunkType.STRING,
|
||||
|
||||
@ -6,7 +6,6 @@ import {
|
||||
ChunkType,
|
||||
FileType,
|
||||
ICodeStruct,
|
||||
IProjectInfo,
|
||||
} from '../../../../../types';
|
||||
|
||||
const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
@ -15,8 +14,6 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
...pre,
|
||||
};
|
||||
|
||||
const ir = next.ir as IProjectInfo;
|
||||
|
||||
next.chunks.push({
|
||||
type: ChunkType.STRING,
|
||||
fileType: FileType.JS,
|
||||
@ -34,10 +31,10 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
content: `
|
||||
const appConfig = {
|
||||
app: {
|
||||
rootId: '${ir.config.targetRootID}',
|
||||
rootId: 'app',
|
||||
},
|
||||
router: {
|
||||
type: '${ir.config.historyMode}',
|
||||
type: 'hash',
|
||||
},
|
||||
};
|
||||
createApp(appConfig);
|
||||
|
||||
@ -31,7 +31,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
<title>${ir.meta.name}</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="${ir.config.targetRootID}"></div>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
`,
|
||||
|
||||
@ -1,3 +1,5 @@
|
||||
import { PackageJSON } from '@ali/lowcode-types';
|
||||
|
||||
import { COMMON_CHUNK_NAME } from '../../../../../const/generator';
|
||||
|
||||
import {
|
||||
@ -6,11 +8,10 @@ import {
|
||||
ChunkType,
|
||||
FileType,
|
||||
ICodeStruct,
|
||||
IPackageJSON,
|
||||
IProjectInfo,
|
||||
} from '../../../../../types';
|
||||
|
||||
interface IIceJsPackageJSON extends IPackageJSON {
|
||||
interface IIceJsPackageJSON extends PackageJSON {
|
||||
ideMode: {
|
||||
name: string;
|
||||
};
|
||||
@ -73,6 +74,8 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
originTemplate: '@alifd/scaffold-lite-js',
|
||||
};
|
||||
|
||||
ir.packages.forEach((packageInfo) => (packageJson.dependencies[packageInfo.package] = packageInfo.version));
|
||||
|
||||
next.chunks.push({
|
||||
type: ChunkType.JSON,
|
||||
fileType: FileType.JSON,
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'README',
|
||||
'md',
|
||||
`
|
||||
|
||||
@ -1,17 +1,17 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
'abc',
|
||||
'json',
|
||||
`
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
return [
|
||||
[],
|
||||
{
|
||||
name: 'abc',
|
||||
ext: 'json',
|
||||
content: `
|
||||
{
|
||||
"type": "ice-app",
|
||||
"builder": "@ali/builder-ice-app"
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
return [[], file];
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
'build',
|
||||
'json',
|
||||
`
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
return [
|
||||
[],
|
||||
{
|
||||
name: 'build',
|
||||
ext: 'json',
|
||||
content: `
|
||||
{
|
||||
"entry": "src/app.js",
|
||||
"plugins": [
|
||||
@ -26,8 +27,7 @@ export default function getFile(): [string[], IResultFile] {
|
||||
"@ali/build-plugin-ice-def"
|
||||
]
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
return [[], file];
|
||||
`,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.editorconfig',
|
||||
'',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.eslintignore',
|
||||
'',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.eslintrc',
|
||||
'js',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.gitignore',
|
||||
'',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'jsconfig',
|
||||
'json',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.prettierignore',
|
||||
'',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.prettierrc',
|
||||
'js',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'index',
|
||||
'jsx',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'index',
|
||||
'module.scss',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'index',
|
||||
'jsx',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'index',
|
||||
'module.scss',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'index',
|
||||
'jsx',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'index',
|
||||
'jsx',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'menuConfig',
|
||||
'js',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.stylelintignore',
|
||||
'',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.stylelintrc',
|
||||
'js',
|
||||
`
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'tsconfig',
|
||||
'json',
|
||||
`
|
||||
|
||||
@ -1,8 +1,7 @@
|
||||
import ResultDir from '../../../../../model/ResultDir';
|
||||
import {
|
||||
IProjectTemplate,
|
||||
IResultDir,
|
||||
} from '../../../../../types';
|
||||
import { ResultDir } from '@ali/lowcode-types';
|
||||
import { IProjectTemplate } from '../../../../../types';
|
||||
|
||||
import { createResultDir } from '../../../../../utils/resultHelper';
|
||||
import { runFileGenerator } from '../../../../../utils/templateHelper';
|
||||
|
||||
import file12 from './files/abc.json';
|
||||
@ -68,8 +67,8 @@ const icejsTemplate: IProjectTemplate = {
|
||||
},
|
||||
},
|
||||
|
||||
generateTemplate(): IResultDir {
|
||||
const root = new ResultDir('.');
|
||||
generateTemplate(): ResultDir {
|
||||
const root = createResultDir('.');
|
||||
|
||||
runFileGenerator(root, file1);
|
||||
runFileGenerator(root, file2);
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { NpmInfo } from '@ali/lowcode-types';
|
||||
import { NpmInfo, PackageJSON } from '@ali/lowcode-types';
|
||||
import { COMMON_CHUNK_NAME } from '../../../../../const/generator';
|
||||
|
||||
import {
|
||||
@ -7,7 +7,6 @@ import {
|
||||
ChunkType,
|
||||
FileType,
|
||||
ICodeStruct,
|
||||
IPackageJSON,
|
||||
IProjectInfo,
|
||||
} from '../../../../../types';
|
||||
import { isNpmInfo } from '../../../../../utils/schema';
|
||||
@ -23,7 +22,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
|
||||
const npmDeps = getNpmDependencies(ir);
|
||||
|
||||
const packageJson: IPackageJSON = {
|
||||
const packageJson: PackageJSON = {
|
||||
name: '@ali/rax-app-demo',
|
||||
private: true,
|
||||
version: '1.0.0',
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.editorconfig',
|
||||
'',
|
||||
`
|
||||
@ -29,4 +28,3 @@ trim_trailing_whitespace = false
|
||||
|
||||
return [[], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.eslintignore',
|
||||
'',
|
||||
`
|
||||
@ -23,4 +23,3 @@ packages/solution
|
||||
|
||||
return [[], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.gitignore',
|
||||
'',
|
||||
`
|
||||
@ -54,4 +53,3 @@ Thumbs.db
|
||||
|
||||
return [[], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'.prettierrc',
|
||||
'',
|
||||
`
|
||||
@ -19,4 +18,3 @@ export default function getFile(): [string[], IResultFile] {
|
||||
|
||||
return [[], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'README',
|
||||
'md',
|
||||
`
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'abc',
|
||||
'json',
|
||||
`
|
||||
@ -25,4 +24,3 @@ export default function getFile(): [string[], IResultFile] {
|
||||
|
||||
return [[], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'build',
|
||||
'json',
|
||||
`
|
||||
@ -29,4 +28,3 @@ export default function getFile(): [string[], IResultFile] {
|
||||
|
||||
return [[], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'package',
|
||||
'json',
|
||||
`
|
||||
@ -63,4 +62,3 @@ export default function getFile(): [string[], IResultFile] {
|
||||
|
||||
return [[], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'index',
|
||||
'html',
|
||||
`
|
||||
@ -48,4 +47,3 @@ export default function getFile(): [string[], IResultFile] {
|
||||
|
||||
return [['public'], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'app',
|
||||
'ts',
|
||||
`
|
||||
@ -72,6 +71,5 @@ export default {
|
||||
`,
|
||||
);
|
||||
|
||||
return [['src','config'], file];
|
||||
return [['src', 'config'], file];
|
||||
}
|
||||
|
||||
@ -1,15 +1,14 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'components',
|
||||
'ts',
|
||||
`
|
||||
/**
|
||||
* 乐高组件
|
||||
*/
|
||||
*/
|
||||
import Div from '@ali/vc-div/build/view';
|
||||
import Text from '@ali/vc-text/build/view';
|
||||
import Slot from '@ali/vc-slot/build/view';
|
||||
@ -38,6 +37,5 @@ export default componentsMap;
|
||||
`,
|
||||
);
|
||||
|
||||
return [['src','config'], file];
|
||||
return [['src', 'config'], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'utils',
|
||||
'ts',
|
||||
`
|
||||
@ -24,6 +23,5 @@ export default {
|
||||
`,
|
||||
);
|
||||
|
||||
return [['src','config'], file];
|
||||
return [['src', 'config'], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'index',
|
||||
'ts',
|
||||
`
|
||||
@ -98,4 +97,3 @@ app.run();
|
||||
|
||||
return [['src'], file];
|
||||
}
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'router',
|
||||
'ts',
|
||||
`
|
||||
|
||||
@ -1,9 +1,8 @@
|
||||
import { ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultFile } from '../../../../../../utils/resultHelper';
|
||||
|
||||
import ResultFile from '../../../../../../model/ResultFile';
|
||||
import { IResultFile } from '../../../../../../types';
|
||||
|
||||
export default function getFile(): [string[], IResultFile] {
|
||||
const file = new ResultFile(
|
||||
export default function getFile(): [string[], ResultFile] {
|
||||
const file = createResultFile(
|
||||
'tsconfig',
|
||||
'json',
|
||||
`
|
||||
@ -50,4 +49,3 @@ export default function getFile(): [string[], IResultFile] {
|
||||
|
||||
return [[], file];
|
||||
}
|
||||
|
||||
@ -1,8 +1,6 @@
|
||||
import ResultDir from '../../../../../model/ResultDir';
|
||||
import {
|
||||
IProjectTemplate,
|
||||
IResultDir,
|
||||
} from '../../../../../types';
|
||||
import { ResultDir } from '@ali/lowcode-types';
|
||||
import { IProjectTemplate } from '../../../../../types';
|
||||
import { createResultDir } from '../../../../../utils/resultHelper';
|
||||
import { runFileGenerator } from '../../../../../utils/templateHelper';
|
||||
|
||||
import file1 from './files/abc.json';
|
||||
@ -28,8 +26,8 @@ const icejsTemplate: IProjectTemplate = {
|
||||
},
|
||||
},
|
||||
|
||||
generateTemplate(): IResultDir {
|
||||
const root = new ResultDir('.');
|
||||
generateTemplate(): ResultDir {
|
||||
const root = createResultDir('.');
|
||||
|
||||
runFileGenerator(root, file1);
|
||||
runFileGenerator(root, file2);
|
||||
|
||||
@ -17,7 +17,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||
|
||||
const ir = next.ir as IProjectInfo;
|
||||
if (ir.i18n) {
|
||||
const [, i18nStr] = generateCompositeType(ir.i18n, {});
|
||||
const i18nStr = generateCompositeType(ir.i18n);
|
||||
|
||||
next.chunks.push({
|
||||
type: ChunkType.STRING,
|
||||
|
||||
@ -1,10 +1,5 @@
|
||||
import {
|
||||
IResultDir,
|
||||
PublisherFactory,
|
||||
IPublisher,
|
||||
IPublisherFactoryParams,
|
||||
PublisherError,
|
||||
} from '../../types';
|
||||
import { ResultDir } from '@ali/lowcode-types';
|
||||
import { PublisherFactory, IPublisher, IPublisherFactoryParams, PublisherError } from '../../types';
|
||||
import { writeFolder } from './utils';
|
||||
|
||||
export interface IDiskFactoryParams extends IPublisherFactoryParams {
|
||||
@ -18,19 +13,18 @@ export interface IDiskPublisher extends IPublisher<IDiskFactoryParams, string> {
|
||||
setOutputPath: (path: string) => void;
|
||||
}
|
||||
|
||||
export const createDiskPublisher: PublisherFactory<
|
||||
IDiskFactoryParams,
|
||||
IDiskPublisher
|
||||
> = (params: IDiskFactoryParams = {}): IDiskPublisher => {
|
||||
export const createDiskPublisher: PublisherFactory<IDiskFactoryParams, IDiskPublisher> = (
|
||||
params: IDiskFactoryParams = {},
|
||||
): IDiskPublisher => {
|
||||
let { project, outputPath = './' } = params;
|
||||
|
||||
const getProject = (): IResultDir => {
|
||||
const getProject = (): ResultDir => {
|
||||
if (!project) {
|
||||
throw new PublisherError('Missing Project');
|
||||
}
|
||||
return project;
|
||||
};
|
||||
const setProject = (projectToSet: IResultDir): void => {
|
||||
const setProject = (projectToSet: ResultDir): void => {
|
||||
project = projectToSet;
|
||||
};
|
||||
|
||||
@ -49,19 +43,14 @@ export const createDiskPublisher: PublisherFactory<
|
||||
|
||||
const projectOutputPath = options.outputPath || outputPath;
|
||||
const overrideProjectSlug = options.projectSlug || params.projectSlug;
|
||||
const createProjectFolder =
|
||||
options.createProjectFolder || params.createProjectFolder;
|
||||
const createProjectFolder = options.createProjectFolder || params.createProjectFolder;
|
||||
|
||||
if (overrideProjectSlug) {
|
||||
projectToPublish.name = overrideProjectSlug;
|
||||
}
|
||||
|
||||
try {
|
||||
await writeFolder(
|
||||
projectToPublish,
|
||||
projectOutputPath,
|
||||
createProjectFolder,
|
||||
);
|
||||
await writeFolder(projectToPublish, projectOutputPath, createProjectFolder);
|
||||
return { success: true, payload: projectOutputPath };
|
||||
} catch (error) {
|
||||
throw new PublisherError(error);
|
||||
|
||||
@ -1,36 +1,27 @@
|
||||
import { existsSync, mkdir, writeFile } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
import { IResultDir, IResultFile } from '../../types';
|
||||
import { ResultDir, ResultFile } from '@ali/lowcode-types';
|
||||
|
||||
export const writeFolder = async (
|
||||
folder: IResultDir,
|
||||
folder: ResultDir,
|
||||
currentPath: string,
|
||||
createProjectFolder = true,
|
||||
): Promise<void> => {
|
||||
const { name, files, dirs } = folder;
|
||||
|
||||
const folderPath = createProjectFolder
|
||||
? join(currentPath, name)
|
||||
: currentPath;
|
||||
const folderPath = createProjectFolder ? join(currentPath, name) : currentPath;
|
||||
|
||||
if (!existsSync(folderPath)) {
|
||||
await createDirectory(folderPath);
|
||||
}
|
||||
|
||||
const promises = [
|
||||
writeFilesToFolder(folderPath, files),
|
||||
writeSubFoldersToFolder(folderPath, dirs),
|
||||
];
|
||||
const promises = [writeFilesToFolder(folderPath, files), writeSubFoldersToFolder(folderPath, dirs)];
|
||||
|
||||
await Promise.all(promises);
|
||||
};
|
||||
|
||||
const writeFilesToFolder = async (
|
||||
folderPath: string,
|
||||
files: IResultFile[],
|
||||
): Promise<void> => {
|
||||
const promises = files.map(file => {
|
||||
const writeFilesToFolder = async (folderPath: string, files: ResultFile[]): Promise<void> => {
|
||||
const promises = files.map((file) => {
|
||||
const fileName = file.ext ? `${file.name}.${file.ext}` : file.name;
|
||||
const filePath = join(folderPath, fileName);
|
||||
return writeContentToFile(filePath, file.content);
|
||||
@ -39,11 +30,8 @@ const writeFilesToFolder = async (
|
||||
await Promise.all(promises);
|
||||
};
|
||||
|
||||
const writeSubFoldersToFolder = async (
|
||||
folderPath: string,
|
||||
subFolders: IResultDir[],
|
||||
): Promise<void> => {
|
||||
const promises = subFolders.map(subFolder => {
|
||||
const writeSubFoldersToFolder = async (folderPath: string, subFolders: ResultDir[]): Promise<void> => {
|
||||
const promises = subFolders.map((subFolder) => {
|
||||
return writeFolder(subFolder, folderPath);
|
||||
});
|
||||
|
||||
@ -52,19 +40,15 @@ const writeSubFoldersToFolder = async (
|
||||
|
||||
const createDirectory = (pathToDir: string): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
mkdir(pathToDir, { recursive: true }, err => {
|
||||
mkdir(pathToDir, { recursive: true }, (err) => {
|
||||
err ? reject(err) : resolve();
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const writeContentToFile = (
|
||||
filePath: string,
|
||||
fileContent: string,
|
||||
encoding: string = 'utf8',
|
||||
): Promise<void> => {
|
||||
const writeContentToFile = (filePath: string, fileContent: string, encoding = 'utf8'): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
writeFile(filePath, fileContent, encoding, err => {
|
||||
writeFile(filePath, fileContent, encoding, (err) => {
|
||||
err ? reject(err) : resolve();
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,11 +1,6 @@
|
||||
import {
|
||||
IResultDir,
|
||||
PublisherFactory,
|
||||
IPublisher,
|
||||
IPublisherFactoryParams,
|
||||
PublisherError,
|
||||
} from '../../types';
|
||||
import { isNodeProcess, writeZipToDisk, generateProjectZip } from './utils'
|
||||
import { ResultDir } from '@ali/lowcode-types';
|
||||
import { PublisherFactory, IPublisher, IPublisherFactoryParams, PublisherError } from '../../types';
|
||||
import { isNodeProcess, writeZipToDisk, generateProjectZip } from './utils';
|
||||
|
||||
// export type ZipBuffer = Buffer | Blob;
|
||||
export type ZipBuffer = Buffer;
|
||||
@ -28,14 +23,14 @@ export const createZipPublisher: PublisherFactory<ZipFactoryParams, ZipPublisher
|
||||
let { project, outputPath } = params;
|
||||
|
||||
const getProject = () => project;
|
||||
const setProject = (projectToSet: IResultDir) => {
|
||||
const setProject = (projectToSet: ResultDir) => {
|
||||
project = projectToSet;
|
||||
}
|
||||
};
|
||||
|
||||
const getOutputPath = () => outputPath;
|
||||
const setOutputPath = (path: string) => {
|
||||
outputPath = path;
|
||||
}
|
||||
};
|
||||
|
||||
const publish = async (options: ZipFactoryParams = {}) => {
|
||||
const projectToPublish = options.project || project;
|
||||
@ -57,7 +52,7 @@ export const createZipPublisher: PublisherFactory<ZipFactoryParams, ZipPublisher
|
||||
} catch (error) {
|
||||
throw new PublisherError(error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
publish,
|
||||
@ -66,4 +61,4 @@ export const createZipPublisher: PublisherFactory<ZipFactoryParams, ZipPublisher
|
||||
getOutputPath,
|
||||
setOutputPath,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,21 +1,17 @@
|
||||
import JSZip from 'jszip';
|
||||
import { IResultDir, IResultFile } from '../../types';
|
||||
import { ResultDir, ResultFile } from '@ali/lowcode-types';
|
||||
import { ZipBuffer } from './index';
|
||||
|
||||
export const isNodeProcess = (): boolean => {
|
||||
return (
|
||||
typeof process === 'object' &&
|
||||
typeof process.versions === 'object' &&
|
||||
typeof process.versions.node !== 'undefined'
|
||||
typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node !== 'undefined'
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const writeZipToDisk = (
|
||||
zipFolderPath: string,
|
||||
content: ZipBuffer,
|
||||
zipName: string,
|
||||
): void => {
|
||||
export const writeZipToDisk = (zipFolderPath: string, content: ZipBuffer, zipName: string): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const fs = require('fs');
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const path = require('path');
|
||||
|
||||
if (!fs.existsSync(zipFolderPath)) {
|
||||
@ -27,34 +23,30 @@ export const writeZipToDisk = (
|
||||
const writeStream = fs.createWriteStream(zipPath);
|
||||
writeStream.write(content);
|
||||
writeStream.end();
|
||||
}
|
||||
};
|
||||
|
||||
export const generateProjectZip = async (project: IResultDir): Promise<ZipBuffer> => {
|
||||
export const generateProjectZip = async (project: ResultDir): Promise<ZipBuffer> => {
|
||||
let zip = new JSZip();
|
||||
zip = writeFolderToZip(project, zip, true);
|
||||
// const zipType = isNodeProcess() ? 'nodebuffer' : 'blob';
|
||||
const zipType = 'nodebuffer'; // 目前先只支持 node 调用
|
||||
return zip.generateAsync({ type: zipType });
|
||||
}
|
||||
};
|
||||
|
||||
const writeFolderToZip = (
|
||||
folder: IResultDir,
|
||||
parentFolder: JSZip,
|
||||
ignoreFolder: boolean = false,
|
||||
) => {
|
||||
const writeFolderToZip = (folder: ResultDir, parentFolder: JSZip, ignoreFolder = false) => {
|
||||
const zipFolder = ignoreFolder ? parentFolder : parentFolder.folder(folder.name);
|
||||
if (zipFolder !== null) {
|
||||
folder.files.forEach((file: IResultFile) => {
|
||||
folder.files.forEach((file: ResultFile) => {
|
||||
// const options = file.contentEncoding === 'base64' ? { base64: true } : {};
|
||||
const options = {};
|
||||
const fileName = file.ext ? `${file.name}.${file.ext}` : file.name;
|
||||
zipFolder.file(fileName, file.content, options);
|
||||
});
|
||||
|
||||
folder.dirs.forEach((subFolder: IResultDir) => {
|
||||
folder.dirs.forEach((subFolder: ResultDir) => {
|
||||
writeFolderToZip(subFolder, zipFolder);
|
||||
});
|
||||
}
|
||||
|
||||
return parentFolder;
|
||||
}
|
||||
};
|
||||
|
||||
@ -5,7 +5,7 @@ import { createProjectBuilder } from '../generator/ProjectBuilder';
|
||||
import esmodule from '../plugins/common/esmodule';
|
||||
import containerClass from '../plugins/component/react/containerClass';
|
||||
import containerInitState from '../plugins/component/react/containerInitState';
|
||||
import containerInjectUtils from '../plugins/component/react/containerInjectUtils';
|
||||
// import containerInjectUtils from '../plugins/component/react/containerInjectUtils';
|
||||
import containerLifeCycle from '../plugins/component/react/containerLifeCycle';
|
||||
import containerMethod from '../plugins/component/react/containerMethod';
|
||||
import jsx from '../plugins/component/react/jsx';
|
||||
@ -29,11 +29,18 @@ export default function createIceJsProjectBuilder(): IProjectBuilder {
|
||||
fileType: 'jsx',
|
||||
}),
|
||||
containerClass(),
|
||||
containerInjectUtils(),
|
||||
// containerInjectUtils(),
|
||||
containerInitState(),
|
||||
containerLifeCycle(),
|
||||
containerMethod(),
|
||||
jsx(),
|
||||
jsx({
|
||||
nodeTypeMapping: {
|
||||
Div: 'div',
|
||||
Component: 'div',
|
||||
Page: 'div',
|
||||
Block: 'div',
|
||||
},
|
||||
}),
|
||||
css(),
|
||||
],
|
||||
pages: [
|
||||
@ -42,11 +49,19 @@ export default function createIceJsProjectBuilder(): IProjectBuilder {
|
||||
fileType: 'jsx',
|
||||
}),
|
||||
containerClass(),
|
||||
containerInjectUtils(),
|
||||
// containerInjectUtils(),
|
||||
containerInitState(),
|
||||
containerLifeCycle(),
|
||||
containerMethod(),
|
||||
jsx(),
|
||||
jsx({
|
||||
nodeTypeMapping: {
|
||||
Div: 'div',
|
||||
Component: 'div',
|
||||
Page: 'div',
|
||||
Block: 'div',
|
||||
// Box: 'div',
|
||||
},
|
||||
}),
|
||||
css(),
|
||||
],
|
||||
router: [esmodule(), icejs.plugins.router()],
|
||||
@ -58,6 +73,6 @@ export default function createIceJsProjectBuilder(): IProjectBuilder {
|
||||
htmlEntry: [icejs.plugins.entryHtml()],
|
||||
packageJSON: [icejs.plugins.packageJSON()],
|
||||
},
|
||||
postProcessors: [prettier()],
|
||||
postProcessors: [prettier()], // prettier()
|
||||
});
|
||||
}
|
||||
|
||||
@ -1,9 +1,19 @@
|
||||
import { JSExpression, JSFunction, NodeSchema } from '@ali/lowcode-types';
|
||||
import {
|
||||
ResultDir,
|
||||
ResultFile,
|
||||
NodeData,
|
||||
NodeSchema,
|
||||
ProjectSchema,
|
||||
JSExpression,
|
||||
JSFunction,
|
||||
CompositeArray,
|
||||
CompositeObject,
|
||||
JSONArray,
|
||||
JSONObject,
|
||||
JSSlot,
|
||||
} from '@ali/lowcode-types';
|
||||
|
||||
import { CustomHandlerSet } from '../utils/compositeType';
|
||||
import { IParseResult } from './intermediate';
|
||||
import { IResultDir, IResultFile } from './result';
|
||||
import { IBasicSchema, IProjectSchema } from './schema';
|
||||
|
||||
export enum FileType {
|
||||
CSS = 'css',
|
||||
@ -68,13 +78,13 @@ export interface ICodeBuilder {
|
||||
}
|
||||
|
||||
export interface ICompiledModule {
|
||||
files: IResultFile[];
|
||||
files: ResultFile[];
|
||||
}
|
||||
|
||||
export interface IModuleBuilder {
|
||||
generateModule(input: unknown): Promise<ICompiledModule>;
|
||||
generateModuleCode(schema: IBasicSchema | string): Promise<IResultDir>;
|
||||
linkCodeChunks(chunks: Record<string, ICodeChunk[]>, fileName: string): IResultFile[];
|
||||
generateModuleCode(schema: ProjectSchema | string): Promise<ResultDir>;
|
||||
linkCodeChunks(chunks: Record<string, ICodeChunk[]>, fileName: string): ResultFile[];
|
||||
addPlugin(plugin: BuilderComponentPlugin): void;
|
||||
}
|
||||
|
||||
@ -88,21 +98,21 @@ export interface ICodeGenerator {
|
||||
/**
|
||||
* 出码接口,把 Schema 转换成代码文件系统描述
|
||||
*
|
||||
* @param {(IBasicSchema)} schema 传入的 Schema
|
||||
* @returns {IResultDir}
|
||||
* @param {(ProjectSchema)} schema 传入的 Schema
|
||||
* @returns {ResultDir}
|
||||
* @memberof ICodeGenerator
|
||||
*/
|
||||
toCode(schema: IBasicSchema): Promise<IResultDir>;
|
||||
toCode(schema: ProjectSchema): Promise<ResultDir>;
|
||||
}
|
||||
|
||||
export interface ISchemaParser {
|
||||
validate(schema: IBasicSchema): boolean;
|
||||
parse(schema: IBasicSchema | string): IParseResult;
|
||||
validate(schema: ProjectSchema): boolean;
|
||||
parse(schema: ProjectSchema | string): IParseResult;
|
||||
}
|
||||
|
||||
export interface IProjectTemplate {
|
||||
slots: Record<string, IProjectSlot>;
|
||||
generateTemplate(): IResultDir;
|
||||
generateTemplate(): ResultDir;
|
||||
}
|
||||
|
||||
export interface IProjectSlot {
|
||||
@ -110,25 +120,12 @@ export interface IProjectSlot {
|
||||
fileName?: string;
|
||||
}
|
||||
|
||||
// export interface IProjectSlots {
|
||||
// components: IProjectSlot;
|
||||
// pages: IProjectSlot;
|
||||
// router: IProjectSlot;
|
||||
// entry: IProjectSlot;
|
||||
// constants?: IProjectSlot;
|
||||
// utils?: IProjectSlot;
|
||||
// i18n?: IProjectSlot;
|
||||
// globalStyle: IProjectSlot;
|
||||
// htmlEntry: IProjectSlot;
|
||||
// packageJSON: IProjectSlot;
|
||||
// }
|
||||
|
||||
export interface IProjectPlugins {
|
||||
[slotName: string]: BuilderComponentPlugin[];
|
||||
}
|
||||
|
||||
export interface IProjectBuilder {
|
||||
generateProject(schema: IProjectSchema | string): Promise<IResultDir>;
|
||||
generateProject(schema: ProjectSchema | string): Promise<ResultDir>;
|
||||
}
|
||||
|
||||
export type PostProcessorFactory<T> = (config?: T) => PostProcessor;
|
||||
@ -161,10 +158,41 @@ export interface HandlerSet<T> {
|
||||
common?: (input: unknown) => T[];
|
||||
}
|
||||
|
||||
export type ExtGeneratorPlugin = (nodeItem: NodeSchema, handlers: CustomHandlerSet) => CodePiece[];
|
||||
export type ExtGeneratorPlugin = (
|
||||
ctx: INodeGeneratorContext,
|
||||
nodeItem: NodeSchema,
|
||||
handlers: CustomHandlerSet,
|
||||
) => CodePiece[];
|
||||
|
||||
// export interface InteratorScope {
|
||||
// [$item: string]: string; // $item 默认取值 "item"
|
||||
// [$index: string]: string | number; // $index 默认取值 "index"
|
||||
// __proto__: BlockInstance;
|
||||
// }
|
||||
export interface INodeGeneratorConfig {
|
||||
nodeTypeMapping?: Record<string, string>;
|
||||
}
|
||||
|
||||
export type NodeGenerator = (nodeItem: NodeData) => string;
|
||||
|
||||
export interface INodeGeneratorContext {
|
||||
generator: NodeGenerator;
|
||||
}
|
||||
|
||||
export type CompositeValueCustomHandler = (data: unknown) => string;
|
||||
export type CompositeTypeContainerHandler = (value: string) => string;
|
||||
export interface CompositeValueCustomHandlerSet {
|
||||
boolean?: CompositeValueCustomHandler;
|
||||
number?: CompositeValueCustomHandler;
|
||||
string?: CompositeValueCustomHandler;
|
||||
array?: CompositeValueCustomHandler;
|
||||
object?: CompositeValueCustomHandler;
|
||||
expression?: CompositeValueCustomHandler;
|
||||
function?: CompositeValueCustomHandler;
|
||||
}
|
||||
|
||||
export interface CompositeTypeContainerHandlerSet {
|
||||
default?: CompositeTypeContainerHandler;
|
||||
string?: CompositeTypeContainerHandler;
|
||||
}
|
||||
|
||||
export type CompositeValueGeneratorOptions = {
|
||||
handlers?: CompositeValueCustomHandlerSet;
|
||||
containerHandlers?: CompositeTypeContainerHandlerSet;
|
||||
nodeGenerator?: NodeGenerator;
|
||||
};
|
||||
|
||||
@ -1,13 +1,15 @@
|
||||
export interface INpmPackage {
|
||||
package: string; // 组件包的名称
|
||||
version: string; // 组件包的版本
|
||||
}
|
||||
|
||||
/**
|
||||
* 外部依赖描述
|
||||
*
|
||||
* @export
|
||||
* @interface IExternalDependency
|
||||
*/
|
||||
export interface IExternalDependency extends IDependency {
|
||||
package: string; // 组件包的名称
|
||||
version: string; // 组件包的版本
|
||||
}
|
||||
export interface IExternalDependency extends INpmPackage, IDependency {}
|
||||
|
||||
export enum InternalDependencyType {
|
||||
PAGE = 'pages',
|
||||
@ -32,5 +34,5 @@ export interface IDependency {
|
||||
subName?: string; // 下标子组件名称
|
||||
main?: string; // 包导出组件入口文件路径 /lib/input
|
||||
dependencyType?: DependencyType; // 依赖类型 内/外
|
||||
importName?: string; // 导入后名称
|
||||
componentName?: string; // 导入后名称
|
||||
}
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
/* eslint-disable @typescript-eslint/no-useless-constructor */
|
||||
export class CodeGeneratorError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
@ -5,21 +6,18 @@ export class CodeGeneratorError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
// tslint:disable-next-line: max-classes-per-file
|
||||
export class ComponentValidationError extends CodeGeneratorError {
|
||||
constructor(errorString: string) {
|
||||
super(errorString);
|
||||
}
|
||||
}
|
||||
|
||||
// tslint:disable-next-line: max-classes-per-file
|
||||
export class CompatibilityError extends CodeGeneratorError {
|
||||
constructor(errorString: string) {
|
||||
super(errorString);
|
||||
}
|
||||
}
|
||||
|
||||
// tslint:disable-next-line: max-classes-per-file
|
||||
export class PublisherError extends CodeGeneratorError {
|
||||
constructor(errorString: string) {
|
||||
super(errorString);
|
||||
|
||||
@ -1,7 +1,5 @@
|
||||
export * from './core';
|
||||
export * from './deps';
|
||||
export * from './error';
|
||||
export * from './result';
|
||||
export * from './schema';
|
||||
export * from './intermediate';
|
||||
export * from './publisher';
|
||||
|
||||
@ -1,25 +1,26 @@
|
||||
import { IAppConfig, IAppMeta, IContainerNodeItem, IDependency, II18nMap, UtilItem } from '.';
|
||||
import { I18nMap, UtilsMap, ContainerSchema, JSONObject } from '@ali/lowcode-types';
|
||||
|
||||
import { IDependency, INpmPackage } from './deps';
|
||||
|
||||
export interface IParseResult {
|
||||
containers: IContainerInfo[];
|
||||
globalUtils?: IUtilInfo;
|
||||
globalI18n?: II18nMap;
|
||||
globalI18n?: I18nMap;
|
||||
globalRouter?: IRouterInfo;
|
||||
project?: IProjectInfo;
|
||||
}
|
||||
|
||||
export type IContainerInfo = IContainerNodeItem &
|
||||
IWithDependency & {
|
||||
containerType: string;
|
||||
moduleName: string;
|
||||
};
|
||||
|
||||
export interface IWithDependency {
|
||||
deps?: IDependency[];
|
||||
}
|
||||
|
||||
export interface IContainerInfo extends ContainerSchema, IWithDependency {
|
||||
containerType: string;
|
||||
moduleName: string;
|
||||
}
|
||||
|
||||
export interface IUtilInfo extends IWithDependency {
|
||||
utils: UtilItem[];
|
||||
utils: UtilsMap;
|
||||
}
|
||||
|
||||
export interface IRouterInfo extends IWithDependency {
|
||||
@ -30,13 +31,15 @@ export interface IRouterInfo extends IWithDependency {
|
||||
}
|
||||
|
||||
export interface IProjectInfo {
|
||||
config: IAppConfig;
|
||||
meta: IAppMeta;
|
||||
css?: string;
|
||||
constants?: Record<string, string>;
|
||||
i18n?: II18nMap;
|
||||
containersDeps?: IDependency[];
|
||||
utilsDeps?: IDependency[];
|
||||
constants?: JSONObject;
|
||||
i18n?: I18nMap;
|
||||
packages: INpmPackage[];
|
||||
meta?: {
|
||||
name?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@ -1,17 +1,15 @@
|
||||
import {
|
||||
IResultDir,
|
||||
} from './index';
|
||||
import { ResultDir } from '@ali/lowcode-types';
|
||||
|
||||
export type PublisherFactory<T, U> = (configuration?: Partial<T>) => U;
|
||||
|
||||
export interface IPublisher<T, U> {
|
||||
publish: (options?: T) => Promise<IPublisherResponse<U>>;
|
||||
getProject: () => IResultDir | void;
|
||||
setProject: (project: IResultDir) => void;
|
||||
getProject: () => ResultDir | void;
|
||||
setProject: (project: ResultDir) => void;
|
||||
}
|
||||
|
||||
export interface IPublisherFactoryParams {
|
||||
project?: IResultDir;
|
||||
project?: ResultDir;
|
||||
}
|
||||
export interface IPublisherResponse<T> {
|
||||
success: boolean;
|
||||
|
||||
@ -1,88 +0,0 @@
|
||||
/**
|
||||
* 导出内容结构,文件夹
|
||||
*
|
||||
* @export
|
||||
* @interface IResultDir
|
||||
*/
|
||||
export interface IResultDir {
|
||||
/**
|
||||
* 文件夹名称,Root 名称默认为 .
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof IResultDir
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* 子目录
|
||||
*
|
||||
* @type {IResultDir[]}
|
||||
* @memberof IResultDir
|
||||
*/
|
||||
dirs: IResultDir[];
|
||||
/**
|
||||
* 文件夹内文件
|
||||
*
|
||||
* @type {IResultFile[]}
|
||||
* @memberof IResultDir
|
||||
*/
|
||||
files: IResultFile[];
|
||||
/**
|
||||
* 添加文件
|
||||
*
|
||||
* @param {IResultFile} file
|
||||
* @memberof IResultDir
|
||||
*/
|
||||
addFile(file: IResultFile): void;
|
||||
/**
|
||||
* 添加子目录
|
||||
*
|
||||
* @param {IResultDir} dir
|
||||
* @memberof IResultDir
|
||||
*/
|
||||
addDirectory(dir: IResultDir): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出内容,对文件的描述
|
||||
*
|
||||
* @export
|
||||
* @interface IResultFile
|
||||
*/
|
||||
export interface IResultFile {
|
||||
/**
|
||||
* 文件名
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof IResultFile
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* 文件类型扩展名,例如 .js .less
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof IResultFile
|
||||
*/
|
||||
ext: string;
|
||||
/**
|
||||
* 文件内容
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof IResultFile
|
||||
*/
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface IPackageJSON {
|
||||
name: string;
|
||||
version: string;
|
||||
description?: string;
|
||||
dependencies: Record<string, string>;
|
||||
devDependencies: Record<string, string>;
|
||||
scripts?: Record<string, string>;
|
||||
engines?: Record<string, string>;
|
||||
repository?: {
|
||||
type: string;
|
||||
url: string;
|
||||
};
|
||||
private?: boolean;
|
||||
}
|
||||
@ -1,69 +0,0 @@
|
||||
import { BlockSchema, ComponentSchema, NodeSchema, PageSchema, ProjectSchema } from '@ali/lowcode-types';
|
||||
|
||||
export * from '@ali/lowcode-types';
|
||||
|
||||
/**
|
||||
* 搭建基础协议 - 多语言描述
|
||||
*
|
||||
* @export
|
||||
* @interface II18nMap
|
||||
*/
|
||||
export interface II18nMap {
|
||||
[lang: string]: {
|
||||
[key: string]: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 搭建基础协议
|
||||
*
|
||||
* @export
|
||||
* @interface IBasicSchema
|
||||
*/
|
||||
export interface IBasicSchema extends ProjectSchema {}
|
||||
|
||||
export interface IProjectSchema extends IBasicSchema {
|
||||
// TODO: 下面的几个值真的需要吗?....
|
||||
constants: Record<string, string>; // 应用范围内的全局常量;
|
||||
css: string; // 应用范围内的全局样式;
|
||||
config: IAppConfig; // 当前应用配置信息
|
||||
meta: IAppMeta; // 当前应用元数据信息
|
||||
}
|
||||
|
||||
/**
|
||||
* 搭建基础协议 - 单个容器节点描述
|
||||
*
|
||||
* @export
|
||||
* @interface IContainerNodeItem
|
||||
* @extends {NodeSchema}
|
||||
*/
|
||||
export type IContainerNodeItem = PageSchema | BlockSchema | ComponentSchema;
|
||||
|
||||
// TODO...
|
||||
export interface IBasicMeta {
|
||||
title: string; // 标题描述
|
||||
}
|
||||
|
||||
// TODO...
|
||||
export interface IPageMeta extends IBasicMeta {
|
||||
router: string; // 页面路由
|
||||
spmb?: string; // spm
|
||||
}
|
||||
|
||||
export interface IAppConfig {
|
||||
sdkVersion?: string; // 渲染模块版本
|
||||
historyMode?: 'browser' | 'hash'; // 浏览器路由:browser 哈希路由:hash
|
||||
targetRootID?: string; // 渲染根节点 ID
|
||||
layout?: NodeSchema;
|
||||
theme?: object; // 主题配置,根据接入的主题模块不同
|
||||
}
|
||||
|
||||
export interface IAppMeta {
|
||||
name: string; // 应用中文名称
|
||||
git_group?: string; // 应用对应git分组名
|
||||
project_name?: string; // 应用对应git的project名称
|
||||
description?: string; // 应用描述
|
||||
spma?: string; // 应用spma A位信息
|
||||
creator?: string; // author
|
||||
[otherAttrName: string]: any;
|
||||
}
|
||||
@ -22,7 +22,10 @@ export function upperCaseFirst(inputValue: string): string {
|
||||
return changeCase.upperCaseFirst(inputValue);
|
||||
}
|
||||
|
||||
export function uniqueArray<T>(arr: T[]) {
|
||||
const uniqueItems = [...new Set<T>(arr)];
|
||||
export function uniqueArray<T>(arr: T[], by: (i: T) => string) {
|
||||
const map: Record<string, T> = {};
|
||||
arr.forEach((item) => (map[by(item)] = item));
|
||||
const uniqueKeys = [...new Set<string>(Object.keys(map))];
|
||||
const uniqueItems = uniqueKeys.map((key) => map[key]);
|
||||
return uniqueItems;
|
||||
}
|
||||
|
||||
@ -2,98 +2,100 @@ import {
|
||||
CompositeArray,
|
||||
CompositeValue,
|
||||
CompositeObject,
|
||||
JSExpression,
|
||||
JSFunction,
|
||||
JSONArray,
|
||||
JSONObject,
|
||||
isJSExpression,
|
||||
isJSFunction,
|
||||
isJSSlot,
|
||||
JSSlot,
|
||||
NodeSchema,
|
||||
NodeData,
|
||||
} from '../types';
|
||||
} from '@ali/lowcode-types';
|
||||
import { generateExpression, generateFunction } from './jsExpression';
|
||||
import { generateJsSlot } from './jsSlot';
|
||||
import { isValidIdentifier } from './validate';
|
||||
import { camelize } from './common';
|
||||
|
||||
export interface CustomHandlerSet {
|
||||
boolean?: (bool: boolean) => string;
|
||||
number?: (num: number) => string;
|
||||
string?: (str: string) => string;
|
||||
array?: (arr: JSONArray | CompositeArray) => string;
|
||||
object?: (obj: JSONObject | CompositeObject) => string;
|
||||
expression?: (jsExpr: JSExpression) => string;
|
||||
function?: (jsFunc: JSFunction) => string;
|
||||
slot?: (jsSlot: JSSlot) => string;
|
||||
node?: (node: NodeSchema) => string;
|
||||
loopDataExpr?: (loopDataExpr: string) => string;
|
||||
conditionExpr?: (conditionExpr: string) => string;
|
||||
tagName?: (tagName: string) => string;
|
||||
}
|
||||
import { CompositeValueGeneratorOptions, CompositeTypeContainerHandlerSet, CodeGeneratorError } from '../types';
|
||||
|
||||
function generateArray(value: CompositeArray, handlers: CustomHandlerSet): string {
|
||||
const body = value.map((v) => generateUnknownType(v, handlers)).join(',');
|
||||
const defaultContainerHandlers: CompositeTypeContainerHandlerSet = {
|
||||
default: (v) => v,
|
||||
string: (v) => `'${v}'`,
|
||||
};
|
||||
|
||||
function generateArray(value: CompositeArray, options: CompositeValueGeneratorOptions = {}): string {
|
||||
const body = value.map((v) => generateUnknownType(v, options)).join(',');
|
||||
return `[${body}]`;
|
||||
}
|
||||
|
||||
function generateObject(value: CompositeObject, handlers: CustomHandlerSet): string {
|
||||
function generateObject(value: CompositeObject, options: CompositeValueGeneratorOptions = {}): string {
|
||||
const body = Object.keys(value)
|
||||
.map((key) => {
|
||||
const v = generateUnknownType(value[key], handlers);
|
||||
return `${key}: ${v}`;
|
||||
let propName = key;
|
||||
|
||||
// TODO: 可以增加更多智能修复的方法
|
||||
const fixMethods: Array<(v: string) => string> = [camelize];
|
||||
// Try to fix propName
|
||||
while (!isValidIdentifier(propName)) {
|
||||
const fixMethod = fixMethods.pop();
|
||||
if (fixMethod) {
|
||||
try {
|
||||
propName = fixMethod(propName);
|
||||
} catch (error) {
|
||||
throw new CodeGeneratorError(error.message);
|
||||
}
|
||||
} else {
|
||||
throw new CodeGeneratorError(`Propname: ${key} is not a valid identifier.`);
|
||||
}
|
||||
}
|
||||
const v = generateUnknownType(value[key], options);
|
||||
return `${propName}: ${v}`;
|
||||
})
|
||||
.join(',\n');
|
||||
|
||||
return `{${body}}`;
|
||||
}
|
||||
|
||||
export function generateUnknownType(value: CompositeValue, handlers: CustomHandlerSet = {}): string {
|
||||
function generateUnknownType(value: CompositeValue, options: CompositeValueGeneratorOptions = {}): string {
|
||||
if (Array.isArray(value)) {
|
||||
if (handlers.array) {
|
||||
return handlers.array(value);
|
||||
if (options.handlers && options.handlers.array) {
|
||||
return options.handlers.array(value);
|
||||
}
|
||||
return generateArray(value, handlers);
|
||||
return generateArray(value, options);
|
||||
} else if (typeof value === 'object') {
|
||||
if (value === null) {
|
||||
return 'null';
|
||||
}
|
||||
|
||||
if (isJSExpression(value)) {
|
||||
if (handlers.expression) {
|
||||
return handlers.expression(value);
|
||||
if (options.handlers && options.handlers.expression) {
|
||||
return options.handlers.expression(value);
|
||||
}
|
||||
return generateExpression(value);
|
||||
}
|
||||
|
||||
if (isJSFunction(value)) {
|
||||
if (handlers.function) {
|
||||
return handlers.function(value);
|
||||
if (options.handlers && options.handlers.function) {
|
||||
return options.handlers.function(value);
|
||||
}
|
||||
return generateFunction(value);
|
||||
return generateFunction(value, { isArrow: true });
|
||||
}
|
||||
|
||||
if (isJSSlot(value)) {
|
||||
if (handlers.slot) {
|
||||
return handlers.slot(value);
|
||||
if (options.nodeGenerator) {
|
||||
return generateJsSlot(value, options.nodeGenerator);
|
||||
}
|
||||
|
||||
return generateSlot(value, handlers);
|
||||
throw new CodeGeneratorError("Can't find Node Generator");
|
||||
}
|
||||
|
||||
if (handlers.object) {
|
||||
return handlers.object(value);
|
||||
if (options.handlers && options.handlers.object) {
|
||||
return options.handlers.object(value);
|
||||
}
|
||||
|
||||
return generateObject(value, handlers);
|
||||
return generateObject(value as CompositeObject, options);
|
||||
} else if (typeof value === 'string') {
|
||||
if (handlers.string) {
|
||||
return handlers.string(value);
|
||||
if (options.handlers && options.handlers.string) {
|
||||
return options.handlers.string(value);
|
||||
}
|
||||
|
||||
return JSON.stringify(value);
|
||||
} else if (typeof value === 'number' && handlers.number) {
|
||||
return handlers.number(value);
|
||||
} else if (typeof value === 'boolean' && handlers.boolean) {
|
||||
return handlers.boolean(value);
|
||||
return `'${value}'`;
|
||||
} else if (typeof value === 'number' && options.handlers && options.handlers.number) {
|
||||
return options.handlers.number(value);
|
||||
} else if (typeof value === 'boolean' && options.handlers && options.handlers.boolean) {
|
||||
return options.handlers.boolean(value);
|
||||
} else if (typeof value === 'undefined') {
|
||||
return 'undefined';
|
||||
}
|
||||
@ -101,65 +103,16 @@ export function generateUnknownType(value: CompositeValue, handlers: CustomHandl
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
export function generateCompositeType(value: CompositeValue, handlers: CustomHandlerSet = {}): [boolean, string] {
|
||||
const result = generateUnknownType(value, handlers);
|
||||
export function generateCompositeType(value: CompositeValue, options: CompositeValueGeneratorOptions = {}): string {
|
||||
const result = generateUnknownType(value, options);
|
||||
const containerHandlers = {
|
||||
...defaultContainerHandlers,
|
||||
...(options.containerHandlers || {}),
|
||||
};
|
||||
|
||||
// TODO:什么场景下会返回这样的字符串??
|
||||
if (result.substr(0, 1) === "'" && result.substr(-1, 1) === "'") {
|
||||
return [true, result.substring(1, result.length - 1)];
|
||||
const isStringType = result.substr(0, 1) === "'" && result.substr(-1, 1) === "'";
|
||||
if (isStringType) {
|
||||
return (containerHandlers.string && containerHandlers.string(result.substring(1, result.length - 1))) || '';
|
||||
}
|
||||
|
||||
return [false, result];
|
||||
}
|
||||
|
||||
export function handleStringValueDefault([isString, result]: [boolean, string]) {
|
||||
if (isString) {
|
||||
return `'${result}'`;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function generateSlot({ title, params, value }: JSSlot, handlers: CustomHandlerSet): string {
|
||||
return [
|
||||
title && generateSingleLineComment(title),
|
||||
`(`,
|
||||
...(params || []),
|
||||
`) => (`,
|
||||
...(!value
|
||||
? ['null']
|
||||
: !Array.isArray(value)
|
||||
? [generateNodeData(value, handlers)]
|
||||
: value.map((node) => generateNodeData(node, handlers))),
|
||||
`)`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('');
|
||||
}
|
||||
|
||||
function generateNodeData(node: NodeData, handlers: CustomHandlerSet): string {
|
||||
if (typeof node === 'string') {
|
||||
if (handlers.string) {
|
||||
return handlers.string(node);
|
||||
}
|
||||
|
||||
return JSON.stringify(node);
|
||||
}
|
||||
|
||||
if (isJSExpression(node)) {
|
||||
if (handlers.expression) {
|
||||
return handlers.expression(node);
|
||||
}
|
||||
return generateExpression(node);
|
||||
}
|
||||
|
||||
if (!handlers.node) {
|
||||
throw new Error('cannot handle NodeSchema, handlers.node is missing');
|
||||
}
|
||||
|
||||
return handlers.node(node);
|
||||
}
|
||||
|
||||
function generateSingleLineComment(commentText: string): string {
|
||||
return '/* ' + commentText.split('\n').join(' ').replace(/\*\//g, '*-/') + '*/';
|
||||
return (containerHandlers.default && containerHandlers.default(result)) || '';
|
||||
}
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { CodeGeneratorError, isJSExpression, isJSFunction } from '../types';
|
||||
import { JSExpression, JSFunction, isJsExpression, isJsFunction } from '@ali/lowcode-types';
|
||||
import { CodeGeneratorError } from '../types';
|
||||
|
||||
export function transformFuncExpr2MethodMember(methodName: string, functionBody: string): string {
|
||||
const args = getFuncExprArguments(functionBody);
|
||||
@ -31,19 +32,52 @@ export function getFuncExprBody(functionBody: string) {
|
||||
return body;
|
||||
}
|
||||
|
||||
export function getArrowFunction(functionBody: string) {
|
||||
const args = getFuncExprArguments(functionBody);
|
||||
const body = getFuncExprBody(functionBody);
|
||||
|
||||
return `(${args}) => { ${body} }`;
|
||||
}
|
||||
|
||||
export function isJsCode(value: unknown): boolean {
|
||||
return isJsExpression(value) || isJsFunction(value);
|
||||
}
|
||||
|
||||
export function generateExpression(value: any): string {
|
||||
if (isJSExpression(value)) {
|
||||
return value.value || 'null';
|
||||
if (isJsExpression(value)) {
|
||||
return (value as JSExpression).value || 'null';
|
||||
}
|
||||
|
||||
throw new CodeGeneratorError('Not a JSExpression');
|
||||
}
|
||||
|
||||
// TODO: 这样真的可以吗?
|
||||
export function generateFunction(value: any): string {
|
||||
if (isJSFunction(value)) {
|
||||
return value.value || 'null';
|
||||
export function generateFunction(
|
||||
value: any,
|
||||
config: {
|
||||
name?: string;
|
||||
isMember?: boolean;
|
||||
isBlock?: boolean;
|
||||
isArrow?: boolean;
|
||||
} = {
|
||||
name: undefined,
|
||||
isMember: false,
|
||||
isBlock: false,
|
||||
isArrow: false,
|
||||
},
|
||||
) {
|
||||
if (isJsCode(value)) {
|
||||
const functionCfg = value as JSFunction;
|
||||
if (config.isMember) {
|
||||
return transformFuncExpr2MethodMember(config.name || '', functionCfg.value);
|
||||
}
|
||||
if (config.isBlock) {
|
||||
return getFuncExprBody(functionCfg.value);
|
||||
}
|
||||
if (config.isArrow) {
|
||||
return getArrowFunction(functionCfg.value);
|
||||
}
|
||||
return functionCfg.value;
|
||||
}
|
||||
|
||||
throw new CodeGeneratorError('Not a isJSFunction');
|
||||
throw new CodeGeneratorError('Not a JSFunction or JSExpression');
|
||||
}
|
||||
|
||||
35
packages/code-generator/src/utils/jsSlot.ts
Normal file
35
packages/code-generator/src/utils/jsSlot.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import { JSSlot, isJSSlot } from '@ali/lowcode-types';
|
||||
import { CodeGeneratorError, NodeGenerator } from '../types';
|
||||
|
||||
function generateSingleLineComment(commentText: string): string {
|
||||
return (
|
||||
'/* ' +
|
||||
commentText
|
||||
.split('\n')
|
||||
.join(' ')
|
||||
.replace(/\*\//g, '*-/') +
|
||||
'*/'
|
||||
);
|
||||
}
|
||||
|
||||
export function generateJsSlot(slot: any, generator: NodeGenerator): string {
|
||||
if (isJSSlot(slot)) {
|
||||
const { title, params, value } = slot as JSSlot;
|
||||
if (!value) {
|
||||
return 'null';
|
||||
}
|
||||
|
||||
return [
|
||||
title && generateSingleLineComment(title),
|
||||
`(`,
|
||||
...(params || []),
|
||||
`) => (`,
|
||||
...(!value ? ['null'] : !Array.isArray(value) ? [generator(value)] : value.map((node) => generator(node))),
|
||||
`)`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('');
|
||||
}
|
||||
|
||||
throw new CodeGeneratorError('Not a JSSlot');
|
||||
}
|
||||
@ -1,54 +1,134 @@
|
||||
import _ from 'lodash';
|
||||
import {
|
||||
PIECE_TYPE,
|
||||
JSSlot,
|
||||
JSExpression,
|
||||
NodeData,
|
||||
NodeSchema,
|
||||
PropsMap,
|
||||
isJSExpression,
|
||||
isJSSlot,
|
||||
isDOMText,
|
||||
} from '@ali/lowcode-types';
|
||||
|
||||
import {
|
||||
CodeGeneratorError,
|
||||
PIECE_TYPE,
|
||||
CodePiece,
|
||||
HandlerSet,
|
||||
NodeGenerator,
|
||||
ExtGeneratorPlugin,
|
||||
isJSExpression,
|
||||
isJSFunction,
|
||||
NodeData,
|
||||
CompositeValue,
|
||||
NodeSchema,
|
||||
INodeGeneratorContext,
|
||||
INodeGeneratorConfig,
|
||||
} from '../types';
|
||||
import { CustomHandlerSet, generateCompositeType } from './compositeType';
|
||||
|
||||
import { generateCompositeType } from './compositeType';
|
||||
import { generateExpression } from './jsExpression';
|
||||
|
||||
// tslint:disable-next-line: no-empty
|
||||
const noop = () => [];
|
||||
|
||||
export function handleChildren(children: NodeData | NodeData[], handlers: HandlerSet<string>): string[] {
|
||||
const handleChildrenDefaultOptions = {
|
||||
rerun: false,
|
||||
};
|
||||
|
||||
export function handleSubNodes<T>(
|
||||
children: unknown,
|
||||
handlers: HandlerSet<T>,
|
||||
options?: {
|
||||
rerun?: boolean;
|
||||
},
|
||||
): T[] {
|
||||
const opt = {
|
||||
...handleChildrenDefaultOptions,
|
||||
...(options || {}),
|
||||
};
|
||||
|
||||
if (Array.isArray(children)) {
|
||||
return children.map((child) => handleChildren(child, handlers)).reduce((p, c) => p.concat(c), []);
|
||||
} else if (typeof children === 'string') {
|
||||
const list: NodeData[] = children as NodeData[];
|
||||
return list.map((child) => handleSubNodes(child, handlers, opt)).reduce((p, c) => p.concat(c), []);
|
||||
} else if (isDOMText(children)) {
|
||||
const handler = handlers.string || handlers.common || noop;
|
||||
return handler(children);
|
||||
return handler(children as string);
|
||||
} else if (isJSExpression(children)) {
|
||||
const handler = handlers.expression || handlers.common || noop;
|
||||
return ['{', ...handler(children), '}'];
|
||||
} else if (isJSFunction(children)) {
|
||||
const handler = handlers.function || handlers.common || noop;
|
||||
return handler(children);
|
||||
return handler(children as JSExpression);
|
||||
} else {
|
||||
const handler = handlers.node || handlers.common || noop;
|
||||
return handler(children);
|
||||
const child = children as NodeSchema;
|
||||
let curRes = handler(child);
|
||||
if (opt.rerun && child.children) {
|
||||
const childRes = handleSubNodes(child.children, handlers, opt);
|
||||
curRes = curRes.concat(childRes || []);
|
||||
}
|
||||
if (child.props) {
|
||||
// FIXME: currently only support PropsMap
|
||||
const childProps = child.props as PropsMap;
|
||||
Object.keys(childProps)
|
||||
.filter((propName) => isJSSlot(childProps[propName]))
|
||||
.forEach((propName) => {
|
||||
const soltVals = (childProps[propName] as JSSlot).value;
|
||||
const childRes = handleSubNodes(soltVals, handlers, opt);
|
||||
curRes = curRes.concat(childRes || []);
|
||||
});
|
||||
}
|
||||
return curRes;
|
||||
}
|
||||
}
|
||||
|
||||
export function generateAttr(attrName: string, attrValue: CompositeValue, handlers: CustomHandlerSet): CodePiece[] {
|
||||
if (attrName === 'initValue' || attrName === 'labelCol') {
|
||||
export function handleChildren<T>(
|
||||
ctx: INodeGeneratorContext,
|
||||
children: unknown,
|
||||
handlers: HandlerSet<T>,
|
||||
options?: {
|
||||
rerun?: boolean;
|
||||
},
|
||||
): T[] {
|
||||
const opt = {
|
||||
...handleChildrenDefaultOptions,
|
||||
...(options || {}),
|
||||
};
|
||||
|
||||
if (Array.isArray(children)) {
|
||||
const list: NodeData[] = children as NodeData[];
|
||||
return list.map((child) => handleChildren(ctx, child, handlers, opt)).reduce((p, c) => p.concat(c), []);
|
||||
} else if (isDOMText(children)) {
|
||||
const handler = handlers.string || handlers.common || noop;
|
||||
return handler(children as string);
|
||||
} else if (isJSExpression(children)) {
|
||||
const handler = handlers.expression || handlers.common || noop;
|
||||
return handler(children as JSExpression);
|
||||
} else {
|
||||
const handler = handlers.node || handlers.common || noop;
|
||||
const child = children as NodeSchema;
|
||||
let curRes = handler(child);
|
||||
if (opt.rerun && child.children) {
|
||||
const childRes = handleChildren(ctx, child.children, handlers, opt);
|
||||
curRes = curRes.concat(childRes || []);
|
||||
}
|
||||
return curRes;
|
||||
}
|
||||
}
|
||||
|
||||
export function generateAttr(ctx: INodeGeneratorContext, attrName: string, attrValue: any): CodePiece[] {
|
||||
if (attrName === 'initValue') {
|
||||
return [];
|
||||
}
|
||||
const [isString, valueStr] = generateCompositeType(attrValue, handlers);
|
||||
const valueStr = generateCompositeType(attrValue, {
|
||||
containerHandlers: {
|
||||
default: (v) => `{${v}}`,
|
||||
string: (v) => `"${v}"`,
|
||||
},
|
||||
nodeGenerator: ctx.generator,
|
||||
});
|
||||
return [
|
||||
{
|
||||
value: `${attrName}=${isString ? `"${valueStr}"` : `{${valueStr}}`}`,
|
||||
value: `${attrName}=${valueStr}`,
|
||||
type: PIECE_TYPE.ATTR,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export function generateAttrs(nodeItem: NodeSchema, handlers: CustomHandlerSet): CodePiece[] {
|
||||
export function generateAttrs(ctx: INodeGeneratorContext, nodeItem: NodeSchema): CodePiece[] {
|
||||
const { props } = nodeItem;
|
||||
|
||||
let pieces: CodePiece[] = [];
|
||||
@ -56,12 +136,12 @@ export function generateAttrs(nodeItem: NodeSchema, handlers: CustomHandlerSet):
|
||||
if (props) {
|
||||
if (!Array.isArray(props)) {
|
||||
Object.keys(props).forEach((propName: string) => {
|
||||
pieces = pieces.concat(generateAttr(propName, props[propName], handlers));
|
||||
pieces = pieces.concat(generateAttr(ctx, propName, props[propName]));
|
||||
});
|
||||
} else {
|
||||
props.forEach((prop) => {
|
||||
if (prop.name && !prop.spread) {
|
||||
pieces = pieces.concat(generateAttr(prop.name, prop.value, handlers));
|
||||
pieces = pieces.concat(generateAttr(ctx, prop.name, prop.value));
|
||||
}
|
||||
|
||||
// TODO: 处理 spread 场景(<Xxx {...(something)}/>)
|
||||
@ -72,32 +152,47 @@ export function generateAttrs(nodeItem: NodeSchema, handlers: CustomHandlerSet):
|
||||
return pieces;
|
||||
}
|
||||
|
||||
export function mapNodeName(src: string): string {
|
||||
if (src === 'Div') {
|
||||
return 'div';
|
||||
function mapNodeName(src: string, mapping: Record<string, string>): string {
|
||||
if (mapping[src]) {
|
||||
return mapping[src];
|
||||
}
|
||||
|
||||
return src;
|
||||
}
|
||||
|
||||
export function generateBasicNode(nodeItem: NodeSchema): CodePiece[] {
|
||||
export function generateBasicNode(
|
||||
ctx: INodeGeneratorContext,
|
||||
nodeItem: NodeSchema,
|
||||
mapping: Record<string, string>,
|
||||
): CodePiece[] {
|
||||
const pieces: CodePiece[] = [];
|
||||
pieces.push({
|
||||
value: mapNodeName(nodeItem.componentName),
|
||||
value: mapNodeName(nodeItem.componentName, mapping),
|
||||
type: PIECE_TYPE.TAG,
|
||||
});
|
||||
|
||||
return pieces;
|
||||
}
|
||||
|
||||
export function generateReactCtrlLine(nodeItem: NodeSchema, handlers: CustomHandlerSet): CodePiece[] {
|
||||
// TODO: 生成文档
|
||||
// 为包裹的代码片段生成子上下文,集成父级上下文,并传入子级上下文新增内容。(如果存在多级上下文怎么处理?)
|
||||
// 创建新的上下文,并从作用域中取对应同名变量塞到作用域里面?
|
||||
// export function createSubContext() {}
|
||||
|
||||
/**
|
||||
* JSX 生成逻辑插件。在 React 代码模式下生成 loop 与 condition 相关的逻辑代码
|
||||
*
|
||||
* @export
|
||||
* @param {NodeSchema} nodeItem 当前 UI 节点
|
||||
* @returns {CodePiece[]} 实现功能的相关代码片段
|
||||
*/
|
||||
export function generateReactCtrlLine(ctx: INodeGeneratorContext, nodeItem: NodeSchema): CodePiece[] {
|
||||
const pieces: CodePiece[] = [];
|
||||
|
||||
if (nodeItem.loop) {
|
||||
const loopItemName = nodeItem.loopArgs?.[0] || 'item';
|
||||
const loopIndexName = nodeItem.loopArgs?.[1] || 'index';
|
||||
|
||||
// TODO: 静态的值可以抽离出来?
|
||||
const loopDataExpr = (handlers.loopDataExpr || _.identity)(
|
||||
isJSExpression(nodeItem.loop) ? `(${nodeItem.loop.value})` : `(${JSON.stringify(nodeItem.loop)})`,
|
||||
);
|
||||
@ -114,8 +209,11 @@ export function generateReactCtrlLine(nodeItem: NodeSchema, handlers: CustomHand
|
||||
}
|
||||
|
||||
if (nodeItem.condition) {
|
||||
const [isString, value] = generateCompositeType(nodeItem.condition, handlers);
|
||||
const conditionExpr = (handlers.conditionExpr || _.identity)(isString ? `'${value}'` : value);
|
||||
const value = generateCompositeType(nodeItem.condition, {
|
||||
nodeGenerator: ctx.generator,
|
||||
});
|
||||
|
||||
const conditionExpr = (handlers.conditionExpr || _.identity)(value);
|
||||
|
||||
pieces.unshift({
|
||||
value: `(${conditionExpr}) && (`,
|
||||
@ -183,21 +281,27 @@ export function linkPieces(pieces: CodePiece[], handlers: CustomHandlerSet): str
|
||||
export function createNodeGenerator(
|
||||
handlers: HandlerSet<string>,
|
||||
plugins: ExtGeneratorPlugin[],
|
||||
customHandlers: CustomHandlerSet = {},
|
||||
) {
|
||||
cfg?: INodeGeneratorConfig,
|
||||
): NodeGenerator {
|
||||
let nodeTypeMapping: Record<string, string> = {};
|
||||
if (cfg && cfg.nodeTypeMapping) {
|
||||
nodeTypeMapping = cfg.nodeTypeMapping;
|
||||
}
|
||||
|
||||
const generateNode = (nodeItem: NodeSchema): string => {
|
||||
let pieces: CodePiece[] = [];
|
||||
const ctx: INodeGeneratorContext = {
|
||||
generator: generateNode,
|
||||
};
|
||||
|
||||
plugins.forEach((p) => {
|
||||
pieces = pieces.concat(p(nodeItem, customHandlers));
|
||||
pieces = pieces.concat(p(ctx, nodeItem));
|
||||
});
|
||||
|
||||
pieces = pieces.concat(generateBasicNode(nodeItem));
|
||||
pieces = pieces.concat(generateAttrs(nodeItem, customHandlers));
|
||||
|
||||
if (nodeItem.children && !_.isEmpty(nodeItem.children)) {
|
||||
pieces = pieces.concat(generateBasicNode(ctx, nodeItem, nodeTypeMapping));
|
||||
pieces = pieces.concat(generateAttrs(ctx, nodeItem));
|
||||
if (nodeItem.children && (nodeItem.children as unknown[]).length > 0) {
|
||||
pieces = pieces.concat(
|
||||
handleChildren(nodeItem.children, handlers).map((l) => ({
|
||||
handleChildren<string>(ctx, nodeItem.children, handlers).map((l) => ({
|
||||
type: PIECE_TYPE.CHILDREN,
|
||||
value: l,
|
||||
})),
|
||||
@ -207,21 +311,20 @@ export function createNodeGenerator(
|
||||
return linkPieces(pieces, customHandlers);
|
||||
};
|
||||
|
||||
handlers.node = (node: NodeSchema) => [generateNode(node)];
|
||||
|
||||
customHandlers.node = customHandlers.node || generateNode;
|
||||
handlers.node = (input: NodeSchema) => [generateNode(input)];
|
||||
|
||||
return generateNode;
|
||||
}
|
||||
|
||||
export const generateString = (input: string) => [input];
|
||||
|
||||
export function createReactNodeGenerator() {
|
||||
export function createReactNodeGenerator(cfg?: INodeGeneratorConfig): NodeGenerator {
|
||||
return createNodeGenerator(
|
||||
{
|
||||
string: generateString,
|
||||
expression: (input) => [generateExpression(input)],
|
||||
},
|
||||
[generateReactCtrlLine],
|
||||
cfg,
|
||||
);
|
||||
}
|
||||
|
||||
35
packages/code-generator/src/utils/resultHelper.ts
Normal file
35
packages/code-generator/src/utils/resultHelper.ts
Normal file
@ -0,0 +1,35 @@
|
||||
import { ResultFile, ResultDir } from '@ali/lowcode-types';
|
||||
|
||||
import { CodeGeneratorError } from '../types/error';
|
||||
|
||||
export function createResultFile(name: string, ext = 'jsx', content = ''): ResultFile {
|
||||
return {
|
||||
name,
|
||||
ext,
|
||||
content,
|
||||
};
|
||||
}
|
||||
|
||||
export function createResultDir(name: string): ResultDir {
|
||||
return {
|
||||
name,
|
||||
dirs: [],
|
||||
files: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function addDirectory(target: ResultDir, dir: ResultDir): void {
|
||||
if (target.dirs.findIndex((d) => d.name === dir.name) < 0) {
|
||||
target.dirs.push(dir);
|
||||
} else {
|
||||
throw new CodeGeneratorError(`Adding same directory to one directory: ${dir.name} -> ${target.name}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function addFile(target: ResultDir, file: ResultFile): void {
|
||||
if (target.files.findIndex((f) => f.name === file.name && f.ext === file.ext) < 0) {
|
||||
target.files.push(file);
|
||||
} else {
|
||||
throw new CodeGeneratorError(`Adding same file to one directory: ${file.name} -> ${target.name}`);
|
||||
}
|
||||
}
|
||||
@ -1,25 +1,25 @@
|
||||
import { IResultFile, IResultDir } from '../types';
|
||||
import ResultDir from '../model/ResultDir';
|
||||
import { ResultDir, ResultFile } from '@ali/lowcode-types';
|
||||
import { createResultDir, addDirectory, addFile } from '../utils/resultHelper';
|
||||
|
||||
type FuncFileGenerator = () => [string[], IResultFile];
|
||||
type FuncFileGenerator = () => [string[], ResultFile];
|
||||
|
||||
export function insertFile(root: IResultDir, path: string[], file: IResultFile) {
|
||||
let current: IResultDir = root;
|
||||
path.forEach(pathNode => {
|
||||
const dir = current.dirs.find(d => d.name === pathNode);
|
||||
export function insertFile(root: ResultDir, path: string[], file: ResultFile) {
|
||||
let current: ResultDir = root;
|
||||
path.forEach((pathNode) => {
|
||||
const dir = current.dirs.find((d) => d.name === pathNode);
|
||||
if (dir) {
|
||||
current = dir;
|
||||
} else {
|
||||
const newDir = new ResultDir(pathNode);
|
||||
current.addDirectory(newDir);
|
||||
const newDir = createResultDir(pathNode);
|
||||
addDirectory(current, newDir);
|
||||
current = newDir;
|
||||
}
|
||||
});
|
||||
|
||||
current.addFile(file);
|
||||
addFile(current, file);
|
||||
}
|
||||
|
||||
export function runFileGenerator(root: IResultDir, fun: FuncFileGenerator) {
|
||||
export function runFileGenerator(root: ResultDir, fun: FuncFileGenerator) {
|
||||
const [path, file] = fun();
|
||||
insertFile(root, path, file);
|
||||
}
|
||||
|
||||
3
packages/code-generator/src/utils/validate.ts
Normal file
3
packages/code-generator/src/utils/validate.ts
Normal file
@ -0,0 +1,3 @@
|
||||
export const isValidIdentifier = (name: string) => {
|
||||
return /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/.test(name);
|
||||
};
|
||||
14
packages/types/src/code-intermediate.ts
Normal file
14
packages/types/src/code-intermediate.ts
Normal file
@ -0,0 +1,14 @@
|
||||
export interface PackageJSON {
|
||||
name: string;
|
||||
version: string;
|
||||
description?: string;
|
||||
dependencies: Record<string, string>;
|
||||
devDependencies: Record<string, string>;
|
||||
scripts?: Record<string, string>;
|
||||
engines?: Record<string, string>;
|
||||
repository?: {
|
||||
type: string;
|
||||
url: string;
|
||||
};
|
||||
private?: boolean;
|
||||
}
|
||||
59
packages/types/src/code-result.ts
Normal file
59
packages/types/src/code-result.ts
Normal file
@ -0,0 +1,59 @@
|
||||
/**
|
||||
* 导出内容结构,文件夹
|
||||
*
|
||||
* @export
|
||||
* @interface ResultDir
|
||||
*/
|
||||
export interface ResultDir {
|
||||
/**
|
||||
* 文件夹名称,Root 名称默认为 .
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof ResultDir
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* 子目录
|
||||
*
|
||||
* @type {ResultDir[]}
|
||||
* @memberof ResultDir
|
||||
*/
|
||||
dirs: ResultDir[];
|
||||
/**
|
||||
* 文件夹内文件
|
||||
*
|
||||
* @type {ResultFile[]}
|
||||
* @memberof ResultDir
|
||||
*/
|
||||
files: ResultFile[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出内容,对文件的描述
|
||||
*
|
||||
* @export
|
||||
* @interface ResultFile
|
||||
*/
|
||||
export interface ResultFile {
|
||||
/**
|
||||
* 文件名
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof ResultFile
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* 文件类型扩展名,例如 .js .less
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof ResultFile
|
||||
*/
|
||||
ext: string;
|
||||
/**
|
||||
* 文件内容
|
||||
*
|
||||
* @type {string}
|
||||
* @memberof ResultFile
|
||||
*/
|
||||
content: string;
|
||||
}
|
||||
@ -51,7 +51,7 @@ export interface FieldExtraProps {
|
||||
mode?: 'plaintext' | 'paragraph' | 'article';
|
||||
// 从 contentEditable 获取内容并设置到属性
|
||||
onSaveContent?: (content: string, prop: any) => any;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export interface FieldConfig extends FieldExtraProps {
|
||||
|
||||
@ -15,3 +15,5 @@ export * from './setter-config';
|
||||
export * from './setting-target';
|
||||
export * from './node';
|
||||
export * from './transform-stage';
|
||||
export * from './code-intermediate';
|
||||
export * from './code-result';
|
||||
|
||||
@ -1,18 +1,20 @@
|
||||
import { ComponentsMap } from './npm';
|
||||
import { CompositeValue, JSExpression, CompositeObject, JSONObject } from './value-type';
|
||||
import { CompositeValue, JSExpression, JSFunction, CompositeObject, JSONObject } from './value-type';
|
||||
import { DataSource } from './data-source';
|
||||
import { I18nMap } from './i18n';
|
||||
import { UtilsMap } from './utils';
|
||||
|
||||
// 搭建基础协议 - 单个组件树节点描述
|
||||
// 转换成一个 .jsx 文件内 React Class 类 render 函数返回的 jsx 代码
|
||||
export interface NodeSchema {
|
||||
id?: string;
|
||||
componentName: string;
|
||||
props?: PropsMap | PropsList;
|
||||
componentName: string; // 组件名称 必填、首字母大写
|
||||
props?: PropsMap | PropsList; // 组件属性对象
|
||||
leadingComponents?: string;
|
||||
condition?: CompositeValue;
|
||||
loop?: CompositeValue;
|
||||
loopArgs?: [string, string];
|
||||
children?: NodeData | NodeData[];
|
||||
condition?: CompositeValue; // 渲染条件
|
||||
loop?: CompositeValue; // 循环数据
|
||||
loopArgs?: [string, string]; // 循环迭代对象、索引名称 ["item", "index"]
|
||||
children?: NodeData | NodeData[]; // 子节点
|
||||
|
||||
// ------- future support -----
|
||||
conditionGroup?: string;
|
||||
@ -30,6 +32,7 @@ export type PropsList = Array<{
|
||||
}>;
|
||||
|
||||
export type NodeData = NodeSchema | JSExpression | DOMText;
|
||||
export type NodeDataType = NodeData | NodeData[];
|
||||
|
||||
export function isDOMText(data: any): data is DOMText {
|
||||
return typeof data === 'string';
|
||||
@ -45,10 +48,10 @@ export interface ContainerSchema extends NodeSchema {
|
||||
[key: string]: CompositeValue;
|
||||
};
|
||||
methods?: {
|
||||
[key: string]: JSExpression;
|
||||
[key: string]: JSExpression | JSFunction;
|
||||
};
|
||||
lifeCycles?: {
|
||||
[key: string]: JSExpression;
|
||||
[key: string]: JSExpression | JSFunction;
|
||||
};
|
||||
css?: string;
|
||||
dataSource?: DataSource;
|
||||
@ -82,7 +85,6 @@ export interface BlockSchema extends ContainerSchema {
|
||||
export type RootSchema = PageSchema | ComponentSchema | BlockSchema;
|
||||
|
||||
export interface SlotSchema extends NodeSchema {
|
||||
name?: string;
|
||||
componentName: 'Slot';
|
||||
params?: string[];
|
||||
}
|
||||
|
||||
@ -1,21 +1,17 @@
|
||||
import { NpmInfo } from './npm';
|
||||
import { JSExpression, JSFunction } from './value-type';
|
||||
|
||||
export type UtilItem =
|
||||
| {
|
||||
name: string;
|
||||
type: 'npm';
|
||||
content: NpmInfo;
|
||||
}
|
||||
| {
|
||||
name: string;
|
||||
type: 'tnpm';
|
||||
content: NpmInfo;
|
||||
}
|
||||
| {
|
||||
name: string;
|
||||
type: 'function';
|
||||
content: JSFunction | JSExpression;
|
||||
};
|
||||
export type InternalUtils = {
|
||||
name: string;
|
||||
type: 'function';
|
||||
content: JSFunction | JSExpression;
|
||||
};
|
||||
|
||||
export type ExternalUtils = {
|
||||
name: string;
|
||||
type: 'npm' | 'tnpm';
|
||||
content: NpmInfo;
|
||||
};
|
||||
|
||||
export type UtilItem = InternalUtils | ExternalUtils;
|
||||
export type UtilsMap = UtilItem[];
|
||||
|
||||
@ -11,10 +11,15 @@ export interface JSExpression {
|
||||
* 模拟值
|
||||
*/
|
||||
mock?: any;
|
||||
}
|
||||
|
||||
// 函数
|
||||
export interface JSFunction {
|
||||
type: 'JSFunction';
|
||||
/**
|
||||
* 额外扩展属性,如 extType、events
|
||||
* 表达式字符串
|
||||
*/
|
||||
[key: string]: any;
|
||||
value: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -34,7 +39,6 @@ export interface JSFunction {
|
||||
}
|
||||
|
||||
export interface JSSlot {
|
||||
name?: string;
|
||||
type: 'JSSlot';
|
||||
title?: string;
|
||||
// 函数的入参
|
||||
@ -61,7 +65,6 @@ export interface CompositeObject {
|
||||
[key: string]: CompositeValue;
|
||||
}
|
||||
|
||||
|
||||
export function isJSExpression(data: any): data is JSExpression {
|
||||
return data && data.type === 'JSExpression';
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user