refactor: code style

Link: https://code.aone.alibaba-inc.com/ali-lowcode/ali-lowcode-engine/codereview/3681622

* chore: remove unnecessary code

* refactor: react-render using TypeScript

* chore: build-script

* refactor: editor-skeleton

* refactor: designer

* refactor: material-parser

* refactor: editor-setters

* refactor: js to ts for rax-provider 

Link: https://code.aone.alibaba-inc.com/ali-lowcode/ali-lowcode-engine/codereview/3678180

* refactor: rax-provider

* feat: add build command

* chore: compilerOptions for rax-provider

* refactor: JS to TS for Rax Renderer 

Link: https://code.aone.alibaba-inc.com/ali-lowcode/ali-lowcode-engine/codereview/3678935

* refactor: rax-renderer

* Merge remote-tracking branch 'origin/refactor/js-to-ts' into refactor/js2ts-rax-renderer

* Merge remote-tracking branch 'origin/refactor/js-to-ts' into refactor/js2ts-rax-renderer

* refactor: ts-nocheck

* chore: ts compile error

* fix: ts rootDir

* fix: compile error

* chore: using same tsconfig for rax component

* refactor: ts compile rax-renderer && rax-provider

* Merge remote-tracking branch 'origin/release/1.0.0' into refactor/js-to-ts

# Conflicts:
#	packages/rax-render/src/utils/appHelper.js
#	packages/rax-render/src/utils/appHelper.ts
#	packages/utils/src/appHelper.ts

* refactor: no JS file

* refactor: remove lint

* feat: add xima

* feat: add eslint ignore

* style: fix by lint

* feat: lint command

* fix: using the same eslint config

* style: eslint settings

* Merge remote-tracking branch 'origin/release/1.0.0' into refactor/code-style

# Conflicts:
#	packages/plugin-event-bind-dialog/src/index.tsx
#	packages/plugin-source-editor/src/index.tsx
#	packages/runtime/src/core/container.ts
#	packages/runtime/src/core/provider.ts

* Merge remote-tracking branch 'origin/release/1.0.0' into refactor/code-style

# Conflicts:
#	packages/designer/src/document/document-model.ts
#	packages/designer/src/document/node/node-children.ts
#	packages/designer/src/document/node/props/prop.ts
#	packages/plugin-source-editor/src/index.tsx

* fix: 修改dataSource items -> list

* Merge remote-tracking branch 'origin/relase/1.0.0' into refactor/code-style

# Conflicts:
#	packages/react-renderer/package.json

* refactor: component-panel 

plugin-component-pane 代码规范化

Link: https://code.aone.alibaba-inc.com/ali-lowcode/ali-lowcode-engine/codereview/3703771

* feat: support bizcomps

* refactor: component-panel

* style: eslint

* Merge branch 'refactor/code-style' into fix/ducheng-source-style

* style: code style

* Merge branch 'fix/ducheng-source-style' into 'refactor/code-style'
Code review title: Fix/ducheng source style
Code review Link: https://code.aone.alibaba-inc.com/ali-lowcode/ali-lowcode-engine/codereview/3705972

* style: for demo

* style: for demo-server

* style: for plugin-event-bind-dialog

* style: for plugin-sample-preview

* style: for plugin-undo-redo

* style: plugin-variable-bind-dialog

* style: types

* style: for utils

* Merge remote-tracking branch 'origin/release/1.0.0' into refactor/code-style

# Conflicts:
#	packages/editor-setters/src/expression-setter/locale/snippets.ts
#	packages/editor-setters/src/json-setter/locale/snippets.ts
#	packages/editor-setters/src/locale/snippets.ts
#	packages/plugin-components-pane/package.json
#	packages/rax-render/src/hoc/compWrapper.tsx
#	packages/rax-render/src/utils/index.ts
#	packages/react-renderer/src/context/appContext.ts

* style: editor-preset-general 

editor-preset-general 代码规范化

Link: https://code.aone.alibaba-inc.com/ali-lowcode/ali-lowcode-engine/codereview/3707974

* style: editor-preset-general

* fix: should set field

* fix: should set field - demo-server

* refactor(style): fix code style for designer

refactor(style): fix code style for editor-core

refactor(style): fix code style for editor-skeleton

refactor(style): fix code style for react-simulator-renderer

refactor(style): fix code style for rax-simulator-renderer

* Merge branch 'refactor/lihao-code-style' into 'refactor/code-style'
Code review title: refactor(style): fix code style for designer
Code review description: refactor(style): fix code style for editor-core

refactor(style): fix code style for editor-skeleton

refactor(style): fix code style for react-simulator-renderer

refactor(style): fix code style for rax-simulator-renderer
Code review Link: https://code.aone.alibaba-inc.com/ali-lowcode/ali-lowcode-engine/codereview/3709472

* style: react/no-multi-comp set to 0 for designer

* style: ignore editor-prset-vision

* style: fix for plugin-outline-pane

* style: fix for rax-provider

* style: react-provider

* style: runtime

* style: rax-render

* Merge remote-tracking branch 'origin/release/1.0.0' into refactor/code-style

# Conflicts:
#	packages/editor-setters/src/expression-setter/index.tsx
#	packages/plugin-source-editor/src/index.tsx
#	packages/plugin-source-editor/src/transform.ts

* refactor: material parser code style 

1. 修复eslint问题
2. instanceOf => any
3. 修复node类型解析失败问题

Link: https://code.aone.alibaba-inc.com/ali-lowcode/ali-lowcode-engine/codereview/3716330

* refactor: material parser code style

* refactor: code-generator code style 

1. rax 出码合并
2. code style 修复

注:合并的代码中带了 datasource 的

Link: https://code.aone.alibaba-inc.com/ali-lowcode/ali-lowcode-engine/codereview/3717159

* Merge branch 'feat/rax-code-generator' of gitlab.alibaba-inc.com:ali-lowcode/ali-lowcode-engine into feat/rax-code-generator

# Conflicts:
#	packages/code-generator/src/generator/ProjectBuilder.ts
#	packages/code-generator/src/parser/SchemaParser.ts
#	packages/code-generator/src/plugins/component/rax/jsx.ts
#	packages/code-generator/src/plugins/project/constants.ts
#	packages/code-generator/src/plugins/project/framework/rax/plugins/packageJSON.ts
#	packages/code-generator/src/plugins/project/i18n.ts
#	packages/code-generator/src/publisher/disk/index.ts
#	packages/code-generator/src/publisher/disk/utils.ts
#	packages/code-generator/src/types/core.ts
#	packages/code-generator/src/types/schema.ts
#	packages/code-generator/src/utils/compositeType.ts
#	packages/code-generator/src/utils/nodeToJSX.ts

* refactor: code-generator

* Merge remote-tracking branch 'origin/refactor/code-style' into refactor/code-style-code-generator

# Conflicts:
#	.vscode/launch.json

* Revert "refactor: code-generator code style "

This reverts commit ebc78e8788f83e8fda0e146758af43b878125c10.

* chore: eslintrc && eslintignore

* style: for plugin-source-editor

* style: fix by eslint --fix

* style: scripts/

* style: datasource-engine

* feat: pre-commit

* Merge branch 'refactor/code-style' of gitlab.alibaba-inc.com:ali-lowcode/ali-lowcode-engine into refactor/code-style

# Conflicts:
#	.eslintignore
#	packages/code-generator/src/parser/SchemaParser.ts
#	packages/code-generator/src/plugins/component/rax/containerInitState.ts
#	packages/code-generator/src/plugins/component/rax/containerInjectDataSourceEngine.ts
#	packages/code-generator/src/plugins/component/rax/containerLifeCycle.ts
#	packages/code-generator/src/plugins/project/framework/rax/plugins/buildConfig.ts
#	packages/code-generator/src/utils/OrderedSet.ts
#	packages/code-generator/src/utils/ScopeBindings.ts
#	packages/code-generator/src/utils/expressionParser.ts
#	packages/code-generator/src/utils/schema.ts
#	packages/datasource-engine/src/core/DataSourceEngine.ts
#	packages/datasource-engine/src/core/RuntimeDataSource.ts
#	packages/datasource-engine/src/types/IRuntimeContext.ts
#	packages/datasource-engine/src/types/index.ts

* refactor: code style code-generator 

对 code style 分支上次合并的  code-generator 修改做了 revert

重新在 code style 分支基础上对代码样式做了修复

rax 合并分支会另行 fix 后向 release 分支提 MR

Link: https://code.aone.alibaba-inc.com/ali-lowcode/ali-lowcode-engine/codereview/3719702

* refactor: code style fix

* style: for code-generator

* Merge remote-tracking branch 'origin/release/1.0.0' into refactor/code-style

# Conflicts:
#	packages/editor-skeleton/src/transducers/addon-combine.ts
#	packages/plugin-components-pane/package.json
#	packages/plugin-components-pane/src/components/base/index.tsx
#	packages/plugin-components-pane/src/components/component-list/index.tsx
#	packages/plugin-components-pane/src/i18n/index.ts
#	packages/plugin-components-pane/src/i18n/strings/index.ts
#	packages/plugin-components-pane/src/index.tsx
#	packages/plugin-event-bind-dialog/src/index.tsx
#	packages/plugin-source-editor/src/index.tsx
#	packages/plugin-source-editor/src/transform.ts

* style: auto fix
This commit is contained in:
wuji.xwt 2020-09-15 19:06:35 +08:00
parent e2da4faf7e
commit 5d259055fb
807 changed files with 48051 additions and 59248 deletions

View File

@ -1,9 +1,9 @@
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

View File

@ -1,7 +1,17 @@
.idea/
.vscode/
build/
# 忽略目录
node_modules
test-cases
test
output
build
dist
demo
es
lib
.*
~*
node_modules
# 忽略文件
**/*.min.js
**/*-min.js
**/*.bundle.js

View File

@ -1,3 +0,0 @@
{
"extends": "./node_modules/@ali/lowcode-config/.eslintrc"
}

3
.eslintrc.js Normal file
View File

@ -0,0 +1,3 @@
module.exports = {
extends: 'eslint-config-ali/typescript/react',
};

View File

@ -1,4 +0,0 @@
**/test/**/*.ts
**/test/**/*.js
**/template/**/*.template
**/template/**/*.tpl

View File

@ -1,8 +0,0 @@
{
"trailingComma": "all",
"tabWidth": 2,
"semi": true,
"singleQuote": true,
"printWidth": 120,
"arrowParens": "always"
}

7
.prettierrc.js Normal file
View File

@ -0,0 +1,7 @@
module.exports = {
printWidth: 100,
tabWidth: 2,
semi: true,
singleQuote: true,
trailingComma: 'all',
};

9
.stylelintignore Normal file
View File

