forked from alibaba/lowcode-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsSlot.ts
More file actions
69 lines (59 loc) · 2 KB
/
jsSlot.ts
File metadata and controls
69 lines (59 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { JSSlot, isJSSlot, NodeData } from '@alilc/lowcode-types';
import { CodeGeneratorError, NodeGenerator, IScope } from '../types';
import { unwrapJsExprQuoteInJsx } from './jsxHelpers';
function generateSingleLineComment(commentText: string): string {
return `/* ${commentText.split('\n').join(' ').replace(/\*\//g, '*-/')}*/`;
}
export function generateJsSlot(slot: any, scope: IScope, generator: NodeGenerator<string>): string {
if (isJSSlot(slot)) {
const { title, params, value } = slot as JSSlot;
// slot 也是分有参数和无参数的
// - 有参数的 slot 就是类似一个 render 函数,需要创建子作用域
// - 无参数的 slot 就是类似一个 JSX 节点,不需要创建子作用域
const slotScope = params ? scope.createSubScope(params || []) : scope;
const contentExpr = !value
? 'null'
: generateNodeDataOrArrayForJsSlot(value, generator, slotScope);
if (params) {
return [
title && generateSingleLineComment(title),
'(',
(params || []).join(', '),
') => ((__$$context) => (',
contentExpr,
'))(',
` __$$createChildContext(__$$context, { ${(params || []).join(', ')} }`,
'))',
]
.filter(Boolean)
.join('');
}
return contentExpr || '[]';
}
throw new CodeGeneratorError('Not a JSSlot');
}
function generateNodeDataOrArrayForJsSlot(
value: NodeData | NodeData[],
generator: NodeGenerator<string>,
scope: IScope,
) {
if (Array.isArray(value)) {
if (value.length === 0) {
return '[]';
}
if (value.length === 1) {
return unwrapJsExprQuoteInJsx(generator(value, scope)) || 'null';
}
return `[\n${
value
.map((v) => {
if (typeof v === 'string') {
return JSON.stringify(v);
}
return unwrapJsExprQuoteInJsx(generator(v, scope)) || 'null';
})
.join(',\n') || 'null'
}\n]`;
}
return unwrapJsExprQuoteInJsx(generator(value, scope)) || 'null';
}