mirror of
https://github.com/alibaba/lowcode-engine.git
synced 2026-03-12 02:46:08 +00:00
Merge branch 'release/1.0.0' into refactor/merge-rax-generator
This commit is contained in:
commit
533e09acb1
@ -1,9 +1,9 @@
|
|||||||
# http://editorconfig.org
|
|
||||||
root = true
|
root = true
|
||||||
|
|
||||||
[*]
|
[*]
|
||||||
indent_style = space
|
indent_style = space
|
||||||
indent_size = 2
|
indent_size = 2
|
||||||
|
end_of_line = lf
|
||||||
charset = utf-8
|
charset = utf-8
|
||||||
trim_trailing_whitespace = true
|
trim_trailing_whitespace = true
|
||||||
insert_final_newline = true
|
insert_final_newline = true
|
||||||
|
|||||||
@ -1,7 +1,18 @@
|
|||||||
.idea/
|
# 忽略目录
|
||||||
.vscode/
|
|
||||||
build/
|
|
||||||
.*
|
|
||||||
~*
|
|
||||||
node_modules
|
node_modules
|
||||||
test-cases
|
test-cases
|
||||||
|
test
|
||||||
|
output
|
||||||
|
build
|
||||||
|
dist
|
||||||
|
demo
|
||||||
|
es
|
||||||
|
lib
|
||||||
|
.*
|
||||||
|
~*
|
||||||
|
test-cases
|
||||||
|
|
||||||
|
# 忽略文件
|
||||||
|
**/*.min.js
|
||||||
|
**/*-min.js
|
||||||
|
**/*.bundle.js
|
||||||
|
|||||||
3
.eslintrc.js
Normal file
3
.eslintrc.js
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
module.exports = {
|
||||||
|
extends: 'eslint-config-ali/typescript/react',
|
||||||
|
};
|
||||||
@ -1,4 +0,0 @@
|
|||||||
**/test/**/*.ts
|
|
||||||
**/test/**/*.js
|
|
||||||
**/template/**/*.template
|
|
||||||
**/template/**/*.tpl
|
|
||||||
@ -1,8 +0,0 @@
|
|||||||
{
|
|
||||||
"trailingComma": "all",
|
|
||||||
"tabWidth": 2,
|
|
||||||
"semi": true,
|
|
||||||
"singleQuote": true,
|
|
||||||
"printWidth": 120,
|
|
||||||
"arrowParens": "always"
|
|
||||||
}
|
|
||||||
7
.prettierrc.js
Normal file
7
.prettierrc.js
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
module.exports = {
|
||||||
|
printWidth: 100,
|
||||||
|
tabWidth: 2,
|
||||||
|
semi: true,
|
||||||
|
singleQuote: true,
|
||||||
|
trailingComma: 'all',
|
||||||
|
};
|
||||||
9
.stylelintignore
Normal file
9
.stylelintignore
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
# 忽略目录
|
||||||
|
node_modules/
|
||||||
|
build/
|
||||||
|
dist/
|
||||||
|
|
||||||
|
# 忽略文件
|
||||||
|
**/*.min.css
|
||||||
|
**/*-min.css
|
||||||
|
**/*.bundle.css
|
||||||
3
.stylelintrc.js
Normal file
3
.stylelintrc.js
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
module.exports = {
|
||||||
|
extends: 'stylelint-config-ali',
|
||||||
|
};
|
||||||
11
README.md
11
README.md
@ -1,22 +1,20 @@
|
|||||||
## Ali Lowcode Engine(阿里低代码引擎)
|
## Ali Lowcode Engine(阿里低代码引擎)
|
||||||
|
|
||||||
[Lerna](https://github.com/lerna/lerna) + [TS](https://www.typescriptlang.org/)
|
|
||||||
|
|
||||||
## 开发
|
## 开发
|
||||||
|
|
||||||
#### 创建新包:
|
#### 创建新包
|
||||||
|
|
||||||
- `./scripts/create.sh <package-name>`
|
- `./scripts/create.sh <package-name>`
|
||||||
|
|
||||||
#### 跑起来:
|
#### 运行示例
|
||||||
|
|
||||||
- `npm run setup`
|
- `npm run setup`
|
||||||
- `npm start`
|
- `npm start`
|
||||||
|
|
||||||
#### 开发提交:
|
#### 开发提交
|
||||||
|
|
||||||
- `git add <your-files>`
|
- `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` 等)会放到工程顶层
|
- `packages` 工程里一些开发时公共依赖(比如:`typescript`、`ava` 等)会放到工程顶层
|
||||||
- 工程里的 `.md`、`test/` 等文件修改不会产生新的发布
|
- 工程里的 `.md`、`test/` 等文件修改不会产生新的发布
|
||||||
- 当工程里存在多个 ts 文件的目录时,最终产生的文件会按文件夹形式放到 `lib` 下
|
- 当工程里存在多个 ts 文件的目录时,最终产生的文件会按文件夹形式放到 `lib` 下
|
||||||
|
|||||||
3
commitlint.config.js
Normal file
3
commitlint.config.js
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
module.exports = {
|
||||||
|
extends: ['ali'],
|
||||||
|
};
|
||||||
36
package.json
36
package.json
@ -12,40 +12,34 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "./scripts/build.sh",
|
"build": "./scripts/build.sh",
|
||||||
"clean": "rm -rf ./packages/*/lib ./packages/*/es ./packages/*/dist ./packages/*/build",
|
"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",
|
"pub": "lerna publish --force-publish --cd-version prepatch",
|
||||||
"setup": "./scripts/setup.sh",
|
"setup": "./scripts/setup.sh",
|
||||||
"start": "./scripts/start.sh",
|
"start": "./scripts/start.sh",
|
||||||
"start:server": "./scripts/start-server.sh",
|
"start:server": "./scripts/start-server.sh",
|
||||||
"test": "lerna run test --stream",
|
"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": {
|
"husky": {
|
||||||
"*.{tsx,ts}": [
|
"hooks": {
|
||||||
"eslint --quiet",
|
"pre-commit": "xima exec lint-staged",
|
||||||
"git add"
|
"commit-msg": "xima exec commitlint -E HUSKY_GIT_PARAMS"
|
||||||
]
|
|
||||||
},
|
|
||||||
"config": {
|
|
||||||
"commitizen": {
|
|
||||||
"path": "node_modules/cz-conventional-changelog"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"lint-staged": {
|
||||||
|
"**/*.{css,scss,less}": "xima exec stylelint",
|
||||||
|
"**/*.{js,jsx,ts,tsx}": "xima exec eslint"
|
||||||
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@ali/lowcode-config": "^2.0.5",
|
|
||||||
"ava": "^1.0.1",
|
"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",
|
"lerna": "^2.11.0",
|
||||||
"lint-staged": "^8.1.0",
|
|
||||||
"prettier": "^1.15.3",
|
|
||||||
"ts-node": "^7.0.1",
|
"ts-node": "^7.0.1",
|
||||||
"tslib": "^1.9.3",
|
"tslib": "^1.9.3",
|
||||||
"typescript": "^3.2.2"
|
"typescript": "^3.2.2",
|
||||||
|
"xima": "^0.2.15"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=10.0.0"
|
"node": ">=10.0.0"
|
||||||
|
|||||||
@ -59,7 +59,7 @@ function main() {
|
|||||||
|
|
||||||
builder.generateProject(schemaJson).then((result) => {
|
builder.generateProject(schemaJson).then((result) => {
|
||||||
displayResultInConsole(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;
|
return result;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -187,7 +187,7 @@ function exportProject() {
|
|||||||
|
|
||||||
builder.generateProject(schemaJson).then((result) => {
|
builder.generateProject(schemaJson).then((result) => {
|
||||||
displayResultInConsole(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;
|
return result;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
/// <reference types="node" />
|
// / <reference types="node" />
|
||||||
|
|
||||||
declare module '@ali/my-prettier' {
|
declare module '@ali/my-prettier' {
|
||||||
function format(text: string, type: string): string;
|
function format(text: string, type: string): string;
|
||||||
|
|||||||
@ -5,7 +5,7 @@ export default class Builder implements ICodeBuilder {
|
|||||||
|
|
||||||
private generators: { [key: string]: CodeGeneratorFunction<ChunkContent> } = {
|
private generators: { [key: string]: CodeGeneratorFunction<ChunkContent> } = {
|
||||||
[ChunkType.STRING]: (str: string) => str, // no-op for string chunks
|
[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[] = []) {
|
constructor(chunkDefinitions: ICodeChunk[] = []) {
|
||||||
@ -49,14 +49,17 @@ export default class Builder implements ICodeBuilder {
|
|||||||
const { type, content, name } = unprocessedChunks[indexToRemove];
|
const { type, content, name } = unprocessedChunks[indexToRemove];
|
||||||
const compiledContent = this.generateByType(type, content);
|
const compiledContent = this.generateByType(type, content);
|
||||||
if (compiledContent) {
|
if (compiledContent) {
|
||||||
resultingString.push(compiledContent + '\n');
|
resultingString.push(`${compiledContent }\n`);
|
||||||
}
|
}
|
||||||
|
|
||||||
unprocessedChunks.splice(indexToRemove, 1);
|
unprocessedChunks.splice(indexToRemove, 1);
|
||||||
if (!unprocessedChunks.some((ch) => ch.name === name)) {
|
if (!unprocessedChunks.some((ch) => ch.name === name)) {
|
||||||
unprocessedChunks.forEach(
|
unprocessedChunks.forEach(
|
||||||
// remove the processed chunk from all the linkAfter arrays from the remaining chunks
|
// remove the processed chunk from all the linkAfter arrays from the remaining chunks
|
||||||
(ch) => (ch.linkAfter = ch.linkAfter.filter((after) => after !== name)),
|
(ch) => {
|
||||||
|
// eslint-disable-next-line no-param-reassign
|
||||||
|
ch.linkAfter = ch.linkAfter.filter((after) => after !== name);
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -48,7 +48,7 @@ export function createModuleBuilder(
|
|||||||
|
|
||||||
if (options.postProcessors.length > 0) {
|
if (options.postProcessors.length > 0) {
|
||||||
files = files.map((file) => {
|
files = files.map((file) => {
|
||||||
let content = file.content;
|
let { content } = file;
|
||||||
const type = file.ext;
|
const type = file.ext;
|
||||||
options.postProcessors.forEach((processer) => {
|
options.postProcessors.forEach((processer) => {
|
||||||
content = processer(content, type);
|
content = processer(content, type);
|
||||||
|
|||||||
@ -39,7 +39,9 @@ function getDirFromRoot(root: ResultDir, path: string[]): ResultDir {
|
|||||||
|
|
||||||
export class ProjectBuilder implements IProjectBuilder {
|
export class ProjectBuilder implements IProjectBuilder {
|
||||||
private template: IProjectTemplate;
|
private template: IProjectTemplate;
|
||||||
|
|
||||||
private plugins: IProjectPlugins;
|
private plugins: IProjectPlugins;
|
||||||
|
|
||||||
private postProcessors: PostProcessor[];
|
private postProcessors: PostProcessor[];
|
||||||
|
|
||||||
constructor({
|
constructor({
|
||||||
|
|||||||
@ -4,14 +4,7 @@
|
|||||||
*/
|
*/
|
||||||
import changeCase from 'change-case';
|
import changeCase from 'change-case';
|
||||||
import { UtilItem, NodeDataType, NodeSchema, ContainerSchema, ProjectSchema, PropsMap } from '@ali/lowcode-types';
|
import { UtilItem, NodeDataType, NodeSchema, ContainerSchema, ProjectSchema, PropsMap } from '@ali/lowcode-types';
|
||||||
import { IPageMeta } from '../types';
|
import { IPageMeta,
|
||||||
|
|
||||||
import { SUPPORT_SCHEMA_VERSION_LIST } from '../const';
|
|
||||||
|
|
||||||
import { handleSubNodes } from '../utils/schema';
|
|
||||||
import { uniqueArray } from '../utils/common';
|
|
||||||
|
|
||||||
import {
|
|
||||||
CodeGeneratorError,
|
CodeGeneratorError,
|
||||||
CompatibilityError,
|
CompatibilityError,
|
||||||
DependencyType,
|
DependencyType,
|
||||||
@ -26,6 +19,12 @@ import {
|
|||||||
IRouterInfo,
|
IRouterInfo,
|
||||||
} from '../types';
|
} from '../types';
|
||||||
|
|
||||||
|
import { SUPPORT_SCHEMA_VERSION_LIST } from '../const';
|
||||||
|
|
||||||
|
import { handleSubNodes } from '../utils/schema';
|
||||||
|
import { uniqueArray } from '../utils/common';
|
||||||
|
|
||||||
|
|
||||||
const defaultContainer: IContainerInfo = {
|
const defaultContainer: IContainerInfo = {
|
||||||
containerType: 'Component',
|
containerType: 'Component',
|
||||||
componentName: 'Component',
|
componentName: 'Component',
|
||||||
@ -100,7 +99,7 @@ class SchemaParser implements ISchemaParser {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
throw new CodeGeneratorError(`Can't find anything to generate.`);
|
throw new CodeGeneratorError('Can\'t find anything to generate.');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 建立所有容器的内部依赖索引
|
// 建立所有容器的内部依赖索引
|
||||||
@ -206,7 +205,9 @@ class SchemaParser implements ISchemaParser {
|
|||||||
let npms: INpmPackage[] = [];
|
let npms: INpmPackage[] = [];
|
||||||
containers.forEach((con) => {
|
containers.forEach((con) => {
|
||||||
const p = (con.deps || [])
|
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);
|
.filter((dep) => dep !== null);
|
||||||
const npmInfos: INpmPackage[] = p
|
const npmInfos: INpmPackage[] = p
|
||||||
.filter((i) => Boolean(i))
|
.filter((i) => Boolean(i))
|
||||||
|
|||||||
@ -109,9 +109,9 @@ function buildPackageImport(
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const items = Object.keys(imports).map((src) =>
|
const items = Object.keys(imports).map((src) => {
|
||||||
src === imports[src] || !useAliasName ? src : `${src} as ${imports[src]}`,
|
return src === imports[src] || !useAliasName ? src : `${src} as ${imports[src]}`;
|
||||||
);
|
});
|
||||||
|
|
||||||
const statementL = ['import'];
|
const statementL = ['import'];
|
||||||
if (defaultImport) {
|
if (defaultImport) {
|
||||||
|
|||||||
@ -13,7 +13,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: FileType.JSX,
|
fileType: FileType.JSX,
|
||||||
name: COMMON_CHUNK_NAME.InternalDepsImport,
|
name: COMMON_CHUNK_NAME.InternalDepsImport,
|
||||||
content: `import * from 'react';`,
|
content: 'import * from \'react\';',
|
||||||
linkAfter: [],
|
linkAfter: [],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -40,7 +40,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: FileType.JSX,
|
fileType: FileType.JSX,
|
||||||
name: CLASS_DEFINE_CHUNK_NAME.End,
|
name: CLASS_DEFINE_CHUNK_NAME.End,
|
||||||
content: `}`,
|
content: '}',
|
||||||
linkAfter: [
|
linkAfter: [
|
||||||
CLASS_DEFINE_CHUNK_NAME.Start,
|
CLASS_DEFINE_CHUNK_NAME.Start,
|
||||||
CLASS_DEFINE_CHUNK_NAME.InsPrivateMethod,
|
CLASS_DEFINE_CHUNK_NAME.InsPrivateMethod,
|
||||||
@ -72,7 +72,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: FileType.JSX,
|
fileType: FileType.JSX,
|
||||||
name: RAX_CHUNK_NAME.ClassDidMountBegin,
|
name: RAX_CHUNK_NAME.ClassDidMountBegin,
|
||||||
content: `componentDidMount() {`,
|
content: 'componentDidMount() {',
|
||||||
linkAfter: [CLASS_DEFINE_CHUNK_NAME.Start, CLASS_DEFINE_CHUNK_NAME.InsVar, CLASS_DEFINE_CHUNK_NAME.InsMethod],
|
linkAfter: [CLASS_DEFINE_CHUNK_NAME.Start, CLASS_DEFINE_CHUNK_NAME.InsVar, CLASS_DEFINE_CHUNK_NAME.InsMethod],
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -80,7 +80,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: FileType.JSX,
|
fileType: FileType.JSX,
|
||||||
name: RAX_CHUNK_NAME.ClassDidMountEnd,
|
name: RAX_CHUNK_NAME.ClassDidMountEnd,
|
||||||
content: `}`,
|
content: '}',
|
||||||
linkAfter: [RAX_CHUNK_NAME.ClassDidMountBegin, RAX_CHUNK_NAME.ClassDidMountContent],
|
linkAfter: [RAX_CHUNK_NAME.ClassDidMountBegin, RAX_CHUNK_NAME.ClassDidMountContent],
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -88,7 +88,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: FileType.JSX,
|
fileType: FileType.JSX,
|
||||||
name: RAX_CHUNK_NAME.ClassWillUnmountBegin,
|
name: RAX_CHUNK_NAME.ClassWillUnmountBegin,
|
||||||
content: `componentWillUnmount() {`,
|
content: 'componentWillUnmount() {',
|
||||||
linkAfter: [
|
linkAfter: [
|
||||||
CLASS_DEFINE_CHUNK_NAME.Start,
|
CLASS_DEFINE_CHUNK_NAME.Start,
|
||||||
CLASS_DEFINE_CHUNK_NAME.InsVar,
|
CLASS_DEFINE_CHUNK_NAME.InsVar,
|
||||||
@ -101,7 +101,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: FileType.JSX,
|
fileType: FileType.JSX,
|
||||||
name: RAX_CHUNK_NAME.ClassWillUnmountEnd,
|
name: RAX_CHUNK_NAME.ClassWillUnmountEnd,
|
||||||
content: `}`,
|
content: '}',
|
||||||
linkAfter: [RAX_CHUNK_NAME.ClassWillUnmountBegin, RAX_CHUNK_NAME.ClassWillUnmountContent],
|
linkAfter: [RAX_CHUNK_NAME.ClassWillUnmountBegin, RAX_CHUNK_NAME.ClassWillUnmountContent],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -28,7 +28,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: cfg.fileType,
|
fileType: cfg.fileType,
|
||||||
name: COMMON_CHUNK_NAME.InternalDepsImport,
|
name: COMMON_CHUNK_NAME.InternalDepsImport,
|
||||||
content: `import __$$constants from '../../constants';`,
|
content: 'import __$$constants from \'../../constants\';',
|
||||||
linkAfter: [COMMON_CHUNK_NAME.ExternalDepsImport],
|
linkAfter: [COMMON_CHUNK_NAME.ExternalDepsImport],
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -37,7 +37,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: cfg.fileType,
|
fileType: cfg.fileType,
|
||||||
name: COMMON_CHUNK_NAME.InternalDepsImport,
|
name: COMMON_CHUNK_NAME.InternalDepsImport,
|
||||||
content: `import * as __$$i18n from '../../i18n';`,
|
content: 'import * as __$$i18n from \'../../i18n\';',
|
||||||
linkAfter: [COMMON_CHUNK_NAME.ExternalDepsImport],
|
linkAfter: [COMMON_CHUNK_NAME.ExternalDepsImport],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -39,7 +39,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: cfg.fileType,
|
fileType: cfg.fileType,
|
||||||
name: CLASS_DEFINE_CHUNK_NAME.InsVar,
|
name: CLASS_DEFINE_CHUNK_NAME.InsVar,
|
||||||
content: `_utils = this._defineUtils();`,
|
content: '_utils = this._defineUtils();',
|
||||||
linkAfter: [CLASS_DEFINE_CHUNK_NAME.Start],
|
linkAfter: [CLASS_DEFINE_CHUNK_NAME.Start],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -74,7 +74,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: cfg.fileType,
|
fileType: cfg.fileType,
|
||||||
name: CLASS_DEFINE_CHUNK_NAME.InsVar,
|
name: CLASS_DEFINE_CHUNK_NAME.InsVar,
|
||||||
content: `_lifeCycles = this._defineLifeCycles();`,
|
content: '_lifeCycles = this._defineLifeCycles();',
|
||||||
linkAfter: [CLASS_DEFINE_CHUNK_NAME.Start],
|
linkAfter: [CLASS_DEFINE_CHUNK_NAME.Start],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -63,8 +63,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 注意:这里其实隐含了一个假设:schema 中的 componentName 应该是一个有效的 JS 标识符,而且是大写字母打头的
|
// 注意:这里其实隐含了一个假设:schema 中的 componentName 应该是一个有效的 JS 标识符,而且是大写字母打头的
|
||||||
const mapComponentNameToAliasOrKeepIt = (componentName: string) =>
|
const mapComponentNameToAliasOrKeepIt = (componentName: string) => componentsNameAliasMap.get(componentName) || componentName;
|
||||||
componentsNameAliasMap.get(componentName) || componentName;
|
|
||||||
|
|
||||||
// 然后过滤掉所有的别名 chunks
|
// 然后过滤掉所有的别名 chunks
|
||||||
next.chunks = next.chunks.filter((chunk) => !isImportAliasDefineChunk(chunk));
|
next.chunks = next.chunks.filter((chunk) => !isImportAliasDefineChunk(chunk));
|
||||||
@ -97,7 +96,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: cfg.fileType,
|
fileType: cfg.fileType,
|
||||||
name: COMMON_CHUNK_NAME.ExternalDepsImport,
|
name: COMMON_CHUNK_NAME.ExternalDepsImport,
|
||||||
content: `import { isMiniApp as __$$isMiniApp } from 'universal-env';`,
|
content: 'import { isMiniApp as __$$isMiniApp } from \'universal-env\';',
|
||||||
linkAfter: [],
|
linkAfter: [],
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -324,15 +323,15 @@ function generateEventHandlerAttrForRax(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const wrappedAttrValueExpr = [
|
const wrappedAttrValueExpr = [
|
||||||
`(...__$$args) => {`,
|
'(...__$$args) => {',
|
||||||
` if (__$$isMiniApp) {`,
|
' if (__$$isMiniApp) {',
|
||||||
` const __$$event = __$$args[0];`,
|
' const __$$event = __$$args[0];',
|
||||||
...referencedLocalVariables.map((localVar) => `const ${localVar} = __$$event.target.dataset.${localVar};`),
|
...referencedLocalVariables.map((localVar) => `const ${localVar} = __$$event.target.dataset.${localVar};`),
|
||||||
` return (${valueExpr}).apply(this, __$$args);`,
|
` return (${valueExpr}).apply(this, __$$args);`,
|
||||||
` } else {`,
|
' } else {',
|
||||||
` return (${valueExpr}).apply(this, __$$args);`,
|
` return (${valueExpr}).apply(this, __$$args);`,
|
||||||
` }`,
|
' }',
|
||||||
`}`,
|
'}',
|
||||||
].join('\n');
|
].join('\n');
|
||||||
|
|
||||||
return [
|
return [
|
||||||
|
|||||||
@ -40,7 +40,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: FileType.JSX,
|
fileType: FileType.JSX,
|
||||||
name: CLASS_DEFINE_CHUNK_NAME.End,
|
name: CLASS_DEFINE_CHUNK_NAME.End,
|
||||||
content: `}`,
|
content: '}',
|
||||||
linkAfter: [
|
linkAfter: [
|
||||||
CLASS_DEFINE_CHUNK_NAME.Start,
|
CLASS_DEFINE_CHUNK_NAME.Start,
|
||||||
REACT_CHUNK_NAME.ClassRenderEnd,
|
REACT_CHUNK_NAME.ClassRenderEnd,
|
||||||
|
|||||||
@ -32,7 +32,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
|||||||
const scope = Scope.createRootScope();
|
const scope = Scope.createRootScope();
|
||||||
|
|
||||||
if (ir.state) {
|
if (ir.state) {
|
||||||
const state = ir.state;
|
const { state } = ir;
|
||||||
const fields = Object.keys(state).map<string>((stateName) => {
|
const fields = Object.keys(state).map<string>((stateName) => {
|
||||||
const value = generateCompositeType(state[stateName], scope);
|
const value = generateCompositeType(state[stateName], scope);
|
||||||
return `${stateName}: ${value},`;
|
return `${stateName}: ${value},`;
|
||||||
|
|||||||
@ -33,7 +33,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
|||||||
const scope = Scope.createRootScope();
|
const scope = Scope.createRootScope();
|
||||||
|
|
||||||
if (ir.state) {
|
if (ir.state) {
|
||||||
const state = ir.state;
|
const { state } = ir;
|
||||||
const fields = Object.keys(state).map<string>((stateName) => {
|
const fields = Object.keys(state).map<string>((stateName) => {
|
||||||
const value = generateCompositeType(state[stateName], scope);
|
const value = generateCompositeType(state[stateName], scope);
|
||||||
return `${stateName}: ${value},`;
|
return `${stateName}: ${value},`;
|
||||||
|
|||||||
@ -10,7 +10,7 @@ import {
|
|||||||
|
|
||||||
type PluginConfig = {
|
type PluginConfig = {
|
||||||
fileType: string;
|
fileType: string;
|
||||||
}
|
};
|
||||||
|
|
||||||
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
|
const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
|
||||||
const cfg: PluginConfig = {
|
const cfg: PluginConfig = {
|
||||||
@ -27,7 +27,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: cfg.fileType,
|
fileType: cfg.fileType,
|
||||||
name: CLASS_DEFINE_CHUNK_NAME.ConstructorContent,
|
name: CLASS_DEFINE_CHUNK_NAME.ConstructorContent,
|
||||||
content: `this.utils = utils;`,
|
content: 'this.utils = utils;',
|
||||||
linkAfter: [CLASS_DEFINE_CHUNK_NAME.ConstructorStart],
|
linkAfter: [CLASS_DEFINE_CHUNK_NAME.ConstructorStart],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -35,7 +35,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
|||||||
const ir = next.ir as IContainerInfo;
|
const ir = next.ir as IContainerInfo;
|
||||||
|
|
||||||
if (ir.lifeCycles) {
|
if (ir.lifeCycles) {
|
||||||
const lifeCycles = ir.lifeCycles;
|
const { lifeCycles } = ir;
|
||||||
const chunks = Object.keys(lifeCycles).map<ICodeChunk>((lifeCycleName) => {
|
const chunks = Object.keys(lifeCycles).map<ICodeChunk>((lifeCycleName) => {
|
||||||
const normalizeName = cfg.normalizeNameMapping[lifeCycleName] || lifeCycleName;
|
const normalizeName = cfg.normalizeNameMapping[lifeCycleName] || lifeCycleName;
|
||||||
const exportName = cfg.exportNameMapping[lifeCycleName] || lifeCycleName;
|
const exportName = cfg.exportNameMapping[lifeCycleName] || lifeCycleName;
|
||||||
|
|||||||
@ -30,7 +30,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
|
|||||||
const ir = next.ir as IContainerInfo;
|
const ir = next.ir as IContainerInfo;
|
||||||
|
|
||||||
if (ir.methods) {
|
if (ir.methods) {
|
||||||
const methods = ir.methods;
|
const { methods } = ir;
|
||||||
const chunks = Object.keys(methods).map<ICodeChunk>((methodName) => ({
|
const chunks = Object.keys(methods).map<ICodeChunk>((methodName) => ({
|
||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: cfg.fileType,
|
fileType: cfg.fileType,
|
||||||
|
|||||||
@ -18,7 +18,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: FileType.JSX,
|
fileType: FileType.JSX,
|
||||||
name: COMMON_CHUNK_NAME.ExternalDepsImport,
|
name: COMMON_CHUNK_NAME.ExternalDepsImport,
|
||||||
content: `import React from 'react';`,
|
content: 'import React from \'react\';',
|
||||||
linkAfter: [],
|
linkAfter: [],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -21,7 +21,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: FileType.TS,
|
fileType: FileType.TS,
|
||||||
name: COMMON_CHUNK_NAME.ExternalDepsImport,
|
name: COMMON_CHUNK_NAME.ExternalDepsImport,
|
||||||
content: `import { BaseController } from '@ali/recore-renderer';`,
|
content: 'import { BaseController } from \'@ali/recore-renderer\';',
|
||||||
linkAfter: [],
|
linkAfter: [],
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -37,7 +37,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: FileType.TS,
|
fileType: FileType.TS,
|
||||||
name: CLASS_DEFINE_CHUNK_NAME.End,
|
name: CLASS_DEFINE_CHUNK_NAME.End,
|
||||||
content: `}`,
|
content: '}',
|
||||||
linkAfter: [...DEFAULT_LINK_AFTER[CLASS_DEFINE_CHUNK_NAME.End]],
|
linkAfter: [...DEFAULT_LINK_AFTER[CLASS_DEFINE_CHUNK_NAME.End]],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -12,7 +12,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: 'vx',
|
fileType: 'vx',
|
||||||
name: COMMON_CHUNK_NAME.CustomContent,
|
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: [],
|
linkAfter: [],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -74,7 +74,9 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
|||||||
originTemplate: '@alifd/scaffold-lite-js',
|
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({
|
next.chunks.push({
|
||||||
type: ChunkType.JSON,
|
type: ChunkType.JSON,
|
||||||
|
|||||||
@ -38,15 +38,15 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
|||||||
component: BasicLayout,
|
component: BasicLayout,
|
||||||
children: [
|
children: [
|
||||||
${ir.routes
|
${ir.routes
|
||||||
.map(
|
.map(
|
||||||
(route) => `
|
(route) => `
|
||||||
{
|
{
|
||||||
path: '${route.path}',
|
path: '${route.path}',
|
||||||
component: ${route.componentName},
|
component: ${route.componentName},
|
||||||
}
|
}
|
||||||
`,
|
`,
|
||||||
)
|
)
|
||||||
.join(',')}
|
.join(',')}
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@ -28,8 +28,8 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
|||||||
targets: ['web', 'miniapp'],
|
targets: ['web', 'miniapp'],
|
||||||
miniapp: miniAppBuildType
|
miniapp: miniAppBuildType
|
||||||
? {
|
? {
|
||||||
buildType: miniAppBuildType,
|
buildType: miniAppBuildType,
|
||||||
}
|
}
|
||||||
: undefined,
|
: undefined,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
|||||||
@ -6,7 +6,6 @@ import {
|
|||||||
ChunkType,
|
ChunkType,
|
||||||
FileType,
|
FileType,
|
||||||
ICodeStruct,
|
ICodeStruct,
|
||||||
IProjectInfo,
|
|
||||||
} from '../../../../../types';
|
} from '../../../../../types';
|
||||||
|
|
||||||
const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
||||||
@ -15,8 +14,6 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
|
|||||||
...pre,
|
...pre,
|
||||||
};
|
};
|
||||||
|
|
||||||
const ir = next.ir as IProjectInfo;
|
|
||||||
|
|
||||||
next.chunks.push({
|
next.chunks.push({
|
||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: FileType.JS,
|
fileType: FileType.JS,
|
||||||
|
|||||||
@ -32,7 +32,7 @@ const pluginFactory: BuilderComponentPluginFactory<GlobalStylePluginConfig> = (
|
|||||||
type: ChunkType.STRING,
|
type: ChunkType.STRING,
|
||||||
fileType: cfg.fileType,
|
fileType: cfg.fileType,
|
||||||
name: COMMON_CHUNK_NAME.StyleDepsImport,
|
name: COMMON_CHUNK_NAME.StyleDepsImport,
|
||||||
content: ``,
|
content: '',
|
||||||
linkAfter: [],
|
linkAfter: [],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -7,7 +7,7 @@ const PARSERS = ['css', 'scss', 'less', 'json', 'html', 'vue'];
|
|||||||
|
|
||||||
type ProcessorConfig = {
|
type ProcessorConfig = {
|
||||||
customFileTypeParser: Record<string, string>;
|
customFileTypeParser: Record<string, string>;
|
||||||
}
|
};
|
||||||
|
|
||||||
const factory: PostProcessorFactory<ProcessorConfig> = (config?: ProcessorConfig) => {
|
const factory: PostProcessorFactory<ProcessorConfig> = (config?: ProcessorConfig) => {
|
||||||
const cfg: ProcessorConfig = {
|
const cfg: ProcessorConfig = {
|
||||||
@ -25,7 +25,7 @@ const factory: PostProcessorFactory<ProcessorConfig> = (config?: ProcessorConfig
|
|||||||
parser = 'json';
|
parser = 'json';
|
||||||
} else if (PARSERS.indexOf(fileType) >= 0) {
|
} else if (PARSERS.indexOf(fileType) >= 0) {
|
||||||
parser = fileType as prettier.BuiltInParserName;
|
parser = fileType as prettier.BuiltInParserName;
|
||||||
} else if (cfg.customFileTypeParser[fileType]){
|
} else if (cfg.customFileTypeParser[fileType]) {
|
||||||
parser = cfg.customFileTypeParser[fileType] as prettier.BuiltInParserName;
|
parser = cfg.customFileTypeParser[fileType] as prettier.BuiltInParserName;
|
||||||
} else if (fileType === 'vx') {
|
} else if (fileType === 'vx') {
|
||||||
return mypretter(content, fileType);
|
return mypretter(content, fileType);
|
||||||
|
|||||||
@ -37,7 +37,7 @@ const writeFilesToFolder = async (folderPath: string, files: ResultFile[], fs: I
|
|||||||
await Promise.all(promises);
|
await Promise.all(promises);
|
||||||
};
|
};
|
||||||
|
|
||||||
const writeSubFoldersToFolder = async (folderPath: string, subFolders: ResultDir[], fs: IFileSystem): Promise<void> => {
|
const writeSubFoldersToFolder = async (folderPath: string, subFolders: ResultDir[]): Promise<void> => {
|
||||||
const promises = subFolders.map((subFolder) => {
|
const promises = subFolders.map((subFolder) => {
|
||||||
return writeFolder(subFolder, folderPath);
|
return writeFolder(subFolder, folderPath);
|
||||||
});
|
});
|
||||||
|
|||||||
@ -7,19 +7,10 @@ export class CodeGeneratorError extends Error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class ComponentValidationError extends CodeGeneratorError {
|
export class ComponentValidationError extends CodeGeneratorError {
|
||||||
constructor(errorString: string) {
|
|
||||||
super(errorString);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export class CompatibilityError extends CodeGeneratorError {
|
export class CompatibilityError extends CodeGeneratorError {
|
||||||
constructor(errorString: string) {
|
|
||||||
super(errorString);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export class PublisherError extends CodeGeneratorError {
|
export class PublisherError extends CodeGeneratorError {
|
||||||
constructor(errorString: string) {
|
|
||||||
super(errorString);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -14,9 +14,13 @@ export interface IScopeBindings {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class ScopeBindings implements IScopeBindings {
|
export class ScopeBindings implements IScopeBindings {
|
||||||
|
readonly parent: IScopeBindings | null;
|
||||||
|
|
||||||
private _bindings = new OrderedSet<string>();
|
private _bindings = new OrderedSet<string>();
|
||||||
|
|
||||||
constructor(readonly parent: IScopeBindings | null = null) {}
|
constructor(p: IScopeBindings | null = null) {
|
||||||
|
this.parent = p;
|
||||||
|
}
|
||||||
|
|
||||||
hasBinding(varName: string): boolean {
|
hasBinding(varName: string): boolean {
|
||||||
return this._bindings.has(varName) || !!this.parent?.hasBinding(varName);
|
return this._bindings.has(varName) || !!this.parent?.hasBinding(varName);
|
||||||
@ -37,7 +41,7 @@ export class ScopeBindings implements IScopeBindings {
|
|||||||
getAllBindings(): string[] {
|
getAllBindings(): string[] {
|
||||||
const allBindings = new OrderedSet(this._bindings.toArray());
|
const allBindings = new OrderedSet(this._bindings.toArray());
|
||||||
|
|
||||||
for (let parent = this.parent; parent; parent = parent?.parent) {
|
for (let { parent } = this; parent; parent = parent?.parent) {
|
||||||
parent.getAllOwnedBindings().forEach((varName) => {
|
parent.getAllOwnedBindings().forEach((varName) => {
|
||||||
allBindings.add(varName);
|
allBindings.add(varName);
|
||||||
});
|
});
|
||||||
|
|||||||
@ -18,7 +18,7 @@ export function executeFunctionStack<I, T, C>(
|
|||||||
while (funcList.length > 0) {
|
while (funcList.length > 0) {
|
||||||
const func = funcList.pop();
|
const func = funcList.pop();
|
||||||
if (func) {
|
if (func) {
|
||||||
const warppedFunc = ((nextFunc) => (input: I, scope: IScope, cfg?: C) => func(input, scope, cfg, nextFunc))(next);
|
const warppedFunc = ((nextFunc) => (i: I, s: IScope, cfg?: C) => func(i, s, cfg, nextFunc))(next);
|
||||||
next = warppedFunc;
|
next = warppedFunc;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -24,7 +24,9 @@ export function upperCaseFirst(inputValue: string): string {
|
|||||||
|
|
||||||
export function uniqueArray<T>(arr: T[], by: (i: T) => string) {
|
export function uniqueArray<T>(arr: T[], by: (i: T) => string) {
|
||||||
const map: Record<string, T> = {};
|
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 uniqueKeys = [...new Set<string>(Object.keys(map))];
|
||||||
const uniqueItems = uniqueKeys.map((key) => map[key]);
|
const uniqueItems = uniqueKeys.map((key) => map[key]);
|
||||||
return uniqueItems;
|
return uniqueItems;
|
||||||
|
|||||||
@ -7,8 +7,14 @@ import { isIdentifier, Node } from '@babel/types';
|
|||||||
import { OrderedSet } from './OrderedSet';
|
import { OrderedSet } from './OrderedSet';
|
||||||
|
|
||||||
export class ParseError extends Error {
|
export class ParseError extends Error {
|
||||||
constructor(readonly expr: string | t.Expression, readonly detail: unknown) {
|
readonly expr: string | t.Expression;
|
||||||
|
|
||||||
|
readonly detail: unknown;
|
||||||
|
|
||||||
|
constructor(expr: string | t.Expression, detail: unknown) {
|
||||||
super(`Failed to parse expression "${typeof expr === 'string' ? expr : generate(expr)}"`);
|
super(`Failed to parse expression "${typeof expr === 'string' ? expr : generate(expr)}"`);
|
||||||
|
this.expr = expr;
|
||||||
|
this.detail = detail;
|
||||||
Object.setPrototypeOf(this, new.target.prototype);
|
Object.setPrototypeOf(this, new.target.prototype);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -31,14 +37,20 @@ const MAYBE_EXPRESSIONS: {
|
|||||||
IfStatement: { fields: ['test'] },
|
IfStatement: { fields: ['test'] },
|
||||||
LogicalExpression: { fields: ['left', 'right'] },
|
LogicalExpression: { fields: ['left', 'right'] },
|
||||||
MemberExpression: {
|
MemberExpression: {
|
||||||
fields: (node) => (node.type === 'MemberExpression' && node.computed ? ['object', 'property'] : ['object']),
|
fields: (node) => {
|
||||||
|
return node.type === 'MemberExpression' && node.computed ? ['object', 'property'] : ['object'];
|
||||||
|
},
|
||||||
},
|
},
|
||||||
NewExpression: { fields: ['callee', 'arguments'] },
|
NewExpression: { fields: ['callee', 'arguments'] },
|
||||||
ObjectMethod: {
|
ObjectMethod: {
|
||||||
fields: (node) => (node.type === 'ObjectMethod' && node.computed ? ['key'] : []),
|
fields: (node) => {
|
||||||
|
return node.type === 'ObjectMethod' && node.computed ? ['key'] : [];
|
||||||
|
},
|
||||||
},
|
},
|
||||||
ObjectProperty: {
|
ObjectProperty: {
|
||||||
fields: (node) => (node.type === 'ObjectProperty' && node.computed ? ['key', 'value'] : ['value']),
|
fields: (node) => {
|
||||||
|
return node.type === 'ObjectProperty' && node.computed ? ['key', 'value'] : ['value'];
|
||||||
|
},
|
||||||
},
|
},
|
||||||
ReturnStatement: { fields: ['argument'] },
|
ReturnStatement: { fields: ['argument'] },
|
||||||
SequenceExpression: { fields: ['expressions'] },
|
SequenceExpression: { fields: ['expressions'] },
|
||||||
@ -57,31 +69,43 @@ const MAYBE_EXPRESSIONS: {
|
|||||||
ClassDeclaration: { fields: ['superClass'] },
|
ClassDeclaration: { fields: ['superClass'] },
|
||||||
ExportDefaultDeclaration: { fields: ['declaration'] },
|
ExportDefaultDeclaration: { fields: ['declaration'] },
|
||||||
ForOfStatement: { fields: ['right'] },
|
ForOfStatement: { fields: ['right'] },
|
||||||
ClassMethod: { fields: (node) => (node.type === 'ClassMethod' && node.computed ? ['key'] : []) },
|
ClassMethod: { fields: (node) => {
|
||||||
|
return node.type === 'ClassMethod' && node.computed ? ['key'] : [];
|
||||||
|
} },
|
||||||
SpreadElement: { fields: ['argument'] },
|
SpreadElement: { fields: ['argument'] },
|
||||||
TaggedTemplateExpression: { fields: ['tag'] },
|
TaggedTemplateExpression: { fields: ['tag'] },
|
||||||
TemplateLiteral: { fields: ['expressions'] },
|
TemplateLiteral: { fields: ['expressions'] },
|
||||||
YieldExpression: { fields: ['argument'] },
|
YieldExpression: { fields: ['argument'] },
|
||||||
AwaitExpression: { fields: ['argument'] },
|
AwaitExpression: { fields: ['argument'] },
|
||||||
OptionalMemberExpression: {
|
OptionalMemberExpression: {
|
||||||
fields: (node) => (node.type === 'OptionalMemberExpression' && node.computed ? ['object', 'property'] : ['object']),
|
fields: (node) => {
|
||||||
|
return node.type === 'OptionalMemberExpression' && node.computed ? ['object', 'property'] : ['object'];
|
||||||
|
},
|
||||||
},
|
},
|
||||||
OptionalCallExpression: { fields: ['callee', 'arguments'] },
|
OptionalCallExpression: { fields: ['callee', 'arguments'] },
|
||||||
JSXSpreadAttribute: { fields: ['argument'] },
|
JSXSpreadAttribute: { fields: ['argument'] },
|
||||||
BindExpression: { fields: ['object', 'callee'] },
|
BindExpression: { fields: ['object', 'callee'] },
|
||||||
ClassProperty: { fields: (node) => (node.type === 'ClassProperty' && node.computed ? ['key', 'value'] : ['value']) },
|
ClassProperty: { fields: (node) => {
|
||||||
|
return node.type === 'ClassProperty' && node.computed ? ['key', 'value'] : ['value'];
|
||||||
|
} },
|
||||||
PipelineTopicExpression: { fields: ['expression'] },
|
PipelineTopicExpression: { fields: ['expression'] },
|
||||||
PipelineBareFunction: { fields: ['callee'] },
|
PipelineBareFunction: { fields: ['callee'] },
|
||||||
ClassPrivateProperty: { fields: ['value'] },
|
ClassPrivateProperty: { fields: ['value'] },
|
||||||
Decorator: { fields: ['expression'] },
|
Decorator: { fields: ['expression'] },
|
||||||
TupleExpression: { fields: ['elements'] },
|
TupleExpression: { fields: ['elements'] },
|
||||||
TSDeclareMethod: { fields: (node) => (node.type === 'TSDeclareMethod' && node.computed ? ['key'] : []) },
|
TSDeclareMethod: { fields: (node) => {
|
||||||
|
return node.type === 'TSDeclareMethod' && node.computed ? ['key'] : [];
|
||||||
|
} },
|
||||||
TSPropertySignature: {
|
TSPropertySignature: {
|
||||||
fields: (node) => (node.type === 'TSPropertySignature' && node.computed ? ['key', 'initializer'] : ['initializer']),
|
fields: (node) => {
|
||||||
|
return node.type === 'TSPropertySignature' && node.computed ? ['key', 'initializer'] : ['initializer'];
|
||||||
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
TSMethodSignature: {
|
TSMethodSignature: {
|
||||||
fields: (node) => (node.type === 'TSMethodSignature' && node.computed ? ['key'] : []),
|
fields: (node) => {
|
||||||
|
return node.type === 'TSMethodSignature' && node.computed ? ['key'] : [];
|
||||||
|
},
|
||||||
},
|
},
|
||||||
TSAsExpression: { fields: ['expression'] },
|
TSAsExpression: { fields: ['expression'] },
|
||||||
TSTypeAssertion: { fields: ['expression'] },
|
TSTypeAssertion: { fields: ['expression'] },
|
||||||
@ -114,7 +138,7 @@ const CROSS_THIS_SCOPE_TYPE_NODE: {
|
|||||||
|
|
||||||
export function parseExpressionGetGlobalVariables(
|
export function parseExpressionGetGlobalVariables(
|
||||||
expr: string | null | undefined,
|
expr: string | null | undefined,
|
||||||
{ filter = (x) => true }: ParseExpressionGetGlobalVariablesOptions = {},
|
{ filter = () => true }: ParseExpressionGetGlobalVariablesOptions = {},
|
||||||
): string[] {
|
): string[] {
|
||||||
if (!expr) {
|
if (!expr) {
|
||||||
return [];
|
return [];
|
||||||
@ -125,7 +149,7 @@ export function parseExpressionGetGlobalVariables(
|
|||||||
|
|
||||||
const ast = parser.parse(`!(${expr});`);
|
const ast = parser.parse(`!(${expr});`);
|
||||||
|
|
||||||
const addUndeclaredIdentifierIfNeeded = (x: object | null | undefined, path: NodePath<Node>) => {
|
const addUndeclaredIdentifierIfNeeded = (x: Record<string, unknown> | null | undefined, path: NodePath<Node>) => {
|
||||||
if (isIdentifier(x) && !path.scope.hasBinding(x.name)) {
|
if (isIdentifier(x) && !path.scope.hasBinding(x.name)) {
|
||||||
undeclaredVars.add(x.name);
|
undeclaredVars.add(x.name);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -18,11 +18,11 @@ export function generateJsSlot(slot: any, scope: IScope, generator: NodeGenerato
|
|||||||
if (params) {
|
if (params) {
|
||||||
return [
|
return [
|
||||||
title && generateSingleLineComment(title),
|
title && generateSingleLineComment(title),
|
||||||
`(`,
|
'(',
|
||||||
...(params || []),
|
...(params || []),
|
||||||
`) => (`,
|
') => (',
|
||||||
!value ? 'null' : generator(value, scope),
|
!value ? 'null' : generator(value, scope),
|
||||||
`)`,
|
')',
|
||||||
]
|
]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join('');
|
.join('');
|
||||||
|
|||||||
@ -188,7 +188,7 @@ function linkPieces(pieces: CodePiece[]): string {
|
|||||||
.map((p) => p.value)
|
.map((p) => p.value)
|
||||||
.join(' ');
|
.join(' ');
|
||||||
|
|
||||||
attrsParts = !!attrsParts ? ` ${attrsParts}` : '';
|
attrsParts = attrsParts ? ` ${attrsParts}` : '';
|
||||||
|
|
||||||
if (childrenParts) {
|
if (childrenParts) {
|
||||||
return `${beforeParts}<${tagName}${attrsParts}>${childrenParts}</${tagName}>${afterParts}`;
|
return `${beforeParts}<${tagName}${attrsParts}>${childrenParts}</${tagName}>${afterParts}`;
|
||||||
|
|||||||
@ -47,7 +47,7 @@ export function handleSubNodes<T>(
|
|||||||
return list.map((child) => handleSubNodes(child, handlers, opt)).reduce((p, c) => p.concat(c), []);
|
return list.map((child) => handleSubNodes(child, handlers, opt)).reduce((p, c) => p.concat(c), []);
|
||||||
}
|
}
|
||||||
|
|
||||||
let result: T | undefined = undefined;
|
let result: T | undefined;
|
||||||
const childrenRes: T[] = [];
|
const childrenRes: T[] = [];
|
||||||
if (isDOMText(children)) {
|
if (isDOMText(children)) {
|
||||||
const handler = handlers.string || noop;
|
const handler = handlers.string || noop;
|
||||||
|
|||||||
@ -1,21 +1,21 @@
|
|||||||
const fs = require("fs");
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
|
||||||
console.log(process.argv);
|
console.log(process.argv);
|
||||||
let root = '';
|
let rootParams = '';
|
||||||
const pathArgIndex = process.argv.indexOf('--path');
|
const pathArgIndex = process.argv.indexOf('--path');
|
||||||
if (pathArgIndex >= 0) {
|
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');
|
throw new Error('Can\'t find path argument');
|
||||||
}
|
}
|
||||||
|
|
||||||
function cloneStr(str, times) {
|
function cloneStr(str, times) {
|
||||||
let count = times;
|
let count = times;
|
||||||
const arr = [];
|
const arr = [];
|
||||||
while(count > 0) {
|
while (count > 0) {
|
||||||
arr.push(str);
|
arr.push(str);
|
||||||
count -= 1;
|
count -= 1;
|
||||||
}
|
}
|
||||||
@ -23,7 +23,7 @@ function cloneStr(str, times) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function createTemplateFile(root, internalPath, fileName) {
|
function createTemplateFile(root, internalPath, fileName) {
|
||||||
//不是文件夹,则添加type属性为文件后缀名
|
// 不是文件夹,则添加type属性为文件后缀名
|
||||||
const fileTypeSrc = path.extname(fileName);
|
const fileTypeSrc = path.extname(fileName);
|
||||||
const fileType = fileTypeSrc.substring(1);
|
const fileType = fileTypeSrc.substring(1);
|
||||||
const baseName = path.basename(fileName, fileTypeSrc);
|
const baseName = path.basename(fileName, fileTypeSrc);
|
||||||
@ -35,7 +35,7 @@ function createTemplateFile(root, internalPath, fileName) {
|
|||||||
encoding: 'utf8',
|
encoding: 'utf8',
|
||||||
});
|
});
|
||||||
const pathList = (internalPath.split(path.sep) || []).filter(p => !!p);
|
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 = `
|
const templateContent = `
|
||||||
import ResultFile from '${depPrefix}model/ResultFile';
|
import ResultFile from '${depPrefix}model/ResultFile';
|
||||||
@ -62,24 +62,24 @@ ${content}
|
|||||||
function fileDisplay(root, internalPath) {
|
function fileDisplay(root, internalPath) {
|
||||||
const dirPath = path.join(root, internalPath);
|
const dirPath = path.join(root, internalPath);
|
||||||
const filesList = fs.readdirSync(dirPath);
|
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];
|
const fileName = filesList[i];
|
||||||
//拼接当前文件的路径(上一层路径+当前file的名字)
|
// 拼接当前文件的路径(上一层路径+当前file的名字)
|
||||||
const filePath = path.join(dirPath, fileName);
|
const filePath = path.join(dirPath, fileName);
|
||||||
//根据文件路径获取文件信息,返回一个fs.Stats对象
|
// 根据文件路径获取文件信息,返回一个fs.Stats对象
|
||||||
const stats = fs.statSync(filePath);
|
const stats = fs.statSync(filePath);
|
||||||
if(stats.isDirectory()){
|
if (stats.isDirectory()) {
|
||||||
//递归调用
|
// 递归调用
|
||||||
fileDisplay(root, path.join(internalPath, fileName));
|
fileDisplay(root, path.join(internalPath, fileName));
|
||||||
}else{
|
} else {
|
||||||
createTemplateFile(root, internalPath, fileName);
|
createTemplateFile(root, internalPath, fileName);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//调用函数遍历根目录,同时传递 文件夹路径和对应的数组
|
// 调用函数遍历根目录,同时传递 文件夹路径和对应的数组
|
||||||
//请使用同步读取
|
// 请使用同步读取
|
||||||
fileDisplay(root, '');
|
fileDisplay(rootParams, '');
|
||||||
//读取完毕则写入到txt文件中
|
// 读取完毕则写入到txt文件中
|
||||||
// fs.writeFileSync('./data.txt', JSON.stringify(arr));
|
// fs.writeFileSync('./data.txt', JSON.stringify(arr));
|
||||||
|
|||||||
6
packages/datasource-engine/.eslintrc.js
Normal file
6
packages/datasource-engine/.eslintrc.js
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
module.exports = {
|
||||||
|
extends: '../../.eslintrc.js',
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/no-parameter-properties': 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -15,6 +15,7 @@ export class DataSourceEngine implements IDataSourceEngine {
|
|||||||
private _runtimeContext: IRuntimeContext,
|
private _runtimeContext: IRuntimeContext,
|
||||||
private _options?: DataSourceEngineOptions,
|
private _options?: DataSourceEngineOptions,
|
||||||
) {
|
) {
|
||||||
|
// eslint-disable-next-line no-unused-expressions
|
||||||
_dataSourceConfig.list?.forEach((ds) => {
|
_dataSourceConfig.list?.forEach((ds) => {
|
||||||
// 确保数据源都有处理器
|
// 确保数据源都有处理器
|
||||||
const requestHandler = ds.requestHandler || _options?.requestHandlersMap?.[ds.type];
|
const requestHandler = ds.requestHandler || _options?.requestHandlersMap?.[ds.type];
|
||||||
@ -77,7 +78,9 @@ export class DataSourceEngine implements IDataSourceEngine {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {}
|
} catch (e) {
|
||||||
|
// ignore error
|
||||||
|
}
|
||||||
|
|
||||||
await Promise.all(asyncLoadings);
|
await Promise.all(asyncLoadings);
|
||||||
} finally {
|
} finally {
|
||||||
@ -116,6 +119,6 @@ function getValue<T extends boolean>(valueOrValueGetter: T | (() => T)): T | und
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function sleep(ms: number = 0) {
|
function sleep(ms = 0) {
|
||||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,8 +7,11 @@ export class RuntimeDataSource<
|
|||||||
TResultData = unknown
|
TResultData = unknown
|
||||||
> implements IRuntimeDataSource<TParams, TResultData> {
|
> implements IRuntimeDataSource<TParams, TResultData> {
|
||||||
private _status: RuntimeDataSourceStatus = RuntimeDataSourceStatus.Initial;
|
private _status: RuntimeDataSourceStatus = RuntimeDataSourceStatus.Initial;
|
||||||
|
|
||||||
private _data?: TResultData;
|
private _data?: TResultData;
|
||||||
|
|
||||||
private _error?: Error;
|
private _error?: Error;
|
||||||
|
|
||||||
private _latestOptions: DataSourceOptions<TParams>;
|
private _latestOptions: DataSourceOptions<TParams>;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@ -17,11 +20,11 @@ export class RuntimeDataSource<
|
|||||||
private _initialOptions: DataSourceOptions<TParams>,
|
private _initialOptions: DataSourceOptions<TParams>,
|
||||||
private _requestHandler: RequestHandler<DataSourceOptions<TParams>, DataSourceResponse<TRequestResult>>,
|
private _requestHandler: RequestHandler<DataSourceOptions<TParams>, DataSourceResponse<TRequestResult>>,
|
||||||
private _dataHandler:
|
private _dataHandler:
|
||||||
| ((
|
| ((
|
||||||
data: DataSourceResponse<TRequestResult> | undefined,
|
data: DataSourceResponse<TRequestResult> | undefined,
|
||||||
error: unknown | undefined,
|
error: unknown | undefined,
|
||||||
) => TResultData | Promise<TResultData>)
|
) => TResultData | Promise<TResultData>)
|
||||||
| undefined,
|
| undefined,
|
||||||
private _onLoaded: (data: TResultData) => void,
|
private _onLoaded: (data: TResultData) => void,
|
||||||
) {
|
) {
|
||||||
this._latestOptions = _initialOptions;
|
this._latestOptions = _initialOptions;
|
||||||
|
|||||||
@ -2,7 +2,7 @@ import { IRuntimeDataSource } from './IRuntimeDataSource';
|
|||||||
|
|
||||||
/** 运行时上下文 */
|
/** 运行时上下文 */
|
||||||
export interface IRuntimeContext<
|
export interface IRuntimeContext<
|
||||||
TState extends object = Record<string, unknown>
|
TState = Record<string, unknown>
|
||||||
> {
|
> {
|
||||||
/** 当前容器的状态 */
|
/** 当前容器的状态 */
|
||||||
readonly state: TState;
|
readonly state: TState;
|
||||||
|
|||||||
@ -1 +1,10 @@
|
|||||||
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';
|
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';
|
||||||
|
|||||||
@ -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',
|
|
||||||
},
|
|
||||||
};
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
{
|
|
||||||
"singleQuote": true,
|
|
||||||
"trailingComma": "all"
|
|
||||||
}
|
|
||||||
@ -5,8 +5,6 @@
|
|||||||
"description": "低代码引擎 DEMO Server 端",
|
"description": "低代码引擎 DEMO Server 端",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prebuild": "rimraf dist",
|
"prebuild": "rimraf dist",
|
||||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
|
||||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
|
||||||
"start": "nest start",
|
"start": "nest start",
|
||||||
"start:debug": "nest start --debug --watch",
|
"start:debug": "nest start --debug --watch",
|
||||||
"start:dev": "nest start --watch",
|
"start:dev": "nest start --watch",
|
||||||
@ -49,13 +47,7 @@
|
|||||||
"@types/jest": "25.2.3",
|
"@types/jest": "25.2.3",
|
||||||
"@types/node": "^13.9.1",
|
"@types/node": "^13.9.1",
|
||||||
"@types/supertest": "^2.0.8",
|
"@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",
|
"jest": "26.0.1",
|
||||||
"prettier": "^1.19.1",
|
|
||||||
"supertest": "^4.0.2",
|
"supertest": "^4.0.2",
|
||||||
"ts-jest": "26.1.0",
|
"ts-jest": "26.1.0",
|
||||||
"ts-loader": "^6.2.1",
|
"ts-loader": "^6.2.1",
|
||||||
|
|||||||
@ -5,7 +5,11 @@ import { GenerateProjectDto } from '../dto/generate-project.dto';
|
|||||||
|
|
||||||
@Controller('api')
|
@Controller('api')
|
||||||
export class ApiController {
|
export class ApiController {
|
||||||
constructor(private readonly apiService: ApiService) {}
|
private readonly apiService: ApiService;
|
||||||
|
|
||||||
|
constructor(apiService: ApiService) {
|
||||||
|
this.apiService = apiService;
|
||||||
|
}
|
||||||
|
|
||||||
@Get('generate/test')
|
@Get('generate/test')
|
||||||
generateTest() {
|
generateTest() {
|
||||||
|
|||||||
@ -3,7 +3,11 @@ import { AppService } from './app.service';
|
|||||||
|
|
||||||
@Controller()
|
@Controller()
|
||||||
export class AppController {
|
export class AppController {
|
||||||
constructor(private readonly appService: AppService) {}
|
private readonly appService: AppService;
|
||||||
|
|
||||||
|
constructor(appService: AppService) {
|
||||||
|
this.appService = appService;
|
||||||
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
getHello(): string {
|
getHello(): string {
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
import { IResultDir } from '@ali/lowcode-code-generator';
|
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;
|
export type PublisherFactory<T, U> = (configuration?: Partial<T>) => U;
|
||||||
|
|
||||||
@ -17,7 +17,7 @@ export interface IPublisherResponse<T> {
|
|||||||
payload?: T;
|
payload?: T;
|
||||||
}
|
}
|
||||||
|
|
||||||
declare type ZipPublisherResponse = string | Buffer | Blob
|
declare type ZipPublisherResponse = string | Buffer | Blob;
|
||||||
|
|
||||||
export interface ZipFactoryParams extends IPublisherFactoryParams {
|
export interface ZipFactoryParams extends IPublisherFactoryParams {
|
||||||
outputPath?: string
|
outputPath?: string
|
||||||
@ -30,41 +30,41 @@ export interface ZipPublisher extends IPublisher<ZipFactoryParams, ZipPublisherR
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const createZipPublisher: PublisherFactory<ZipFactoryParams, ZipPublisher> = (
|
export const createZipPublisher: PublisherFactory<ZipFactoryParams, ZipPublisher> = (
|
||||||
params: ZipFactoryParams = {}
|
params: ZipFactoryParams = {},
|
||||||
): ZipPublisher => {
|
): ZipPublisher => {
|
||||||
let { project, outputPath } = params
|
let { project, outputPath } = params;
|
||||||
|
|
||||||
const getProject = () => project
|
const getProject = () => project;
|
||||||
const setProject = (projectToSet: IResultDir) => {
|
const setProject = (projectToSet: IResultDir) => {
|
||||||
project = projectToSet
|
project = projectToSet;
|
||||||
}
|
};
|
||||||
|
|
||||||
const getOutputPath = () => outputPath
|
const getOutputPath = () => outputPath;
|
||||||
const setOutputPath = (path: string) => {
|
const setOutputPath = (path: string) => {
|
||||||
outputPath = path
|
outputPath = path;
|
||||||
}
|
};
|
||||||
|
|
||||||
const publish = async (options: ZipFactoryParams = {}) => {
|
const publish = async (options: ZipFactoryParams = {}) => {
|
||||||
const projectToPublish = options.project || project
|
const projectToPublish = options.project || project;
|
||||||
if (!projectToPublish) {
|
if (!projectToPublish) {
|
||||||
throw new Error('MissingProject');
|
throw new Error('MissingProject');
|
||||||
}
|
}
|
||||||
|
|
||||||
const zipName = options.projectSlug || params.projectSlug || projectToPublish.name
|
const zipName = options.projectSlug || params.projectSlug || projectToPublish.name;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const zipContent = await generateProjectZip(projectToPublish)
|
const zipContent = await generateProjectZip(projectToPublish);
|
||||||
|
|
||||||
// If not output path is provided, zip is not written to disk
|
// 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()) {
|
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) {
|
} catch (error) {
|
||||||
throw new Error('ZipUnexpected');
|
throw new Error('ZipUnexpected');
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
publish,
|
publish,
|
||||||
@ -72,5 +72,5 @@ export const createZipPublisher: PublisherFactory<ZipFactoryParams, ZipPublisher
|
|||||||
setProject,
|
setProject,
|
||||||
getOutputPath,
|
getOutputPath,
|
||||||
setOutputPath,
|
setOutputPath,
|
||||||
}
|
};
|
||||||
}
|
};
|
||||||
|
|||||||
@ -6,52 +6,52 @@ export const isNodeProcess = (): boolean => {
|
|||||||
typeof process === 'object' &&
|
typeof process === 'object' &&
|
||||||
typeof process.versions === 'object' &&
|
typeof process.versions === 'object' &&
|
||||||
typeof process.versions.node !== 'undefined'
|
typeof process.versions.node !== 'undefined'
|
||||||
)
|
);
|
||||||
}
|
};
|
||||||
|
|
||||||
export const writeZipToDisk = (
|
export const writeZipToDisk = (
|
||||||
zipFolderPath: string,
|
zipFolderPath: string,
|
||||||
content: Buffer | Blob,
|
content: Buffer | Blob,
|
||||||
zipName: string
|
zipName: string,
|
||||||
): void => {
|
): void => {
|
||||||
const fs = require('fs')
|
const fs = require('fs');
|
||||||
const path = require('path')
|
const path = require('path');
|
||||||
|
|
||||||
if (!fs.existsSync(zipFolderPath)) {
|
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)
|
const writeStream = fs.createWriteStream(zipPath);
|
||||||
writeStream.write(content)
|
writeStream.write(content);
|
||||||
writeStream.end()
|
writeStream.end();
|
||||||
}
|
};
|
||||||
|
|
||||||
export const generateProjectZip = async (project: IResultDir): Promise<Buffer | Blob> => {
|
export const generateProjectZip = async (project: IResultDir): Promise<Buffer | Blob> => {
|
||||||
let zip = new JSZip()
|
let zip = new JSZip();
|
||||||
zip = writeFolderToZip(project, zip, true)
|
zip = writeFolderToZip(project, zip, true);
|
||||||
const zipType = isNodeProcess() ? 'nodebuffer' : 'blob'
|
const zipType = isNodeProcess() ? 'nodebuffer' : 'blob';
|
||||||
return zip.generateAsync({ type: zipType })
|
return zip.generateAsync({ type: zipType });
|
||||||
}
|
};
|
||||||
|
|
||||||
const writeFolderToZip = (
|
const writeFolderToZip = (
|
||||||
folder: IResultDir,
|
folder: IResultDir,
|
||||||
parentFolder: JSZip,
|
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) => {
|
folder.files.forEach((file: IResultFile) => {
|
||||||
// const options = file.contentEncoding === 'base64' ? { base64: true } : {}
|
// const options = file.contentEncoding === 'base64' ? { base64: true } : {}
|
||||||
const options = {};
|
const options = {};
|
||||||
const fileName = file.ext ? `${file.name}.${file.ext}` : file.name
|
const fileName = file.ext ? `${file.name}.${file.ext}` : file.name;
|
||||||
zipFolder.file(fileName, file.content, options)
|
zipFolder.file(fileName, file.content, options);
|
||||||
})
|
});
|
||||||
|
|
||||||
folder.dirs.forEach((subFolder: IResultDir) => {
|
folder.dirs.forEach((subFolder: IResultDir) => {
|
||||||
writeFolderToZip(subFolder, zipFolder)
|
writeFolderToZip(subFolder, zipFolder);
|
||||||
})
|
});
|
||||||
|
|
||||||
return parentFolder
|
return parentFolder;
|
||||||
}
|
};
|
||||||
|
|||||||
@ -34,7 +34,7 @@ export default class Preview extends ReactProvider {
|
|||||||
containerId,
|
containerId,
|
||||||
components: { ...builtInComps, ...buildComponents({ '@alifd/next': 'Next' }, componentsMap) },
|
components: { ...builtInComps, ...buildComponents({ '@alifd/next': 'Next' }, componentsMap) },
|
||||||
componentsMap,
|
componentsMap,
|
||||||
utils: utils,
|
utils,
|
||||||
constants,
|
constants,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -44,7 +44,7 @@ export default class Preview extends ReactProvider {
|
|||||||
const appSchemaStr = localStorage.getItem('lce-dev-store');
|
const appSchemaStr = localStorage.getItem('lce-dev-store');
|
||||||
const appSchema = JSON.parse(appSchemaStr || '');
|
const appSchema = JSON.parse(appSchemaStr || '');
|
||||||
const idx = appSchema.componentsTree.findIndex(
|
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];
|
const schema = appSchema.componentsTree[idx];
|
||||||
return schema;
|
return schema;
|
||||||
|
|||||||
@ -2,7 +2,7 @@ import logo from '@ali/lowcode-plugin-sample-logo';
|
|||||||
import samplePreview from '@ali/lowcode-plugin-sample-preview';
|
import samplePreview from '@ali/lowcode-plugin-sample-preview';
|
||||||
import undoRedo from '@ali/lowcode-plugin-undo-redo';
|
import undoRedo from '@ali/lowcode-plugin-undo-redo';
|
||||||
import componentsPane from '@ali/lowcode-plugin-components-pane';
|
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 zhEn from '@ali/lowcode-plugin-zh-en';
|
||||||
import eventBindDialog from '@ali/lowcode-plugin-event-bind-dialog';
|
import eventBindDialog from '@ali/lowcode-plugin-event-bind-dialog';
|
||||||
import variableBindDialog from '@ali/lowcode-plugin-variable-bind-dialog';
|
import variableBindDialog from '@ali/lowcode-plugin-variable-bind-dialog';
|
||||||
|
|||||||
@ -123,9 +123,6 @@ export default {
|
|||||||
const simulatorUrl = [
|
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.css',
|
||||||
'https://dev.g.alicdn.com/ali-lowcode/ali-lowcode-engine/0.9.50/react-simulator-renderer.js',
|
'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('simulatorUrl', simulatorUrl);
|
||||||
// editor.set('renderEnv', 'rax');
|
// editor.set('renderEnv', 'rax');
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
import { render } from 'react-dom';
|
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 config from './config';
|
||||||
import components from './components';
|
import components from './components';
|
||||||
import './global.scss';
|
import './global.scss';
|
||||||
|
|||||||
@ -28,7 +28,7 @@ const Codeout = ({ editor }: PluginProps) => {
|
|||||||
const designer = editor.get(Designer);
|
const designer = editor.get(Designer);
|
||||||
if (designer) {
|
if (designer) {
|
||||||
const assets = editor.get('assets') as { components: BasicSection[] };
|
const assets = editor.get('assets') as { components: BasicSection[] };
|
||||||
const components = assets.components;
|
const { components } = assets;
|
||||||
|
|
||||||
const componentsMap = components
|
const componentsMap = components
|
||||||
.filter((c) => !!c.npm)
|
.filter((c) => !!c.npm)
|
||||||
|
|||||||
@ -22,10 +22,7 @@ interface BasicSection {
|
|||||||
|
|
||||||
const Codeout = ({ editor }: PluginProps) => {
|
const Codeout = ({ editor }: PluginProps) => {
|
||||||
const handleSaveClick = () => {
|
const handleSaveClick = () => {
|
||||||
|
const schema = editor.get('designer').project.getSchema();
|
||||||
debugger;
|
|
||||||
|
|
||||||
let schema = editor.get('designer').project.getSchema();
|
|
||||||
console.log(schema);
|
console.log(schema);
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
4
packages/demo/src/vision/module.d.ts
vendored
4
packages/demo/src/vision/module.d.ts
vendored
@ -9,5 +9,5 @@ declare module '@ali/ve-page-history';
|
|||||||
declare module '@ali/ve-i18n-manage-pane';
|
declare module '@ali/ve-i18n-manage-pane';
|
||||||
declare module '@ali/ve-action-pane';
|
declare module '@ali/ve-action-pane';
|
||||||
declare module '@ali/vu-legao-design-fetch-context';
|
declare module '@ali/vu-legao-design-fetch-context';
|
||||||
declare module "@ali/vu-function-parser";
|
declare module '@ali/vu-function-parser';
|
||||||
declare module "compare-versions";
|
declare module 'compare-versions';
|
||||||
|
|||||||
16
packages/designer/.eslintrc.js
Normal file
16
packages/designer/.eslintrc.js
Normal 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,
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -56,10 +56,10 @@ export class BorderDetecting extends Component<{ host: BuiltinSimulatorHost }> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@computed get current() {
|
@computed get current() {
|
||||||
const host = this.props.host;
|
const { host } = this.props;
|
||||||
const doc = host.document;
|
const doc = host.document;
|
||||||
const selection = doc.selection;
|
const { selection } = doc;
|
||||||
const current = host.designer.detecting.current;
|
const { current } = host.designer.detecting;
|
||||||
if (!current || current.document !== doc || selection.has(current.id)) {
|
if (!current || current.document !== doc || selection.has(current.id)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -67,8 +67,8 @@ export class BorderDetecting extends Component<{ host: BuiltinSimulatorHost }> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const host = this.props.host;
|
const { host } = this.props;
|
||||||
const current = this.current;
|
const { current } = this;
|
||||||
if (!current || host.viewport.scrolling || host.liveEditing.editing) {
|
if (!current || host.viewport.scrolling || host.liveEditing.editing) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -23,7 +23,7 @@ export default class BoxResizing extends Component<{ host: BuiltinSimulatorHost
|
|||||||
if (doc.suspensed) {
|
if (doc.suspensed) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const selection = doc.selection;
|
const { selection } = doc;
|
||||||
return this.dragging ? selection.getTopNodes() : selection.getNodes();
|
return this.dragging ? selection.getTopNodes() : selection.getNodes();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -37,7 +37,7 @@ export default class BoxResizing extends Component<{ host: BuiltinSimulatorHost
|
|||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const selecting = this.selecting;
|
const { selecting } = this;
|
||||||
if (!selecting || selecting.length < 1) {
|
if (!selecting || selecting.length < 1) {
|
||||||
// DIRTY FIX, recore has a bug!
|
// DIRTY FIX, recore has a bug!
|
||||||
return <Fragment />;
|
return <Fragment />;
|
||||||
@ -79,7 +79,7 @@ export class BoxResizingForNode extends Component<{ host: BuiltinSimulatorHost;
|
|||||||
render() {
|
render() {
|
||||||
const { instances } = this;
|
const { instances } = this;
|
||||||
const { node } = this.props;
|
const { node } = this.props;
|
||||||
const designer = this.host.designer;
|
const { designer } = this.host;
|
||||||
|
|
||||||
if (!instances || instances.length < 1) {
|
if (!instances || instances.length < 1) {
|
||||||
return null;
|
return null;
|
||||||
@ -112,8 +112,11 @@ export class BoxResizingInstance extends Component<{
|
|||||||
}> {
|
}> {
|
||||||
// private outline: any;
|
// private outline: any;
|
||||||
private willUnbind: () => any;
|
private willUnbind: () => any;
|
||||||
|
|
||||||
private outlineRight: any;
|
private outlineRight: any;
|
||||||
|
|
||||||
private outlineLeft: any;
|
private outlineLeft: any;
|
||||||
|
|
||||||
private dragEngine: DragResizeEngine;
|
private dragEngine: DragResizeEngine;
|
||||||
|
|
||||||
constructor(props: any) {
|
constructor(props: any) {
|
||||||
|
|||||||
@ -59,6 +59,7 @@ class Toolbar extends Component<{ observed: OffsetObserver }> {
|
|||||||
shouldComponentUpdate() {
|
shouldComponentUpdate() {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const { observed } = this.props;
|
const { observed } = this.props;
|
||||||
const { height, width } = observed.viewport;
|
const { height, width } = observed.viewport;
|
||||||
@ -169,7 +170,7 @@ export class BorderSelectingForNode extends Component<{ host: BuiltinSimulatorHo
|
|||||||
render() {
|
render() {
|
||||||
const { instances } = this;
|
const { instances } = this;
|
||||||
const { node } = this.props;
|
const { node } = this.props;
|
||||||
const designer = this.host.designer;
|
const { designer } = this.host;
|
||||||
|
|
||||||
if (!instances || instances.length < 1) {
|
if (!instances || instances.length < 1) {
|
||||||
return null;
|
return null;
|
||||||
@ -206,7 +207,7 @@ export class BorderSelecting extends Component<{ host: BuiltinSimulatorHost }> {
|
|||||||
if (doc.suspensed || this.host.liveEditing.editing) {
|
if (doc.suspensed || this.host.liveEditing.editing) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const selection = doc.selection;
|
const { selection } = doc;
|
||||||
return this.dragging ? selection.getTopNodes() : selection.getNodes();
|
return this.dragging ? selection.getTopNodes() : selection.getNodes();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -215,7 +216,7 @@ export class BorderSelecting extends Component<{ host: BuiltinSimulatorHost }> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const selecting = this.selecting;
|
const { selecting } = this;
|
||||||
if (!selecting || selecting.length < 1) {
|
if (!selecting || selecting.length < 1) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
import { EventEmitter } from 'events';
|
import { EventEmitter } from 'events';
|
||||||
import { ISimulatorHost, isSimulatorHost } from '../../simulator';
|
import { ISimulatorHost } from '../../simulator';
|
||||||
import { Designer, Point } from '../../designer';
|
import { Designer, Point } from '../../designer';
|
||||||
import { setNativeSelection, cursor } from '@ali/lowcode-utils';
|
import { cursor } from '@ali/lowcode-utils';
|
||||||
// import Cursor from './cursor';
|
// import Cursor from './cursor';
|
||||||
// import Pages from './pages';
|
// import Pages from './pages';
|
||||||
|
|
||||||
@ -19,7 +19,7 @@ function makeEventsHandler(
|
|||||||
// }
|
// }
|
||||||
docs.add(sourceDoc);
|
docs.add(sourceDoc);
|
||||||
// if (sourceDoc !== topDoc || isDragEvent(boostEvent)) {
|
// if (sourceDoc !== topDoc || isDragEvent(boostEvent)) {
|
||||||
sensors.forEach((sim) => {
|
sensors.forEach(sim => {
|
||||||
const sdoc = sim.contentDocument;
|
const sdoc = sim.contentDocument;
|
||||||
if (sdoc) {
|
if (sdoc) {
|
||||||
docs.add(sdoc);
|
docs.add(sdoc);
|
||||||
@ -28,32 +28,21 @@ function makeEventsHandler(
|
|||||||
// }
|
// }
|
||||||
|
|
||||||
return (handle: (sdoc: Document) => void) => {
|
return (handle: (sdoc: Document) => void) => {
|
||||||
docs.forEach((doc) => handle(doc));
|
docs.forEach(doc => handle(doc));
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 拖动缩放
|
// 拖动缩放
|
||||||
export default class DragResizeEngine {
|
export default class DragResizeEngine {
|
||||||
private emitter: EventEmitter;
|
private emitter: EventEmitter;
|
||||||
|
|
||||||
private dragResizing = false;
|
private dragResizing = false;
|
||||||
|
|
||||||
constructor(readonly designer: Designer) {
|
constructor(designer: Designer) {
|
||||||
this.designer = designer;
|
this.designer = designer;
|
||||||
this.emitter = new EventEmitter();
|
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() {
|
isDragResizing() {
|
||||||
return this.dragResizing;
|
return this.dragResizing;
|
||||||
}
|
}
|
||||||
@ -83,14 +72,12 @@ export default class DragResizeEngine {
|
|||||||
const masterSensors = this.getMasterSensors();
|
const masterSensors = this.getMasterSensors();
|
||||||
|
|
||||||
const createResizeEvent = (e: MouseEvent | DragEvent): Point => {
|
const createResizeEvent = (e: MouseEvent | DragEvent): Point => {
|
||||||
const evt: any = {};
|
|
||||||
|
|
||||||
const sourceDocument = e.view?.document;
|
const sourceDocument = e.view?.document;
|
||||||
|
|
||||||
if (!sourceDocument || sourceDocument === document) {
|
if (!sourceDocument || sourceDocument === document) {
|
||||||
return e;
|
return e;
|
||||||
}
|
}
|
||||||
const srcSim = masterSensors.find((sim) => sim.contentDocument === sourceDocument);
|
const srcSim = masterSensors.find(sim => sim.contentDocument === sourceDocument);
|
||||||
if (srcSim) {
|
if (srcSim) {
|
||||||
return srcSim.viewport.toGlobalPoint(e);
|
return srcSim.viewport.toGlobalPoint(e);
|
||||||
}
|
}
|
||||||
@ -99,7 +86,7 @@ export default class DragResizeEngine {
|
|||||||
|
|
||||||
const over = (e: MouseEvent) => {
|
const over = (e: MouseEvent) => {
|
||||||
const handleEvents = makeEventsHandler(e, masterSensors);
|
const handleEvents = makeEventsHandler(e, masterSensors);
|
||||||
handleEvents((doc) => {
|
handleEvents(doc => {
|
||||||
doc.removeEventListener('mousemove', move, true);
|
doc.removeEventListener('mousemove', move, true);
|
||||||
doc.removeEventListener('mouseup', over, true);
|
doc.removeEventListener('mouseup', over, true);
|
||||||
});
|
});
|
||||||
@ -114,7 +101,7 @@ export default class DragResizeEngine {
|
|||||||
node = boost(e);
|
node = boost(e);
|
||||||
startEvent = createResizeEvent(e);
|
startEvent = createResizeEvent(e);
|
||||||
const handleEvents = makeEventsHandler(e, masterSensors);
|
const handleEvents = makeEventsHandler(e, masterSensors);
|
||||||
handleEvents((doc) => {
|
handleEvents(doc => {
|
||||||
doc.addEventListener('mousemove', move, true);
|
doc.addEventListener('mousemove', move, true);
|
||||||
doc.addEventListener('mouseup', over, 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);
|
this.emitter.on('resize', func);
|
||||||
return () => {
|
return () => {
|
||||||
this.emitter.removeListener('resize', func);
|
this.emitter.removeListener('resize', func);
|
||||||
@ -149,6 +138,18 @@ export default class DragResizeEngine {
|
|||||||
this.emitter.removeListener('resizeEnd', func);
|
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();
|
// new DragResizeEngine();
|
||||||
|
|||||||
@ -15,7 +15,7 @@ export class BemTools extends Component<{ host: BuiltinSimulatorHost }> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
const host = this.props.host;
|
const { host } = this.props;
|
||||||
const { scrollX, scrollY, scale } = host.viewport;
|
const { scrollX, scrollY, scale } = host.viewport;
|
||||||
return (
|
return (
|
||||||
<div className="lc-bem-tools" style={{ transform: `translate(${-scrollX * scale}px,${-scrollY * scale}px)` }}>
|
<div className="lc-bem-tools" style={{ transform: `translate(${-scrollX * scale}px,${-scrollY * scale}px)` }}>
|
||||||
|
|||||||
@ -1,15 +1,14 @@
|
|||||||
import { Component } from 'react';
|
import { Component } from 'react';
|
||||||
import { computed, observer } from '@ali/lowcode-editor-core';
|
import { observer } from '@ali/lowcode-editor-core';
|
||||||
import { SimulatorContext } from '../context';
|
|
||||||
import { BuiltinSimulatorHost } from '../host';
|
import { BuiltinSimulatorHost } from '../host';
|
||||||
import {
|
import {
|
||||||
DropLocation,
|
DropLocation,
|
||||||
Rect,
|
Rect,
|
||||||
isLocationChildrenDetail,
|
isLocationChildrenDetail,
|
||||||
LocationChildrenDetail,
|
LocationChildrenDetail,
|
||||||
isVertical
|
isVertical,
|
||||||
} from '../../designer';
|
} from '../../designer';
|
||||||
import { ISimulatorHost, } from '../../simulator';
|
import { ISimulatorHost } from '../../simulator';
|
||||||
import { ParentalNode } from '../../document';
|
import { ParentalNode } from '../../document';
|
||||||
import './insertion.less';
|
import './insertion.less';
|
||||||
|
|
||||||
|
|||||||
@ -8,8 +8,8 @@ import {
|
|||||||
isAssetItem,
|
isAssetItem,
|
||||||
AssetType,
|
AssetType,
|
||||||
assetItem,
|
assetItem,
|
||||||
} from '@ali/lowcode-utils';
|
isCSSUrl } from '@ali/lowcode-utils';
|
||||||
import { isCSSUrl } from '@ali/lowcode-utils';
|
|
||||||
import { BuiltinSimulatorRenderer } from './renderer';
|
import { BuiltinSimulatorRenderer } from './renderer';
|
||||||
|
|
||||||
export function createSimulator(
|
export function createSimulator(
|
||||||
@ -65,7 +65,7 @@ export function createSimulator(
|
|||||||
|
|
||||||
const styleFrags = Object.keys(styles)
|
const styleFrags = Object.keys(styles)
|
||||||
.map((key) => {
|
.map((key) => {
|
||||||
return styles[key].join('\n') + `<meta level="${key}" />`;
|
return `${styles[key].join('\n') }<meta level="${key}" />`;
|
||||||
})
|
})
|
||||||
.join('');
|
.join('');
|
||||||
const scriptFrags = Object.keys(scripts)
|
const scriptFrags = Object.keys(scripts)
|
||||||
|
|||||||
@ -2,7 +2,6 @@ import { Component } from 'react';
|
|||||||
import { observer } from '@ali/lowcode-editor-core';
|
import { observer } from '@ali/lowcode-editor-core';
|
||||||
import { BuiltinSimulatorHost, BuiltinSimulatorProps } from './host';
|
import { BuiltinSimulatorHost, BuiltinSimulatorProps } from './host';
|
||||||
import { DocumentModel } from '../document';
|
import { DocumentModel } from '../document';
|
||||||
import { SimulatorContext } from './context';
|
|
||||||
import { BemTools } from './bem-tools';
|
import { BemTools } from './bem-tools';
|
||||||
import './host.less';
|
import './host.less';
|
||||||
|
|
||||||
@ -22,25 +21,29 @@ type SimulatorHostProps = BuiltinSimulatorProps & {
|
|||||||
|
|
||||||
export class BuiltinSimulatorHostView extends Component<SimulatorHostProps> {
|
export class BuiltinSimulatorHostView extends Component<SimulatorHostProps> {
|
||||||
readonly host: BuiltinSimulatorHost;
|
readonly host: BuiltinSimulatorHost;
|
||||||
|
|
||||||
constructor(props: any) {
|
constructor(props: any) {
|
||||||
super(props);
|
super(props);
|
||||||
const { documentContext } = this.props;
|
const { documentContext } = this.props;
|
||||||
this.host = (documentContext.simulator as BuiltinSimulatorHost) || new BuiltinSimulatorHost(documentContext);
|
this.host = (documentContext.simulator as BuiltinSimulatorHost) || new BuiltinSimulatorHost(documentContext);
|
||||||
this.host.setProps(this.props);
|
this.host.setProps(this.props);
|
||||||
}
|
}
|
||||||
|
|
||||||
shouldComponentUpdate(nextProps: BuiltinSimulatorProps) {
|
shouldComponentUpdate(nextProps: BuiltinSimulatorProps) {
|
||||||
this.host.setProps(nextProps);
|
this.host.setProps(nextProps);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
componentDidMount() {
|
componentDidMount() {
|
||||||
if (this.props.onMount) {
|
if (this.props.onMount) {
|
||||||
this.props.onMount(this.host);
|
this.props.onMount(this.host);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
render() {
|
render() {
|
||||||
return (
|
return (
|
||||||
<div className="lc-simulator">
|
<div className="lc-simulator">
|
||||||
{/*progressing.visible ? <PreLoaderView /> : null*/}
|
{/* progressing.visible ? <PreLoaderView /> : null */}
|
||||||
<Canvas host={this.host} />
|
<Canvas host={this.host} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@ -73,7 +76,7 @@ class Canvas extends Component<{ host: BuiltinSimulatorHost }> {
|
|||||||
class Content extends Component<{ host: BuiltinSimulatorHost }> {
|
class Content extends Component<{ host: BuiltinSimulatorHost }> {
|
||||||
render() {
|
render() {
|
||||||
const sim = this.props.host;
|
const sim = this.props.host;
|
||||||
const viewport = sim.viewport;
|
const { viewport } = sim;
|
||||||
const frameStyle = {
|
const frameStyle = {
|
||||||
transform: `scale(${viewport.scale})`,
|
transform: `scale(${viewport.scale})`,
|
||||||
height: viewport.contentHeight,
|
height: viewport.contentHeight,
|
||||||
|
|||||||
@ -60,6 +60,7 @@ export interface BuiltinSimulatorProps {
|
|||||||
const defaultSimulatorUrl = (() => {
|
const defaultSimulatorUrl = (() => {
|
||||||
const publicPath = getPublicPath();
|
const publicPath = getPublicPath();
|
||||||
let urls;
|
let urls;
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
const [_, prefix = '', dev] = /^(.+?)(\/js)?\/?$/.exec(publicPath) || [];
|
const [_, prefix = '', dev] = /^(.+?)(\/js)?\/?$/.exec(publicPath) || [];
|
||||||
if (dev) {
|
if (dev) {
|
||||||
urls = [`${prefix}/css/react-simulator-renderer.css`, `${prefix}/js/react-simulator-renderer.js`];
|
urls = [`${prefix}/css/react-simulator-renderer.css`, `${prefix}/js/react-simulator-renderer.js`];
|
||||||
@ -74,6 +75,7 @@ const defaultSimulatorUrl = (() => {
|
|||||||
const defaultRaxSimulatorUrl = (() => {
|
const defaultRaxSimulatorUrl = (() => {
|
||||||
const publicPath = getPublicPath();
|
const publicPath = getPublicPath();
|
||||||
let urls;
|
let urls;
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
const [_, prefix = '', dev] = /^(.+?)(\/js)?\/?$/.exec(publicPath) || [];
|
const [_, prefix = '', dev] = /^(.+?)(\/js)?\/?$/.exec(publicPath) || [];
|
||||||
if (dev) {
|
if (dev) {
|
||||||
urls = [`${prefix}/css/rax-simulator-renderer.css`, `${prefix}/js/rax-simulator-renderer.js`];
|
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 = {};
|
@obx.ref _props: BuiltinSimulatorProps = {};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @see ISimulator
|
* @see ISimulator
|
||||||
*/
|
*/
|
||||||
setProps(props: BuiltinSimulatorProps) {
|
setProps(props: BuiltinSimulatorProps) {
|
||||||
this._props = props;
|
this._props = props;
|
||||||
}
|
}
|
||||||
|
|
||||||
set(key: string, value: any) {
|
set(key: string, value: any) {
|
||||||
this._props = {
|
this._props = {
|
||||||
...this._props,
|
...this._props,
|
||||||
[key]: value,
|
[key]: value,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
get(key: string): any {
|
get(key: string): any {
|
||||||
return this._props[key];
|
return this._props[key];
|
||||||
}
|
}
|
||||||
@ -173,6 +178,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
}
|
}
|
||||||
|
|
||||||
readonly viewport = new Viewport();
|
readonly viewport = new Viewport();
|
||||||
|
|
||||||
readonly scroller = this.designer.createScroller(this.viewport);
|
readonly scroller = this.designer.createScroller(this.viewport);
|
||||||
|
|
||||||
mountViewport(viewport: Element | null) {
|
mountViewport(viewport: Element | null) {
|
||||||
@ -180,16 +186,19 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
}
|
}
|
||||||
|
|
||||||
@obx.ref private _contentWindow?: Window;
|
@obx.ref private _contentWindow?: Window;
|
||||||
|
|
||||||
get contentWindow() {
|
get contentWindow() {
|
||||||
return this._contentWindow;
|
return this._contentWindow;
|
||||||
}
|
}
|
||||||
|
|
||||||
@obx.ref private _contentDocument?: Document;
|
@obx.ref private _contentDocument?: Document;
|
||||||
|
|
||||||
get contentDocument() {
|
get contentDocument() {
|
||||||
return this._contentDocument;
|
return this._contentDocument;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _renderer?: BuiltinSimulatorRenderer;
|
private _renderer?: BuiltinSimulatorRenderer;
|
||||||
|
|
||||||
get renderer() {
|
get renderer() {
|
||||||
return this._renderer;
|
return this._renderer;
|
||||||
}
|
}
|
||||||
@ -203,6 +212,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
readonly libraryMap: { [key: string]: string } = {};
|
readonly libraryMap: { [key: string]: string } = {};
|
||||||
|
|
||||||
private _iframe?: HTMLIFrameElement;
|
private _iframe?: HTMLIFrameElement;
|
||||||
|
|
||||||
async mountContentFrame(iframe: HTMLIFrameElement | null) {
|
async mountContentFrame(iframe: HTMLIFrameElement | null) {
|
||||||
if (!iframe || this._iframe === iframe) {
|
if (!iframe || this._iframe === iframe) {
|
||||||
return;
|
return;
|
||||||
@ -279,8 +289,8 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
|
|
||||||
setupDragAndClick() {
|
setupDragAndClick() {
|
||||||
const documentModel = this.document;
|
const documentModel = this.document;
|
||||||
const selection = documentModel.selection;
|
const { selection } = documentModel;
|
||||||
const designer = documentModel.designer;
|
const { designer } = documentModel;
|
||||||
const doc = this.contentDocument!;
|
const doc = this.contentDocument!;
|
||||||
|
|
||||||
// TODO: think of lock when edit a node
|
// TODO: think of lock when edit a node
|
||||||
@ -312,7 +322,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
const checkSelect = (e: MouseEvent) => {
|
const checkSelect = (e: MouseEvent) => {
|
||||||
doc.removeEventListener('mouseup', checkSelect, true);
|
doc.removeEventListener('mouseup', checkSelect, true);
|
||||||
if (!isShaken(downEvent, e)) {
|
if (!isShaken(downEvent, e)) {
|
||||||
const id = node.id;
|
const { id } = node;
|
||||||
designer.activeTracker.track({ node, instance: nodeInst?.instance });
|
designer.activeTracker.track({ node, instance: nodeInst?.instance });
|
||||||
if (isMulti && !isRootNode(node) && selection.has(id)) {
|
if (isMulti && !isRootNode(node) && selection.has(id)) {
|
||||||
selection.remove(id);
|
selection.remove(id);
|
||||||
@ -411,12 +421,13 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
}
|
}
|
||||||
|
|
||||||
private disableHovering?: () => void;
|
private disableHovering?: () => void;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 设置悬停处理
|
* 设置悬停处理
|
||||||
*/
|
*/
|
||||||
setupDetecting() {
|
setupDetecting() {
|
||||||
const doc = this.contentDocument!;
|
const doc = this.contentDocument!;
|
||||||
const detecting = this.document.designer.detecting;
|
const { detecting } = this.document.designer;
|
||||||
const hover = (e: MouseEvent) => {
|
const hover = (e: MouseEvent) => {
|
||||||
if (!detecting.enable) {
|
if (!detecting.enable) {
|
||||||
return;
|
return;
|
||||||
@ -448,6 +459,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
}
|
}
|
||||||
|
|
||||||
readonly liveEditing = new LiveEditing();
|
readonly liveEditing = new LiveEditing();
|
||||||
|
|
||||||
setupLiveEditing() {
|
setupLiveEditing() {
|
||||||
const doc = this.contentDocument!;
|
const doc = this.contentDocument!;
|
||||||
// cause edit
|
// cause edit
|
||||||
@ -493,11 +505,9 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
this.disableHovering();
|
this.disableHovering();
|
||||||
}
|
}
|
||||||
// sleep some autorun reaction
|
// sleep some autorun reaction
|
||||||
} else {
|
} else if (!this.disableHovering) {
|
||||||
// weekup some autorun reaction
|
// 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[]>();
|
@obx.val private instancesMap = new Map<string, ComponentInstance[]>();
|
||||||
|
|
||||||
setInstance(id: string, instances: ComponentInstance[] | null) {
|
setInstance(id: string, instances: ComponentInstance[] | null) {
|
||||||
if (instances == null) {
|
if (instances == null) {
|
||||||
this.instancesMap.delete(id);
|
this.instancesMap.delete(id);
|
||||||
@ -585,14 +596,14 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
/**
|
/**
|
||||||
* @see ISimulator
|
* @see ISimulator
|
||||||
*/
|
*/
|
||||||
getComponentInstanceId(instance: ComponentInstance) {
|
getComponentInstanceId(/* instance: ComponentInstance */) {
|
||||||
throw new Error('Method not implemented.');
|
throw new Error('Method not implemented.');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @see ISimulator
|
* @see ISimulator
|
||||||
*/
|
*/
|
||||||
getComponentContext(node: Node): object {
|
getComponentContext(/* node: Node */): any {
|
||||||
throw new Error('Method not implemented.');
|
throw new Error('Method not implemented.');
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -627,7 +638,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
const elems = elements.slice();
|
const elems = elements.slice();
|
||||||
let rects: DOMRect[] | undefined;
|
let rects: DOMRect[] | undefined;
|
||||||
let last: { x: number; y: number; r: number; b: number } | undefined;
|
let last: { x: number; y: number; r: number; b: number } | undefined;
|
||||||
let computed = false;
|
let _computed = false;
|
||||||
while (true) {
|
while (true) {
|
||||||
if (!rects || rects.length < 1) {
|
if (!rects || rects.length < 1) {
|
||||||
const elem = elems.pop();
|
const elem = elems.pop();
|
||||||
@ -654,26 +665,26 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
}
|
}
|
||||||
if (rect.left < last.x) {
|
if (rect.left < last.x) {
|
||||||
last.x = rect.left;
|
last.x = rect.left;
|
||||||
computed = true;
|
_computed = true;
|
||||||
}
|
}
|
||||||
if (rect.top < last.y) {
|
if (rect.top < last.y) {
|
||||||
last.y = rect.top;
|
last.y = rect.top;
|
||||||
computed = true;
|
_computed = true;
|
||||||
}
|
}
|
||||||
if (rect.right > last.r) {
|
if (rect.right > last.r) {
|
||||||
last.r = rect.right;
|
last.r = rect.right;
|
||||||
computed = true;
|
_computed = true;
|
||||||
}
|
}
|
||||||
if (rect.bottom > last.b) {
|
if (rect.bottom > last.b) {
|
||||||
last.b = rect.bottom;
|
last.b = rect.bottom;
|
||||||
computed = true;
|
_computed = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (last) {
|
if (last) {
|
||||||
const r: any = new DOMRect(last.x, last.y, last.r - last.x, last.b - last.y);
|
const r: any = new DOMRect(last.x, last.y, last.r - last.x, last.b - last.y);
|
||||||
r.elements = elements;
|
r.elements = elements;
|
||||||
r.computed = computed;
|
r.computed = _computed;
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -719,10 +730,11 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
}
|
}
|
||||||
|
|
||||||
private tryScrollAgain: number | null = null;
|
private tryScrollAgain: number | null = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @see ISimulator
|
* @see ISimulator
|
||||||
*/
|
*/
|
||||||
scrollToNode(node: Node, detail?: any, tryTimes = 0) {
|
scrollToNode(node: Node, detail?: any/* , tryTimes = 0 */) {
|
||||||
this.tryScrollAgain = null;
|
this.tryScrollAgain = null;
|
||||||
if (this.sensing) {
|
if (this.sensing) {
|
||||||
// actived sensor
|
// actived sensor
|
||||||
@ -744,7 +756,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
if (y < bounds.top || y > bounds.bottom) {
|
if (y < bounds.top || y > bounds.bottom) {
|
||||||
scroll = true;
|
scroll = true;
|
||||||
}
|
}
|
||||||
}*/
|
} */
|
||||||
} else {
|
} else {
|
||||||
/*
|
/*
|
||||||
const rect = this.document.computeRect(node);
|
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) {
|
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);
|
opt.left = Math.min(rect.left + rect.width / 2 + sl - left - width / 2, scrollWidth - width);
|
||||||
scroll = true;
|
scroll = true;
|
||||||
}*/
|
} */
|
||||||
}
|
}
|
||||||
|
|
||||||
if (scroll && this.scroller) {
|
if (scroll && this.scroller) {
|
||||||
@ -783,18 +795,21 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
setNativeSelection(enableFlag: boolean) {
|
setNativeSelection(enableFlag: boolean) {
|
||||||
this.renderer?.setNativeSelection(enableFlag);
|
this.renderer?.setNativeSelection(enableFlag);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @see ISimulator
|
* @see ISimulator
|
||||||
*/
|
*/
|
||||||
setDraggingState(state: boolean) {
|
setDraggingState(state: boolean) {
|
||||||
this.renderer?.setDraggingState(state);
|
this.renderer?.setDraggingState(state);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @see ISimulator
|
* @see ISimulator
|
||||||
*/
|
*/
|
||||||
setCopyState(state: boolean) {
|
setCopyState(state: boolean) {
|
||||||
this.renderer?.setCopyState(state);
|
this.renderer?.setCopyState(state);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @see ISimulator
|
* @see ISimulator
|
||||||
*/
|
*/
|
||||||
@ -803,6 +818,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
}
|
}
|
||||||
|
|
||||||
private _sensorAvailable = true;
|
private _sensorAvailable = true;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @see ISensor
|
* @see ISensor
|
||||||
*/
|
*/
|
||||||
@ -851,6 +867,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
}
|
}
|
||||||
|
|
||||||
private sensing = false;
|
private sensing = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @see ISensor
|
* @see ISensor
|
||||||
*/
|
*/
|
||||||
@ -905,7 +922,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const children = container.children;
|
const { children } = container;
|
||||||
|
|
||||||
const detail: LocationChildrenDetail = {
|
const detail: LocationChildrenDetail = {
|
||||||
type: LocationDetailType.Children,
|
type: LocationDetailType.Children,
|
||||||
@ -916,7 +933,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
const locationData = {
|
const locationData = {
|
||||||
target: container,
|
target: container,
|
||||||
detail,
|
detail,
|
||||||
source: 'simulator' + this.document.id,
|
source: `simulator${ this.document.id}`,
|
||||||
event: e,
|
event: e,
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -934,7 +951,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
index: 0,
|
index: 0,
|
||||||
valid: true,
|
valid: true,
|
||||||
},
|
},
|
||||||
source: 'simulator' + this.document.id,
|
source: `simulator${ this.document.id}`,
|
||||||
event: e,
|
event: e,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -956,7 +973,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
const instances = this.getComponentInstances(node);
|
const instances = this.getComponentInstances(node);
|
||||||
const inst = instances
|
const inst = instances
|
||||||
? instances.length > 1
|
? 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]
|
: instances[0]
|
||||||
: null;
|
: null;
|
||||||
const rect = inst ? this.computeComponentInstanceRect(inst, node.componentMeta.rootSelector) : 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) {
|
if (!row && nearDistance !== 0) {
|
||||||
const edgeDistance = distanceToEdge(e as any, edge);
|
const edgeDistance = distanceToEdge(e as any, edge);
|
||||||
if (edgeDistance.distance < nearDistance!) {
|
if (edgeDistance.distance < nearDistance!) {
|
||||||
const nearAfter = edgeDistance.nearAfter;
|
const { nearAfter } = edgeDistance;
|
||||||
if (minTop == null) {
|
if (minTop == null) {
|
||||||
minTop = edge.top;
|
minTop = edge.top;
|
||||||
}
|
}
|
||||||
@ -1077,7 +1094,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
// TODO: renderengine support pointerEvents: none for acceleration
|
// TODO: renderengine support pointerEvents: none for acceleration
|
||||||
const drillDownExcludes = new Set<Node>();
|
const drillDownExcludes = new Set<Node>();
|
||||||
if (isDragNodeObject(dragObject)) {
|
if (isDragNodeObject(dragObject)) {
|
||||||
const nodes = dragObject.nodes;
|
const { nodes } = dragObject;
|
||||||
let i = nodes.length;
|
let i = nodes.length;
|
||||||
let p: any = container;
|
let p: any = container;
|
||||||
while (i-- > 0) {
|
while (i-- > 0) {
|
||||||
@ -1139,7 +1156,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
container = upward;
|
container = upward;
|
||||||
upward = null;
|
upward = null;
|
||||||
}
|
}
|
||||||
}*/
|
} */
|
||||||
container = res;
|
container = res;
|
||||||
upward = null;
|
upward = null;
|
||||||
}
|
}
|
||||||
@ -1147,7 +1164,7 @@ export class BuiltinSimulatorHost implements ISimulatorHost<BuiltinSimulatorProp
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
isAcceptable(container: ParentalNode): boolean {
|
isAcceptable(/* container: ParentalNode */): boolean {
|
||||||
return false;
|
return false;
|
||||||
/*
|
/*
|
||||||
const meta = container.componentMeta;
|
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;
|
const { dragObject } = e;
|
||||||
if (isRootNode(container)) {
|
if (isRootNode(container)) {
|
||||||
return this.document.checkDropTarget(container, dragObject as any);
|
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;
|
const children = container.children;
|
||||||
if (!children || children.length < 1) {
|
if (!children || children.length < 1) {
|
||||||
|
|||||||
@ -34,13 +34,15 @@ function addLiveEditingSpecificRule(rule: SpecificRule) {
|
|||||||
|
|
||||||
export class LiveEditing {
|
export class LiveEditing {
|
||||||
static addLiveEditingSpecificRule = addLiveEditingSpecificRule;
|
static addLiveEditingSpecificRule = addLiveEditingSpecificRule;
|
||||||
|
|
||||||
static addLiveEditingSaveHandler = addLiveEditingSaveHandler;
|
static addLiveEditingSaveHandler = addLiveEditingSaveHandler;
|
||||||
|
|
||||||
@obx.ref private _editing: Prop | null = null;
|
@obx.ref private _editing: Prop | null = null;
|
||||||
|
|
||||||
apply(target: EditingTarget) {
|
apply(target: EditingTarget) {
|
||||||
const { node, event, rootElement } = target;
|
const { node, event, rootElement } = target;
|
||||||
const targetElement = event.target as HTMLElement;
|
const targetElement = event.target as HTMLElement;
|
||||||
const liveTextEditing = node.componentMeta.liveTextEditing;
|
const { liveTextEditing } = node.componentMeta;
|
||||||
|
|
||||||
const editor = globalContext.get(Editor);
|
const editor = globalContext.get(Editor);
|
||||||
const npm = node?.componentMeta?.npm;
|
const npm = node?.componentMeta?.npm;
|
||||||
@ -64,14 +66,14 @@ export class LiveEditing {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
setterPropElement = queryPropElement(rootElement, targetElement, config.selector);
|
setterPropElement = queryPropElement(rootElement, targetElement, config.selector);
|
||||||
return setterPropElement ? true : false;
|
return !!setterPropElement;
|
||||||
});
|
});
|
||||||
propTarget = matched?.propTarget;
|
propTarget = matched?.propTarget;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
specificRules.some((rule) => {
|
specificRules.some((rule) => {
|
||||||
matched = rule(target);
|
matched = rule(target);
|
||||||
return matched ? true : false;
|
return !!matched;
|
||||||
});
|
});
|
||||||
if (matched) {
|
if (matched) {
|
||||||
propTarget = matched.propTarget;
|
propTarget = matched.propTarget;
|
||||||
@ -79,15 +81,15 @@ export class LiveEditing {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!propTarget) {
|
// if (!propTarget) {
|
||||||
// 自动纯文本编辑满足一下情况:
|
// // 自动纯文本编辑满足一下情况:
|
||||||
// 1. children 内容都是 Leaf 且都是文本(一期)
|
// // 1. children 内容都是 Leaf 且都是文本(一期)
|
||||||
// 2. DOM 节点是单层容器,子集都是文本节点 (已满足)
|
// // 2. DOM 节点是单层容器,子集都是文本节点 (已满足)
|
||||||
const isAllText = node.children?.every(item => {
|
// const isAllText = node.children?.every(item => {
|
||||||
return item.isLeaf() && item.getProp('children')?.type === 'literal';
|
// return item.isLeaf() && item.getProp('children')?.type === 'literal';
|
||||||
});
|
// });
|
||||||
// TODO:
|
// // TODO:
|
||||||
}
|
// }
|
||||||
|
|
||||||
if (propTarget && setterPropElement) {
|
if (propTarget && setterPropElement) {
|
||||||
const prop = node.getProp(propTarget, true)!;
|
const prop = node.getProp(propTarget, true)!;
|
||||||
@ -119,8 +121,10 @@ export class LiveEditing {
|
|||||||
console.info(e.code);
|
console.info(e.code);
|
||||||
switch (e.code) {
|
switch (e.code) {
|
||||||
case 'Enter':
|
case 'Enter':
|
||||||
|
break;
|
||||||
// TODO: check is richtext?
|
// TODO: check is richtext?
|
||||||
case 'Escape':
|
case 'Escape':
|
||||||
|
break;
|
||||||
case 'Tab':
|
case 'Tab':
|
||||||
setterPropElement?.blur();
|
setterPropElement?.blur();
|
||||||
}
|
}
|
||||||
@ -128,7 +132,7 @@ export class LiveEditing {
|
|||||||
// enter
|
// enter
|
||||||
// tab
|
// tab
|
||||||
};
|
};
|
||||||
const focusout = (e: FocusEvent) => {
|
const focusout = (/* e: FocusEvent */) => {
|
||||||
this.saveAndDispose();
|
this.saveAndDispose();
|
||||||
};
|
};
|
||||||
setterPropElement.addEventListener('focusout', focusout);
|
setterPropElement.addEventListener('focusout', focusout);
|
||||||
@ -147,8 +151,6 @@ export class LiveEditing {
|
|||||||
// TODO: process enter | esc events & joint the FocusTracker
|
// TODO: process enter | esc events & joint the FocusTracker
|
||||||
|
|
||||||
// TODO: upward testing for b/i/a html elements
|
// TODO: upward testing for b/i/a html elements
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
get editing() {
|
get editing() {
|
||||||
@ -156,7 +158,9 @@ export class LiveEditing {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private _dispose?: () => void;
|
private _dispose?: () => void;
|
||||||
|
|
||||||
private _save?: () => void;
|
private _save?: () => void;
|
||||||
|
|
||||||
saveAndDispose() {
|
saveAndDispose() {
|
||||||
if (this._save) {
|
if (this._save) {
|
||||||
this._save();
|
this._save();
|
||||||
|
|||||||
@ -58,17 +58,20 @@ export default class InstanceNodeSelector extends React.Component<IProps, IState
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
onMouseOver = (node: Node) => (_: any, flag = true) => {
|
onMouseOver = (node: Node) => (_: any, flag = true) => {
|
||||||
if (node && typeof node.hover === 'function') {
|
if (node && typeof node.hover === 'function') {
|
||||||
node.hover(flag);
|
node.hover(flag);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
onMouseOut = (node: Node) => (_: any, flag = false) => {
|
onMouseOut = (node: Node) => (_: any, flag = false) => {
|
||||||
if (node && typeof node.hover === 'function') {
|
if (node && typeof node.hover === 'function') {
|
||||||
node.hover(flag);
|
node.hover(flag);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
renderNodes = (node: Node) => {
|
|
||||||
|
renderNodes = (/* node: Node */) => {
|
||||||
const nodes = this.state.parentNodes || [];
|
const nodes = this.state.parentNodes || [];
|
||||||
const children = nodes.map((node, key) => {
|
const children = nodes.map((node, key) => {
|
||||||
return (
|
return (
|
||||||
|
|||||||
@ -21,16 +21,19 @@ export type RendererConsumer<T> = (renderer: BuiltinSimulatorRenderer, data: T)
|
|||||||
|
|
||||||
export default class ResourceConsumer<T = any> {
|
export default class ResourceConsumer<T = any> {
|
||||||
private emitter = new EventEmitter();
|
private emitter = new EventEmitter();
|
||||||
|
|
||||||
@obx.ref private _data: T | typeof UNSET = UNSET;
|
@obx.ref private _data: T | typeof UNSET = UNSET;
|
||||||
|
|
||||||
private _providing?: () => void;
|
private _providing?: () => void;
|
||||||
|
|
||||||
|
private _consuming?: () => void;
|
||||||
|
|
||||||
constructor(provider: () => T, private consumer?: RendererConsumer<T>) {
|
constructor(provider: () => T, private consumer?: RendererConsumer<T>) {
|
||||||
this._providing = autorun(() => {
|
this._providing = autorun(() => {
|
||||||
this._data = provider();
|
this._data = provider();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private _consuming?: () => void;
|
|
||||||
consume(consumerOrRenderer: BuiltinSimulatorRenderer | ((data: T) => any)) {
|
consume(consumerOrRenderer: BuiltinSimulatorRenderer | ((data: T) => any)) {
|
||||||
if (this._consuming) {
|
if (this._consuming) {
|
||||||
return;
|
return;
|
||||||
@ -72,6 +75,7 @@ export default class ResourceConsumer<T = any> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private _firstConsumed = false;
|
private _firstConsumed = false;
|
||||||
|
|
||||||
private resovleFirst?: () => void;
|
private resovleFirst?: () => void;
|
||||||
|
|
||||||
waitFirstConsume(): Promise<any> {
|
waitFirstConsume(): Promise<any> {
|
||||||
|
|||||||
@ -16,6 +16,7 @@ export const primitiveTypes = [
|
|||||||
'any',
|
'any',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||||
function makeRequired(propType: any, lowcodeType: string | object) {
|
function makeRequired(propType: any, lowcodeType: string | object) {
|
||||||
function lowcodeCheckTypeIsRequired(...rest: any[]) {
|
function lowcodeCheckTypeIsRequired(...rest: any[]) {
|
||||||
return propType.isRequired(...rest);
|
return propType.isRequired(...rest);
|
||||||
@ -32,6 +33,7 @@ function makeRequired(propType: any, lowcodeType: string | object) {
|
|||||||
return lowcodeCheckTypeIsRequired;
|
return lowcodeCheckTypeIsRequired;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||||
function define(propType: any = PropTypes.any, lowcodeType: string | object = {}) {
|
function define(propType: any = PropTypes.any, lowcodeType: string | object = {}) {
|
||||||
if (!propType._inner && propType.name !== 'lowcodeCheckType') {
|
if (!propType._inner && propType.name !== 'lowcodeCheckType') {
|
||||||
propType.lowcodeType = lowcodeType;
|
propType.lowcodeType = lowcodeType;
|
||||||
@ -136,7 +138,7 @@ export function parseProps(component: any): PropConfig[] {
|
|||||||
Object.keys(propTypes).forEach(key => {
|
Object.keys(propTypes).forEach(key => {
|
||||||
const propTypeItem = propTypes[key];
|
const propTypeItem = propTypes[key];
|
||||||
const defaultValue = defaultProps[key];
|
const defaultValue = defaultProps[key];
|
||||||
const lowcodeType = propTypeItem.lowcodeType;
|
const { lowcodeType } = propTypeItem;
|
||||||
if (lowcodeType) {
|
if (lowcodeType) {
|
||||||
result[key] = {
|
result[key] = {
|
||||||
name: key,
|
name: key,
|
||||||
|
|||||||
@ -158,7 +158,7 @@ export function joinPath(...segments: string[]) {
|
|||||||
if (path === '') {
|
if (path === '') {
|
||||||
path += seg;
|
path += seg;
|
||||||
} else {
|
} else {
|
||||||
path += '/' + seg;
|
path += `/${ seg}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,5 +1,6 @@
|
|||||||
const useRAF = typeof requestAnimationFrame === 'function';
|
const useRAF = typeof requestAnimationFrame === 'function';
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||||
export function throttle(func: Function, delay: number) {
|
export function throttle(func: Function, delay: number) {
|
||||||
let lastArgs: any;
|
let lastArgs: any;
|
||||||
let lastThis: any;
|
let lastThis: any;
|
||||||
|
|||||||
@ -4,7 +4,9 @@ import { AutoFit, IViewport } from '../simulator';
|
|||||||
|
|
||||||
export default class Viewport implements IViewport {
|
export default class Viewport implements IViewport {
|
||||||
@obx.ref private rect?: DOMRect;
|
@obx.ref private rect?: DOMRect;
|
||||||
|
|
||||||
private _bounds?: DOMRect;
|
private _bounds?: DOMRect;
|
||||||
|
|
||||||
get bounds(): DOMRect {
|
get bounds(): DOMRect {
|
||||||
if (this._bounds) {
|
if (this._bounds) {
|
||||||
return this._bounds;
|
return this._bounds;
|
||||||
@ -17,12 +19,13 @@ export default class Viewport implements IViewport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get contentBounds(): DOMRect {
|
get contentBounds(): DOMRect {
|
||||||
const bounds = this.bounds;
|
const { bounds } = this;
|
||||||
const scale = this.scale;
|
const { scale } = this;
|
||||||
return new DOMRect(0, 0, bounds.width / scale, bounds.height / scale);
|
return new DOMRect(0, 0, bounds.width / scale, bounds.height / scale);
|
||||||
}
|
}
|
||||||
|
|
||||||
private viewportElement?: HTMLElement;
|
private viewportElement?: HTMLElement;
|
||||||
|
|
||||||
mount(viewportElement: HTMLElement | null) {
|
mount(viewportElement: HTMLElement | null) {
|
||||||
if (!viewportElement || this.viewportElement === viewportElement) {
|
if (!viewportElement || this.viewportElement === viewportElement) {
|
||||||
return;
|
return;
|
||||||
@ -67,7 +70,7 @@ export default class Viewport implements IViewport {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@obx.ref private _scale: number = 1;
|
@obx.ref private _scale = 1;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 缩放比例
|
* 缩放比例
|
||||||
@ -87,6 +90,7 @@ export default class Viewport implements IViewport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@obx.ref private _contentWidth: number | AutoFit = AutoFit;
|
@obx.ref private _contentWidth: number | AutoFit = AutoFit;
|
||||||
|
|
||||||
@obx.ref private _contentHeight: number | AutoFit = AutoFit;
|
@obx.ref private _contentHeight: number | AutoFit = AutoFit;
|
||||||
|
|
||||||
@computed get contentHeight(): number | AutoFit {
|
@computed get contentHeight(): number | AutoFit {
|
||||||
@ -106,15 +110,19 @@ export default class Viewport implements IViewport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@obx.ref private _scrollX = 0;
|
@obx.ref private _scrollX = 0;
|
||||||
|
|
||||||
@obx.ref private _scrollY = 0;
|
@obx.ref private _scrollY = 0;
|
||||||
|
|
||||||
get scrollX() {
|
get scrollX() {
|
||||||
return this._scrollX;
|
return this._scrollX;
|
||||||
}
|
}
|
||||||
|
|
||||||
get scrollY() {
|
get scrollY() {
|
||||||
return this._scrollY;
|
return this._scrollY;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _scrollTarget?: ScrollTarget;
|
private _scrollTarget?: ScrollTarget;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 滚动对象
|
* 滚动对象
|
||||||
*/
|
*/
|
||||||
@ -123,6 +131,7 @@ export default class Viewport implements IViewport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@obx private _scrolling = false;
|
@obx private _scrolling = false;
|
||||||
|
|
||||||
get scrolling(): boolean {
|
get scrolling(): boolean {
|
||||||
return this._scrolling;
|
return this._scrolling;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -13,7 +13,7 @@ import {
|
|||||||
FieldConfig,
|
FieldConfig,
|
||||||
} from '@ali/lowcode-types';
|
} from '@ali/lowcode-types';
|
||||||
import { computed } from '@ali/lowcode-editor-core';
|
import { computed } from '@ali/lowcode-editor-core';
|
||||||
import { Node, ParentalNode, TransformStage } from './document';
|
import { Node, ParentalNode } from './document';
|
||||||
import { Designer } from './designer';
|
import { Designer } from './designer';
|
||||||
import { intlNode } from './locale';
|
import { intlNode } from './locale';
|
||||||
import { IconContainer } from './icons/container';
|
import { IconContainer } from './icons/container';
|
||||||
@ -63,45 +63,62 @@ function buildFilter(rule?: string | string[] | RegExp | NestingFilter) {
|
|||||||
|
|
||||||
export class ComponentMeta {
|
export class ComponentMeta {
|
||||||
readonly isComponentMeta = true;
|
readonly isComponentMeta = true;
|
||||||
|
|
||||||
private _npm?: NpmInfo;
|
private _npm?: NpmInfo;
|
||||||
|
|
||||||
get npm() {
|
get npm() {
|
||||||
return this._npm;
|
return this._npm;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _componentName?: string;
|
private _componentName?: string;
|
||||||
|
|
||||||
get componentName(): string {
|
get componentName(): string {
|
||||||
return this._componentName!;
|
return this._componentName!;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _isContainer?: boolean;
|
private _isContainer?: boolean;
|
||||||
|
|
||||||
get isContainer(): boolean {
|
get isContainer(): boolean {
|
||||||
return this._isContainer! || this.isRootComponent();
|
return this._isContainer! || this.isRootComponent();
|
||||||
}
|
}
|
||||||
|
|
||||||
private _isModal?: boolean;
|
private _isModal?: boolean;
|
||||||
|
|
||||||
get isModal(): boolean {
|
get isModal(): boolean {
|
||||||
return this._isModal!;
|
return this._isModal!;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _descriptor?: string;
|
private _descriptor?: string;
|
||||||
|
|
||||||
get descriptor(): string | undefined {
|
get descriptor(): string | undefined {
|
||||||
return this._descriptor;
|
return this._descriptor;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _rootSelector?: string;
|
private _rootSelector?: string;
|
||||||
|
|
||||||
get rootSelector(): string | undefined {
|
get rootSelector(): string | undefined {
|
||||||
return this._rootSelector;
|
return this._rootSelector;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _transformedMetadata?: TransformedComponentMetadata;
|
private _transformedMetadata?: TransformedComponentMetadata;
|
||||||
|
|
||||||
get configure() {
|
get configure() {
|
||||||
const config = this._transformedMetadata?.configure;
|
const config = this._transformedMetadata?.configure;
|
||||||
return config?.combined || config?.props || [];
|
return config?.combined || config?.props || [];
|
||||||
}
|
}
|
||||||
|
|
||||||
private _liveTextEditing?: LiveTextEditingConfig[];
|
private _liveTextEditing?: LiveTextEditingConfig[];
|
||||||
|
|
||||||
get liveTextEditing() {
|
get liveTextEditing() {
|
||||||
return this._liveTextEditing;
|
return this._liveTextEditing;
|
||||||
}
|
}
|
||||||
|
|
||||||
private parentWhitelist?: NestingFilter | null;
|
private parentWhitelist?: NestingFilter | null;
|
||||||
|
|
||||||
private childWhitelist?: NestingFilter | null;
|
private childWhitelist?: NestingFilter | null;
|
||||||
|
|
||||||
private _title?: TitleContent;
|
private _title?: TitleContent;
|
||||||
|
|
||||||
get title(): string | I18nData | ReactElement {
|
get title(): string | I18nData | ReactElement {
|
||||||
// TODO: 标记下。这块需要康师傅加一下API,页面正常渲染。
|
// TODO: 标记下。这块需要康师傅加一下API,页面正常渲染。
|
||||||
// string | i18nData | ReactElement
|
// string | i18nData | ReactElement
|
||||||
@ -123,6 +140,7 @@ export class ComponentMeta {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private _acceptable?: boolean;
|
private _acceptable?: boolean;
|
||||||
|
|
||||||
get acceptable(): boolean {
|
get acceptable(): boolean {
|
||||||
return this._acceptable!;
|
return this._acceptable!;
|
||||||
}
|
}
|
||||||
@ -145,7 +163,7 @@ export class ComponentMeta {
|
|||||||
// 额外转换逻辑
|
// 额外转换逻辑
|
||||||
this._transformedMetadata = this.transformMetadata(metadata);
|
this._transformedMetadata = this.transformMetadata(metadata);
|
||||||
|
|
||||||
const title = this._transformedMetadata.title;
|
const { title } = this._transformedMetadata;
|
||||||
if (title) {
|
if (title) {
|
||||||
this._title =
|
this._title =
|
||||||
typeof title === 'string'
|
typeof title === 'string'
|
||||||
@ -182,8 +200,8 @@ export class ComponentMeta {
|
|||||||
|
|
||||||
const { component } = configure;
|
const { component } = configure;
|
||||||
if (component) {
|
if (component) {
|
||||||
this._isContainer = component.isContainer ? true : false;
|
this._isContainer = !!component.isContainer;
|
||||||
this._isModal = component.isModal ? true : false;
|
this._isModal = !!component.isModal;
|
||||||
this._descriptor = component.descriptor;
|
this._descriptor = component.descriptor;
|
||||||
this._rootSelector = component.rootSelector;
|
this._rootSelector = component.rootSelector;
|
||||||
if (component.nestingRule) {
|
if (component.nestingRule) {
|
||||||
@ -208,11 +226,12 @@ export class ComponentMeta {
|
|||||||
return result as any;
|
return result as any;
|
||||||
}
|
}
|
||||||
|
|
||||||
isRootComponent(includeBlock: boolean = true) {
|
isRootComponent(includeBlock = true) {
|
||||||
return this.componentName === 'Page' || this.componentName === 'Component' || (includeBlock && this.componentName === 'Block');
|
return this.componentName === 'Page' || this.componentName === 'Component' || (includeBlock && this.componentName === 'Block');
|
||||||
}
|
}
|
||||||
|
|
||||||
@computed get availableActions() {
|
@computed get availableActions() {
|
||||||
|
// eslint-disable-next-line prefer-const
|
||||||
let { disableBehaviors, actions } = this._transformedMetadata?.configure.component || {};
|
let { disableBehaviors, actions } = this._transformedMetadata?.configure.component || {};
|
||||||
const disabled = ensureAList(disableBehaviors) || (this.isRootComponent(false) ? ['copy', 'remove'] : null);
|
const disabled = ensureAList(disableBehaviors) || (this.isRootComponent(false) ? ['copy', 'remove'] : null);
|
||||||
actions = builtinComponentActions.concat(this.designer.getGlobalComponentActions() || [], actions || []);
|
actions = builtinComponentActions.concat(this.designer.getGlobalComponentActions() || [], actions || []);
|
||||||
@ -313,6 +332,7 @@ registerMetadataTransducer((metadata) => {
|
|||||||
if (!component.nestingRule) {
|
if (!component.nestingRule) {
|
||||||
let m;
|
let m;
|
||||||
// uri match xx.Group set subcontrolling: true, childWhiteList
|
// uri match xx.Group set subcontrolling: true, childWhiteList
|
||||||
|
// eslint-disable-next-line no-cond-assign
|
||||||
if ((m = /^(.+)\.Group$/.exec(componentName))) {
|
if ((m = /^(.+)\.Group$/.exec(componentName))) {
|
||||||
// component.subControlling = true;
|
// component.subControlling = true;
|
||||||
if (!component.nestingRule) {
|
if (!component.nestingRule) {
|
||||||
@ -320,16 +340,16 @@ registerMetadataTransducer((metadata) => {
|
|||||||
childWhitelist: [`${m[1]}`],
|
childWhitelist: [`${m[1]}`],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
// eslint-disable-next-line no-cond-assign
|
||||||
// uri match xx.Node set selfControlled: false, parentWhiteList
|
} else if ((m = /^(.+)\.Node$/.exec(componentName))) {
|
||||||
else if ((m = /^(.+)\.Node$/.exec(componentName))) {
|
// uri match xx.Node set selfControlled: false, parentWhiteList
|
||||||
// component.selfControlled = false;
|
// component.selfControlled = false;
|
||||||
component.nestingRule = {
|
component.nestingRule = {
|
||||||
parentWhitelist: [`${m[1]}`, componentName],
|
parentWhitelist: [`${m[1]}`, componentName],
|
||||||
};
|
};
|
||||||
}
|
// eslint-disable-next-line no-cond-assign
|
||||||
// uri match .Item .Node .Option set parentWhiteList
|
} else if ((m = /^(.+)\.(Item|Node|Option)$/.exec(componentName))) {
|
||||||
else if ((m = /^(.+)\.(Item|Node|Option)$/.exec(componentName))) {
|
// uri match .Item .Node .Option set parentWhiteList
|
||||||
component.nestingRule = {
|
component.nestingRule = {
|
||||||
parentWhitelist: [`${m[1]}`],
|
parentWhitelist: [`${m[1]}`],
|
||||||
};
|
};
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
import { EventEmitter } from 'events';
|
import { EventEmitter } from 'events';
|
||||||
import { LocationDetail } from './location';
|
import { LocationDetail } from './location';
|
||||||
import { Node, isNode } from '../document/node/node';
|
import { Node, isNode } from '../document/node/node';
|
||||||
import { ComponentInstance } from '../simulator';
|
import { ComponentInstance } from '../simulator';
|
||||||
import { obx } from '@ali/lowcode-editor-core';
|
import { obx } from '@ali/lowcode-editor-core';
|
||||||
|
|
||||||
|
|||||||
@ -107,7 +107,7 @@ hotkey.bind(['command+c', 'ctrl+c', 'command+x', 'ctrl+x'], (e, action) => {
|
|||||||
let selected = doc.selection.getTopNodes(true);
|
let selected = doc.selection.getTopNodes(true);
|
||||||
selected = selected.filter((node) => {
|
selected = selected.filter((node) => {
|
||||||
return node.canPerformAction('copy');
|
return node.canPerformAction('copy');
|
||||||
})
|
});
|
||||||
if (!selected || selected.length < 1) {
|
if (!selected || selected.length < 1) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -242,11 +242,10 @@ hotkey.bind(['option+left', 'option+right'], (e, action) => {
|
|||||||
parent.insertAfter(firstNode, silbing);
|
parent.insertAfter(firstNode, silbing);
|
||||||
}
|
}
|
||||||
firstNode?.select();
|
firstNode?.select();
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
hotkey.bind(['option+up'], (e, action) => {
|
hotkey.bind(['option+up'], (e) => {
|
||||||
const designer = focusing.focusDesigner;
|
const designer = focusing.focusDesigner;
|
||||||
const doc = designer?.currentDocument;
|
const doc = designer?.currentDocument;
|
||||||
if (isFormEvent(e) || !doc) {
|
if (isFormEvent(e) || !doc) {
|
||||||
@ -275,7 +274,6 @@ hotkey.bind(['option+up'], (e, action) => {
|
|||||||
parent.insertBefore(firstNode, silbing);
|
parent.insertBefore(firstNode, silbing);
|
||||||
}
|
}
|
||||||
firstNode?.select();
|
firstNode?.select();
|
||||||
return;
|
|
||||||
} else {
|
} else {
|
||||||
const place = parent.getSuitablePlace(firstNode, null); // upwards
|
const place = parent.getSuitablePlace(firstNode, null); // upwards
|
||||||
if (place) {
|
if (place) {
|
||||||
@ -285,7 +283,7 @@ hotkey.bind(['option+up'], (e, action) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
hotkey.bind(['option+down'], (e, action) => {
|
hotkey.bind(['option+down'], (e) => {
|
||||||
const designer = focusing.focusDesigner;
|
const designer = focusing.focusDesigner;
|
||||||
const doc = designer?.currentDocument;
|
const doc = designer?.currentDocument;
|
||||||
if (isFormEvent(e) || !doc) {
|
if (isFormEvent(e) || !doc) {
|
||||||
@ -315,7 +313,6 @@ hotkey.bind(['option+down'], (e, action) => {
|
|||||||
parent.insertAfter(firstNode, silbing);
|
parent.insertAfter(firstNode, silbing);
|
||||||
}
|
}
|
||||||
firstNode?.select();
|
firstNode?.select();
|
||||||
return;
|
|
||||||
} else {
|
} else {
|
||||||
const place = parent.getSuitablePlace(firstNode, null); // upwards
|
const place = parent.getSuitablePlace(firstNode, null); // upwards
|
||||||
if (place) {
|
if (place) {
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
function getDataFromPasteEvent(event: ClipboardEvent) {
|
function getDataFromPasteEvent(event: ClipboardEvent) {
|
||||||
const clipboardData = event.clipboardData;
|
const { clipboardData } = event;
|
||||||
if (!clipboardData) {
|
if (!clipboardData) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -14,7 +14,7 @@ function getDataFromPasteEvent(event: ClipboardEvent) {
|
|||||||
return data;
|
return data;
|
||||||
} else if (data.componentName) {
|
} else if (data.componentName) {
|
||||||
return {
|
return {
|
||||||
componentsTree: [ data ]
|
componentsTree: [data],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -34,12 +34,13 @@ function getDataFromPasteEvent(event: ClipboardEvent) {
|
|||||||
return {
|
return {
|
||||||
code: clipboardData.getData('text/plain'),
|
code: clipboardData.getData('text/plain'),
|
||||||
maps: {},
|
maps: {},
|
||||||
};*/
|
}; */
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class Clipboard {
|
class Clipboard {
|
||||||
private copyPasters: HTMLTextAreaElement[] = [];
|
private copyPasters: HTMLTextAreaElement[] = [];
|
||||||
|
|
||||||
private waitFn?: (data: any, e: ClipboardEvent) => void;
|
private waitFn?: (data: any, e: ClipboardEvent) => void;
|
||||||
|
|
||||||
isCopyPasteEvent(e: Event) {
|
isCopyPasteEvent(e: Event) {
|
||||||
|
|||||||
@ -24,7 +24,7 @@ export class DesignerView extends Component<DesignerProps & {
|
|||||||
|
|
||||||
shouldComponentUpdate(nextProps: DesignerProps) {
|
shouldComponentUpdate(nextProps: DesignerProps) {
|
||||||
this.designer.setProps(nextProps);
|
this.designer.setProps(nextProps);
|
||||||
const props = this.props;
|
const { props } = this;
|
||||||
if (
|
if (
|
||||||
nextProps.className !== props.className ||
|
nextProps.className !== props.className ||
|
||||||
nextProps.style !== props.style ||
|
nextProps.style !== props.style ||
|
||||||
@ -40,11 +40,11 @@ export class DesignerView extends Component<DesignerProps & {
|
|||||||
if (onMount) {
|
if (onMount) {
|
||||||
onMount(this.designer);
|
onMount(this.designer);
|
||||||
}
|
}
|
||||||
clipboard.injectCopyPaster(document)
|
clipboard.injectCopyPaster(document);
|
||||||
this.designer.postEvent('mount', this.designer);
|
this.designer.postEvent('mount', this.designer);
|
||||||
}
|
}
|
||||||
|
|
||||||
componentWillMount() {
|
UNSAFE_componentWillMount() {
|
||||||
this.designer.purge();
|
this.designer.purge();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -44,9 +44,13 @@ export interface DesignerProps {
|
|||||||
|
|
||||||
export class Designer {
|
export class Designer {
|
||||||
readonly dragon = new Dragon(this);
|
readonly dragon = new Dragon(this);
|
||||||
|
|
||||||
readonly activeTracker = new ActiveTracker();
|
readonly activeTracker = new ActiveTracker();
|
||||||
|
|
||||||
readonly detecting = new Detecting();
|
readonly detecting = new Detecting();
|
||||||
|
|
||||||
readonly project: Project;
|
readonly project: Project;
|
||||||
|
|
||||||
readonly editor: IEditor;
|
readonly editor: IEditor;
|
||||||
|
|
||||||
get currentDocument() {
|
get currentDocument() {
|
||||||
@ -132,6 +136,7 @@ export class Designer {
|
|||||||
[npm?.package, npm?.componentName].filter((item) => !!item).join('-') ||
|
[npm?.package, npm?.componentName].filter((item) => !!item).join('-') ||
|
||||||
parent?.componentMeta?.componentName ||
|
parent?.componentMeta?.componentName ||
|
||||||
'';
|
'';
|
||||||
|
// eslint-disable-next-line no-unused-expressions
|
||||||
this.editor?.emit('designer.drag', {
|
this.editor?.emit('designer.drag', {
|
||||||
time: (endTime - startTime).toFixed(2),
|
time: (endTime - startTime).toFixed(2),
|
||||||
selected: nodes
|
selected: nodes
|
||||||
@ -139,6 +144,7 @@ export class Designer {
|
|||||||
if (!n) {
|
if (!n) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// eslint-disable-next-line no-shadow
|
||||||
const npm = n?.componentMeta?.npm;
|
const npm = n?.componentMeta?.npm;
|
||||||
return (
|
return (
|
||||||
[npm?.package, npm?.componentName].filter((item) => !!item).join('-') ||
|
[npm?.package, npm?.componentName].filter((item) => !!item).join('-') ||
|
||||||
@ -173,7 +179,7 @@ export class Designer {
|
|||||||
}
|
}
|
||||||
this.postEvent('selection.change', this.currentSelection);
|
this.postEvent('selection.change', this.currentSelection);
|
||||||
if (this.currentSelection) {
|
if (this.currentSelection) {
|
||||||
const currentSelection = this.currentSelection;
|
const { currentSelection } = this;
|
||||||
selectionDispose = currentSelection.onSelectionChange(() => {
|
selectionDispose = currentSelection.onSelectionChange(() => {
|
||||||
this.postEvent('selection.change', currentSelection);
|
this.postEvent('selection.change', currentSelection);
|
||||||
});
|
});
|
||||||
@ -187,7 +193,7 @@ export class Designer {
|
|||||||
}
|
}
|
||||||
this.postEvent('history.change', this.currentHistory);
|
this.postEvent('history.change', this.currentHistory);
|
||||||
if (this.currentHistory) {
|
if (this.currentHistory) {
|
||||||
const currentHistory = this.currentHistory;
|
const { currentHistory } = this;
|
||||||
historyDispose = currentHistory.onStateChange(() => {
|
historyDispose = currentHistory.onStateChange(() => {
|
||||||
this.postEvent('history.change', currentHistory);
|
this.postEvent('history.change', currentHistory);
|
||||||
});
|
});
|
||||||
@ -217,6 +223,7 @@ export class Designer {
|
|||||||
get dropLocation() {
|
get dropLocation() {
|
||||||
return this._dropLocation;
|
return this._dropLocation;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 创建插入位置,考虑放到 dragon 中
|
* 创建插入位置,考虑放到 dragon 中
|
||||||
*/
|
*/
|
||||||
@ -246,6 +253,7 @@ export class Designer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private oobxList: OffsetObserver[] = [];
|
private oobxList: OffsetObserver[] = [];
|
||||||
|
|
||||||
createOffsetObserver(nodeInstance: INodeSelector): OffsetObserver | null {
|
createOffsetObserver(nodeInstance: INodeSelector): OffsetObserver | null {
|
||||||
const oobx = createOffsetObserver(nodeInstance);
|
const oobx = createOffsetObserver(nodeInstance);
|
||||||
this.clearOobxList();
|
this.clearOobxList();
|
||||||
@ -302,6 +310,7 @@ export class Designer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private props?: DesignerProps;
|
private props?: DesignerProps;
|
||||||
|
|
||||||
setProps(nextProps: DesignerProps) {
|
setProps(nextProps: DesignerProps) {
|
||||||
const props = this.props ? { ...this.props, ...nextProps } : nextProps;
|
const props = this.props ? { ...this.props, ...nextProps } : nextProps;
|
||||||
if (this.props) {
|
if (this.props) {
|
||||||
@ -380,6 +389,7 @@ export class Designer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@obx.val private _componentMetasMap = new Map<string, ComponentMeta>();
|
@obx.val private _componentMetasMap = new Map<string, ComponentMeta>();
|
||||||
|
|
||||||
private _lostComponentMetasMap = new Map<string, ComponentMeta>();
|
private _lostComponentMetasMap = new Map<string, ComponentMeta>();
|
||||||
|
|
||||||
private buildComponentMetasMap(metas: ComponentMetadata[]) {
|
private buildComponentMetasMap(metas: ComponentMetadata[]) {
|
||||||
@ -451,6 +461,7 @@ export class Designer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private propsReducers = new Map<TransformStage, PropsReducer[]>();
|
private propsReducers = new Map<TransformStage, PropsReducer[]>();
|
||||||
|
|
||||||
transformProps(props: CompositeObject | PropsList, node: Node, stage: TransformStage) {
|
transformProps(props: CompositeObject | PropsList, node: Node, stage: TransformStage) {
|
||||||
if (Array.isArray(props)) {
|
if (Array.isArray(props)) {
|
||||||
// current not support, make this future
|
// current not support, make this future
|
||||||
@ -464,7 +475,7 @@ export class Designer {
|
|||||||
|
|
||||||
return reducers.reduce((xprops, reducer) => {
|
return reducers.reduce((xprops, reducer) => {
|
||||||
try {
|
try {
|
||||||
return reducer(xprops, node)
|
return reducer(xprops, node);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// todo: add log
|
// todo: add log
|
||||||
console.warn(e);
|
console.warn(e);
|
||||||
|
|||||||
@ -3,18 +3,22 @@ import { Node, DocumentModel } from '../document';
|
|||||||
|
|
||||||
export class Detecting {
|
export class Detecting {
|
||||||
@obx.ref private _enable = true;
|
@obx.ref private _enable = true;
|
||||||
|
|
||||||
get enable() {
|
get enable() {
|
||||||
return this._enable;
|
return this._enable;
|
||||||
}
|
}
|
||||||
|
|
||||||
set enable(flag: boolean) {
|
set enable(flag: boolean) {
|
||||||
this._enable = flag;
|
this._enable = flag;
|
||||||
if (!flag) {
|
if (!flag) {
|
||||||
this._current = null;
|
this._current = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@obx.ref xRayMode = false;
|
@obx.ref xRayMode = false;
|
||||||
|
|
||||||
@obx.ref private _current: Node | null = null;
|
@obx.ref private _current: Node | null = null;
|
||||||
|
|
||||||
get current() {
|
get current() {
|
||||||
return this._current;
|
return this._current;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -9,9 +9,13 @@ type offBinding = () => any;
|
|||||||
@observer
|
@observer
|
||||||
export default class DragGhost extends Component<{ designer: Designer }> {
|
export default class DragGhost extends Component<{ designer: Designer }> {
|
||||||
private dispose: offBinding[] = [];
|
private dispose: offBinding[] = [];
|
||||||
|
|
||||||
@obx.ref private dragObject: DragObject | null = null;
|
@obx.ref private dragObject: DragObject | null = null;
|
||||||
|
|
||||||
@obx.ref private x = 0;
|
@obx.ref private x = 0;
|
||||||
|
|
||||||
@obx.ref private y = 0;
|
@obx.ref private y = 0;
|
||||||
|
|
||||||
private dragon = this.props.designer.dragon;
|
private dragon = this.props.designer.dragon;
|
||||||
|
|
||||||
constructor(props: any) {
|
constructor(props: any) {
|
||||||
@ -48,7 +52,7 @@ export default class DragGhost extends Component<{ designer: Designer }> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
renderGhostGroup() {
|
renderGhostGroup() {
|
||||||
const dragObject = this.dragObject;
|
const { dragObject } = this;
|
||||||
if (isDragNodeObject(dragObject)) {
|
if (isDragNodeObject(dragObject)) {
|
||||||
return dragObject.nodes.map(node => {
|
return dragObject.nodes.map(node => {
|
||||||
const ghost = (
|
const ghost = (
|
||||||
|
|||||||
@ -77,6 +77,7 @@ export interface ISensor {
|
|||||||
export type DragObject = DragNodeObject | DragNodeDataObject | DragAnyObject;
|
export type DragObject = DragNodeObject | DragNodeDataObject | DragAnyObject;
|
||||||
|
|
||||||
export enum DragObjectType {
|
export enum DragObjectType {
|
||||||
|
// eslint-disable-next-line no-shadow
|
||||||
Node = 'node',
|
Node = 'node',
|
||||||
NodeData = 'nodedata',
|
NodeData = 'nodedata',
|
||||||
}
|
}
|
||||||
@ -191,19 +192,20 @@ export class Dragon {
|
|||||||
* current actived sensor, 可用于感应区高亮
|
* current actived sensor, 可用于感应区高亮
|
||||||
*/
|
*/
|
||||||
@obx.ref private _activeSensor: ISensor | undefined;
|
@obx.ref private _activeSensor: ISensor | undefined;
|
||||||
|
|
||||||
get activeSensor(): ISensor | undefined {
|
get activeSensor(): ISensor | undefined {
|
||||||
return this._activeSensor;
|
return this._activeSensor;
|
||||||
}
|
}
|
||||||
|
|
||||||
@obx.ref private _dragging = false;
|
@obx.ref private _dragging = false;
|
||||||
|
|
||||||
get dragging(): boolean {
|
get dragging(): boolean {
|
||||||
return this._dragging;
|
return this._dragging;
|
||||||
}
|
}
|
||||||
|
|
||||||
private emitter = new EventEmitter();
|
private emitter = new EventEmitter();
|
||||||
|
|
||||||
constructor(readonly designer: Designer) {
|
constructor(readonly designer: Designer) {}
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Quick listen a shell(container element) drag behavior
|
* Quick listen a shell(container element) drag behavior
|
||||||
@ -238,7 +240,7 @@ export class Dragon {
|
|||||||
* @param boostEvent 拖拽初始时事件
|
* @param boostEvent 拖拽初始时事件
|
||||||
*/
|
*/
|
||||||
boost(dragObject: DragObject, boostEvent: MouseEvent | DragEvent) {
|
boost(dragObject: DragObject, boostEvent: MouseEvent | DragEvent) {
|
||||||
const designer = this.designer;
|
const { designer } = this;
|
||||||
const masterSensors = this.getMasterSensors();
|
const masterSensors = this.getMasterSensors();
|
||||||
const handleEvents = makeEventsHandler(boostEvent, masterSensors);
|
const handleEvents = makeEventsHandler(boostEvent, masterSensors);
|
||||||
const newBie = !isDragNodeObject(dragObject);
|
const newBie = !isDragNodeObject(dragObject);
|
||||||
|
|||||||
@ -1,4 +1,5 @@
|
|||||||
import './builtin-hotkey';
|
import './builtin-hotkey';
|
||||||
|
|
||||||
export * from './designer';
|
export * from './designer';
|
||||||
export * from './designer-view';
|
export * from './designer-view';
|
||||||
export * from './dragon';
|
export * from './dragon';
|
||||||
|
|||||||
@ -127,9 +127,13 @@ export function getWindow(elem: Element | Document): Window {
|
|||||||
|
|
||||||
export class DropLocation {
|
export class DropLocation {
|
||||||
readonly target: ParentalNode;
|
readonly target: ParentalNode;
|
||||||
|
|
||||||
readonly detail: LocationDetail;
|
readonly detail: LocationDetail;
|
||||||
|
|
||||||
readonly event: LocateEvent;
|
readonly event: LocateEvent;
|
||||||
|
|
||||||
readonly source: string;
|
readonly source: string;
|
||||||
|
|
||||||
get document(): DocumentModel {
|
get document(): DocumentModel {
|
||||||
return this.target.document;
|
return this.target.document;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,14 +7,23 @@ export class OffsetObserver {
|
|||||||
readonly id = uniqueId('oobx');
|
readonly id = uniqueId('oobx');
|
||||||
|
|
||||||
private lastOffsetLeft?: number;
|
private lastOffsetLeft?: number;
|
||||||
|
|
||||||
private lastOffsetTop?: number;
|
private lastOffsetTop?: number;
|
||||||
|
|
||||||
private lastOffsetHeight?: number;
|
private lastOffsetHeight?: number;
|
||||||
|
|
||||||
private lastOffsetWidth?: number;
|
private lastOffsetWidth?: number;
|
||||||
|
|
||||||
@obx private _height = 0;
|
@obx private _height = 0;
|
||||||
|
|
||||||
@obx private _width = 0;
|
@obx private _width = 0;
|
||||||
|
|
||||||
@obx private _left = 0;
|
@obx private _left = 0;
|
||||||
|
|
||||||
@obx private _top = 0;
|
@obx private _top = 0;
|
||||||
|
|
||||||
@obx private _right = 0;
|
@obx private _right = 0;
|
||||||
|
|
||||||
@obx private _bottom = 0;
|
@obx private _bottom = 0;
|
||||||
|
|
||||||
@computed get height() {
|
@computed get height() {
|
||||||
@ -42,6 +51,7 @@ export class OffsetObserver {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@obx hasOffset = false;
|
@obx hasOffset = false;
|
||||||
|
|
||||||
@computed get offsetLeft() {
|
@computed get offsetLeft() {
|
||||||
if (this.isRoot) {
|
if (this.isRoot) {
|
||||||
return this.viewport.scrollX * this.scale;
|
return this.viewport.scrollX * this.scale;
|
||||||
@ -51,6 +61,7 @@ export class OffsetObserver {
|
|||||||
}
|
}
|
||||||
return this.lastOffsetLeft;
|
return this.lastOffsetLeft;
|
||||||
}
|
}
|
||||||
|
|
||||||
@computed get offsetTop() {
|
@computed get offsetTop() {
|
||||||
if (this.isRoot) {
|
if (this.isRoot) {
|
||||||
return this.viewport.scrollY * this.scale;
|
return this.viewport.scrollY * this.scale;
|
||||||
@ -60,12 +71,14 @@ export class OffsetObserver {
|
|||||||
}
|
}
|
||||||
return this.lastOffsetTop;
|
return this.lastOffsetTop;
|
||||||
}
|
}
|
||||||
|
|
||||||
@computed get offsetHeight() {
|
@computed get offsetHeight() {
|
||||||
if (!this.viewport.scrolling || this.lastOffsetHeight == null) {
|
if (!this.viewport.scrolling || this.lastOffsetHeight == null) {
|
||||||
this.lastOffsetHeight = this.isRoot ? this.viewport.height : this.height;
|
this.lastOffsetHeight = this.isRoot ? this.viewport.height : this.height;
|
||||||
}
|
}
|
||||||
return this.lastOffsetHeight;
|
return this.lastOffsetHeight;
|
||||||
}
|
}
|
||||||
|
|
||||||
@computed get offsetWidth() {
|
@computed get offsetWidth() {
|
||||||
if (!this.viewport.scrolling || this.lastOffsetWidth == null) {
|
if (!this.viewport.scrolling || this.lastOffsetWidth == null) {
|
||||||
this.lastOffsetWidth = this.isRoot ? this.viewport.width : this.width;
|
this.lastOffsetWidth = this.isRoot ? this.viewport.width : this.width;
|
||||||
@ -78,8 +91,11 @@ export class OffsetObserver {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private pid: number | undefined;
|
private pid: number | undefined;
|
||||||
|
|
||||||
readonly viewport: IViewport;
|
readonly viewport: IViewport;
|
||||||
|
|
||||||
private isRoot: boolean;
|
private isRoot: boolean;
|
||||||
|
|
||||||
readonly node: Node;
|
readonly node: Node;
|
||||||
|
|
||||||
readonly compute: () => void;
|
readonly compute: () => void;
|
||||||
@ -109,18 +125,17 @@ export class OffsetObserver {
|
|||||||
|
|
||||||
if (!rect) {
|
if (!rect) {
|
||||||
this.hasOffset = false;
|
this.hasOffset = false;
|
||||||
} else {
|
} else if (!this.viewport.scrolling || !this.hasOffset) {
|
||||||
if (!this.viewport.scrolling || !this.hasOffset) {
|
this._height = rect.height;
|
||||||
this._height = rect.height;
|
this._width = rect.width;
|
||||||
this._width = rect.width;
|
this._left = rect.left;
|
||||||
this._left = rect.left;
|
this._top = rect.top;
|
||||||
this._top = rect.top;
|
this._right = rect.right;
|
||||||
this._right = rect.right;
|
this._bottom = rect.bottom;
|
||||||
this._bottom = rect.bottom;
|
this.hasOffset = true;
|
||||||
this.hasOffset = true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
this.pid = pid = (window as any).requestIdleCallback(compute);
|
this.pid = (window as any).requestIdleCallback(compute);
|
||||||
|
pid = this.pid;
|
||||||
};
|
};
|
||||||
|
|
||||||
this.compute = compute;
|
this.compute = compute;
|
||||||
@ -128,7 +143,8 @@ export class OffsetObserver {
|
|||||||
// try first
|
// try first
|
||||||
compute();
|
compute();
|
||||||
// try second, ensure the dom mounted
|
// try second, ensure the dom mounted
|
||||||
this.pid = pid = (window as any).requestIdleCallback(compute);
|
this.pid = (window as any).requestIdleCallback(compute);
|
||||||
|
pid = this.pid;
|
||||||
}
|
}
|
||||||
|
|
||||||
purge() {
|
purge() {
|
||||||
|
|||||||
@ -4,9 +4,11 @@ export class ScrollTarget {
|
|||||||
get left() {
|
get left() {
|
||||||
return 'scrollX' in this.target ? this.target.scrollX : this.target.scrollLeft;
|
return 'scrollX' in this.target ? this.target.scrollX : this.target.scrollLeft;
|
||||||
}
|
}
|
||||||
|
|
||||||
get top() {
|
get top() {
|
||||||
return 'scrollY' in this.target ? this.target.scrollY : this.target.scrollTop;
|
return 'scrollY' in this.target ? this.target.scrollY : this.target.scrollTop;
|
||||||
}
|
}
|
||||||
|
|
||||||
scrollTo(options: { left?: number; top?: number }) {
|
scrollTo(options: { left?: number; top?: number }) {
|
||||||
this.target.scrollTo(options);
|
this.target.scrollTo(options);
|
||||||
}
|
}
|
||||||
@ -24,6 +26,7 @@ export class ScrollTarget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private doe?: HTMLElement;
|
private doe?: HTMLElement;
|
||||||
|
|
||||||
constructor(private target: Window | Element) {
|
constructor(private target: Window | Element) {
|
||||||
if (isWindow(target)) {
|
if (isWindow(target)) {
|
||||||
this.doe = target.document.documentElement;
|
this.doe = target.document.documentElement;
|
||||||
@ -50,6 +53,8 @@ export interface IScrollable {
|
|||||||
export class Scroller {
|
export class Scroller {
|
||||||
private pid: number | undefined;
|
private pid: number | undefined;
|
||||||
|
|
||||||
|
constructor(private scrollable: IScrollable) {}
|
||||||
|
|
||||||
get scrollTarget(): ScrollTarget | null {
|
get scrollTarget(): ScrollTarget | null {
|
||||||
let target = this.scrollable.scrollTarget;
|
let target = this.scrollable.scrollTarget;
|
||||||
if (!target) {
|
if (!target) {
|
||||||
@ -62,19 +67,17 @@ export class Scroller {
|
|||||||
return target;
|
return target;
|
||||||
}
|
}
|
||||||
|
|
||||||
constructor(private scrollable: IScrollable) {}
|
|
||||||
|
|
||||||
scrollTo(options: { left?: number; top?: number }) {
|
scrollTo(options: { left?: number; top?: number }) {
|
||||||
this.cancel();
|
this.cancel();
|
||||||
|
|
||||||
const scrollTarget = this.scrollTarget;
|
const { scrollTarget } = this;
|
||||||
if (!scrollTarget) {
|
if (!scrollTarget) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let pid: number;
|
let pid: number;
|
||||||
const left = scrollTarget.left;
|
const { left } = scrollTarget;
|
||||||
const top = scrollTarget.top;
|
const { top } = scrollTarget;
|
||||||
const end = () => {
|
const end = () => {
|
||||||
this.cancel();
|
this.cancel();
|
||||||
};
|
};
|
||||||
@ -106,20 +109,22 @@ export class Scroller {
|
|||||||
scrollTarget.scrollTo(opt);
|
scrollTarget.scrollTo(opt);
|
||||||
|
|
||||||
if (time < 1) {
|
if (time < 1) {
|
||||||
this.pid = pid = requestAnimationFrame(animate);
|
this.pid = requestAnimationFrame(animate);
|
||||||
|
pid = this.pid;
|
||||||
} else {
|
} else {
|
||||||
end();
|
end();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
this.pid = pid = requestAnimationFrame(animate);
|
this.pid = requestAnimationFrame(animate);
|
||||||
|
pid = this.pid;
|
||||||
}
|
}
|
||||||
|
|
||||||
scrolling(point: { globalX: number; globalY: number }) {
|
scrolling(point: { globalX: number; globalY: number }) {
|
||||||
this.cancel();
|
this.cancel();
|
||||||
|
|
||||||
const { bounds, scale = 1 } = this.scrollable;
|
const { bounds, scale = 1 } = this.scrollable;
|
||||||
const scrollTarget = this.scrollTarget;
|
const { scrollTarget } = this;
|
||||||
if (!scrollTarget || !bounds) {
|
if (!scrollTarget || !bounds) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -19,29 +19,37 @@ function getSettingFieldCollectorKey(parent: SettingEntry, config: FieldConfig)
|
|||||||
|
|
||||||
export class SettingField extends SettingPropEntry implements SettingEntry {
|
export class SettingField extends SettingPropEntry implements SettingEntry {
|
||||||
readonly isSettingField = true;
|
readonly isSettingField = true;
|
||||||
|
|
||||||
readonly isRequired: boolean;
|
readonly isRequired: boolean;
|
||||||
|
|
||||||
readonly transducer: Transducer;
|
readonly transducer: Transducer;
|
||||||
|
|
||||||
private _config: FieldConfig;
|
private _config: FieldConfig;
|
||||||
|
|
||||||
extraProps: FieldExtraProps;
|
extraProps: FieldExtraProps;
|
||||||
|
|
||||||
// ==== dynamic properties ====
|
// ==== dynamic properties ====
|
||||||
private _title?: TitleContent;
|
private _title?: TitleContent;
|
||||||
|
|
||||||
get title() {
|
get title() {
|
||||||
// FIXME! intl
|
// FIXME! intl
|
||||||
return this._title || (typeof this.name === 'number' ? `项目 ${this.name}` : this.name);
|
return this._title || (typeof this.name === 'number' ? `项目 ${this.name}` : this.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
private _setter?: SetterType | DynamicSetter;
|
private _setter?: SetterType | DynamicSetter;
|
||||||
|
|
||||||
@computed get setter(): SetterType | null {
|
@computed get setter(): SetterType | null {
|
||||||
if (!this._setter) {
|
if (!this._setter) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
if (isDynamicSetter(this._setter)) {
|
if (isDynamicSetter(this._setter)) {
|
||||||
return this._setter.call(this,this);
|
return this._setter.call(this, this);
|
||||||
}
|
}
|
||||||
return this._setter;
|
return this._setter;
|
||||||
}
|
}
|
||||||
|
|
||||||
@obx.ref private _expanded = true;
|
@obx.ref private _expanded = true;
|
||||||
|
|
||||||
get expanded(): boolean {
|
get expanded(): boolean {
|
||||||
return this._expanded;
|
return this._expanded;
|
||||||
}
|
}
|
||||||
@ -62,7 +70,7 @@ export class SettingField extends SettingPropEntry implements SettingEntry {
|
|||||||
...extraProps,
|
...extraProps,
|
||||||
};
|
};
|
||||||
this.isRequired = config.isRequired || (setter as any)?.isRequired;
|
this.isRequired = config.isRequired || (setter as any)?.isRequired;
|
||||||
this._expanded = extraProps?.defaultCollapsed ? false : true;
|
this._expanded = !extraProps?.defaultCollapsed;
|
||||||
|
|
||||||
// initial items
|
// initial items
|
||||||
if (items && items.length > 0) {
|
if (items && items.length > 0) {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user