@ -0,0 +1,9 @@
# 忽略目录
node_modules/
build/
dist/
# 忽略文件
**/*.min.css
**/*-min.css
**/*.bundle.css

3
.stylelintrc.js Normal file
View File

@ -0,0 +1,3 @@
module.exports = {
extends: 'stylelint-config-ali',
};

2
.vscode/launch.json vendored
View File

@ -9,7 +9,7 @@
"type": "node",
"request": "launch",
"runtimeExecutable": "${workspaceFolder}/packages/material-parser/node_modules/.bin/ava",
"runtimeArgs": ["debug", "--break", "${file}"]
"runtimeArgs": ["debug", "--break", "${workspaceFolder}/packages/material-parser/test/antd.ts"]
}
]
}

View File

@ -1,22 +1,20 @@
## Ali Lowcode Engine阿里低代码引擎
[Lerna](https://github.com/lerna/lerna) + [TS](https://www.typescriptlang.org/)
## 开发
#### 创建新包
#### 创建新包
- `./scripts/create.sh <package-name>`
#### 跑起来:
#### 运行示例
- `npm run setup`
- `npm start`
#### 开发提交
#### 开发提交
- `git add <your-files>`
- `npm run commit` # 在根目录
- `git commit -a "feat: xxx"`
## 发布
@ -24,7 +22,6 @@
## 注意
- Commit 动作尽量使用 `npm run commit`,其内部调用了 `git cz`,方便按语义化版本自动递增,以及自动生成 `CHANGELOG.md`
- `packages` 工程里一些开发时公共依赖(比如:`typescript``ava` 等)会放到工程顶层
- 工程里的 `.md``test/` 等文件修改不会产生新的发布
- 当工程里存在多个 ts 文件的目录时,最终产生的文件会按文件夹形式放到 `lib`

3
commitlint.config.js Normal file
View File

@ -0,0 +1,3 @@
module.exports = {
extends: ['ali'],
};

View File

@ -12,40 +12,34 @@
"scripts": {
"build": "./scripts/build.sh",
"clean": "rm -rf ./packages/*/lib ./packages/*/es ./packages/*/dist ./packages/*/build",
"commit": "git-cz",
"lint": "eslint --ext .ts,.tsx,.js,.jsx ./ --quiet",
"lint:fix": "eslint --ext .ts,.tsx,.js,.jsx ./ --quiet --fix",
"pub": "lerna publish --force-publish --cd-version prepatch",
"setup": "./scripts/setup.sh",
"start": "./scripts/start.sh",
"start:server": "./scripts/start-server.sh",
"test": "lerna run test --stream",
"test:snapshot": "lerna run test:snapshot"
"test:snapshot": "lerna run test:snapshot",
"xima:fix": "xima fix",
"xima:scan": "xima scan"
},
"lint-staged": {
"*.{tsx,ts}": [
"eslint --quiet",
"git add"
]
},
"config": {
"commitizen": {
"path": "node_modules/cz-conventional-changelog"
"husky": {
"hooks": {
"commit-msg": "xima exec commitlint -E HUSKY_GIT_PARAMS",
"pre-commit": "xima exec lint-staged"
}
},
"lint-staged": {
"**/*.{js,jsx,ts,tsx}": "xima exec eslint",
"**/*.{css,scss,less}": "xima exec stylelint"
},
"devDependencies": {
"@ali/lowcode-config": "^2.0.5",
"ava": "^1.0.1",
"babel-eslint": "^10.0.3",
"commitizen": "^3.0.5",
"cz-conventional-changelog": "^2.1.0",
"eslint": "^6.5.1",
"git-cz": "^4.3.1",
"husky": "^4.2.3",
"lerna": "^2.11.0",
"lint-staged": "^8.1.0",
"prettier": "^1.15.3",
"ts-node": "^7.0.1",
"tslib": "^1.9.3",
"typescript": "^3.2.2"
"typescript": "^3.2.2",
"xima": "^0.2.15"
},
"engines": {
"node": ">=10.0.0"
@ -54,4 +48,4 @@
"mode": "yarn",
"lockfile": "enable"
}
}
}

View File

@ -59,7 +59,7 @@ function main() {
builder.generateProject(schemaJson).then((result) => {
displayResultInConsole(result);
writeResultToDisk(result, 'output/lowcodeDemo').then((response) => console.log('Write to disk: ', JSON.stringify(response)),);
writeResultToDisk(result, 'output/lowcodeDemo').then((response) => console.log('Write to disk: ', JSON.stringify(response)));
return result;
});
}
@ -160,7 +160,7 @@ function exportProject() {
builder.generateProject(schemaJson).then((result) => {
displayResultInConsole(result);
writeResultToDisk(result, 'output/lowcodeDemo').then((response) => console.log('Write to disk: ', JSON.stringify(response)),);
writeResultToDisk(result, 'output/lowcodeDemo').then((response) => console.log('Write to disk: ', JSON.stringify(response)));
return result;
});
}

View File

@ -1,4 +1,4 @@
/// <reference types="node" />
// / <reference types="node" />
declare module '@ali/my-prettier' {
function format(text: string, type: string): string;

View File

@ -109,6 +109,6 @@ export const DEFAULT_LINK_AFTER = {
[COMMON_CHUNK_NAME.StyleDepsImport]: [],
[COMMON_CHUNK_NAME.StyleCssContent]: [COMMON_CHUNK_NAME.StyleDepsImport],
[COMMON_CHUNK_NAME.HtmlContent]: [],
}
};
export const COMMON_SUB_MODULE_NAME = 'index';

View File

@ -1,4 +1,4 @@
export const NATIVE_ELE_PKG: string = 'native';
export const NATIVE_ELE_PKG = 'native';
export const CONTAINER_TYPE = {
COMPONENT: 'Component',

View File

@ -12,7 +12,7 @@ export default class Builder implements ICodeBuilder {
private generators: { [key: string]: CodeGeneratorFunction<ChunkContent> } = {
[ChunkType.STRING]: (str: string) => str, // no-op for string chunks
[ChunkType.JSON]: (json: object) => JSON.stringify(json), // stringify json to string
[ChunkType.JSON]: (json: Record<string, unknown>) => JSON.stringify(json), // stringify json to string
};
constructor(chunkDefinitions: ICodeChunk[] = []) {
@ -58,14 +58,15 @@ export default class Builder implements ICodeBuilder {
const { type, content, name } = unprocessedChunks[indexToRemove];
const compiledContent = this.generateByType(type, content);
if (compiledContent) {
resultingString.push(compiledContent + '\n');
resultingString.push(`${compiledContent }\n`);
}
unprocessedChunks.splice(indexToRemove, 1);
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)),
// eslint-disable-next-line no-param-reassign
ch => { ch.linkAfter = ch.linkAfter.filter(after => after !== name); },
);
}
}
@ -95,8 +96,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));
}
}

View File

@ -51,7 +51,7 @@ export function createModuleBuilder(
if (options.postProcessors.length > 0) {
files = files.map((file) => {
let content = file.content;
let { content } = file;
const type = file.ext;
options.postProcessors.forEach((processer) => {
content = processer(content, type);

View File

@ -40,7 +40,9 @@ function getDirFromRoot(root: IResultDir, path: string[]): IResultDir {
export class ProjectBuilder implements IProjectBuilder {
private template: IProjectTemplate;
private plugins: IProjectPlugins;
private postProcessors: PostProcessor[];
constructor({

View File

@ -2,7 +2,9 @@ import { CodeGeneratorError, IResultDir, IResultFile } from '../types';
export default class ResultDir implements IResultDir {
public name: string;
public dirs: IResultDir[];
public files: IResultFile[];
constructor(name: string) {

View File

@ -2,10 +2,12 @@ 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 = '') {
constructor(name: string, ext = 'jsx', content = '') {
this.name = name;
this.ext = ext;
this.content = content;

View File

@ -20,7 +20,6 @@ import {
IExternalDependency,
IInternalDependency,
InternalDependencyType,
IPageMeta,
IParseResult,
IProjectSchema,
ISchemaParser,
@ -95,7 +94,7 @@ class SchemaParser implements ISchemaParser {
});
}
} else {
throw new CodeGeneratorError(`Can't find anything to generate.`);
throw new CodeGeneratorError('Can\'t find anything to generate.');
}
// 建立所有容器的内部依赖索引
@ -160,7 +159,7 @@ class SchemaParser implements ISchemaParser {
const routes = containers
.filter((container) => container.containerType === 'Page')
.map((page) => {
const meta = page.meta as IPageMeta;
const { meta } = page;
if (meta) {
return {
path: meta.router,
@ -190,7 +189,9 @@ class SchemaParser implements ISchemaParser {
let npms: INpmPackage[] = [];
containers.forEach((con) => {
const p = (con.deps || [])
.map((dep) => (dep.dependencyType === DependencyType.External ? dep : null))
.map((dep) => {
return dep.dependencyType === DependencyType.External ? dep : null;
})
.filter((dep) => dep !== null);
npms.push(...((p as unknown) as INpmPackage[]));
});

View File

@ -88,7 +88,9 @@ function buildPackageImport(pkg: string, deps: IDependency[], targetFileType: st
}
});
const items = Object.keys(imports).map((src) => (src === imports[src] ? src : `${src} as ${imports[src]}`));
const items = Object.keys(imports).map((src) => {
return src === imports[src] ? src : `${src} as ${imports[src]}`;
});
const statementL = ['import'];
if (defaultImport) {

View File

@ -19,7 +19,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
type: ChunkType.STRING,
fileType: FileType.JSX,
name: COMMON_CHUNK_NAME.InternalDepsImport,
content: `import * from 'react';`,
content: 'import * from \'react\';',
linkAfter: [],
});

View File

@ -0,0 +1,68 @@
import { CLASS_DEFINE_CHUNK_NAME, DEFAULT_LINK_AFTER } from '../../../const/generator';
import { generateCompositeType } from '../../../utils/compositeType';
import Scope from '../../../utils/Scope';
import {
BuilderComponentPlugin,
BuilderComponentPluginFactory,
ChunkType,
FileType,
ICodeStruct,
IContainerInfo,
} from '../../../types';
type PluginConfig = {
fileType: string;
implementType: 'inConstructor' | 'insMember' | 'hooks';
};
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
const cfg: PluginConfig = {
fileType: FileType.JSX,
implementType: 'insMember',
...config,
};
const plugin: BuilderComponentPlugin = async (pre: ICodeStruct) => {
const next: ICodeStruct = {
...pre,
};
const ir = next.ir as IContainerInfo;
const scope = Scope.createRootScope();
if (ir.state) {
const { state } = ir;
const fields = Object.keys(state).map<string>((stateName) => {
// TODO: 这里用什么 handlers?
const value = generateCompositeType(state[stateName], scope);
return `${stateName}: ${value}`;
});
if (cfg.implementType === 'inConstructor') {
next.chunks.push({
type: ChunkType.STRING,
fileType: cfg.fileType,
name: CLASS_DEFINE_CHUNK_NAME.ConstructorContent,
content: `this.state = { ${fields.join(',')} };`,
linkAfter: [...DEFAULT_LINK_AFTER[CLASS_DEFINE_CHUNK_NAME.ConstructorContent]],
});
} else if (cfg.implementType === 'insMember') {
next.chunks.push({
type: ChunkType.STRING,
fileType: cfg.fileType,
name: CLASS_DEFINE_CHUNK_NAME.InsVar,
content: `state = { ${fields.join(',')} };`,
linkAfter: [...DEFAULT_LINK_AFTER[CLASS_DEFINE_CHUNK_NAME.InsVar]],
});
}
// TODO: hooks state??
}
return next;
};
return plugin;
};
export default pluginFactory;

View File

@ -0,0 +1,157 @@
/* eslint-disable @typescript-eslint/indent */
import { CompositeValue, JSExpression, DataSourceConfig, isJSExpression, isJSFunction } from '@ali/lowcode-types';
import changeCase from 'change-case';
import { CLASS_DEFINE_CHUNK_NAME, COMMON_CHUNK_NAME } from '../../../const/generator';
import Scope from '../../../utils/Scope';
import {
BuilderComponentPlugin,
BuilderComponentPluginFactory,
ChunkType,
FileType,
ICodeStruct,
IScope,
} from '../../../types';
import { generateCompositeType } from '../../../utils/compositeType';
import { parseExpressionConvertThis2Context } from '../../../utils/expressionParser';
import { isContainerSchema } from '../../../utils/schema';
import { RAX_CHUNK_NAME } from './const';
type PluginConfig = {
fileType: string;
};
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
const cfg: PluginConfig = {
fileType: FileType.JSX,
...config,
};
const plugin: BuilderComponentPlugin = async (pre: ICodeStruct) => {
const next: ICodeStruct = {
...pre,
};
const scope = Scope.createRootScope();
const dataSourceConfig = isContainerSchema(pre.ir) ? pre.ir.dataSource : null;
const dataSourceItems: DataSourceConfig[] = (dataSourceConfig && dataSourceConfig.list) || [];
const dataSourceEngineOptions = { runtimeConfig: true };
if (dataSourceItems.length > 0) {
const requestHandlersMap = {} as Record<string, JSExpression>;
dataSourceItems.forEach((ds) => {
const dsType = ds.type || 'fetch';
if (!(dsType in requestHandlersMap) && dsType !== 'custom') {
const handlerFactoryName = `__$$create${ changeCase.pascal(dsType) }RequestHandler`;
requestHandlersMap[dsType] = {
type: 'JSExpression',
value: handlerFactoryName + (dsType === 'urlParams' ? '(this.props.location.search)' : '()'),
};
const handlerFactoryExportName = `create${changeCase.pascal(dsType)}Handler`;
const handlerPkgName = `@ali/lowcode-datasource-${changeCase.kebab(dsType)}-handler`;
next.chunks.push({
type: ChunkType.STRING,
fileType: FileType.JSX,
name: COMMON_CHUNK_NAME.ExternalDepsImport,
content: `
import { ${handlerFactoryExportName} as ${handlerFactoryName} } from '${handlerPkgName}';
`,
linkAfter: [],
});
}
});
Object.assign(dataSourceEngineOptions, { requestHandlersMap });
}
next.chunks.push({
type: ChunkType.STRING,
fileType: FileType.JSX,
name: COMMON_CHUNK_NAME.ExternalDepsImport,
content: `
import { create as __$$createDataSourceEngine } from '@ali/lowcode-datasource-engine/runtime';
`,
linkAfter: [],
});
next.chunks.push({
type: ChunkType.STRING,
fileType: cfg.fileType,
name: CLASS_DEFINE_CHUNK_NAME.InsVar,
content: `
_dataSourceConfig = this._defineDataSourceConfig();
_dataSourceEngine = __$$createDataSourceEngine(
this._dataSourceConfig,
this._context,
${generateCompositeType(dataSourceEngineOptions, scope)}
);`,
linkAfter: [CLASS_DEFINE_CHUNK_NAME.Start],
});
next.chunks.push({
type: ChunkType.STRING,
fileType: cfg.fileType,
name: RAX_CHUNK_NAME.ClassDidMountContent,
content: `
this._dataSourceEngine.reloadDataSource();
`,
linkAfter: [RAX_CHUNK_NAME.ClassDidMountBegin],
});
next.chunks.push({
type: ChunkType.STRING,
fileType: cfg.fileType,
name: CLASS_DEFINE_CHUNK_NAME.InsPrivateMethod,
content: `
_defineDataSourceConfig() {
const __$$context = this._context;
return (${generateCompositeType(
{
...dataSourceConfig,
list: [
...dataSourceItems.map((item) => ({
...item,
isInit: wrapAsFunction(item.isInit, scope),
options: wrapAsFunction(item.options, scope),
})),
],
},
scope,
{
handlers: {
function: (jsFunc) => parseExpressionConvertThis2Context(jsFunc.value, '__$$context'),
expression: (jsExpr) => parseExpressionConvertThis2Context(jsExpr.value, '__$$context'),
},
},
)});
}
`,
linkAfter: [RAX_CHUNK_NAME.ClassRenderEnd],
});
return next;
};
return plugin;
};
export default pluginFactory;
function wrapAsFunction(value: CompositeValue, scope: IScope): CompositeValue {
if (isJSExpression(value) || isJSFunction(value)) {
return {
type: 'JSExpression',
value: `function(){ return ((${value.value}))}`,
};
}
return {
type: 'JSExpression',
value: `function(){return((${generateCompositeType(value, scope)}))}`,
};
}

View File

@ -0,0 +1,120 @@
import _ from 'lodash';
import { CLASS_DEFINE_CHUNK_NAME } from '../../../const/generator';
import { RAX_CHUNK_NAME } from './const';
import {
BuilderComponentPlugin,
BuilderComponentPluginFactory,
FileType,
ChunkType,
ICodeStruct,
IContainerInfo,
} from '../../../types';
type PluginConfig = {
fileType: string;
exportNameMapping: Record<string, string>;
normalizeNameMapping: Record<string, string>;
};
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
const cfg: PluginConfig = {
fileType: FileType.JSX,
exportNameMapping: {},
normalizeNameMapping: {},
...config,
};
const plugin: BuilderComponentPlugin = async (pre: ICodeStruct) => {
const next: ICodeStruct = {
...pre,
};
// Rax 先只支持 didMount 和 willUnmount 吧
const ir = next.ir as IContainerInfo;
const { lifeCycles } = ir;
if (lifeCycles && !_.isEmpty(lifeCycles)) {
Object.entries(lifeCycles).forEach(([lifeCycleName, lifeCycleMethodExpr]) => {
const normalizeName = cfg.normalizeNameMapping[lifeCycleName] || lifeCycleName;
const exportName = cfg.exportNameMapping[lifeCycleName] || lifeCycleName;
next.chunks.push({
type: ChunkType.STRING,
fileType: cfg.fileType,
name: RAX_CHUNK_NAME.LifeCyclesContent,
content: `${exportName}: (${lifeCycleMethodExpr.value}),`,
linkAfter: [RAX_CHUNK_NAME.LifeCyclesBegin],
});
if (normalizeName === 'didMount') {
next.chunks.push({
type: ChunkType.STRING,
fileType: cfg.fileType,
name: RAX_CHUNK_NAME.ClassDidMountContent,
content: `this._lifeCycles.${exportName}();`,
linkAfter: [RAX_CHUNK_NAME.ClassDidMountBegin],
});
} else if (normalizeName === 'willUnmount') {
next.chunks.push({
type: ChunkType.STRING,
fileType: cfg.fileType,
name: RAX_CHUNK_NAME.ClassWillUnmountContent,
content: `this._lifeCycles.${exportName}();`,
linkAfter: [RAX_CHUNK_NAME.ClassWillUnmountBegin],
});
} else {
// TODO: print warnings? Unknown life cycle
}
});
next.chunks.push({
type: ChunkType.STRING,
fileType: cfg.fileType,
name: CLASS_DEFINE_CHUNK_NAME.InsVar,
content: '_lifeCycles = this._defineLifeCycles();',
linkAfter: [CLASS_DEFINE_CHUNK_NAME.Start],
});
next.chunks.push({
type: ChunkType.STRING,
fileType: cfg.fileType,
name: RAX_CHUNK_NAME.LifeCyclesBegin,
content: `
_defineLifeCycles() {
const __$$lifeCycles = ({
`,
linkAfter: [RAX_CHUNK_NAME.ClassRenderEnd, CLASS_DEFINE_CHUNK_NAME.InsPrivateMethod],
});
next.chunks.push({
type: ChunkType.STRING,
fileType: cfg.fileType,
name: RAX_CHUNK_NAME.LifeCyclesEnd,
content: `
});
// 为所有的方法绑定上下文
Object.entries(__$$lifeCycles).forEach(([lifeCycleName, lifeCycleMethod]) => {
if (typeof lifeCycleMethod === 'function') {
__$$lifeCycles[lifeCycleName] = (...args) => {
return lifeCycleMethod.apply(this._context, args);
}
}
});
return __$$lifeCycles;
}
`,
linkAfter: [RAX_CHUNK_NAME.LifeCyclesBegin, RAX_CHUNK_NAME.LifeCyclesContent],
});
}
return next;
};
return plugin;
};
export default pluginFactory;

View File

@ -35,7 +35,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
type: ChunkType.STRING,
fileType: FileType.JSX,
name: CLASS_DEFINE_CHUNK_NAME.End,
content: `}`,
content: '}',
linkAfter: [CLASS_DEFINE_CHUNK_NAME.Start, REACT_CHUNK_NAME.ClassRenderEnd],
});

View File

@ -29,7 +29,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
const ir = next.ir as IContainerInfo;
if (ir.state) {
const state = ir.state;
const { state } = ir;
const fields = Object.keys(state).map<string>((stateName) => {
const value = generateCompositeType(state[stateName]);
return `${stateName}: ${value},`;

View File

@ -31,7 +31,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
const ir = next.ir as IContainerInfo;
if (ir.state) {
const state = ir.state;
const { state } = ir;
const fields = Object.keys(state).map<string>((stateName) => {
const value = generateCompositeType(state[stateName]);
return `${stateName}: ${value},`;

View File

@ -10,7 +10,7 @@ import {
type PluginConfig = {
fileType: string;
}
};
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
const cfg: PluginConfig = {
@ -27,7 +27,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
type: ChunkType.STRING,
fileType: cfg.fileType,
name: CLASS_DEFINE_CHUNK_NAME.ConstructorContent,
content: `this.utils = utils;`,
content: 'this.utils = utils;',
linkAfter: [CLASS_DEFINE_CHUNK_NAME.ConstructorStart],
});

View File

@ -35,7 +35,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
const ir = next.ir as IContainerInfo;
if (ir.lifeCycles) {
const lifeCycles = ir.lifeCycles;
const { lifeCycles } = ir;
const chunks = Object.keys(lifeCycles).map<ICodeChunk>((lifeCycleName) => {
const normalizeName = cfg.normalizeNameMapping[lifeCycleName] || lifeCycleName;
const exportName = cfg.exportNameMapping[lifeCycleName] || lifeCycleName;

View File

@ -30,7 +30,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
const ir = next.ir as IContainerInfo;
if (ir.methods) {
const methods = ir.methods;
const { methods } = ir;
const chunks = Object.keys(methods).map<ICodeChunk>((methodName) => ({
type: ChunkType.STRING,
fileType: cfg.fileType,

View File

@ -14,7 +14,7 @@ import { createReactNodeGenerator } from '../../../utils/nodeToJSX';
type PluginConfig = {
fileType?: string;
nodeTypeMapping?: Record<string, string>;
}
};
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
const cfg = {

View File

@ -6,7 +6,6 @@ import {
ChunkType,
FileType,
ICodeStruct,
IContainerInfo,
} from '../../../types';
const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
@ -19,7 +18,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
type: ChunkType.STRING,
fileType: FileType.JSX,
name: COMMON_CHUNK_NAME.ExternalDepsImport,
content: `import React from 'react';`,
content: 'import React from \'react\';',
linkAfter: [],
});

View File

@ -21,7 +21,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
type: ChunkType.STRING,
fileType: FileType.TS,
name: COMMON_CHUNK_NAME.ExternalDepsImport,
content: `import { BaseController } from '@ali/recore-renderer';`,
content: 'import { BaseController } from \'@ali/recore-renderer\';',
linkAfter: [],
});
@ -37,7 +37,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
type: ChunkType.STRING,
fileType: FileType.TS,
name: CLASS_DEFINE_CHUNK_NAME.End,
content: `}`,
content: '}',
linkAfter: [...DEFAULT_LINK_AFTER[CLASS_DEFINE_CHUNK_NAME.End]],
});

View File

@ -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]],
});
}

View File

@ -17,7 +17,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
type: ChunkType.STRING,
fileType: 'vx',
name: COMMON_CHUNK_NAME.CustomContent,
content: `<div {...globalProps.div} className="recore-loading" x-if={this.__loading} />`,
content: '<div {...globalProps.div} className="recore-loading" x-if={this.__loading} />',
linkAfter: [],
});

View File

@ -12,7 +12,7 @@ import {
type PluginConfig = {
fileType: string;
moduleFileType: string;
}
};
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
const cfg: PluginConfig = {

View File

@ -73,7 +73,9 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
originTemplate: '@alifd/scaffold-lite-js',
};
ir.packages.forEach((packageInfo) => (packageJson.dependencies[packageInfo.package] = packageInfo.version));
ir.packages.forEach((packageInfo) => {
packageJson.dependencies[packageInfo.package] = packageInfo.version;
});
next.chunks.push({
type: ChunkType.JSON,

View File

@ -38,15 +38,15 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
component: BasicLayout,
children: [
${ir.routes
.map(
route => `
.map(
route => `
{
path: '${route.path}',
component: ${route.componentName},
}
`,
)
.join(',')}
)
.join(',')}
],
},
];

View File

@ -0,0 +1,52 @@
import { COMMON_CHUNK_NAME } from '../../../../../const/generator';
import {
BuilderComponentPlugin,
BuilderComponentPluginFactory,
ChunkType,
FileType,
ICodeStruct,
IParseResult,
} from '../../../../../types';
const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
const plugin: BuilderComponentPlugin = async (pre: ICodeStruct) => {
const next: ICodeStruct = {
...pre,
};
const ir = next.ir as IParseResult;
const miniAppBuildType = ir.project?.config.miniAppBuildType;
const buildCfg = {
inlineStyle: false,
plugins: [
[
'build-plugin-rax-app',
{
targets: ['web', 'miniapp'],
miniapp: miniAppBuildType
? {
buildType: miniAppBuildType,
}
: undefined,
},
],
'@ali/build-plugin-rax-app-def',
],
};
next.chunks.push({
type: ChunkType.STRING,
fileType: FileType.JSON,
name: COMMON_CHUNK_NAME.CustomContent,
content: `${JSON.stringify(buildCfg, null, 2) }\n`,
linkAfter: [],
});
return next;
};
return plugin;
};
export default pluginFactory;

View File

@ -25,4 +25,3 @@ export default function getFile(): [string[], IResultFile] {
return [[], file];
}

View File

@ -29,4 +29,3 @@ export default function getFile(): [string[], IResultFile] {
return [[], file];
}

View File

@ -63,4 +63,3 @@ export default function getFile(): [string[], IResultFile] {
return [[], file];
}

View File

@ -48,4 +48,3 @@ export default function getFile(): [string[], IResultFile] {
return [['public'], file];
}

View File

@ -72,6 +72,5 @@ export default {
`,
);
return [['src','config'], file];
return [['src', 'config'], file];
}

View File

@ -38,6 +38,5 @@ export default componentsMap;
`,
);
return [['src','config'], file];
return [['src', 'config'], file];
}

View File

@ -24,6 +24,5 @@ export default {
`,
);
return [['src','config'], file];
return [['src', 'config'], file];
}

View File

@ -98,4 +98,3 @@ app.run();
return [['src'], file];
}

View File

@ -50,4 +50,3 @@ export default function getFile(): [string[], IResultFile] {
return [[], file];
}

View File

@ -7,7 +7,7 @@ const PARSERS = ['css', 'scss', 'less', 'json', 'html', 'vue'];
type ProcessorConfig = {
customFileTypeParser: Record<string, string>;
}
};
const factory: PostProcessorFactory<ProcessorConfig> = (config?: ProcessorConfig) => {
const cfg: ProcessorConfig = {
@ -23,7 +23,7 @@ const factory: PostProcessorFactory<ProcessorConfig> = (config?: ProcessorConfig
parser = 'typescript';
} else if (PARSERS.indexOf(fileType) >= 0) {
parser = fileType as prettier.BuiltInParserName;
} else if (cfg.customFileTypeParser[fileType]){
} else if (cfg.customFileTypeParser[fileType]) {
parser = cfg.customFileTypeParser[fileType] as prettier.BuiltInParserName;
} else if (fileType === 'vx') {
return mypretter(content, fileType);

View File

@ -19,8 +19,8 @@ export interface IDiskPublisher extends IPublisher<IDiskFactoryParams, string> {
}
export const createDiskPublisher: PublisherFactory<
IDiskFactoryParams,
IDiskPublisher
IDiskFactoryParams,
IDiskPublisher
> = (params: IDiskFactoryParams = {}): IDiskPublisher => {
let { project, outputPath = './' } = params;

View File

@ -61,7 +61,7 @@ const createDirectory = (pathToDir: string): Promise<void> => {
const writeContentToFile = (
filePath: string,
fileContent: string,
encoding: string = 'utf8',
encoding = 'utf8',
): Promise<void> => {
return new Promise((resolve, reject) => {
writeFile(filePath, fileContent, encoding, err => {

View File

@ -5,7 +5,7 @@ import {
IPublisherFactoryParams,
PublisherError,
} from '../../types';
import { isNodeProcess, writeZipToDisk, generateProjectZip } from './utils'
import { isNodeProcess, writeZipToDisk, generateProjectZip } from './utils';
// export type ZipBuffer = Buffer | Blob;
export type ZipBuffer = Buffer;
@ -30,12 +30,12 @@ export const createZipPublisher: PublisherFactory<ZipFactoryParams, ZipPublisher
const getProject = () => project;
const setProject = (projectToSet: IResultDir) => {
project = projectToSet;
}
};
const getOutputPath = () => outputPath;
const setOutputPath = (path: string) => {
outputPath = path;
}
};
const publish = async (options: ZipFactoryParams = {}) => {
const projectToPublish = options.project || project;
@ -57,7 +57,7 @@ export const createZipPublisher: PublisherFactory<ZipFactoryParams, ZipPublisher
} catch (error) {
throw new PublisherError(error);
}
}
};
return {
publish,
@ -66,4 +66,4 @@ export const createZipPublisher: PublisherFactory<ZipFactoryParams, ZipPublisher
getOutputPath,
setOutputPath,
};
}
};

View File

@ -8,7 +8,7 @@ export const isNodeProcess = (): boolean => {
typeof process.versions === 'object' &&
typeof process.versions.node !== 'undefined'
);
}
};
export const writeZipToDisk = (
zipFolderPath: string,
@ -27,7 +27,7 @@ export const writeZipToDisk = (
const writeStream = fs.createWriteStream(zipPath);
writeStream.write(content);
writeStream.end();
}
};
export const generateProjectZip = async (project: IResultDir): Promise<ZipBuffer> => {
let zip = new JSZip();
@ -35,12 +35,12 @@ export const generateProjectZip = async (project: IResultDir): Promise<ZipBuffer
// const zipType = isNodeProcess() ? 'nodebuffer' : 'blob';
const zipType = 'nodebuffer'; // 目前先只支持 node 调用
return zip.generateAsync({ type: zipType });
}
};
const writeFolderToZip = (
folder: IResultDir,
parentFolder: JSZip,
ignoreFolder: boolean = false,
ignoreFolder = false,
) => {
const zipFolder = ignoreFolder ? parentFolder : parentFolder.folder(folder.name);
if (zipFolder !== null) {
@ -57,4 +57,4 @@ const writeFolderToZip = (
}
return parentFolder;
}
};

View File

@ -7,21 +7,12 @@ 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);
}
}

View File

@ -4,7 +4,6 @@ import {
IContainerNodeItem,
IDependency,
II18nMap,
IInternalDependency,
INpmPackage,
IUtilItem,
} from './index';

View File

@ -227,7 +227,7 @@ export interface IAppConfig {
historyMode: 'brower' | 'hash'; // 浏览器路由brower 哈希路由hash
targetRootID: string; // 渲染根节点 ID
layout: IComponentNodeItem;
theme: object; // 主题配置,根据接入的主题模块不同
theme: Record<string, unknown>; // 主题配置,根据接入的主题模块不同
}
export interface IAppMeta {

View File

@ -0,0 +1,34 @@
export class OrderedSet<T> {
private _set = new Set<T>();
private _arr: T[] = [];
constructor(items?: T[]) {
if (items) {
this._set = new Set(items);
this._arr = items.slice(0);
}
}
add(item: T) {
if (!this._set.has(item)) {
this._set.add(item);
this._arr.push(item);
}
}
delete(item: T) {
if (this._set.has(item)) {
this._set.delete(item);
this._arr.splice(this._arr.indexOf(item), 1);
}
}
has(item: T) {
return this._set.has(item);
}
toArray() {
return this._arr.slice(0);
}
}

View File

@ -0,0 +1,56 @@
import { OrderedSet } from './OrderedSet';
export interface IScopeBindings {
readonly parent: IScopeBindings | null;
hasBinding(varName: string): boolean;
hasOwnBinding(varName: string): boolean;
addBinding(varName: string): void;
removeBinding(varName: string): void;
getAllBindings(): string[];
getAllOwnedBindings(): string[];
}
export class ScopeBindings implements IScopeBindings {
readonly parent: IScopeBindings | null;
private _bindings = new OrderedSet<string>();
constructor(p: IScopeBindings | null = null) {
this.parent = p;
}
hasBinding(varName: string): boolean {
return this._bindings.has(varName) || !!this.parent?.hasBinding(varName);
}
hasOwnBinding(varName: string): boolean {
return this._bindings.has(varName);
}
addBinding(varName: string): void {
this._bindings.add(varName);
}
removeBinding(varName: string): void {
this._bindings.delete(varName);
}
getAllBindings(): string[] {
const allBindings = new OrderedSet(this._bindings.toArray());
for (let { parent } = this; parent; parent = parent?.parent) {
parent.getAllOwnedBindings().forEach((varName) => {
allBindings.add(varName);
});
}
return allBindings.toArray();
}
getAllOwnedBindings(): string[] {
return this._bindings.toArray();
}
}

View File

@ -24,7 +24,9 @@ export function upperCaseFirst(inputValue: string): string {
export function uniqueArray<T>(arr: T[], by: (i: T) => string) {
const map: Record<string, T> = {};
arr.forEach((item) => (map[by(item)] = item));
arr.forEach((item) => {
map[by(item)] = item;
});
const uniqueKeys = [...new Set<string>(Object.keys(map))];
const uniqueItems = uniqueKeys.map((key) => map[key]);
return uniqueItems;

View File

@ -0,0 +1,243 @@
import * as parser from '@babel/parser';
import generate from '@babel/generator';
import traverse, { NodePath } from '@babel/traverse';
import * as t from '@babel/types';
import { isIdentifier, Node } from '@babel/types';
import { OrderedSet } from './OrderedSet';
export class ParseError extends Error {
constructor(expr: string | t.Expression) {
super(`Failed to parse expression "${typeof expr === 'string' ? expr : generate(expr)}"`);
Object.setPrototypeOf(this, new.target.prototype);
}
}
const MAYBE_EXPRESSIONS: {
[k in Node['type']]?: {
// fields: Array<keyof (Node & { type: k })>
fields: string[] | ((node: Node) => string[]);
};
} = {
ArrayExpression: { fields: ['elements'] },
AssignmentExpression: { fields: ['left', 'right'] },
BinaryExpression: { fields: ['left', 'right'] },
CallExpression: { fields: ['arguments', 'callee'] },
ConditionalExpression: { fields: ['test', 'consequent', 'alternate'] },
DoWhileStatement: { fields: ['test'] },
ExpressionStatement: { fields: ['expression'] },
ForInStatement: { fields: ['right'] },
ForStatement: { fields: ['init', 'test', 'update'] },
IfStatement: { fields: ['test'] },
LogicalExpression: { fields: ['left', 'right'] },
MemberExpression: {
fields: (node) => { return (node.type === 'MemberExpression' && node.computed) ? ['object', 'property'] : ['object']; },
},
NewExpression: { fields: ['callee', 'arguments'] },
ObjectMethod: {
fields: (node) => { return (node.type === 'ObjectMethod' && node.computed) ? ['key'] : []; },
},
ObjectProperty: {
fields: (node) => { return (node.type === 'ObjectProperty' && node.computed) ? ['key', 'value'] : ['value']; },
},
ReturnStatement: { fields: ['argument'] },
SequenceExpression: { fields: ['expressions'] },
ParenthesizedExpression: { fields: ['expression'] },
SwitchCase: { fields: ['test'] },
SwitchStatement: { fields: ['discriminant'] },
ThrowStatement: { fields: ['argument'] },
UnaryExpression: { fields: ['argument'] },
UpdateExpression: { fields: ['argument'] },
VariableDeclarator: { fields: ['init'] },
WhileStatement: { fields: ['test'] },
WithStatement: { fields: ['object'] },
AssignmentPattern: { fields: ['right'] },
ArrowFunctionExpression: { fields: ['body'] },
ClassExpression: { fields: ['superClass'] },
ClassDeclaration: { fields: ['superClass'] },
ExportDefaultDeclaration: { fields: ['declaration'] },
ForOfStatement: { fields: ['right'] },
ClassMethod: { fields: (node) => { return (node.type === 'ClassMethod' && node.computed) ? ['key'] : []; } },
SpreadElement: { fields: ['argument'] },
TaggedTemplateExpression: { fields: ['tag'] },
TemplateLiteral: { fields: ['expressions'] },
YieldExpression: { fields: ['argument'] },
AwaitExpression: { fields: ['argument'] },
OptionalMemberExpression: {
fields: (node) => { return (node.type === 'OptionalMemberExpression' && node.computed) ? ['object', 'property'] : ['object']; },
},
OptionalCallExpression: { fields: ['callee', 'arguments'] },
JSXSpreadAttribute: { fields: ['argument'] },
BindExpression: { fields: ['object', 'callee'] },
ClassProperty: { fields: (node) => { return (node.type === 'ClassProperty' && node.computed) ? ['key', 'value'] : ['value']; } },
PipelineTopicExpression: { fields: ['expression'] },
PipelineBareFunction: { fields: ['callee'] },
ClassPrivateProperty: { fields: ['value'] },
Decorator: { fields: ['expression'] },
TupleExpression: { fields: ['elements'] },
TSDeclareMethod: { fields: (node) => { return (node.type === 'TSDeclareMethod' && node.computed) ? ['key'] : []; } },
TSPropertySignature: {
fields: (node) => { return (node.type === 'TSPropertySignature' && node.computed) ? ['key', 'initializer'] : ['initializer']; },
},
TSMethodSignature: {
fields: (node) => { return (node.type === 'TSMethodSignature' && node.computed) ? ['key'] : []; },
},
TSAsExpression: { fields: ['expression'] },
TSTypeAssertion: { fields: ['expression'] },
TSEnumDeclaration: { fields: ['initializer'] },
TSEnumMember: { fields: ['initializer'] },
TSNonNullExpression: { fields: ['expression'] },
TSExportAssignment: { fields: ['expression'] },
};
export type ParseExpressionGetGlobalVariablesOptions = { filter?: (varName: string) => boolean };
const CROSS_THIS_SCOPE_TYPE_NODE: {
[k in Node['type']]?: boolean;
} = {
ArrowFunctionExpression: false, // 箭头函数不跨越 this 的 scope
FunctionExpression: true,
FunctionDeclaration: true,
// FunctionTypeAnnotation: false, // 这是 TS 定义
// FunctionTypeParam: false, // 这是 TS 定义
ClassDeclaration: true,
ClassExpression: true,
ClassBody: true,
ClassImplements: true,
ClassMethod: true,
ClassPrivateMethod: true,
ClassProperty: true,
ClassPrivateProperty: true,
DeclareClass: true,
};
export function parseExpressionGetGlobalVariables(
expr: string | null | undefined,
{ filter = () => true }: ParseExpressionGetGlobalVariablesOptions = {},
): string[] {
if (!expr) {
return [];
}
try {
const undeclaredVars = new OrderedSet<string>();
const ast = parser.parse(`!(${expr});`);
const addUndeclaredIdentifierIfNeeded =
(x: Record<string, unknown> | null | undefined, path: NodePath<Node>) => {
if (isIdentifier(x) && !path.scope.hasBinding(x.name)) {
undeclaredVars.add(x.name);
}
};
traverse(ast, {
enter(path) {
const { node } = path;
const expressionFields = MAYBE_EXPRESSIONS[node.type]?.fields;
if (expressionFields) {
(typeof expressionFields === 'function' ? expressionFields(node) : expressionFields).forEach((fieldName) => {
const fieldValue = node[fieldName as keyof typeof node];
if (typeof fieldValue === 'object') {
if (Array.isArray(fieldValue)) {
fieldValue.forEach((item) => {
addUndeclaredIdentifierIfNeeded(item, path);
});
} else {
addUndeclaredIdentifierIfNeeded(fieldValue, path);
}
}
});
}
},
});
return undeclaredVars.toArray().filter(filter);
} catch (e) {
throw new ParseError(expr);
}
}
export function parseExpressionConvertThis2Context(
expr: string | t.Expression,
contextName = '__$$context',
localVariables: string[] = [],
): string {
if (!expr) {
return expr;
}
try {
const exprAst = typeof expr === 'string' ? parser.parseExpression(expr) : expr;
const exprWrapAst = t.expressionStatement(exprAst);
const fileAst = t.file(t.program([exprWrapAst]));
const localVariablesSet = new Set(localVariables);
let thisScopeLevel = CROSS_THIS_SCOPE_TYPE_NODE[exprAst.type] ? -1 : 0;
traverse(fileAst, {
enter(path) {
if (CROSS_THIS_SCOPE_TYPE_NODE[path.node.type]) {
thisScopeLevel++;
}
},
exit(path) {
if (CROSS_THIS_SCOPE_TYPE_NODE[path.node.type]) {
thisScopeLevel--;
}
},
MemberExpression(path) {
if (!path.isMemberExpression()) {
return;
}
const obj = path.get('object');
if (!obj.isThisExpression()) {
return;
}
// 处理局部变量
if (!path.node.computed) {
const prop = path.get('property');
if (prop.isIdentifier() && localVariablesSet.has(prop.node.name)) {
path.replaceWith(t.identifier(prop.node.name));
return;
}
}
// 替换 this (只在顶层替换)
if (thisScopeLevel <= 0) {
obj.replaceWith(t.identifier(contextName));
}
},
ThisExpression(path) {
if (!path.isThisExpression()) {
return;
}
// MemberExpression 中的 this.xxx 已经处理过了
if (path.parent.type === 'MemberExpression') {
return;
}
if (thisScopeLevel <= 0) {
path.replaceWith(t.identifier(contextName));
}
},
});
const { code } = generate(exprWrapAst.expression, { sourceMaps: false });
return code;
} catch (e) {
throw new ParseError(expr);
}
}
export function parseExpression(expr: string) {
try {
return parser.parseExpression(expr);
} catch (e) {
throw new ParseError(expr);
}
}

View File

@ -124,7 +124,9 @@ export function generateAttrs(ctx: INodeGeneratorContext, nodeItem: IComponentNo
let pieces: CodePiece[] = [];
Object.keys(props).forEach(
(propName: string) => (pieces = pieces.concat(generateAttr(ctx, propName, props[propName]))),
(propName: string) => {
pieces = pieces.concat(generateAttr(ctx, propName, props[propName]));
},
);
return pieces;
@ -236,7 +238,7 @@ export function linkPieces(pieces: CodePiece[]): string {
.map((p) => p.value)
.join(' ');
attrsParts = !!attrsParts ? ` ${attrsParts}` : '';
attrsParts = attrsParts ? ` ${attrsParts}` : '';
if (childrenParts) {
return `${beforeParts}<${tagName}${attrsParts}>${childrenParts}</${tagName}>${afterParts}`;

View File

@ -0,0 +1,87 @@
import {
JSSlot,
JSExpression,
NodeData,
NodeSchema,
PropsMap,
isJSExpression,
isJSSlot,
isDOMText,
ContainerSchema,
NpmInfo,
} from '@ali/lowcode-types';
export function isContainerSchema(x: any): x is ContainerSchema {
return typeof x === 'object' && x && typeof x.componentName === 'string' && typeof x.fileName === 'string';
}
export function isNpmInfo(x: any): x is NpmInfo {
return typeof x === 'object' && x && typeof x.package === 'string';
}
// tslint:disable-next-line: no-empty
const noop = () => undefined;
const handleChildrenDefaultOptions = {
rerun: false,
};
export function handleSubNodes<T>(
children: unknown,
handlers: {
string?: (i: string) => T;
expression?: (i: JSExpression) => T;
node?: (i: NodeSchema) => T;
},
options?: {
rerun?: boolean;
},
): T[] {
const opt = {
...handleChildrenDefaultOptions,
...(options || {}),
};
if (Array.isArray(children)) {
const list: NodeData[] = children as NodeData[];
return list.map(
(child) => handleSubNodes(child, handlers, opt),
).reduce((p, c) => p.concat(c), []);
}
let result: T | undefined;
const childrenRes: T[] = [];
if (isDOMText(children)) {
const handler = handlers.string || noop;
result = handler(children as string);
} else if (isJSExpression(children)) {
const handler = handlers.expression || noop;
result = handler(children as JSExpression);
} else {
const handler = handlers.node || noop;
const child = children as NodeSchema;
result = handler(child);
if (opt.rerun && child.children) {
const childRes = handleSubNodes(child.children, handlers, opt);
childrenRes.push(...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);
childrenRes.push(...childRes);
});
}
}
if (result !== undefined) {
childrenRes.unshift(result);
}
return childrenRes;
}

View File

@ -1,21 +1,21 @@
const fs = require("fs");
const fs = require('fs');
const path = require('path');
console.log(process.argv);
let root = '';
let rootParams = '';
const pathArgIndex = process.argv.indexOf('--path');
if (pathArgIndex >= 0) {
root = process.argv[pathArgIndex + 1];
rootParams = process.argv[pathArgIndex + 1];
}
if (!root) {
if (!rootParams) {
throw new Error('Can\'t find path argument');
}
function cloneStr(str, times) {
let count = times;
const arr = [];
while(count > 0) {
while (count > 0) {
arr.push(str);
count -= 1;
}
@ -23,7 +23,7 @@ function cloneStr(str, times) {
}
function createTemplateFile(root, internalPath, fileName) {
//不是文件夹,则添加type属性为文件后缀名
// 不是文件夹,则添加type属性为文件后缀名
const fileTypeSrc = path.extname(fileName);
const fileType = fileTypeSrc.substring(1);
const baseName = path.basename(fileName, fileTypeSrc);
@ -35,7 +35,7 @@ function createTemplateFile(root, internalPath, fileName) {
encoding: 'utf8',
});
const pathList = (internalPath.split(path.sep) || []).filter(p => !!p);
const modulePathStr = JSON.stringify(pathList).replace(/\"/g, '\'');
const modulePathStr = JSON.stringify(pathList).replace(/"/g, '\'');
const templateContent = `
import ResultFile from '${depPrefix}model/ResultFile';
@ -62,24 +62,24 @@ ${content}
function fileDisplay(root, internalPath) {
const dirPath = path.join(root, internalPath);
const filesList = fs.readdirSync(dirPath);
for(let i = 0; i < filesList.length; i++){
//描述此文件/文件夹的对象
for (let i = 0; i < filesList.length; i++) {
// 描述此文件/文件夹的对象
const fileName = filesList[i];
//拼接当前文件的路径(上一层路径+当前file的名字)
// 拼接当前文件的路径(上一层路径+当前file的名字)
const filePath = path.join(dirPath, fileName);
//根据文件路径获取文件信息返回一个fs.Stats对象
// 根据文件路径获取文件信息返回一个fs.Stats对象
const stats = fs.statSync(filePath);
if(stats.isDirectory()){
//递归调用
if (stats.isDirectory()) {
// 递归调用
fileDisplay(root, path.join(internalPath, fileName));
}else{
} else {
createTemplateFile(root, internalPath, fileName);
}
}
}
//调用函数遍历根目录,同时传递 文件夹路径和对应的数组
//请使用同步读取
fileDisplay(root, '');
//读取完毕则写入到txt文件中
// 调用函数遍历根目录,同时传递 文件夹路径和对应的数组
// 请使用同步读取
fileDisplay(rootParams, '');
// 读取完毕则写入到txt文件中
// fs.writeFileSync('./data.txt', JSON.stringify(arr));

View File

@ -0,0 +1,6 @@
module.exports = {
extends: '../../.eslintrc.js',
rules: {
'@typescript-eslint/no-parameter-properties': 1,
}
}

View File

@ -0,0 +1,124 @@
import {
DataSourceConfig,
DataSourceEngineOptions,
IDataSourceEngine,
IDataSourceEngineFactory,
IRuntimeContext,
} from '../types';
import { RuntimeDataSource } from './RuntimeDataSource';
export class DataSourceEngine implements IDataSourceEngine {
private _dataSourceMap: Record<string, RuntimeDataSource> = {};
constructor(
private _dataSourceConfig: DataSourceConfig,
private _runtimeContext: IRuntimeContext,
private _options?: DataSourceEngineOptions,
) {
// eslint-disable-next-line no-unused-expressions
_dataSourceConfig.list?.forEach((ds) => {
// 确保数据源都有处理器
const requestHandler = ds.requestHandler || _options?.requestHandlersMap?.[ds.type];
if (!requestHandler) {
throw new Error(`No request handler for "${ds.type}" data source`);
}
this._dataSourceMap[ds.id] = new RuntimeDataSource(
ds.id,
ds.type,
getValue(ds.options) || {},
requestHandler.bind(_runtimeContext),
ds.dataHandler ? ds.dataHandler.bind(_runtimeContext) : undefined,
(data) => {
_runtimeContext.setState({ [ds.id]: data });
},
);
});
}
public get dataSourceMap() {
return this._dataSourceMap;
}
public async reloadDataSource() {
try {
const allDataSourceConfigList = this._dataSourceConfig.list || [];
// urlParams 类型的优先加载
for (const ds of allDataSourceConfigList) {
if (ds.type === 'urlParams' && (getValue(ds.isInit) ?? true)) {
await this._dataSourceMap[ds.id].load();
}
}
// 然后是所有其他的
const remainDataSourceConfigList = allDataSourceConfigList.filter((x) => x.type !== 'urlParams');
// 先发起异步的
const asyncLoadings: Array<Promise<unknown>> = [];
for (const ds of remainDataSourceConfigList) {
if (getValue(ds.isInit) ?? true) {
const options = getValue(ds.options);
if (options && !options.isSync) {
this._dataSourceMap[ds.id].setOptions(options);
asyncLoadings.push(this._dataSourceMap[ds.id].load(options?.params).catch(() => {}));
}
}
}
try {
// 再按先后顺序发起同步请求
for (const ds of remainDataSourceConfigList) {
if (getValue(ds.isInit) ?? true) {
const options = getValue(ds.options);
if (options && options.isSync) {
this._dataSourceMap[ds.id].setOptions(options);
await this._dataSourceMap[ds.id].load(options?.params);
await sleep(0); // TODO: 如何优雅地解决 setState 的异步问题?
}
}
}
} catch (e) {
// ignore error
}
await Promise.all(asyncLoadings);
} finally {
const allDataHandler = this._dataSourceConfig.dataHandler;
if (allDataHandler) {
await allDataHandler(this._getDataMapOfAll());
}
}
}
private _getDataMapOfAll(): Record<string, unknown> {
const dataMap: Record<string, unknown> = {};
Object.entries(this._dataSourceMap).forEach(([dsId, ds]) => {
dataMap[dsId] = ds.data;
});
return dataMap;
}
}
export const create: IDataSourceEngineFactory['create'] = (dataSourceConfig, runtimeContext, options) => {
return new DataSourceEngine(dataSourceConfig, runtimeContext, options);
};
function getValue<T>(valueOrValueGetter: T | (() => T)): T;
function getValue<T extends boolean>(valueOrValueGetter: T | (() => T)): T | undefined {
if (typeof valueOrValueGetter === 'function') {
try {
return valueOrValueGetter();
} catch (e) {
return undefined;
}
} else {
return valueOrValueGetter;
}
}
function sleep(ms = 0) {
return new Promise((resolve) => setTimeout(resolve, ms));
}

View File

@ -0,0 +1,94 @@
import { DataSourceOptions, IRuntimeDataSource, RequestHandler, RuntimeDataSourceStatus } from '../types';
import { DataSourceResponse } from '../types/DataSourceResponse';
export class RuntimeDataSource<
TParams extends Record<string, unknown> = Record<string, unknown>,
TRequestResult = unknown,
TResultData = unknown
> implements IRuntimeDataSource<TParams, TResultData> {
private _status: RuntimeDataSourceStatus = RuntimeDataSourceStatus.Initial;
private _data?: TResultData;
private _error?: Error;
private _latestOptions: DataSourceOptions<TParams>;
constructor(
private _id: string,
private _type: string,
private _initialOptions: DataSourceOptions<TParams>,
private _requestHandler: RequestHandler<DataSourceOptions<TParams>, DataSourceResponse<TRequestResult>>,
private _dataHandler:
| ((
data: DataSourceResponse<TRequestResult> | undefined,
error: unknown | undefined,
) => TResultData | Promise<TResultData>)
| undefined,
private _onLoaded: (data: TResultData) => void,
) {
this._latestOptions = _initialOptions;
}
public get status() {
return this._status;
}
public get data() {
return this._data;
}
public get error() {
return this._error;
}
public async load(params?: TParams): Promise<TResultData> {
try {
this._latestOptions = {
...this._latestOptions,
params: {
...this._latestOptions.params,
...params,
} as TParams,
};
this._status = RuntimeDataSourceStatus.Loading;
const data = await this._request(this._latestOptions);
this._status = RuntimeDataSourceStatus.Loaded;
this._onLoaded(data);
this._data = data;
return data;
} catch (err) {
this._error = err;
this._status = RuntimeDataSourceStatus.Error;
throw err;
}
}
public setOptions(options: DataSourceOptions<TParams>) {
this._latestOptions = options;
}
private async _request(options: DataSourceOptions<TParams>) {
try {
const response = await this._requestHandler(options);
const data = this._dataHandler
? await this._dataHandler(response, undefined)
: ((response.data as unknown) as TResultData);
return data;
} catch (err) {
if (this._dataHandler) {
const data = await this._dataHandler(undefined, err);
return data;
}
throw err;
}
}
}

View File

@ -0,0 +1,24 @@
import { IRuntimeDataSource } from './IRuntimeDataSource';
/** 运行时上下文 */
export interface IRuntimeContext<
TState = Record<string, unknown>
> {
/** 当前容器的状态 */
readonly state: TState;
/** 设置状态(浅合并) */
setState(state: Partial<TState>): void;
/** 数据源, key 是数据源的 ID */
dataSourceMap: Record<string, IRuntimeDataSource>;
/** 重新加载所有的数据源 */
reloadDataSource(): Promise<void>;
/** 页面容器 */
readonly page: IRuntimeContext & { props: Record<string, unknown> };
/** 低代码业务组件容器 */
readonly component: IRuntimeContext & { props: Record<string, unknown> };
}

View File

@ -0,0 +1 @@
export * from './DataSourceConfig'; export * from './DataSourceConfigItem'; export * from './DataSourceEngineOptions'; export * from './DataSourceOptions'; export * from './IDataSourceEngine'; export * from './IDataSourceEngineFactory'; export * from './IRuntimeContext'; export * from './IRuntimeDataSource'; export * from './RequestHandler'; export * from './RuntimeDataSourceStatus';

View File

@ -1,24 +0,0 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
'prettier/@typescript-eslint',
],
root: true,
env: {
node: true,
jest: true,
},
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};

View File

@ -1,4 +0,0 @@
{
"singleQuote": true,
"trailingComma": "all"
}

View File

@ -5,8 +5,6 @@
"description": "低代码引擎 DEMO Server 端",
"scripts": {
"prebuild": "rimraf dist",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"start": "nest start",
"start:debug": "nest start --debug --watch",
"start:dev": "nest start --watch",
@ -49,13 +47,7 @@
"@types/jest": "25.2.3",
"@types/node": "^13.9.1",
"@types/supertest": "^2.0.8",
"@typescript-eslint/eslint-plugin": "3.0.2",
"@typescript-eslint/parser": "3.0.2",
"eslint": "7.1.0",
"eslint-config-prettier": "^6.10.0",
"eslint-plugin-import": "^2.20.1",
"jest": "26.0.1",
"prettier": "^1.19.1",
"supertest": "^4.0.2",
"ts-jest": "26.1.0",
"ts-loader": "^6.2.1",

View File

@ -5,7 +5,11 @@ import { GenerateProjectDto } from '../dto/generate-project.dto';
@Controller('api')
export class ApiController {
constructor(private readonly apiService: ApiService) {}
private readonly apiService: ApiService;
constructor(apiService: ApiService) {
this.apiService = apiService;
}
@Get('generate/test')
generateTest() {

View File

@ -3,7 +3,11 @@ import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
private readonly appService: AppService;
constructor(appService: AppService) {
this.appService = appService;
}
@Get()
getHello(): string {

View File

@ -1,5 +1,5 @@
import { IResultDir } from '@ali/lowcode-code-generator';
import { isNodeProcess, writeZipToDisk, generateProjectZip } from './utils'
import { isNodeProcess, writeZipToDisk, generateProjectZip } from './utils';
export type PublisherFactory<T, U> = (configuration?: Partial<T>) => U;
@ -17,7 +17,7 @@ export interface IPublisherResponse<T> {
payload?: T;
}
declare type ZipPublisherResponse = string | Buffer | Blob
declare type ZipPublisherResponse = string | Buffer | Blob;
export interface ZipFactoryParams extends IPublisherFactoryParams {
outputPath?: string
@ -30,41 +30,41 @@ export interface ZipPublisher extends IPublisher<ZipFactoryParams, ZipPublisherR
}
export const createZipPublisher: PublisherFactory<ZipFactoryParams, ZipPublisher> = (
params: ZipFactoryParams = {}
params: ZipFactoryParams = {},
): ZipPublisher => {
let { project, outputPath } = params
let { project, outputPath } = params;
const getProject = () => project
const getProject = () => project;
const setProject = (projectToSet: IResultDir) => {
project = projectToSet
}
project = projectToSet;
};
const getOutputPath = () => outputPath
const getOutputPath = () => outputPath;
const setOutputPath = (path: string) => {
outputPath = path
}
outputPath = path;
};
const publish = async (options: ZipFactoryParams = {}) => {
const projectToPublish = options.project || project
const projectToPublish = options.project || project;
if (!projectToPublish) {
throw new Error('MissingProject');
}
const zipName = options.projectSlug || params.projectSlug || projectToPublish.name
const zipName = options.projectSlug || params.projectSlug || projectToPublish.name;
try {
const zipContent = await generateProjectZip(projectToPublish)
const zipContent = await generateProjectZip(projectToPublish);
// If not output path is provided, zip is not written to disk
const projectOutputPath = options.outputPath || outputPath
const projectOutputPath = options.outputPath || outputPath;
if (projectOutputPath && isNodeProcess()) {
await writeZipToDisk(projectOutputPath, zipContent, zipName)
await writeZipToDisk(projectOutputPath, zipContent, zipName);
}
return { success: true, payload: zipContent }
return { success: true, payload: zipContent };
} catch (error) {
throw new Error('ZipUnexpected');
}
}
};
return {
publish,
@ -72,5 +72,5 @@ export const createZipPublisher: PublisherFactory<ZipFactoryParams, ZipPublisher
setProject,
getOutputPath,
setOutputPath,
}
}
};
};

View File

@ -6,52 +6,52 @@ export const isNodeProcess = (): boolean => {
typeof process === 'object' &&
typeof process.versions === 'object' &&
typeof process.versions.node !== 'undefined'
)
}
);
};
export const writeZipToDisk = (
zipFolderPath: string,
content: Buffer | Blob,
zipName: string
zipName: string,
): void => {
const fs = require('fs')
const path = require('path')
const fs = require('fs');
const path = require('path');
if (!fs.existsSync(zipFolderPath)) {
fs.mkdirSync(zipFolderPath, { recursive: true })
fs.mkdirSync(zipFolderPath, { recursive: true });
}
const zipPath = path.join(zipFolderPath, `${zipName}.zip`)
const zipPath = path.join(zipFolderPath, `${zipName}.zip`);
const writeStream = fs.createWriteStream(zipPath)
writeStream.write(content)
writeStream.end()
}
const writeStream = fs.createWriteStream(zipPath);
writeStream.write(content);
writeStream.end();
};
export const generateProjectZip = async (project: IResultDir): Promise<Buffer | Blob> => {
let zip = new JSZip()
zip = writeFolderToZip(project, zip, true)
const zipType = isNodeProcess() ? 'nodebuffer' : 'blob'
return zip.generateAsync({ type: zipType })
}
let zip = new JSZip();
zip = writeFolderToZip(project, zip, true);
const zipType = isNodeProcess() ? 'nodebuffer' : 'blob';
return zip.generateAsync({ type: zipType });
};
const writeFolderToZip = (
folder: IResultDir,
parentFolder: JSZip,
ignoreFolder: boolean = false
ignoreFolder = false,
) => {
const zipFolder = ignoreFolder ? parentFolder : parentFolder.folder(folder.name)
const zipFolder = ignoreFolder ? parentFolder : parentFolder.folder(folder.name);
folder.files.forEach((file: IResultFile) => {
// 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)
})
const fileName = file.ext ? `${file.name}.${file.ext}` : file.name;
zipFolder.file(fileName, file.content, options);
});
folder.dirs.forEach((subFolder: IResultDir) => {
writeFolderToZip(subFolder, zipFolder)
})
writeFolderToZip(subFolder, zipFolder);
});
return parentFolder
}
return parentFolder;
};

View File

@ -34,7 +34,7 @@ export default class Preview extends ReactProvider {
containerId,
components: { ...builtInComps, ...buildComponents({ '@alifd/next': 'Next' }, componentsMap) },
componentsMap,
utils: utils,
utils,
constants,
};
}
@ -44,7 +44,7 @@ export default class Preview extends ReactProvider {
const appSchemaStr = localStorage.getItem('lce-dev-store');
const appSchema = JSON.parse(appSchemaStr || '');
const idx = appSchema.componentsTree.findIndex(
(page: any, idx: number) => (page.fileName || `page${idx}`) === pageId,
(page: any, index: number) => (page.fileName || `page${index}`) === pageId,
);
const schema = appSchema.componentsTree[idx];
return schema;

View File

@ -2,7 +2,7 @@ import logo from '@ali/lowcode-plugin-sample-logo';
import samplePreview from '@ali/lowcode-plugin-sample-preview';
import undoRedo from '@ali/lowcode-plugin-undo-redo';
import componentsPane from '@ali/lowcode-plugin-components-pane';
import outline, { OutlinePane } from '@ali/lowcode-plugin-outline-pane';
import outline from '@ali/lowcode-plugin-outline-pane';
import zhEn from '@ali/lowcode-plugin-zh-en';
import eventBindDialog from '@ali/lowcode-plugin-event-bind-dialog';
import variableBindDialog from '@ali/lowcode-plugin-variable-bind-dialog';

View File

@ -123,9 +123,6 @@ export default {
const simulatorUrl = [
'https://dev.g.alicdn.com/ali-lowcode/ali-lowcode-engine/0.9.50/react-simulator-renderer.css',
'https://dev.g.alicdn.com/ali-lowcode/ali-lowcode-engine/0.9.50/react-simulator-renderer.js',
// for debug simulator
// 'http://localhost:3333/js/react-simulator-renderer.js',
];
editor.set('simulatorUrl', simulatorUrl);
// editor.set('renderEnv', 'rax');

View File

@ -1,5 +1,5 @@
import { render } from 'react-dom';
import GeneralWorkbench, { editor } from '@ali/lowcode-editor-preset-general';
import GeneralWorkbench from '@ali/lowcode-editor-preset-general';
import config from './config';
import components from './components';
import './global.scss';

View File

@ -28,7 +28,7 @@ const Codeout = ({ editor }: PluginProps) => {
const designer = editor.get(Designer);
if (designer) {
const assets = editor.get('assets') as { components: BasicSection[] };
const components = assets.components;
const { components } = assets;
const componentsMap = components
.filter((c) => !!c.npm)

View File

@ -22,10 +22,7 @@ interface BasicSection {
const Codeout = ({ editor }: PluginProps) => {
const handleSaveClick = () => {
debugger;
let schema = editor.get('designer').project.getSchema();
const schema = editor.get('designer').project.getSchema();
console.log(schema);

View File

@ -9,5 +9,5 @@ declare module '@ali/ve-page-history';
declare module '@ali/ve-i18n-manage-pane';
declare module '@ali/ve-action-pane';
declare module '@ali/vu-legao-design-fetch-context';
declare module "@ali/vu-function-parser";
declare module "compare-versions";
declare module '@ali/vu-function-parser';
declare module 'compare-versions';

View File

@ -0,0 +1,16 @@
module.exports = {
extends: '../../.eslintrc.js',
rules: {
'react/no-multi-comp': 0,
'no-unused-expressions': 1,
'implicit-arrow-linebreak': 1,
'no-nested-ternary': 1,
'no-mixed-operators': 1,
'@typescript-eslint/no-parameter-properties': 1,
'@typescript-eslint/ban-types': 1,
'no-shadow': 1,
'no-prototype-builtins': 1,
'no-useless-constructor': 1,
'no-empty-function': 1,
}
}

View File

@ -56,10 +56,10 @@ export class BorderDetecting extends Component<{ host: BuiltinSimulatorHost }> {
}
@computed get current() {
const host = this.props.host;
const { host } = this.props;
const doc = host.document;
const selection = doc.selection;
const current = host.designer.detecting.current;
const { selection } = doc;
const { current } = host.designer.detecting;
if (!current || current.document !== doc || selection.has(current.id)) {
return null;
}
@ -67,8 +67,8 @@ export class BorderDetecting extends Component<{ host: BuiltinSimulatorHost }> {
}
render() {
const host = this.props.host;
const current = this.current;
const { host } = this.props;
const { current } = this;
if (!current || host.viewport.scrolling || host.liveEditing.editing) {
return null;
}

View File

@ -23,7 +23,7 @@ export default class BoxResizing extends Component<{ host: BuiltinSimulatorHost
if (doc.suspensed) {
return null;
}
const selection = doc.selection;
const { selection } = doc;
return this.dragging ? selection.getTopNodes() : selection.getNodes();
}
@ -37,7 +37,7 @@ export default class BoxResizing extends Component<{ host: BuiltinSimulatorHost
}
render() {
const selecting = this.selecting;
const { selecting } = this;
if (!selecting || selecting.length < 1) {
// DIRTY FIX, recore has a bug!
return <Fragment />;
@ -79,7 +79,7 @@ export class BoxResizingForNode extends Component<{ host: BuiltinSimulatorHost;
render() {
const { instances } = this;
const { node } = this.props;
const designer = this.host.designer;
const { designer } = this.host;
if (!instances || instances.length < 1) {
return null;
@ -112,8 +112,11 @@ export class BoxResizingInstance extends Component<{
}> {
// private outline: any;
private willUnbind: () => any;
private outlineRight: any;
private outlineLeft: any;
private dragEngine: DragResizeEngine;
constructor(props: any) {

View File

@ -59,6 +59,7 @@ class Toolbar extends Component<{ observed: OffsetObserver }> {
shouldComponentUpdate() {
return false;
}
render() {
const { observed } = this.props;
const { height, width } = observed.viewport;
@ -169,7 +170,7 @@ export class BorderSelectingForNode extends Component<{ host: BuiltinSimulatorHo
render() {
const { instances } = this;
const { node } = this.props;
const designer = this.host.designer;
const { designer } = this.host;
if (!instances || instances.length < 1) {
return null;
@ -206,7 +207,7 @@ export class BorderSelecting extends Component<{ host: BuiltinSimulatorHost }> {
if (doc.suspensed || this.host.liveEditing.editing) {
return null;
}
const selection = doc.selection;
const { selection } = doc;
return this.dragging ? selection.getTopNodes() : selection.getNodes();
}
@ -215,7 +216,7 @@ export class BorderSelecting extends Component<{ host: BuiltinSimulatorHost }> {
}
render() {
const selecting = this.selecting;
const { selecting } = this;
if (!selecting || selecting.length < 1) {
return null;
}

View File

@ -1,7 +1,7 @@
import { EventEmitter } from 'events';
import { ISimulatorHost, isSimulatorHost } from '../../simulator';
import { ISimulatorHost } from '../../simulator';
import { Designer, Point } from '../../designer';
import { setNativeSelection, cursor } from '@ali/lowcode-utils';
import { cursor } from '@ali/lowcode-utils';
// import Cursor from './cursor';
// import Pages from './pages';
@ -19,7 +19,7 @@ function makeEventsHandler(
// }
docs.add(sourceDoc);
// if (sourceDoc !== topDoc || isDragEvent(boostEvent)) {
sensors.forEach((sim) => {
sensors.forEach(sim => {
const sdoc = sim.contentDocument;
if (sdoc) {
docs.add(sdoc);
@ -28,32 +28,21 @@ function makeEventsHandler(
// }
return (handle: (sdoc: Document) => void) => {
docs.forEach((doc) => handle(doc));
docs.forEach(doc => handle(doc));
};
}
// 拖动缩放
export default class DragResizeEngine {
private emitter: EventEmitter;
private dragResizing = false;
constructor(readonly designer: Designer) {
constructor(designer: Designer) {
this.designer = designer;
this.emitter = new EventEmitter();
}
private getMasterSensors(): ISimulatorHost[] {
return this.designer.project.documents
.map((doc) => {
// TODO: not use actived,
if (doc.actived && doc.simulator?.sensorAvailable) {
return doc.simulator;
}
return null;
})
.filter(Boolean) as any;
}
isDragResizing() {
return this.dragResizing;
}
@ -83,14 +72,12 @@ export default class DragResizeEngine {
const masterSensors = this.getMasterSensors();
const createResizeEvent = (e: MouseEvent | DragEvent): Point => {
const evt: any = {};
const sourceDocument = e.view?.document;
if (!sourceDocument || sourceDocument === document) {
return e;
}
const srcSim = masterSensors.find((sim) => sim.contentDocument === sourceDocument);
const srcSim = masterSensors.find(sim => sim.contentDocument === sourceDocument);
if (srcSim) {
return srcSim.viewport.toGlobalPoint(e);
}
@ -99,7 +86,7 @@ export default class DragResizeEngine {
const over = (e: MouseEvent) => {
const handleEvents = makeEventsHandler(e, masterSensors);
handleEvents((doc) => {
handleEvents(doc => {
doc.removeEventListener('mousemove', move, true);
doc.removeEventListener('mouseup', over, true);
});
@ -114,7 +101,7 @@ export default class DragResizeEngine {
node = boost(e);
startEvent = createResizeEvent(e);
const handleEvents = makeEventsHandler(e, masterSensors);
handleEvents((doc) => {
handleEvents(doc => {
doc.addEventListener('mousemove', move, true);
doc.addEventListener('mouseup', over, true);
});
@ -136,7 +123,9 @@ export default class DragResizeEngine {
};
}
onResize(func: (e: MouseEvent, direction: string, node: any, moveX: number, moveY: number) => any) {
onResize(
func: (e: MouseEvent, direction: string, node: any, moveX: number, moveY: number) => any,
) {
this.emitter.on('resize', func);
return () => {
this.emitter.removeListener('resize', func);
@ -149,6 +138,18 @@ export default class DragResizeEngine {
this.emitter.removeListener('resizeEnd', func);
};
}
private getMasterSensors(): ISimulatorHost[] {
return this.designer.project.documents
.map(doc => {
// TODO: not use actived,
if (doc.actived && doc.simulator?.sensorAvailable) {
return doc.simulator;
}
return null;
})
.filter(Boolean) as any;
}
}
// new DragResizeEngine();

View File

@ -15,7 +15,7 @@ export class BemTools extends Component<{ host: BuiltinSimulatorHost }> {
}
render() {
const host = this.props.host;
const { host } = this.props;
const { scrollX, scrollY, scale } = host.viewport;
return (
<div className="lc-bem-tools" style={{ transform: `translate(${-scrollX * scale}px,${-scrollY * scale}px)` }}>

View File

@ -1,15 +1,14 @@
import { Component } from 'react';
import { computed, observer } from '@ali/lowcode-editor-core';
import { SimulatorContext } from '../context';
import { observer } from '@ali/lowcode-editor-core';
import { BuiltinSimulatorHost } from '../host';
import {
DropLocation,
Rect,
isLocationChildrenDetail,
LocationChildrenDetail,
isVertical
isVertical,
} from '../../designer';
import { ISimulatorHost, } from '../../simulator';
import { ISimulatorHost } from '../../simulator';
import { ParentalNode } from '../../document';
import './insertion.less';

View File

@ -8,8 +8,8 @@ import {
isAssetItem,
AssetType,
assetItem,
} from '@ali/lowcode-utils';
import { isCSSUrl } from '@ali/lowcode-utils';
isCSSUrl } from '@ali/lowcode-utils';
import { BuiltinSimulatorRenderer } from './renderer';
export function createSimulator(
@ -65,7 +65,7 @@ export function createSimulator(
const styleFrags = Object.keys(styles)
.map((key) => {
return styles[key].join('\n') + `<meta level="${key}" />`;
return `${styles[key].join('\n') }<meta level="${key}" />`;
})
.join('');
const scriptFrags = Object.keys(scripts)

View File

@ -2,7 +2,6 @@ import { Component } from 'react';
import { observer } from '@ali/lowcode-editor-core';
import { BuiltinSimulatorHost, BuiltinSimulatorProps } from './host';
import { DocumentModel } from '../document';
import { SimulatorContext } from './context';
import { BemTools } from './bem-tools';
import './host.less';
@ -22,25 +21,29 @@ type SimulatorHostProps = BuiltinSimulatorProps & {
export class BuiltinSimulatorHostView extends Component<SimulatorHostProps> {
readonly host: BuiltinSimulatorHost;
constructor(props: any) {
super(props);
const { documentContext } = this.props;
this.host = (documentContext.simulator as BuiltinSimulatorHost) || new BuiltinSimulatorHost(documentContext);
this.host.setProps(this.props);
}
shouldComponentUpdate(nextProps: BuiltinSimulatorProps) {
this.host.setProps(nextProps);
return false;
}
componentDidMount() {
if (this.props.onMount) {
this.props.onMount(this.host);
}
}
render() {
return (
<div className="lc-simulator">
{/*progressing.visible ? <PreLoaderView /> : null*/}
{/* progressing.visible ? <PreLoaderView /> : null */}
<Canvas host={this.host} />
</div>
);
@ -73,7 +76,7 @@ class Canvas extends Component<{ host: BuiltinSimulatorHost }> {
class Content extends Component<{ host: BuiltinSimulatorHost }> {
render() {
const sim = this.props.host;
const viewport = sim.viewport;
const { viewport } = sim;
const frameStyle = {
transform: `scale(${viewport.scale})`,
height: viewport.contentHeight,

View File

@ -60,6 +60,7 @@ export interface BuiltinSimulatorProps {
const defaultSimulatorUrl = (() => {
const publicPath = getPublicPath();
let urls;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, prefix = '', dev] = /^(.+?)(\/js)?\/?$/.exec(publicPath) || [];
if (dev) {
urls = [`${prefix}/css/react-simulator-renderer.css`, `${prefix}/js/react-simulator-renderer.js`];
@ -74,6 +75,7 @@ const defaultSimulatorUrl = (() => {
const defaultRaxSimulatorUrl = (() => {
const publicPath = getPublicPath();
let urls;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_, prefix = '', dev] = /^(.+?)(\/js)?\/?$/.exec(publicPath) || [];
if (dev) {
urls = [`${prefix}/css/rax-simulator-renderer.css`, `${prefix}/js/rax-simulator-renderer.js`];
@ -144,18 +146,21 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
}
@obx.ref _props: BuiltinSimulatorProps = {};
/**
* @see ISimulator
*/
setProps(props: BuiltinSimulatorProps) {
this._props = props;
}
set(key: string, value: any) {
this._props = {
...this._props,
[key]: value,
};
}
get(key: string): any {
return this._props[key];
}
@ -173,6 +178,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
}
readonly viewport = new Viewport();
readonly scroller = this.designer.createScroller(this.viewport);
mountViewport(viewport: Element | null) {
@ -180,16 +186,19 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
}
@obx.ref private _contentWindow?: Window;
get contentWindow() {
return this._contentWindow;
}
@obx.ref private _contentDocument?: Document;
get contentDocument() {
return this._contentDocument;
}
private _renderer?: BuiltinSimulatorRenderer;
get renderer() {
return this._renderer;
}
@ -203,6 +212,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
readonly libraryMap: { [key: string]: string } = {};
private _iframe?: HTMLIFrameElement;
async mountContentFrame(iframe: HTMLIFrameElement | null) {
if (!iframe || this._iframe === iframe) {
return;
@ -279,8 +289,8 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
setupDragAndClick() {
const documentModel = this.document;
const selection = documentModel.selection;
const designer = documentModel.designer;
const { selection } = documentModel;
const { designer } = documentModel;
const doc = this.contentDocument!;
// TODO: think of lock when edit a node
@ -312,7 +322,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
const checkSelect = (e: MouseEvent) => {
doc.removeEventListener('mouseup', checkSelect, true);
if (!isShaken(downEvent, e)) {
const id = node.id;
const { id } = node;
designer.activeTracker.track({ node, instance: nodeInst?.instance });
if (isMulti && !isRootNode(node) && selection.has(id)) {
selection.remove(id);
@ -411,12 +421,13 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
}
private disableHovering?: () => void;
/**
*
*/
setupDetecting() {
const doc = this.contentDocument!;
const detecting = this.document.designer.detecting;
const { detecting } = this.document.designer;
const hover = (e: MouseEvent) => {
if (!detecting.enable) {
return;
@ -448,6 +459,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
}
readonly liveEditing = new LiveEditing();
setupLiveEditing() {
const doc = this.contentDocument!;
// cause edit
@ -493,11 +505,9 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
this.disableHovering();
}
// sleep some autorun reaction
} else {
} else if (!this.disableHovering) {
// weekup some autorun reaction
if (!this.disableHovering) {
this.setupDetecting();
}
this.setupDetecting();
}
}
@ -567,6 +577,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
}
@obx.val private instancesMap = new Map<string, ComponentInstance[]>();
setInstance(id: string, instances: ComponentInstance[] | null) {
if (instances == null) {
this.instancesMap.delete(id);
@ -585,14 +596,14 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
/**
* @see ISimulator
*/
getComponentInstanceId(instance: ComponentInstance) {
getComponentInstanceId(/* instance: ComponentInstance */) {
throw new Error('Method not implemented.');
}
/**
* @see ISimulator
*/
getComponentContext(node: Node): object {
getComponentContext(/* node: Node */): any {
throw new Error('Method not implemented.');
}
@ -627,7 +638,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
const elems = elements.slice();
let rects: DOMRect[] | undefined;
let last: { x: number; y: number; r: number; b: number } | undefined;
let computed = false;
let _computed = false;
while (true) {
if (!rects || rects.length < 1) {
const elem = elems.pop();
@ -654,26 +665,26 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
}
if (rect.left < last.x) {
last.x = rect.left;
computed = true;
_computed = true;
}
if (rect.top < last.y) {
last.y = rect.top;
computed = true;
_computed = true;
}
if (rect.right > last.r) {
last.r = rect.right;
computed = true;
_computed = true;
}
if (rect.bottom > last.b) {
last.b = rect.bottom;
computed = true;
_computed = true;
}
}
if (last) {
const r: any = new DOMRect(last.x, last.y, last.r - last.x, last.b - last.y);
r.elements = elements;
r.computed = computed;
r.computed = _computed;
return r;
}
@ -719,10 +730,11 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
}
private tryScrollAgain: number | null = null;
/**
* @see ISimulator
*/
scrollToNode(node: Node, detail?: any, tryTimes = 0) {
scrollToNode(node: Node, detail?: any/* , tryTimes = 0 */) {
this.tryScrollAgain = null;
if (this.sensing) {
// actived sensor
@ -744,7 +756,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
if (y < bounds.top || y > bounds.bottom) {
scroll = true;
}
}*/
} */
} else {
/*
const rect = this.document.computeRect(node);
@ -768,7 +780,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
if (rect.width > width ? rect.left > right || rect.right < left : rect.left < left || rect.right > right) {
opt.left = Math.min(rect.left + rect.width / 2 + sl - left - width / 2, scrollWidth - width);
scroll = true;
}*/
} */
}
if (scroll && this.scroller) {
@ -783,18 +795,21 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
setNativeSelection(enableFlag: boolean) {
this.renderer?.setNativeSelection(enableFlag);
}
/**
* @see ISimulator
*/
setDraggingState(state: boolean) {
this.renderer?.setDraggingState(state);
}
/**
* @see ISimulator
*/
setCopyState(state: boolean) {
this.renderer?.setCopyState(state);
}
/**
* @see ISimulator
*/
@ -803,6 +818,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
}
private _sensorAvailable = true;
/**
* @see ISensor
*/
@ -851,6 +867,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
}
private sensing = false;
/**
* @see ISensor
*/
@ -905,7 +922,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
return null;
}
const children = container.children;
const { children } = container;
const detail: LocationChildrenDetail = {
type: LocationDetailType.Children,
@ -916,7 +933,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
const locationData = {
target: container,
detail,
source: 'simulator' + this.document.id,
source: `simulator${ this.document.id}`,
event: e,
};
@ -934,7 +951,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
index: 0,
valid: true,
},
source: 'simulator' + this.document.id,
source: `simulator${ this.document.id}`,
event: e,
});
}
@ -956,7 +973,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
const instances = this.getComponentInstances(node);
const inst = instances
? instances.length > 1
? instances.find((inst) => this.getClosestNodeInstance(inst, container.id)?.instance === containerInstance)
? instances.find((_inst) => this.getClosestNodeInstance(_inst, container.id)?.instance === containerInstance)
: instances[0]
: null;
const rect = inst ? this.computeComponentInstanceRect(inst, node.componentMeta.rootSelector) : null;
@ -1014,7 +1031,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
if (!row && nearDistance !== 0) {
const edgeDistance = distanceToEdge(e as any, edge);
if (edgeDistance.distance < nearDistance!) {
const nearAfter = edgeDistance.nearAfter;
const { nearAfter } = edgeDistance;
if (minTop == null) {
minTop = edge.top;
}
@ -1077,7 +1094,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
// TODO: renderengine support pointerEvents: none for acceleration
const drillDownExcludes = new Set<Node>();
if (isDragNodeObject(dragObject)) {
const nodes = dragObject.nodes;
const { nodes } = dragObject;
let i = nodes.length;
let p: any = container;
while (i-- > 0) {
@ -1139,7 +1156,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
container = upward;
upward = null;
}
}*/
} */
container = res;
upward = null;
}
@ -1147,7 +1164,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
return null;
}
isAcceptable(container: ParentalNode): boolean {
isAcceptable(/* container: ParentalNode */): boolean {
return false;
/*
const meta = container.componentMeta;
@ -1162,7 +1179,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
/**
*
*/
handleAccept({ container, instance }: DropContainer, e: LocateEvent) {
handleAccept({ container/* , instance */ }: DropContainer, e: LocateEvent) {
const { dragObject } = e;
if (isRootNode(container)) {
return this.document.checkDropTarget(container, dragObject as any);
@ -1210,7 +1227,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
/**
*
*/
getNearByContainer(container: ParentalNode, e: LocateEvent) {
getNearByContainer(/* container: ParentalNode, e: LocateEvent */) {
/*
const children = container.children;
if (!children || children.length < 1) {

View File

@ -34,13 +34,15 @@ function addLiveEditingSpecificRule(rule: SpecificRule) {
export class LiveEditing {
static addLiveEditingSpecificRule = addLiveEditingSpecificRule;
static addLiveEditingSaveHandler = addLiveEditingSaveHandler;
@obx.ref private _editing: Prop | null = null;
apply(target: EditingTarget) {
const { node, event, rootElement } = target;
const targetElement = event.target as HTMLElement;
const liveTextEditing = node.componentMeta.liveTextEditing;
const { liveTextEditing } = node.componentMeta;
const editor = globalContext.get(Editor);
const npm = node?.componentMeta?.npm;
@ -64,14 +66,14 @@ export class LiveEditing {
return false;
}
setterPropElement = queryPropElement(rootElement, targetElement, config.selector);
return setterPropElement ? true : false;
return !!setterPropElement;
});
propTarget = matched?.propTarget;
}
} else {
specificRules.some((rule) => {
matched = rule(target);
return matched ? true : false;
return !!matched;
});
if (matched) {
propTarget = matched.propTarget;
@ -79,15 +81,15 @@ export class LiveEditing {
}
}
if (!propTarget) {
// 自动纯文本编辑满足一下情况:
// 1. children 内容都是 Leaf 且都是文本(一期)
// 2. DOM 节点是单层容器,子集都是文本节点 (已满足)
const isAllText = node.children?.every(item => {
return item.isLeaf() && item.getProp('children')?.type === 'literal';
});
// TODO:
}
// if (!propTarget) {
// // 自动纯文本编辑满足一下情况:
// // 1. children 内容都是 Leaf 且都是文本(一期)
// // 2. DOM 节点是单层容器,子集都是文本节点 (已满足)
// const isAllText = node.children?.every(item => {
// return item.isLeaf() && item.getProp('children')?.type === 'literal';
// });
// // TODO:
// }
if (propTarget && setterPropElement) {
const prop = node.getProp(propTarget, true)!;
@ -119,8 +121,10 @@ export class LiveEditing {
console.info(e.code);
switch (e.code) {
case 'Enter':
break;
// TODO: check is richtext?
case 'Escape':
break;
case 'Tab':
setterPropElement?.blur();
}
@ -128,7 +132,7 @@ export class LiveEditing {
// enter
// tab
};
const focusout = (e: FocusEvent) => {
const focusout = (/* e: FocusEvent */) => {
this.saveAndDispose();
};
setterPropElement.addEventListener('focusout', focusout);
@ -147,8 +151,6 @@ export class LiveEditing {
// TODO: process enter | esc events & joint the FocusTracker
// TODO: upward testing for b/i/a html elements
}
get editing() {
@ -156,7 +158,9 @@ export class LiveEditing {
}
private _dispose?: () => void;
private _save?: () => void;
saveAndDispose() {
if (this._save) {
this._save();

View File

@ -58,17 +58,20 @@ export default class InstanceNodeSelector extends React.Component<IProps, IState
});
}
};
onMouseOver = (node: Node) => (_: any, flag = true) => {
if (node && typeof node.hover === 'function') {
node.hover(flag);
}
};
onMouseOut = (node: Node) => (_: any, flag = false) => {
if (node && typeof node.hover === 'function') {
node.hover(flag);
}
};
renderNodes = (node: Node) => {
renderNodes = (/* node: Node */) => {
const nodes = this.state.parentNodes || [];
const children = nodes.map((node, key) => {
return (

View File

@ -21,16 +21,19 @@ export type RendererConsumer<T> = (renderer: BuiltinSimulatorRenderer, data: T)
export default class ResourceConsumer<T = any> {
private emitter = new EventEmitter();
@obx.ref private _data: T | typeof UNSET = UNSET;
private _providing?: () => void;
private _consuming?: () => void;
constructor(provider: () => T, private consumer?: RendererConsumer<T>) {
this._providing = autorun(() => {
this._data = provider();
});
}
private _consuming?: () => void;
consume(consumerOrRenderer: BuiltinSimulatorRenderer | ((data: T) => any)) {
if (this._consuming) {
return;
@ -72,6 +75,7 @@ export default class ResourceConsumer<T = any> {
}
private _firstConsumed = false;
private resovleFirst?: () => void;
waitFirstConsume(): Promise<any> {

View File

@ -16,6 +16,7 @@ export const primitiveTypes = [
'any',
];
// eslint-disable-next-line @typescript-eslint/ban-types
function makeRequired(propType: any, lowcodeType: string | object) {
function lowcodeCheckTypeIsRequired(...rest: any[]) {
return propType.isRequired(...rest);
@ -32,6 +33,7 @@ function makeRequired(propType: any, lowcodeType: string | object) {
return lowcodeCheckTypeIsRequired;
}
// eslint-disable-next-line @typescript-eslint/ban-types
function define(propType: any = PropTypes.any, lowcodeType: string | object = {}) {
if (!propType._inner && propType.name !== 'lowcodeCheckType') {
propType.lowcodeType = lowcodeType;
@ -136,7 +138,7 @@ export function parseProps(component: any): PropConfig[] {
Object.keys(propTypes).forEach(key => {
const propTypeItem = propTypes[key];
const defaultValue = defaultProps[key];
const lowcodeType = propTypeItem.lowcodeType;
const { lowcodeType } = propTypeItem;
if (lowcodeType) {
result[key] = {
name: key,

Some files were not shown because too many files have changed in this diff Show More