vendor: amis 6.13.0 base (fork root)
This commit is contained in:
6
packages/amis-core/.gitignore
vendored
Normal file
6
packages/amis-core/.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
/lib
|
||||
/node_modules
|
||||
/esm
|
||||
/.rollup.cache
|
||||
/tsconfig.tsbuildinfo
|
||||
/coverage
|
||||
22
packages/amis-core/.swcrc
Normal file
22
packages/amis-core/.swcrc
Normal file
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/swcrc",
|
||||
"jsc": {
|
||||
"parser": {
|
||||
"syntax": "typescript",
|
||||
"tsx": true,
|
||||
"decorators": true,
|
||||
"dynamicImport": true
|
||||
},
|
||||
"transform": {
|
||||
"decoratorMetadata": true,
|
||||
"legacyDecorator": true,
|
||||
"react": {
|
||||
"runtime": "classic"
|
||||
}
|
||||
},
|
||||
"keepClassNames": true,
|
||||
"externalHelpers": true,
|
||||
"loose": false
|
||||
},
|
||||
"minify": false
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`factory custom not found 2! 1`] = `
|
||||
<div>
|
||||
<div>
|
||||
Not Found
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`factory custom not found 3! 1`] = `
|
||||
<div>
|
||||
<div>
|
||||
Not Found
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`factory custom not found! 1`] = `
|
||||
<div>
|
||||
<div>
|
||||
Not Found
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`factory load Renderer on need 1`] = `
|
||||
<div>
|
||||
<div>
|
||||
This is Custom Renderer2, a is
|
||||
23
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`factory unregistered Renderer 1`] = `
|
||||
<div>
|
||||
<div
|
||||
class="RuntimeError"
|
||||
>
|
||||
<p>
|
||||
Error: 找不到对应的渲染器
|
||||
</p>
|
||||
<p>
|
||||
Path:
|
||||
my-renderer
|
||||
</p>
|
||||
<pre>
|
||||
<code>
|
||||
{
|
||||
"type": "my-renderer",
|
||||
"a": 23
|
||||
}
|
||||
</code>
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
exports[`factory:registerRenderer 1`] = `
|
||||
<div>
|
||||
<div>
|
||||
This is Custom Renderer, a is
|
||||
23
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
403
packages/amis-core/__tests__/async-filter.test.ts
Normal file
403
packages/amis-core/__tests__/async-filter.test.ts
Normal file
@@ -0,0 +1,403 @@
|
||||
import {resolveVariableAndFilterForAsync} from '../src/utils/tpl-builtin';
|
||||
import {evaluateForAsync} from 'amis-formula';
|
||||
|
||||
test(`filter:map`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a | map: toInt}', {
|
||||
a: ['123', '3434']
|
||||
})
|
||||
).toMatchObject([123, 3434]);
|
||||
});
|
||||
test(`filter:html`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a}', {
|
||||
a: '<html>'
|
||||
})
|
||||
).toEqual('<html>');
|
||||
});
|
||||
|
||||
test(`filter:complex`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${`${a}`}', {
|
||||
a: '<html>'
|
||||
})
|
||||
).toEqual('<html>');
|
||||
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a ? a : a}', {
|
||||
a: '<html>'
|
||||
})
|
||||
).toEqual('<html>');
|
||||
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${b.a}', {
|
||||
a: '<html>',
|
||||
b: {
|
||||
a: '<br />'
|
||||
}
|
||||
})
|
||||
).toEqual('<br />');
|
||||
});
|
||||
|
||||
test(`filter:json`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a | json : 0}', {
|
||||
a: {a: 1}
|
||||
})
|
||||
).toEqual('{"a":1}');
|
||||
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a | json : 2}', {
|
||||
a: {a: 1}
|
||||
})
|
||||
).toEqual('{\n "a": 1\n}');
|
||||
});
|
||||
|
||||
test(`filter:toJson`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|toJson}', {
|
||||
a: '{"a":1}'
|
||||
})
|
||||
).toMatchObject({a: 1});
|
||||
});
|
||||
|
||||
test(`filter:toInt`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|toInt}', {
|
||||
a: '233'
|
||||
})
|
||||
).toBe(233);
|
||||
});
|
||||
|
||||
test(`filter:toFloat`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|toFloat}', {
|
||||
a: '233.233'
|
||||
})
|
||||
).toBe(233.233);
|
||||
});
|
||||
|
||||
test(`filter:toDate`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|toDate:x|date: YYYY-MM-DD}', {
|
||||
a: 1638028267226
|
||||
})
|
||||
).toBe('2021-11-27');
|
||||
});
|
||||
|
||||
test(`filter:fromNow`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|toDate:x|fromNow}', {
|
||||
a: Date.now() - 2 * 60 * 1000
|
||||
})
|
||||
).toBe('2 minutes ago');
|
||||
});
|
||||
|
||||
test(`filter:dateModify`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync(
|
||||
'${a|toDate:x|dateModify:subtract:2:m|fromNow}',
|
||||
{
|
||||
a: Date.now()
|
||||
}
|
||||
)
|
||||
).toBe('2 minutes ago');
|
||||
});
|
||||
|
||||
test(`filter:number`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|number}', {
|
||||
a: 1234
|
||||
})
|
||||
).toBe('1,234');
|
||||
});
|
||||
|
||||
test(`filter:trim`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|trim}', {
|
||||
a: ' ab '
|
||||
})
|
||||
).toBe('ab');
|
||||
});
|
||||
|
||||
test(`filter:duration`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|duration}', {
|
||||
a: 234343
|
||||
})
|
||||
).toBe('2天17时5分43秒');
|
||||
});
|
||||
|
||||
test(`filter:bytes`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|bytes}', {
|
||||
a: 234343
|
||||
})
|
||||
).toBe('234 KB');
|
||||
});
|
||||
|
||||
test(`filter:bytes:step`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|bytes:1024}', {
|
||||
a: 234343
|
||||
})
|
||||
).toBe('229 KB');
|
||||
});
|
||||
|
||||
test(`filter:round`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|round}', {
|
||||
a: 23.234
|
||||
})
|
||||
).toBe('23.23');
|
||||
});
|
||||
|
||||
test(`filter:truncate`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|truncate:5}', {
|
||||
a: 'abcdefghijklmnopqrst'
|
||||
})
|
||||
).toBe('abcde...');
|
||||
});
|
||||
|
||||
test(`filter:url_encode`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|url_encode}', {
|
||||
a: '='
|
||||
})
|
||||
).toBe('%3D');
|
||||
});
|
||||
|
||||
describe('filter:url_decode', () => {
|
||||
test(`filter:url_decode:normal`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|url_decode}', {
|
||||
a: '%3D'
|
||||
})
|
||||
).toBe('=');
|
||||
});
|
||||
|
||||
test(`filter:url_decode:error`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|url_decode}', {
|
||||
a: '%'
|
||||
})
|
||||
).toBe(undefined);
|
||||
});
|
||||
});
|
||||
|
||||
test(`filter:default`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|default:-}', {
|
||||
a: ''
|
||||
})
|
||||
).toBe('-');
|
||||
});
|
||||
|
||||
test(`filter:join`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|join:-}', {
|
||||
a: [1, 2, 3]
|
||||
})
|
||||
).toBe('1-2-3');
|
||||
});
|
||||
|
||||
test(`filter:split`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|split:-}', {
|
||||
a: '1-2-3'
|
||||
})
|
||||
).toMatchObject(['1', '2', '3']);
|
||||
});
|
||||
|
||||
test(`filter:sortBy`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|sortBy:&|join}', {
|
||||
a: ['b', 'c', 'a']
|
||||
})
|
||||
).toBe('a,b,c');
|
||||
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|sortBy:&:numerical|join}', {
|
||||
a: ['023', '20', '44']
|
||||
})
|
||||
).toBe('20,023,44');
|
||||
});
|
||||
|
||||
test(`filter:objectToArray`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|objectToArray}', {
|
||||
a: {
|
||||
a: 1,
|
||||
b: 2,
|
||||
done: 'Done'
|
||||
}
|
||||
})
|
||||
).toMatchObject([
|
||||
{
|
||||
value: 'a',
|
||||
label: 1
|
||||
},
|
||||
{
|
||||
value: 'b',
|
||||
label: 2
|
||||
},
|
||||
{
|
||||
value: 'done',
|
||||
label: 'Done'
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
test(`filter:substring`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|substring:0:2}', {
|
||||
a: 'abcdefg'
|
||||
})
|
||||
).toBe('ab');
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a|substring:1:3}', {
|
||||
a: 'abcdefg'
|
||||
})
|
||||
).toBe('bc');
|
||||
});
|
||||
|
||||
test(`filter:variableInVariable`, async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${a}', {
|
||||
a: 'abc$0defg'
|
||||
})
|
||||
).toBe('abc$0defg');
|
||||
});
|
||||
|
||||
test('filter:isMatch', async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync(
|
||||
'${status | isMatch:2:1|isMatch:5:1:4}',
|
||||
{
|
||||
status: 2
|
||||
}
|
||||
)
|
||||
).toBe(1);
|
||||
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync(
|
||||
'${status | isMatch:2:1|isMatch:5:1:4}',
|
||||
{
|
||||
status: 1
|
||||
}
|
||||
)
|
||||
).toBe(4);
|
||||
});
|
||||
|
||||
test('filter:filter:isMatch', async () => {
|
||||
expect(
|
||||
await resolveVariableAndFilterForAsync('${items|filter:text:match:"ab"}', {
|
||||
items: [
|
||||
{
|
||||
text: 'abc'
|
||||
},
|
||||
{
|
||||
text: 'bcd'
|
||||
},
|
||||
{
|
||||
text: 'cde'
|
||||
}
|
||||
]
|
||||
})
|
||||
).toMatchObject([
|
||||
{
|
||||
text: 'abc'
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
test('evalute:conditional', async () => {
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${a | isTrue: true : false}',
|
||||
{
|
||||
a: 4
|
||||
},
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${a | isTrue: b : false}',
|
||||
{
|
||||
a: 4,
|
||||
b: 5
|
||||
},
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toBe(5);
|
||||
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${a | isTrue: b : false}',
|
||||
{
|
||||
a: null,
|
||||
b: 5
|
||||
},
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${a | isTrue : trueValue : falseValue}',
|
||||
{
|
||||
a: true,
|
||||
trueValue: 5,
|
||||
falseValue: 10
|
||||
},
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toBe(5);
|
||||
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${a | isEquals: 1 : "1" |isEquals: 2 : "2" | isEquals: 3 : "3" }',
|
||||
{
|
||||
a: 3
|
||||
},
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toBe('3');
|
||||
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${a | isEquals: 1 : "1" |isEquals: 1 : "2" | isEquals: 1 : "3" }',
|
||||
{
|
||||
a: 1
|
||||
},
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toBe('1');
|
||||
|
||||
expect(
|
||||
await evaluateForAsync(
|
||||
'${a | isEquals: 1 : "1" : "12" |isEquals: 2 : "2" | isEquals: 3 : "3" }',
|
||||
{
|
||||
a: 2
|
||||
},
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toBe('12');
|
||||
});
|
||||
1
packages/amis-core/__tests__/compat.test.d.ts
vendored
Normal file
1
packages/amis-core/__tests__/compat.test.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
660
packages/amis-core/__tests__/compat.test.ts
Normal file
660
packages/amis-core/__tests__/compat.test.ts
Normal file
@@ -0,0 +1,660 @@
|
||||
import moment from 'moment';
|
||||
import {
|
||||
resolveVariable,
|
||||
resolveVariableAndFilter,
|
||||
resolveVariableAndFilterForAsync
|
||||
} from '../src/utils/tpl-builtin';
|
||||
import {setFormulaEvalErrorHandler} from '../src/utils';
|
||||
|
||||
const filters = [
|
||||
{
|
||||
type: 'raw1',
|
||||
data: {
|
||||
value: 1
|
||||
},
|
||||
path: '${value}',
|
||||
filter: '| raw',
|
||||
expectValue: 1
|
||||
},
|
||||
{
|
||||
type: 'raw2',
|
||||
data: {
|
||||
value: '2'
|
||||
},
|
||||
path: '${value}',
|
||||
filter: '| raw',
|
||||
expectValue: '2'
|
||||
},
|
||||
{
|
||||
type: 'raw3',
|
||||
data: {
|
||||
a: 1,
|
||||
b: '2',
|
||||
c: {
|
||||
'1': 'first',
|
||||
'2': 'second'
|
||||
}
|
||||
},
|
||||
path: '${c.${a}}',
|
||||
filter: '| raw',
|
||||
expectValue: 'first'
|
||||
},
|
||||
{
|
||||
type: 'raw4',
|
||||
data: {
|
||||
a: 1,
|
||||
b: '2',
|
||||
c: {
|
||||
'1': 'first',
|
||||
'2': 'second'
|
||||
}
|
||||
},
|
||||
path: '${c.${b}}',
|
||||
filter: '| raw',
|
||||
expectValue: 'second'
|
||||
},
|
||||
{
|
||||
type: 'raw5',
|
||||
data: {
|
||||
a: 1
|
||||
},
|
||||
path: '',
|
||||
filter: '| raw',
|
||||
expectValue: undefined
|
||||
},
|
||||
{
|
||||
type: 'raw6',
|
||||
data: {
|
||||
a: 1
|
||||
},
|
||||
path: '$$',
|
||||
filter: 'raw',
|
||||
expectValue: {a: 1}
|
||||
},
|
||||
{
|
||||
type: 'raw7',
|
||||
data: {
|
||||
a: 1
|
||||
},
|
||||
path: '$a',
|
||||
filter: '| raw',
|
||||
expectValue: 1
|
||||
},
|
||||
{
|
||||
type: 'json',
|
||||
data: {
|
||||
value: {
|
||||
a: 'a',
|
||||
b: 'b'
|
||||
}
|
||||
},
|
||||
path: '${value | json:0}',
|
||||
filter: '',
|
||||
expectValue: '{"a":"a","b":"b"}'
|
||||
},
|
||||
{
|
||||
type: 'toJson',
|
||||
data: {
|
||||
value: '{"a":"a","b":"b"}'
|
||||
},
|
||||
path: '${value | toJson}',
|
||||
filter: '',
|
||||
expectValue: {
|
||||
a: 'a',
|
||||
b: 'b'
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'date',
|
||||
data: {
|
||||
value: 1559649981
|
||||
},
|
||||
path: '${value | date}',
|
||||
filter: '',
|
||||
expectValue: moment(1559649981, 'X').format('LLL')
|
||||
},
|
||||
{
|
||||
type: 'number',
|
||||
data: {
|
||||
value: 9999
|
||||
},
|
||||
path: '${value| number}',
|
||||
filter: '',
|
||||
expectValue: '9,999'
|
||||
},
|
||||
{
|
||||
type: 'trim',
|
||||
data: {
|
||||
value: ' abc '
|
||||
},
|
||||
path: '${value| trim}',
|
||||
filter: '',
|
||||
expectValue: 'abc'
|
||||
},
|
||||
{
|
||||
type: 'percent',
|
||||
data: {
|
||||
value: 0.8232343
|
||||
},
|
||||
path: '${value| percent}',
|
||||
filter: '',
|
||||
expectValue: '82%'
|
||||
},
|
||||
// duration
|
||||
{
|
||||
type: 'duration1',
|
||||
data: {
|
||||
value: 1
|
||||
},
|
||||
path: '${value| duration}',
|
||||
filter: '',
|
||||
expectValue: '1秒'
|
||||
},
|
||||
{
|
||||
type: 'duration2',
|
||||
data: {
|
||||
value: 61
|
||||
},
|
||||
path: '${value| duration}',
|
||||
filter: '',
|
||||
expectValue: '1分1秒'
|
||||
},
|
||||
{
|
||||
type: 'duration3',
|
||||
data: {
|
||||
value: 233233
|
||||
},
|
||||
path: '${value| duration}',
|
||||
filter: '',
|
||||
expectValue: '2天16时47分13秒'
|
||||
},
|
||||
// bytes
|
||||
{
|
||||
type: 'bytes1',
|
||||
data: {
|
||||
value: 1024
|
||||
},
|
||||
path: '${value| bytes}',
|
||||
filter: '',
|
||||
expectValue: '1.02 KB'
|
||||
},
|
||||
{
|
||||
type: 'bytes2',
|
||||
data: {
|
||||
value: 1024000
|
||||
},
|
||||
path: '${value| bytes}',
|
||||
filter: '',
|
||||
expectValue: '1.02 MB'
|
||||
},
|
||||
{
|
||||
type: 'bytes3',
|
||||
data: {
|
||||
value: -1024
|
||||
},
|
||||
path: '${value| bytes}',
|
||||
filter: '',
|
||||
expectValue: '-1.02 KB'
|
||||
},
|
||||
{
|
||||
type: 'bytes4',
|
||||
data: {
|
||||
value: 0.5
|
||||
},
|
||||
path: '${value| bytes}',
|
||||
filter: '',
|
||||
expectValue: '0.5 B'
|
||||
},
|
||||
// round
|
||||
{
|
||||
type: 'round1',
|
||||
data: {
|
||||
value: '啥啊'
|
||||
},
|
||||
path: '${value| round}',
|
||||
filter: '',
|
||||
expectValue: 0
|
||||
},
|
||||
{
|
||||
type: 'round2',
|
||||
data: {
|
||||
value: 1.22
|
||||
},
|
||||
path: '${value| round:1}',
|
||||
filter: '',
|
||||
expectValue: '1.2'
|
||||
},
|
||||
{
|
||||
type: 'round3',
|
||||
data: {
|
||||
value: 1.26
|
||||
},
|
||||
path: '${value| round:1}',
|
||||
filter: '',
|
||||
expectValue: '1.3'
|
||||
},
|
||||
{
|
||||
type: 'truncate1',
|
||||
data: {
|
||||
value: 'this is a very loooooong sentence.'
|
||||
},
|
||||
path: '${value| truncate:10}',
|
||||
filter: '',
|
||||
expectValue: 'this is a ...'
|
||||
},
|
||||
{
|
||||
type: 'truncate2',
|
||||
data: {
|
||||
value: 'this is a very loooooong sentence.'
|
||||
},
|
||||
path: '${value| truncate:null}',
|
||||
filter: '',
|
||||
expectValue: 'this is a very loooooong sentence.'
|
||||
},
|
||||
{
|
||||
type: 'url_encode',
|
||||
data: {
|
||||
value: 'http://www.baidu.com?query=123'
|
||||
},
|
||||
path: '${value| url_encode}',
|
||||
filter: '',
|
||||
expectValue: 'http%3A%2F%2Fwww.baidu.com%3Fquery%3D123'
|
||||
},
|
||||
{
|
||||
type: 'url_decode',
|
||||
data: {
|
||||
value: 'http%3A%2F%2Fwww.baidu.com%3Fquery%3D123'
|
||||
},
|
||||
path: '${value| url_decode:10}',
|
||||
filter: '',
|
||||
expectValue: 'http://www.baidu.com?query=123'
|
||||
},
|
||||
{
|
||||
type: 'default1',
|
||||
data: {
|
||||
value: ''
|
||||
},
|
||||
path: '${value| default}',
|
||||
filter: '',
|
||||
expectValue: undefined
|
||||
},
|
||||
{
|
||||
type: 'default2',
|
||||
data: {
|
||||
value: ''
|
||||
},
|
||||
path: '${value| default:-}',
|
||||
filter: '',
|
||||
expectValue: '-'
|
||||
},
|
||||
{
|
||||
type: 'join',
|
||||
data: {
|
||||
value: ['a', 'b', 'c']
|
||||
},
|
||||
path: '${value| join:,}',
|
||||
filter: '',
|
||||
expectValue: 'a,b,c'
|
||||
},
|
||||
{
|
||||
type: 'split',
|
||||
data: {
|
||||
value: 'a,b,c'
|
||||
},
|
||||
path: '${value| split}',
|
||||
filter: '',
|
||||
expectValue: ['a', 'b', 'c']
|
||||
},
|
||||
{
|
||||
type: 'first',
|
||||
data: {
|
||||
value: ['a', 'b', 'c']
|
||||
},
|
||||
path: '${value| first}',
|
||||
filter: '',
|
||||
expectValue: 'a'
|
||||
},
|
||||
{
|
||||
type: 'nth',
|
||||
data: {
|
||||
value: ['a', 'b', 'c']
|
||||
},
|
||||
path: '${value| nth:1}',
|
||||
filter: '',
|
||||
expectValue: 'b'
|
||||
},
|
||||
{
|
||||
type: 'last',
|
||||
data: {
|
||||
value: ['a', 'b', 'c']
|
||||
},
|
||||
path: '${value| last}',
|
||||
filter: '',
|
||||
expectValue: 'c'
|
||||
},
|
||||
{
|
||||
type: 'minus',
|
||||
data: {
|
||||
value: 5
|
||||
},
|
||||
path: '${value| minus:1}',
|
||||
filter: '',
|
||||
expectValue: 4
|
||||
},
|
||||
{
|
||||
type: 'plus',
|
||||
data: {
|
||||
value: 5
|
||||
},
|
||||
path: '${value| plus:1}',
|
||||
filter: '',
|
||||
expectValue: 6
|
||||
},
|
||||
{
|
||||
type: 'pick1',
|
||||
data: {
|
||||
value: {
|
||||
a: '1',
|
||||
b: '2'
|
||||
}
|
||||
},
|
||||
path: '${value| pick:a}',
|
||||
filter: '',
|
||||
expectValue: '1'
|
||||
},
|
||||
{
|
||||
type: 'pick2',
|
||||
data: {
|
||||
value: [
|
||||
{
|
||||
label: 'A',
|
||||
value: 'a'
|
||||
},
|
||||
{
|
||||
label: 'B',
|
||||
value: 'b'
|
||||
},
|
||||
{
|
||||
label: 'C',
|
||||
value: 'c'
|
||||
}
|
||||
]
|
||||
},
|
||||
path: '${value| pick:value}',
|
||||
filter: '',
|
||||
expectValue: ['a', 'b', 'c']
|
||||
},
|
||||
{
|
||||
type: 'pick_if_exist',
|
||||
data: {
|
||||
value: [
|
||||
{
|
||||
label: 'A',
|
||||
value: 'a'
|
||||
},
|
||||
{
|
||||
label: 'B',
|
||||
value: 'b'
|
||||
},
|
||||
{
|
||||
label: 'C',
|
||||
value: 'c'
|
||||
}
|
||||
]
|
||||
},
|
||||
path: '${value| pick_if_exist:value}',
|
||||
filter: '',
|
||||
expectValue: ['a', 'b', 'c']
|
||||
},
|
||||
{
|
||||
type: 'str2date',
|
||||
data: {
|
||||
value: '1559649981'
|
||||
},
|
||||
path: '${value| str2date:X:YYYY-MM-DD HH-mm-ss}',
|
||||
filter: '',
|
||||
expectValue: moment('1559649981', 'X').format('YYYY-MM-DD HH-mm-ss')
|
||||
},
|
||||
{
|
||||
type: 'asArray',
|
||||
data: {
|
||||
value: 'a'
|
||||
},
|
||||
path: '${value| asArray}',
|
||||
filter: '',
|
||||
expectValue: ['a']
|
||||
},
|
||||
{
|
||||
type: 'base64Encode',
|
||||
data: {
|
||||
value: 'I love amis'
|
||||
},
|
||||
path: '${value| base64Encode}',
|
||||
filter: '',
|
||||
expectValue: 'SSBsb3ZlIGFtaXM='
|
||||
},
|
||||
{
|
||||
type: 'base64Decode',
|
||||
data: {
|
||||
value: 'SSBsb3ZlIGFtaXM='
|
||||
},
|
||||
path: '${value| base64Decode}',
|
||||
filter: '',
|
||||
expectValue: 'I love amis'
|
||||
},
|
||||
{
|
||||
type: 'lowerCase',
|
||||
data: {
|
||||
value: 'AbC'
|
||||
},
|
||||
path: '${value| lowerCase}',
|
||||
filter: '',
|
||||
expectValue: 'abc'
|
||||
},
|
||||
{
|
||||
type: 'upperCase',
|
||||
data: {
|
||||
value: 'aBc'
|
||||
},
|
||||
path: '${value| upperCase}',
|
||||
filter: '',
|
||||
expectValue: 'ABC'
|
||||
}
|
||||
];
|
||||
|
||||
filters.forEach(f => {
|
||||
test(`compat:${f.type}`, () => {
|
||||
const result = resolveVariableAndFilter(f.path, f.data, f.filter);
|
||||
expect(result).toEqual(f.expectValue);
|
||||
});
|
||||
});
|
||||
|
||||
test(`compat:filter`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter(
|
||||
'${rows | filter:engine:match:keywords}',
|
||||
{
|
||||
rows: [
|
||||
{
|
||||
engine: 'a'
|
||||
},
|
||||
{
|
||||
engine: 'b'
|
||||
},
|
||||
{
|
||||
engine: 'c'
|
||||
}
|
||||
]
|
||||
},
|
||||
'| raw'
|
||||
)
|
||||
).toMatchObject([
|
||||
{
|
||||
engine: 'a'
|
||||
},
|
||||
{
|
||||
engine: 'b'
|
||||
},
|
||||
{
|
||||
engine: 'c'
|
||||
}
|
||||
]);
|
||||
|
||||
expect(
|
||||
resolveVariableAndFilter(
|
||||
'${rows | filter:engine:match:keywords}',
|
||||
{
|
||||
keywords: 'a',
|
||||
rows: [
|
||||
{
|
||||
engine: 'a'
|
||||
},
|
||||
{
|
||||
engine: 'b'
|
||||
},
|
||||
{
|
||||
engine: 'c'
|
||||
}
|
||||
]
|
||||
},
|
||||
'| raw'
|
||||
)
|
||||
).toMatchObject([
|
||||
{
|
||||
engine: 'a'
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
test(`compat:&`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter(
|
||||
'${& | json:0}',
|
||||
{
|
||||
a: 1,
|
||||
b: 2
|
||||
},
|
||||
'| raw'
|
||||
)
|
||||
).toBe('{"a":1,"b":2}');
|
||||
});
|
||||
|
||||
test(`compat:filter-default`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter(
|
||||
'${a | default:undefined}',
|
||||
{
|
||||
a: 1
|
||||
},
|
||||
'| raw'
|
||||
)
|
||||
).toBe(1);
|
||||
|
||||
expect(
|
||||
resolveVariableAndFilter(
|
||||
'${a | default:undefined}',
|
||||
{
|
||||
a: [1, 2, 3]
|
||||
},
|
||||
'| raw'
|
||||
)
|
||||
).toMatchObject([1, 2, 3]);
|
||||
|
||||
expect(
|
||||
resolveVariableAndFilter(
|
||||
'${b | default:undefined}',
|
||||
{
|
||||
a: 1
|
||||
},
|
||||
'| raw'
|
||||
)
|
||||
).toBe(undefined);
|
||||
expect(
|
||||
resolveVariableAndFilter(
|
||||
'${b | default:-}',
|
||||
{
|
||||
a: 1
|
||||
},
|
||||
'| raw'
|
||||
)
|
||||
).toBe('-');
|
||||
|
||||
expect(
|
||||
resolveVariableAndFilter(
|
||||
'${b | default:undefined}',
|
||||
{
|
||||
a: 1
|
||||
},
|
||||
'| raw',
|
||||
() => ''
|
||||
)
|
||||
).toBe(undefined);
|
||||
expect(
|
||||
resolveVariableAndFilter(
|
||||
'${b}',
|
||||
{
|
||||
a: 1
|
||||
},
|
||||
'| raw',
|
||||
() => ''
|
||||
)
|
||||
).toBe('');
|
||||
});
|
||||
|
||||
test(`compat:numberVariable`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter(
|
||||
'a $1 ',
|
||||
{
|
||||
'1': 233
|
||||
},
|
||||
'| raw'
|
||||
)
|
||||
).toEqual('a 233 ');
|
||||
|
||||
expect(
|
||||
resolveVariableAndFilter(
|
||||
'a $1',
|
||||
{
|
||||
'1': 233
|
||||
},
|
||||
'| raw'
|
||||
)
|
||||
).toEqual('a 233');
|
||||
});
|
||||
|
||||
test(`compat:test`, () => {
|
||||
const result = resolveVariableAndFilter('', {}, '| raw');
|
||||
expect(result).toEqual(undefined);
|
||||
});
|
||||
|
||||
test(`compat:test2`, () => {
|
||||
const data = {
|
||||
'123': 123,
|
||||
'123.123': 123,
|
||||
'中文': 123,
|
||||
'obj': {
|
||||
x: 123
|
||||
}
|
||||
};
|
||||
expect(resolveVariable('123', data)).toEqual(123);
|
||||
expect(resolveVariable('123.123', data)).toEqual(123);
|
||||
expect(resolveVariable('中文', data)).toEqual(123);
|
||||
expect(resolveVariable('obj.x', data)).toEqual(123);
|
||||
});
|
||||
|
||||
test('compat:formulaEvalErrorHandler', async () => {
|
||||
setFormulaEvalErrorHandler(
|
||||
(
|
||||
path?: string,
|
||||
data: object = {},
|
||||
defaultFilter: string = '| html',
|
||||
fallbackValue = (value: any) => value,
|
||||
skipFormulaEvalErrorHandler: boolean = false
|
||||
) => {
|
||||
return Promise.resolve(1 * 2 * 2);
|
||||
}
|
||||
);
|
||||
|
||||
expect(await resolveVariableAndFilterForAsync('${AAA(1,2)}')).toBe(4);
|
||||
});
|
||||
547
packages/amis-core/__tests__/condition.test.ts
Normal file
547
packages/amis-core/__tests__/condition.test.ts
Normal file
@@ -0,0 +1,547 @@
|
||||
import moment from 'moment';
|
||||
import {
|
||||
resolveConditionAsync,
|
||||
guid,
|
||||
registerConditionComputer,
|
||||
setConditionComputeErrorHandler
|
||||
} from '../src/utils/';
|
||||
|
||||
const data = {
|
||||
name: 'amis',
|
||||
feature: 'flexible',
|
||||
features: ['flexible', 'powerful'],
|
||||
tool: 'amis-editor',
|
||||
platform: 'aisuda',
|
||||
version: '2.9.0',
|
||||
num: 1,
|
||||
num2: 0,
|
||||
num3: undefined,
|
||||
str: '',
|
||||
obj: {},
|
||||
arr: [],
|
||||
bool: true,
|
||||
detail: {
|
||||
version: '2.8.0',
|
||||
github: 'https://github.com/baidu/amis'
|
||||
},
|
||||
range: 1678723200,
|
||||
date: '2023-03-19',
|
||||
datetime: '2023-03-20T04:55:00+08:00',
|
||||
time: '00:05'
|
||||
};
|
||||
|
||||
const equal1 = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'name'
|
||||
},
|
||||
op: 'equal',
|
||||
right: '${name}'
|
||||
};
|
||||
const equal2 = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'detail'
|
||||
},
|
||||
op: 'equal',
|
||||
right: '${detail}'
|
||||
};
|
||||
const equal3 = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'bool'
|
||||
},
|
||||
op: 'equal',
|
||||
right: '${!num2}'
|
||||
};
|
||||
const not_equal = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'version'
|
||||
},
|
||||
op: 'not_equal',
|
||||
right: '${version}'
|
||||
};
|
||||
const greater = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'num'
|
||||
},
|
||||
op: 'greater',
|
||||
right: '${num + 0.5}'
|
||||
};
|
||||
const less = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'num'
|
||||
},
|
||||
op: 'less',
|
||||
right: '${num - 0.5}'
|
||||
};
|
||||
const greater_or_equal = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'num'
|
||||
},
|
||||
op: 'greater_or_equal',
|
||||
right: '${num}'
|
||||
};
|
||||
const less_or_equal = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'num'
|
||||
},
|
||||
op: 'less_or_equal',
|
||||
right: '${num}'
|
||||
};
|
||||
const starts_with = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'tool'
|
||||
},
|
||||
op: 'starts_with',
|
||||
right: 'amis-'
|
||||
};
|
||||
const ends_with = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'tool'
|
||||
},
|
||||
op: 'ends_with',
|
||||
right: '-editor'
|
||||
};
|
||||
const like = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'tool'
|
||||
},
|
||||
op: 'like',
|
||||
right: '${tool}-core'
|
||||
};
|
||||
const not_like = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'tool'
|
||||
},
|
||||
op: 'not_like',
|
||||
right: '${tool}r'
|
||||
};
|
||||
const is_empty1 = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'num2'
|
||||
},
|
||||
op: 'is_empty'
|
||||
};
|
||||
const is_empty2 = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'str'
|
||||
},
|
||||
op: 'is_empty'
|
||||
};
|
||||
const is_empty3 = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'obj'
|
||||
},
|
||||
op: 'is_empty'
|
||||
};
|
||||
const is_not_empty1 = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'num3'
|
||||
},
|
||||
op: 'is_not_empty'
|
||||
};
|
||||
const is_not_empty2 = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'name'
|
||||
},
|
||||
op: 'is_not_empty'
|
||||
};
|
||||
const is_not_empty3 = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'detail'
|
||||
},
|
||||
op: 'is_not_empty'
|
||||
};
|
||||
const is_not_empty4 = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'arr'
|
||||
},
|
||||
op: 'is_not_empty'
|
||||
};
|
||||
const between = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'num'
|
||||
},
|
||||
op: 'between',
|
||||
right: '${[0.5,1]}'
|
||||
};
|
||||
const not_between = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'range'
|
||||
},
|
||||
op: 'not_between',
|
||||
right: '${[1678636800,1678895999]}'
|
||||
};
|
||||
const select_any_in1 = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'features'
|
||||
},
|
||||
op: 'select_any_in',
|
||||
right: '${[LAST(features)]}'
|
||||
};
|
||||
const select_any_in2 = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'feature'
|
||||
},
|
||||
op: 'select_any_in',
|
||||
right: '${features}'
|
||||
};
|
||||
const select_not_any_in = {
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'features'
|
||||
},
|
||||
op: 'select_not_any_in',
|
||||
right: "${['powerful']}"
|
||||
};
|
||||
|
||||
const conditions1 = {
|
||||
id: guid(),
|
||||
conjunction: 'and',
|
||||
children: [equal1, equal2, equal3, not_equal]
|
||||
};
|
||||
|
||||
const conditions2 = {
|
||||
id: guid(),
|
||||
conjunction: 'or',
|
||||
children: [greater, less, greater_or_equal, less_or_equal]
|
||||
};
|
||||
|
||||
const conditions3 = {
|
||||
id: guid(),
|
||||
conjunction: 'and',
|
||||
children: [starts_with, ends_with, like, not_like]
|
||||
};
|
||||
|
||||
const conditions4 = {
|
||||
id: guid(),
|
||||
conjunction: 'and',
|
||||
children: [is_empty1, is_empty2, is_empty3]
|
||||
};
|
||||
|
||||
const conditions5 = {
|
||||
id: guid(),
|
||||
conjunction: 'and',
|
||||
children: [is_not_empty1, is_not_empty2, is_not_empty3, is_not_empty4]
|
||||
};
|
||||
|
||||
const conditions6 = {
|
||||
id: guid(),
|
||||
conjunction: 'and',
|
||||
children: [between, not_between]
|
||||
};
|
||||
|
||||
const conditions7 = {
|
||||
id: guid(),
|
||||
conjunction: 'and',
|
||||
children: [select_any_in1, select_any_in2, select_not_any_in]
|
||||
};
|
||||
|
||||
test(`condition`, async () => {
|
||||
expect(await resolveConditionAsync(conditions1, data)).toBe(false);
|
||||
expect(await resolveConditionAsync(conditions2, data)).toBe(true);
|
||||
expect(await resolveConditionAsync(conditions3, data)).toBe(false);
|
||||
expect(await resolveConditionAsync(conditions4, data)).toBe(false);
|
||||
expect(await resolveConditionAsync(conditions5, data)).toBe(false);
|
||||
expect(await resolveConditionAsync(conditions6, data)).toBe(false);
|
||||
expect(await resolveConditionAsync(conditions7, data)).toBe(false);
|
||||
});
|
||||
|
||||
test(`condition date`, async () => {
|
||||
const conditions = {
|
||||
id: guid(),
|
||||
conjunction: 'and',
|
||||
children: [
|
||||
{
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'date',
|
||||
field: 'date'
|
||||
},
|
||||
op: 'less',
|
||||
right: '2023-03-20'
|
||||
},
|
||||
{
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'date',
|
||||
field: 'datetime'
|
||||
},
|
||||
op: 'less',
|
||||
right: '2023-03-21T04:55:00+08:00'
|
||||
},
|
||||
{
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'date',
|
||||
field: 'time'
|
||||
},
|
||||
op: 'less',
|
||||
right: '00:08'
|
||||
},
|
||||
{
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'date',
|
||||
field: 'date'
|
||||
},
|
||||
op: 'less_or_equal',
|
||||
right: '2023-03-19'
|
||||
},
|
||||
{
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'date',
|
||||
field: 'datetime'
|
||||
},
|
||||
op: 'less_or_equal',
|
||||
right: '2023-03-20T04:55:00+08:00'
|
||||
},
|
||||
{
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'date',
|
||||
field: 'time'
|
||||
},
|
||||
op: 'less_or_equal',
|
||||
right: '00:05'
|
||||
},
|
||||
{
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'date',
|
||||
field: 'date'
|
||||
},
|
||||
op: 'between',
|
||||
right: '${["2023-03-19","2023-03-20"]}'
|
||||
},
|
||||
{
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'date',
|
||||
field: 'datetime'
|
||||
},
|
||||
op: 'between',
|
||||
right: '${["2023-03-20T04:55:00+08:00","2023-03-21T04:55:00+08:00"]}'
|
||||
},
|
||||
{
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'date',
|
||||
field: 'time'
|
||||
},
|
||||
op: 'between',
|
||||
right: '${["00:05","00:06"]}'
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
expect(await resolveConditionAsync(conditions, data)).toBe(true);
|
||||
});
|
||||
|
||||
test(`condition tree`, async () => {
|
||||
const conditions8 = {
|
||||
id: guid(),
|
||||
conjunction: 'and',
|
||||
children: [
|
||||
select_any_in1,
|
||||
{
|
||||
id: guid(),
|
||||
conjunction: 'and',
|
||||
children: [
|
||||
equal1,
|
||||
{
|
||||
id: guid(),
|
||||
conjunction: 'or',
|
||||
children: [between, not_between]
|
||||
},
|
||||
between,
|
||||
{
|
||||
id: guid(),
|
||||
conjunction: 'and',
|
||||
children: [between, select_any_in2, conditions5]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const conditions9 = {
|
||||
id: guid(),
|
||||
conjunction: 'or',
|
||||
children: [
|
||||
is_empty1,
|
||||
{
|
||||
id: guid(),
|
||||
conjunction: 'or',
|
||||
children: [
|
||||
is_empty1,
|
||||
conditions6,
|
||||
between,
|
||||
{
|
||||
id: guid(),
|
||||
conjunction: 'or',
|
||||
children: [is_empty1, select_any_in2, conditions5]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
const conditions10 = {
|
||||
id: guid(),
|
||||
conjunction: 'or',
|
||||
children: [
|
||||
{
|
||||
id: guid(),
|
||||
conjunction: 'or',
|
||||
children: [
|
||||
conditions6,
|
||||
is_empty1,
|
||||
{
|
||||
id: guid(),
|
||||
conjunction: 'or',
|
||||
children: [
|
||||
is_empty1,
|
||||
{
|
||||
id: guid(),
|
||||
conjunction: 'or',
|
||||
children: [
|
||||
is_not_empty1,
|
||||
is_not_empty2,
|
||||
is_not_empty3,
|
||||
is_not_empty4
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
is_empty1
|
||||
]
|
||||
};
|
||||
|
||||
expect(await resolveConditionAsync(conditions8, data)).toBe(false);
|
||||
expect(await resolveConditionAsync(conditions9, data)).toBe(true);
|
||||
expect(await resolveConditionAsync(conditions10, data)).toBe(true);
|
||||
});
|
||||
|
||||
test(`condition register`, async () => {
|
||||
registerConditionComputer(
|
||||
'customless',
|
||||
(left: any, right?: any, fieldType?: string) => {
|
||||
if (fieldType === 'date') {
|
||||
return moment(left).isBefore(moment(right), 'day');
|
||||
}
|
||||
return left < right;
|
||||
}
|
||||
);
|
||||
|
||||
const conditions = {
|
||||
id: guid(),
|
||||
conjunction: 'and',
|
||||
children: [
|
||||
{
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'date',
|
||||
field: 'date'
|
||||
},
|
||||
op: 'customless',
|
||||
right: '2023-03-20'
|
||||
},
|
||||
{
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'num'
|
||||
},
|
||||
op: 'customless',
|
||||
right: '5'
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
expect(await resolveConditionAsync(conditions, data)).toBe(true);
|
||||
});
|
||||
|
||||
test(`condition conditionComputeHander`, async () => {
|
||||
// 无法解析时,自定义解析逻辑
|
||||
setConditionComputeErrorHandler(
|
||||
(conditions: any, data: any, defaultResult: boolean) => {
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
);
|
||||
|
||||
const conditions = {
|
||||
id: guid(),
|
||||
conjunction: 'and',
|
||||
children: [
|
||||
{
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'date',
|
||||
field: 'date'
|
||||
},
|
||||
op: 'equal',
|
||||
right: '2023-03-19'
|
||||
},
|
||||
{
|
||||
id: guid(),
|
||||
left: {
|
||||
type: 'field',
|
||||
field: 'num'
|
||||
},
|
||||
op: 'equal',
|
||||
right: '${AAA(5)}'
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
expect(await resolveConditionAsync(conditions, data)).toBe(true);
|
||||
});
|
||||
33
packages/amis-core/__tests__/datamapping.test.ts
Normal file
33
packages/amis-core/__tests__/datamapping.test.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import {dataMapping} from '../src';
|
||||
|
||||
test('datamapping', async () => {
|
||||
const context = {
|
||||
a: 1,
|
||||
b: 2,
|
||||
c: [
|
||||
{a: 1, b: 1},
|
||||
{a: 2, b: 2}
|
||||
]
|
||||
};
|
||||
|
||||
const result = dataMapping(
|
||||
{
|
||||
a: '${a}',
|
||||
b: '${c}',
|
||||
c: '${ARRAYMAP(c, item => {a: item.a, c: item.b})}'
|
||||
},
|
||||
context
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
a: 1,
|
||||
b: [
|
||||
{a: 1, b: 1},
|
||||
{a: 2, b: 2}
|
||||
],
|
||||
c: [
|
||||
{a: 1, c: 1},
|
||||
{a: 2, c: 2}
|
||||
]
|
||||
});
|
||||
});
|
||||
1
packages/amis-core/__tests__/factory.test.d.ts
vendored
Normal file
1
packages/amis-core/__tests__/factory.test.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
292
packages/amis-core/__tests__/factory.test.tsx
Normal file
292
packages/amis-core/__tests__/factory.test.tsx
Normal file
@@ -0,0 +1,292 @@
|
||||
import {
|
||||
registerRenderer,
|
||||
unRegisterRenderer,
|
||||
RendererProps
|
||||
} from '../src/factory';
|
||||
import {render as amisRender} from '../src';
|
||||
import React from 'react';
|
||||
import {render, fireEvent, waitFor} from '@testing-library/react';
|
||||
import {makeEnv} from './helper';
|
||||
|
||||
test('factory unregistered Renderer', async () => {
|
||||
const {container, getByText} = render(
|
||||
amisRender({
|
||||
type: 'my-renderer',
|
||||
a: 23
|
||||
})
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(getByText('Error: 找不到对应的渲染器')).toBeInTheDocument();
|
||||
});
|
||||
expect(container).toMatchSnapshot();
|
||||
});
|
||||
|
||||
test('factory custom not found!', async () => {
|
||||
const {container, getByText} = render(
|
||||
amisRender(
|
||||
{
|
||||
type: 'my-renderer',
|
||||
a: 23
|
||||
},
|
||||
{},
|
||||
makeEnv({
|
||||
loadRenderer: () => Promise.resolve(() => <div>Not Found</div>)
|
||||
})
|
||||
)
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(getByText('Not Found')).toBeInTheDocument();
|
||||
});
|
||||
expect(container).toMatchSnapshot(); // not found
|
||||
});
|
||||
|
||||
test('factory custom not found 2!', async () => {
|
||||
const {container, getByText} = render(
|
||||
amisRender(
|
||||
{
|
||||
type: 'my-renderer',
|
||||
a: 23
|
||||
},
|
||||
{},
|
||||
makeEnv({
|
||||
loadRenderer: () => () => <div>Not Found</div>
|
||||
})
|
||||
)
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(getByText('Not Found')).toBeInTheDocument();
|
||||
});
|
||||
expect(container).toMatchSnapshot(); // not found
|
||||
});
|
||||
|
||||
test('factory custom not found 3!', async () => {
|
||||
const {container, getByText} = render(
|
||||
amisRender(
|
||||
{
|
||||
type: 'my-renderer',
|
||||
a: 23
|
||||
},
|
||||
{},
|
||||
makeEnv({
|
||||
loadRenderer: () => <div>Not Found</div>
|
||||
})
|
||||
)
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(getByText('Not Found')).toBeInTheDocument();
|
||||
});
|
||||
expect(container).toMatchSnapshot(); // not found
|
||||
});
|
||||
|
||||
test('factory load Renderer on need', async () => {
|
||||
const {container, getByText} = render(
|
||||
amisRender(
|
||||
{
|
||||
type: 'my-renderer2',
|
||||
a: 23
|
||||
},
|
||||
{},
|
||||
makeEnv({
|
||||
session: 'loadRenderer',
|
||||
loadRenderer: schema => {
|
||||
interface MyProps extends RendererProps {
|
||||
a?: number;
|
||||
}
|
||||
|
||||
class MyComponent extends React.Component<MyProps> {
|
||||
render() {
|
||||
return <div>This is Custom Renderer2, a is {this.props.a}</div>;
|
||||
}
|
||||
}
|
||||
|
||||
registerRenderer({
|
||||
component: MyComponent,
|
||||
test: /\bmy-renderer2$/
|
||||
});
|
||||
}
|
||||
})
|
||||
)
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(getByText('This is Custom Renderer2, a is 23')).toBeInTheDocument();
|
||||
});
|
||||
expect(container).toMatchSnapshot(); // not found
|
||||
});
|
||||
|
||||
test('factory:registerRenderer', () => {
|
||||
interface MyProps extends RendererProps {
|
||||
a?: number;
|
||||
}
|
||||
|
||||
class MyComponent extends React.Component<MyProps> {
|
||||
render() {
|
||||
return <div>This is Custom Renderer, a is {this.props.a}</div>;
|
||||
}
|
||||
}
|
||||
|
||||
const renderer = registerRenderer({
|
||||
component: MyComponent,
|
||||
test: /\bmy-renderer$/
|
||||
});
|
||||
|
||||
const {container} = render(
|
||||
amisRender({
|
||||
type: 'my-renderer',
|
||||
a: 23
|
||||
})
|
||||
);
|
||||
|
||||
expect(container).toMatchSnapshot();
|
||||
unRegisterRenderer(renderer);
|
||||
});
|
||||
|
||||
// test('factory:definitions', async () => {
|
||||
// const {container, getByText} = render(
|
||||
// amisRender(
|
||||
// {
|
||||
// definitions: {
|
||||
// aa: {
|
||||
// type: 'text',
|
||||
// name: 'jack',
|
||||
// value: 'ref value',
|
||||
// remark: '通过<code>\\$ref</code>引入的组件'
|
||||
// },
|
||||
// bb: {
|
||||
// type: 'combo',
|
||||
// multiple: true,
|
||||
// multiLine: true,
|
||||
// remark: '<code>combo</code>中的子项引入自身,实现嵌套的效果',
|
||||
// controls: [
|
||||
// {
|
||||
// label: 'combo 1',
|
||||
// type: 'text',
|
||||
// name: 'key'
|
||||
// },
|
||||
// {
|
||||
// label: 'combo 2',
|
||||
// name: 'value',
|
||||
// $ref: 'aa'
|
||||
// },
|
||||
// {
|
||||
// name: 'children',
|
||||
// label: 'children',
|
||||
// $ref: 'bb'
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
// },
|
||||
// type: 'page',
|
||||
// title: '引用',
|
||||
// body: [
|
||||
// {
|
||||
// type: 'form',
|
||||
// api: 'api/xxx',
|
||||
// actions: [],
|
||||
// controls: [
|
||||
// {
|
||||
// label: 'text2',
|
||||
// $ref: 'aa',
|
||||
// name: 'ref1'
|
||||
// },
|
||||
// {
|
||||
// label: 'combo',
|
||||
// $ref: 'bb',
|
||||
// name: 'ref2'
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
// ]
|
||||
// },
|
||||
// {},
|
||||
// makeEnv({})
|
||||
// )
|
||||
// );
|
||||
|
||||
// await waitFor(() => {
|
||||
// expect(getByText('新增')).toBeInTheDocument();
|
||||
// });
|
||||
// fireEvent.click(getByText('新增'));
|
||||
// await waitFor(() => {
|
||||
// expect(getByText('combo 1')).toBeInTheDocument();
|
||||
// });
|
||||
// expect(container).toMatchSnapshot();
|
||||
// });
|
||||
|
||||
// test('factory:definitions override', async () => {
|
||||
// const {container, getByText} = render(
|
||||
// amisRender(
|
||||
// {
|
||||
// definitions: {
|
||||
// aa: {
|
||||
// type: 'text',
|
||||
// name: 'jack',
|
||||
// remark: '通过<code>\\$ref</code>引入的组件'
|
||||
// },
|
||||
// bb: {
|
||||
// type: 'combo',
|
||||
// multiple: true,
|
||||
// multiLine: true,
|
||||
// remark: '<code>combo</code>中的子项引入自身,实现嵌套的效果',
|
||||
// controls: [
|
||||
// {
|
||||
// label: 'combo 1',
|
||||
// type: 'text',
|
||||
// name: 'key'
|
||||
// },
|
||||
// {
|
||||
// label: 'combo 2',
|
||||
// name: 'value',
|
||||
// $ref: 'aa'
|
||||
// },
|
||||
// {
|
||||
// name: 'children',
|
||||
// label: 'children',
|
||||
// $ref: 'bb'
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
// },
|
||||
// type: 'page',
|
||||
// title: '引用',
|
||||
// body: [
|
||||
// {
|
||||
// type: 'form',
|
||||
// api: 'api/xxx',
|
||||
// actions: [],
|
||||
// controls: [
|
||||
// {
|
||||
// label: 'text2',
|
||||
// $ref: 'aa',
|
||||
// name: 'ref1'
|
||||
// },
|
||||
// {
|
||||
// label: 'combo',
|
||||
// $ref: 'bb',
|
||||
// name: 'ref2',
|
||||
// type: 'checkboxes',
|
||||
// value: 1,
|
||||
// options: [
|
||||
// {
|
||||
// label: 'Option A',
|
||||
// value: 1
|
||||
// },
|
||||
// {
|
||||
// label: 'Option B',
|
||||
// value: 2
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
// ]
|
||||
// },
|
||||
// {},
|
||||
// makeEnv({})
|
||||
// )
|
||||
// );
|
||||
|
||||
// await waitFor(() => {
|
||||
// expect(getByText('combo')).toBeInTheDocument();
|
||||
// });
|
||||
// expect(container).toMatchSnapshot();
|
||||
// });
|
||||
1
packages/amis-core/__tests__/filter.test.d.ts
vendored
Normal file
1
packages/amis-core/__tests__/filter.test.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
394
packages/amis-core/__tests__/filter.test.ts
Normal file
394
packages/amis-core/__tests__/filter.test.ts
Normal file
@@ -0,0 +1,394 @@
|
||||
import {resolveVariableAndFilter} from '../src/utils/tpl-builtin';
|
||||
import {evaluate} from 'amis-formula';
|
||||
|
||||
test(`filter:map`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a | map: toInt}', {
|
||||
a: ['123', '3434']
|
||||
})
|
||||
).toMatchObject([123, 3434]);
|
||||
});
|
||||
test(`filter:html`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a}', {
|
||||
a: '<html>'
|
||||
})
|
||||
).toEqual('<html>');
|
||||
});
|
||||
|
||||
test(`filter:complex`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${`${a}`}', {
|
||||
a: '<html>'
|
||||
})
|
||||
).toEqual('<html>');
|
||||
|
||||
expect(
|
||||
resolveVariableAndFilter('${a ? a : a}', {
|
||||
a: '<html>'
|
||||
})
|
||||
).toEqual('<html>');
|
||||
|
||||
expect(
|
||||
resolveVariableAndFilter('${b.a}', {
|
||||
a: '<html>',
|
||||
b: {
|
||||
a: '<br />'
|
||||
}
|
||||
})
|
||||
).toEqual('<br />');
|
||||
});
|
||||
|
||||
test(`filter:json`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a | json : 0}', {
|
||||
a: {a: 1}
|
||||
})
|
||||
).toEqual('{"a":1}');
|
||||
|
||||
expect(
|
||||
resolveVariableAndFilter('${a | json : 2}', {
|
||||
a: {a: 1}
|
||||
})
|
||||
).toEqual('{\n "a": 1\n}');
|
||||
});
|
||||
|
||||
test(`filter:toJson`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|toJson}', {
|
||||
a: '{"a":1}'
|
||||
})
|
||||
).toMatchObject({a: 1});
|
||||
});
|
||||
|
||||
test(`filter:toInt`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|toInt}', {
|
||||
a: '233'
|
||||
})
|
||||
).toBe(233);
|
||||
});
|
||||
|
||||
test(`filter:toFloat`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|toFloat}', {
|
||||
a: '233.233'
|
||||
})
|
||||
).toBe(233.233);
|
||||
});
|
||||
|
||||
test(`filter:toDate`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|toDate:x|date: YYYY-MM-DD}', {
|
||||
a: 1638028267226
|
||||
})
|
||||
).toBe('2021-11-27');
|
||||
});
|
||||
|
||||
test(`filter:fromNow`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|toDate:x|fromNow}', {
|
||||
a: Date.now() - 2 * 60 * 1000
|
||||
})
|
||||
).toBe('2 minutes ago');
|
||||
});
|
||||
|
||||
test(`filter:dateModify`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|toDate:x|dateModify:subtract:2:m|fromNow}', {
|
||||
a: Date.now()
|
||||
})
|
||||
).toBe('2 minutes ago');
|
||||
});
|
||||
|
||||
test(`filter:number`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|number}', {
|
||||
a: 1234
|
||||
})
|
||||
).toBe('1,234');
|
||||
});
|
||||
|
||||
test(`filter:trim`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|trim}', {
|
||||
a: ' ab '
|
||||
})
|
||||
).toBe('ab');
|
||||
});
|
||||
|
||||
test(`filter:duration`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|duration}', {
|
||||
a: 234343
|
||||
})
|
||||
).toBe('2天17时5分43秒');
|
||||
});
|
||||
|
||||
test(`filter:bytes`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|bytes}', {
|
||||
a: 234343
|
||||
})
|
||||
).toBe('234 KB');
|
||||
});
|
||||
|
||||
test(`filter:bytes:step`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|bytes:1024}', {
|
||||
a: 234343
|
||||
})
|
||||
).toBe('229 KB');
|
||||
});
|
||||
|
||||
test(`filter:round`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|round}', {
|
||||
a: 23.234
|
||||
})
|
||||
).toBe('23.23');
|
||||
});
|
||||
|
||||
test(`filter:truncate`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|truncate:5}', {
|
||||
a: 'abcdefghijklmnopqrst'
|
||||
})
|
||||
).toBe('abcde...');
|
||||
});
|
||||
|
||||
test(`filter:url_encode`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|url_encode}', {
|
||||
a: '='
|
||||
})
|
||||
).toBe('%3D');
|
||||
});
|
||||
|
||||
describe('filter:url_decode', () => {
|
||||
test(`filter:url_decode:normal`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|url_decode}', {
|
||||
a: '%3D'
|
||||
})
|
||||
).toBe('=');
|
||||
});
|
||||
|
||||
test(`filter:url_decode:error`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|url_decode}', {
|
||||
a: '%'
|
||||
})
|
||||
).toBe(undefined);
|
||||
});
|
||||
});
|
||||
|
||||
test(`filter:default`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|default:-}', {
|
||||
a: ''
|
||||
})
|
||||
).toBe('-');
|
||||
});
|
||||
|
||||
test(`filter:join`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|join:-}', {
|
||||
a: [1, 2, 3]
|
||||
})
|
||||
).toBe('1-2-3');
|
||||
});
|
||||
|
||||
test(`filter:split`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|split:-}', {
|
||||
a: '1-2-3'
|
||||
})
|
||||
).toMatchObject(['1', '2', '3']);
|
||||
});
|
||||
|
||||
test(`filter:sortBy`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|sortBy:&|join}', {
|
||||
a: ['b', 'c', 'a']
|
||||
})
|
||||
).toBe('a,b,c');
|
||||
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|sortBy:&:numerical|join}', {
|
||||
a: ['023', '20', '44']
|
||||
})
|
||||
).toBe('20,023,44');
|
||||
});
|
||||
|
||||
test(`filter:objectToArray`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|objectToArray}', {
|
||||
a: {
|
||||
a: 1,
|
||||
b: 2,
|
||||
done: 'Done'
|
||||
}
|
||||
})
|
||||
).toMatchObject([
|
||||
{
|
||||
value: 'a',
|
||||
label: 1
|
||||
},
|
||||
{
|
||||
value: 'b',
|
||||
label: 2
|
||||
},
|
||||
{
|
||||
value: 'done',
|
||||
label: 'Done'
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
test(`filter:substring`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|substring:0:2}', {
|
||||
a: 'abcdefg'
|
||||
})
|
||||
).toBe('ab');
|
||||
expect(
|
||||
resolveVariableAndFilter('${a|substring:1:3}', {
|
||||
a: 'abcdefg'
|
||||
})
|
||||
).toBe('bc');
|
||||
});
|
||||
|
||||
test(`filter:variableInVariable`, () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${a}', {
|
||||
a: 'abc$0defg'
|
||||
})
|
||||
).toBe('abc$0defg');
|
||||
});
|
||||
|
||||
test('filter:isMatch', () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${status | isMatch:2:1|isMatch:5:1:4}', {
|
||||
status: 2
|
||||
})
|
||||
).toBe(1);
|
||||
|
||||
expect(
|
||||
resolveVariableAndFilter('${status | isMatch:2:1|isMatch:5:1:4}', {
|
||||
status: 1
|
||||
})
|
||||
).toBe(4);
|
||||
});
|
||||
|
||||
test('filter:filter:isMatch', () => {
|
||||
expect(
|
||||
resolveVariableAndFilter('${items|filter:text:match:"ab"}', {
|
||||
items: [
|
||||
{
|
||||
text: 'abc'
|
||||
},
|
||||
{
|
||||
text: 'bcd'
|
||||
},
|
||||
{
|
||||
text: 'cde'
|
||||
}
|
||||
]
|
||||
})
|
||||
).toMatchObject([
|
||||
{
|
||||
text: 'abc'
|
||||
}
|
||||
]);
|
||||
});
|
||||
|
||||
test('evalute:conditional', () => {
|
||||
expect(
|
||||
evaluate(
|
||||
'${a | isTrue: true : false}',
|
||||
{
|
||||
a: 4
|
||||
},
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toBe(true);
|
||||
|
||||
expect(
|
||||
evaluate(
|
||||
'${a | isTrue: b : false}',
|
||||
{
|
||||
a: 4,
|
||||
b: 5
|
||||
},
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toBe(5);
|
||||
|
||||
expect(
|
||||
evaluate(
|
||||
'${a | isTrue: b : false}',
|
||||
{
|
||||
a: null,
|
||||
b: 5
|
||||
},
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
evaluate(
|
||||
'${a | isTrue : trueValue : falseValue}',
|
||||
{
|
||||
a: true,
|
||||
trueValue: 5,
|
||||
falseValue: 10
|
||||
},
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toBe(5);
|
||||
|
||||
expect(
|
||||
evaluate(
|
||||
'${a | isEquals: 1 : "1" |isEquals: 2 : "2" | isEquals: 3 : "3" }',
|
||||
{
|
||||
a: 3
|
||||
},
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toBe('3');
|
||||
|
||||
expect(
|
||||
evaluate(
|
||||
'${a | isEquals: 1 : "1" |isEquals: 1 : "2" | isEquals: 1 : "3" }',
|
||||
{
|
||||
a: 1
|
||||
},
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toBe('1');
|
||||
|
||||
expect(
|
||||
evaluate(
|
||||
'${a | isEquals: 1 : "1" : "12" |isEquals: 2 : "2" | isEquals: 3 : "3" }',
|
||||
{
|
||||
a: 2
|
||||
},
|
||||
{
|
||||
defaultFilter: 'raw'
|
||||
}
|
||||
)
|
||||
).toBe('12');
|
||||
});
|
||||
13
packages/amis-core/__tests__/helper.d.ts
vendored
Normal file
13
packages/amis-core/__tests__/helper.d.ts
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
import { RenderOptions } from '../src/factory';
|
||||
export declare function wait(duration: number, fnOrUseWaitFor?: Function | boolean): Promise<void>;
|
||||
export declare function makeEnv(env?: Partial<RenderOptions>): RenderOptions;
|
||||
export declare const createMockMediaMatcher: (matchesOrMapOfMatches: any) => (qs: any) => {
|
||||
matches: any;
|
||||
media: string;
|
||||
addListener: () => void;
|
||||
addEventListener: () => void;
|
||||
removeEventListener: () => void;
|
||||
onchange: () => void;
|
||||
removeListener: () => void;
|
||||
dispatchEvent: () => boolean;
|
||||
};
|
||||
78
packages/amis-core/__tests__/helper.tsx
Normal file
78
packages/amis-core/__tests__/helper.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
import {waitFor} from '@testing-library/react';
|
||||
import {RenderOptions} from '../src/factory';
|
||||
|
||||
// jest.useFakeTimers 会修改 global 的 setTimeout 所以需要把原始的记录下来。
|
||||
const timerFn = (global as any).originSetTimeout || setTimeout;
|
||||
export function wait(duration: number, fnOrUseWaitFor?: Function | boolean) {
|
||||
const useWaitFor = fnOrUseWaitFor !== false;
|
||||
const fn = (
|
||||
typeof fnOrUseWaitFor === 'function' ? fnOrUseWaitFor : undefined
|
||||
) as Function;
|
||||
|
||||
return useWaitFor
|
||||
? waitFor(
|
||||
() =>
|
||||
new Promise<void>(resolve => {
|
||||
timerFn(() => {
|
||||
fn && fn();
|
||||
resolve();
|
||||
}, duration);
|
||||
}),
|
||||
{
|
||||
timeout: duration + 100
|
||||
}
|
||||
)
|
||||
: new Promise<void>(resolve => {
|
||||
timerFn(() => {
|
||||
fn && fn();
|
||||
resolve();
|
||||
}, duration);
|
||||
});
|
||||
}
|
||||
|
||||
export function makeEnv(env?: Partial<RenderOptions>): RenderOptions {
|
||||
return {
|
||||
session: 'test-case',
|
||||
isCancel: () => false,
|
||||
notify: (msg: string) => null,
|
||||
jumpTo: (to: string) => console.info('Now should jump to ' + to),
|
||||
alert: msg => console.info(`Alert: ${msg}`),
|
||||
...env
|
||||
};
|
||||
}
|
||||
|
||||
export const createMockMediaMatcher =
|
||||
(matchesOrMapOfMatches: any) => (qs: any) => ({
|
||||
matches:
|
||||
typeof matchesOrMapOfMatches === 'object'
|
||||
? matchesOrMapOfMatches[qs]
|
||||
: matchesOrMapOfMatches,
|
||||
media: '',
|
||||
addListener: () => {},
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
onchange: () => {},
|
||||
removeListener: () => {},
|
||||
dispatchEvent: () => {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
// Mock IntersectionObserver
|
||||
class IntersectionObserver {
|
||||
observe = jest.fn();
|
||||
disconnect = jest.fn();
|
||||
unobserve = jest.fn();
|
||||
}
|
||||
|
||||
Object.defineProperty(window, 'IntersectionObserver', {
|
||||
writable: true,
|
||||
configurable: true,
|
||||
value: IntersectionObserver
|
||||
});
|
||||
|
||||
Object.defineProperty(global, 'IntersectionObserver', {
|
||||
writable: true,
|
||||
configurable: true,
|
||||
value: IntersectionObserver
|
||||
});
|
||||
1
packages/amis-core/__tests__/jest.setup.d.ts
vendored
Normal file
1
packages/amis-core/__tests__/jest.setup.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
87
packages/amis-core/__tests__/jest.setup.js
Normal file
87
packages/amis-core/__tests__/jest.setup.js
Normal file
@@ -0,0 +1,87 @@
|
||||
const originalWarn = console.warn.bind(console.warn);
|
||||
const originalGroupCollapsed = console.warn.bind(console.groupCollapsed);
|
||||
const originalGroup = console.warn.bind(console.group);
|
||||
const originalGroupEnd = console.warn.bind(console.groupEnd);
|
||||
const originalDebug = console.warn.bind(console.debug);
|
||||
const originalError = console.error.bind(console.error);
|
||||
require('@testing-library/jest-dom');
|
||||
require('moment-timezone');
|
||||
const loadAllAsyncRenderers = require('amis-core').loadAllAsyncRenderers;
|
||||
const moment = require('moment');
|
||||
moment.tz.setDefault('Asia/Shanghai');
|
||||
const cleanup = require('@testing-library/react').cleanup;
|
||||
|
||||
// https://github.com/nrwl/nx/issues/1178
|
||||
// 解决jest 运行的时候报:
|
||||
// ReferenceError: DragEvent is not defined
|
||||
if (!window.DragEvent) {
|
||||
Object.defineProperty(window, 'DragEvent', {
|
||||
value: class DragEvent {}
|
||||
});
|
||||
}
|
||||
|
||||
// Mock ResizeObserver in jest env
|
||||
global.ResizeObserver = require('resize-observer-polyfill');
|
||||
|
||||
global.__buildVersion = '';
|
||||
|
||||
global.BroadcastChannel = class {
|
||||
constructor(channelName) {
|
||||
this.channelName = channelName;
|
||||
this.listeners = [];
|
||||
}
|
||||
postMessage(message) {
|
||||
this.listeners.forEach(listener => listener({data: message}));
|
||||
}
|
||||
addEventListener(event, listener) {
|
||||
if (event === 'message') {
|
||||
this.listeners.push(listener);
|
||||
}
|
||||
}
|
||||
removeEventListener(event, listener) {
|
||||
if (event === 'message') {
|
||||
this.listeners = this.listeners.filter(l => l !== listener);
|
||||
}
|
||||
}
|
||||
close() {
|
||||
this.listeners = [];
|
||||
}
|
||||
};
|
||||
|
||||
global.beforeAll(async () => {
|
||||
console.warn =
|
||||
console.groupCollapsed =
|
||||
console.group =
|
||||
console.groupEnd =
|
||||
console.debug =
|
||||
console.error =
|
||||
msg => {
|
||||
// warning 先关了,实在太吵。
|
||||
// const str = msg.toString();
|
||||
// if (
|
||||
// str.includes('componentWillMount') ||
|
||||
// str.includes('componentWillReceiveProps')
|
||||
// ) {
|
||||
// return;
|
||||
// }
|
||||
// originalWarn(msg);
|
||||
};
|
||||
|
||||
await loadAllAsyncRenderers();
|
||||
});
|
||||
global.afterAll(() => {
|
||||
console.warn = originalWarn;
|
||||
console.groupCollapsed = originalGroupCollapsed;
|
||||
console.group = originalGroup;
|
||||
console.groupEnd = originalGroupEnd;
|
||||
console.debug = originalDebug;
|
||||
console.error = originalError;
|
||||
cleanup();
|
||||
});
|
||||
|
||||
// expect.addSnapshotSerializer({
|
||||
// test: val => typeof val === 'string' && /^[a-z0-9]{12}$/.test(val),
|
||||
// print: val => {
|
||||
// return JSON.stringify('__guid_dynamic_value__');
|
||||
// }
|
||||
// });
|
||||
58
packages/amis-core/__tests__/renderers/wrapControl.test.tsx
Normal file
58
packages/amis-core/__tests__/renderers/wrapControl.test.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* @author: ranqirong
|
||||
* @date: 2024-10-10
|
||||
* @description:
|
||||
*/
|
||||
import React from 'react';
|
||||
import {wrapControl} from '../../src/renderers/wrapControl';
|
||||
import {render, screen} from '@testing-library/react';
|
||||
import {RootStoreContext} from '../../src/WithRootStore';
|
||||
import {RendererStore} from '../../src/store/index';
|
||||
import {FormItemProps} from '../../src/renderers/Item';
|
||||
|
||||
const renderComponent = (WrappedComponent: any, props: any) => {
|
||||
const store = RendererStore.create({});
|
||||
return render(
|
||||
<RootStoreContext.Provider value={store}>
|
||||
<WrappedComponent rootStore={{}} $schema={{}} {...props} />
|
||||
</RootStoreContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
describe('constructor', () => {
|
||||
it('如果传入有defaultProps包含name属性,则创建FormItemStore', () => {
|
||||
const OriginComponent = (props: FormItemProps) => {
|
||||
// 用于断言formItem已被注册
|
||||
return <div>{props.formItem?.storeType}</div>;
|
||||
};
|
||||
OriginComponent.defaultProps = {
|
||||
name: 'test'
|
||||
};
|
||||
const WrappedComponent = wrapControl({}, OriginComponent as any);
|
||||
|
||||
renderComponent(WrappedComponent, {$schema: {}});
|
||||
expect(screen.getByText('FormItemStore')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('如果$schema中包含name属性,则创建FormItemStore', () => {
|
||||
const OriginComponent = (props: FormItemProps) => {
|
||||
// 用于断言formItem已被注册
|
||||
return <div>{props.formItem?.storeType}</div>;
|
||||
};
|
||||
const WrappedComponent = wrapControl({}, OriginComponent as any);
|
||||
|
||||
renderComponent(WrappedComponent, {$schema: {name: 'test'}});
|
||||
expect(screen.getByText('FormItemStore')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('如果$schema和defaultProps中都不包含name属性,则不创建FormItemStore', () => {
|
||||
const OriginComponent = (props: FormItemProps) => {
|
||||
// 用于断言formItem已被注册
|
||||
return <div>{props.formItem?.storeType}</div>;
|
||||
};
|
||||
const WrappedComponent = wrapControl({}, OriginComponent as any);
|
||||
|
||||
renderComponent(WrappedComponent, {$schema: {}});
|
||||
expect(screen.queryByText('FormItemStore')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
18
packages/amis-core/__tests__/scoped.test.ts
Normal file
18
packages/amis-core/__tests__/scoped.test.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import {
|
||||
registerRenderer,
|
||||
unRegisterRenderer,
|
||||
RendererProps
|
||||
} from '../src/factory';
|
||||
import {render as amisRender, splitTarget} from '../src';
|
||||
import React from 'react';
|
||||
import {render, fireEvent, waitFor} from '@testing-library/react';
|
||||
import {makeEnv} from './helper';
|
||||
|
||||
test('Scoped splitTarget', async () => {
|
||||
expect(splitTarget('abc')).toEqual(['abc']);
|
||||
expect(splitTarget('a,b,c')).toEqual(['a', 'b', 'c']);
|
||||
expect(splitTarget('a, b, c ')).toEqual(['a', 'b', 'c']);
|
||||
expect(splitTarget('a?x=1&y=2,b,c')).toEqual(['a?x=1&y=2', 'b', 'c']);
|
||||
expect(splitTarget('a?x=${[a, b]},b,c')).toEqual(['a?x=${[a, b]}', 'b', 'c']);
|
||||
expect(splitTarget('a?x=${[a, b]}')).toEqual(['a?x=${[a, b]}']);
|
||||
});
|
||||
113
packages/amis-core/__tests__/store/table.test.ts
Normal file
113
packages/amis-core/__tests__/store/table.test.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
import {TableStore, SELECTED_STATUS} from '../../src/store/table';
|
||||
|
||||
import type {IRow, ITableStore} from '../../src/store/table';
|
||||
|
||||
let table: ITableStore;
|
||||
let firstLevel: IRow;
|
||||
let secondLevel: IRow;
|
||||
let secondLevel2: IRow;
|
||||
let thirdLevel: IRow;
|
||||
let thirdLevel2: IRow;
|
||||
let thirdLevel3: IRow;
|
||||
|
||||
beforeEach(() => {
|
||||
table = TableStore.create({id: 'mock-id', storeType: 'table'});
|
||||
table.initRows([
|
||||
{
|
||||
name: '手机维修',
|
||||
children: [
|
||||
{
|
||||
name: '苹果',
|
||||
children: [
|
||||
{
|
||||
name: 'iphone系列'
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
name: '华为',
|
||||
children: [
|
||||
{
|
||||
name: 'mate系列'
|
||||
},
|
||||
{
|
||||
name: 'p系列'
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]);
|
||||
|
||||
firstLevel = table.rows[0];
|
||||
secondLevel = table.rows[0].children[0];
|
||||
secondLevel2 = table.rows[0].children[1];
|
||||
thirdLevel = table.rows[0].children[0].children[0];
|
||||
thirdLevel2 = table.rows[0].children[1].children[0];
|
||||
thirdLevel3 = table.rows[0].children[1].children[1];
|
||||
});
|
||||
|
||||
describe('Row', () => {
|
||||
it('通过parent快速拿到父节点', () => {
|
||||
expect(secondLevel.parent).toEqual(firstLevel);
|
||||
});
|
||||
|
||||
it('通过table快速拿到根节点', () => {
|
||||
expect(thirdLevel.table).toEqual(table);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TableStore', () => {
|
||||
it('选中父节点,所有子节点自动选中', () => {
|
||||
firstLevel.toggle(true);
|
||||
|
||||
const selectedRows = table.selectedRows.map(row => row.data.name);
|
||||
|
||||
expect(selectedRows).toEqual(
|
||||
expect.arrayContaining([
|
||||
'苹果',
|
||||
'iphone系列',
|
||||
'华为',
|
||||
'mate系列',
|
||||
'p系列'
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it('选中所有子节点,所有父节点自动选中', () => {
|
||||
thirdLevel.toggle(true);
|
||||
thirdLevel2.toggle(true);
|
||||
thirdLevel3.toggle(true);
|
||||
|
||||
const selectedRows = table.selectedRows.map(row => row.data.name);
|
||||
|
||||
expect(selectedRows).toEqual(
|
||||
expect.arrayContaining(['苹果', '华为', '手机维修'])
|
||||
);
|
||||
});
|
||||
|
||||
it('默认情况下,父节点是未选中状态,选中一个子节点切换到部分选中状态,选中所有2个子节点切换到全部选中状态', () => {
|
||||
expect(firstLevel.childrenSelected()).toBe(SELECTED_STATUS.NONE);
|
||||
expect(firstLevel.partial).toBe(false);
|
||||
|
||||
secondLevel.toggle(true);
|
||||
|
||||
expect(firstLevel.childrenSelected()).toBe(SELECTED_STATUS.PARTIAL);
|
||||
expect(firstLevel.partial).toBe(true);
|
||||
|
||||
secondLevel2.toggle(true);
|
||||
|
||||
expect(firstLevel.childrenSelected()).toBe(SELECTED_STATUS.ALL);
|
||||
expect(firstLevel.partial).toBe(false);
|
||||
});
|
||||
|
||||
it('多个子节点只选中一个,祖先节点不会被选中,但会被标记为部分选中状态', () => {
|
||||
thirdLevel2.toggle(true);
|
||||
|
||||
expect(secondLevel2.checked).toBe(false);
|
||||
expect(secondLevel2.partial).toBe(true);
|
||||
|
||||
expect(firstLevel.checked).toBe(false);
|
||||
expect(firstLevel.partial).toBe(true);
|
||||
});
|
||||
});
|
||||
1
packages/amis-core/__tests__/tokenize.test.d.ts
vendored
Normal file
1
packages/amis-core/__tests__/tokenize.test.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export {};
|
||||
26
packages/amis-core/__tests__/tokenize.test.ts
Normal file
26
packages/amis-core/__tests__/tokenize.test.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import {tokenize} from '../src/utils/tpl-builtin';
|
||||
|
||||
test(`tokenize:null`, () => {
|
||||
expect(
|
||||
tokenize('abc${a}', {
|
||||
a: ''
|
||||
})
|
||||
).toBe('abc');
|
||||
expect(
|
||||
tokenize('abc${a}', {
|
||||
a: null
|
||||
})
|
||||
).toBe('abc');
|
||||
|
||||
expect(
|
||||
tokenize('abc${a}', {
|
||||
a: undefined
|
||||
})
|
||||
).toBe('abc');
|
||||
|
||||
expect(
|
||||
tokenize('abc${a}', {
|
||||
a: 0
|
||||
})
|
||||
).toBe('abc0');
|
||||
});
|
||||
11
packages/amis-core/__tests__/utils/arraySlice.test.ts
Normal file
11
packages/amis-core/__tests__/utils/arraySlice.test.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import {arraySlice} from '../../src/utils/arraySlice';
|
||||
|
||||
test(`arrayslice:test`, () => {
|
||||
const testArray = [0, 1, 2, 3, 4, 5];
|
||||
expect(arraySlice(testArray, ':')).toEqual([0, 1, 2, 3, 4, 5]);
|
||||
expect(arraySlice(testArray, '0,3,4')).toEqual([0, 3, 4]);
|
||||
expect(arraySlice(testArray, '1:2')).toEqual([1]);
|
||||
expect(arraySlice(testArray, '0:-2')).toEqual([0, 1, 2, 3]);
|
||||
expect(arraySlice(testArray, '1:-2')).toEqual([1, 2, 3]);
|
||||
expect(arraySlice(testArray, '0,1:-2')).toEqual([0, 1, 2, 3]);
|
||||
});
|
||||
28
packages/amis-core/__tests__/utils/math.test.ts
Normal file
28
packages/amis-core/__tests__/utils/math.test.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import {safeAdd, safeSub, numberFormatter} from '../../src/utils/math';
|
||||
|
||||
test(`math safeAdd:test`, () => {
|
||||
expect(safeAdd(0.1, 0.2)).toEqual(0.3);
|
||||
expect(safeAdd(0.111, 0.455)).toEqual(0.566);
|
||||
expect(safeAdd(NaN, 1)).toEqual(NaN);
|
||||
expect(safeAdd(NaN, NaN)).toEqual(NaN);
|
||||
});
|
||||
|
||||
test(`math safeSub:test`, () => {
|
||||
expect(safeSub(0.8, 0.1)).toEqual(0.7);
|
||||
expect(safeSub(0.1, 0.111111)).toEqual(-0.011111);
|
||||
expect(safeAdd(NaN, 1)).toEqual(NaN);
|
||||
expect(safeAdd(NaN, NaN)).toEqual(NaN);
|
||||
});
|
||||
|
||||
test('numberFormatter:test', () => {
|
||||
expect(numberFormatter(0)).toEqual('0');
|
||||
expect(numberFormatter(0.123)).toEqual('0.123');
|
||||
expect(numberFormatter(0.123, 0)).toEqual('0');
|
||||
expect(numberFormatter(0, 2)).toEqual('0.00');
|
||||
expect(numberFormatter(0, 8)).toEqual('0.00000000');
|
||||
expect(numberFormatter(123456)).toEqual('123,456');
|
||||
expect(numberFormatter(123456, 2)).toEqual('123,456.00');
|
||||
expect(numberFormatter(1234567890000)).toEqual('1,234,567,890,000');
|
||||
expect(numberFormatter(1234567890000, 4)).toEqual('1,234,567,890,000.0000');
|
||||
expect(numberFormatter(1000000000000000)).toEqual('1,000,000,000,000,000');
|
||||
});
|
||||
76
packages/amis-core/__tests__/utils/styleHelper.test.ts
Normal file
76
packages/amis-core/__tests__/utils/styleHelper.test.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import {formatCustomStyle} from '../../src/utils/style-helper';
|
||||
|
||||
const customStyleCases: [any, string][] = [
|
||||
[
|
||||
{
|
||||
root: {
|
||||
color: 'red'
|
||||
}
|
||||
},
|
||||
'\n.wrapperCustomStyle-test {\n color: red;\n}'
|
||||
],
|
||||
[
|
||||
{
|
||||
root: {
|
||||
a: {
|
||||
color: 'blue'
|
||||
}
|
||||
}
|
||||
},
|
||||
'\n.wrapperCustomStyle-test a {\n color: blue;\n}'
|
||||
],
|
||||
[
|
||||
{
|
||||
root: {
|
||||
'a,i': {
|
||||
color: 'blue'
|
||||
}
|
||||
}
|
||||
},
|
||||
'\n.wrapperCustomStyle-test a,.wrapperCustomStyle-test i {\n color: blue;\n}'
|
||||
],
|
||||
[
|
||||
{
|
||||
root: {
|
||||
'a,i': {
|
||||
span: {
|
||||
color: 'blue'
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'\n.wrapperCustomStyle-test a span,.wrapperCustomStyle-test i span {\n color: blue;\n}'
|
||||
],
|
||||
[
|
||||
{
|
||||
root: {
|
||||
'a,i': {
|
||||
'span,.custom': {
|
||||
color: 'blue'
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
'\n.wrapperCustomStyle-test a span,.wrapperCustomStyle-test i span,.wrapperCustomStyle-test a .custom,.wrapperCustomStyle-test i .custom {\n color: blue;\n}'
|
||||
],
|
||||
[
|
||||
{
|
||||
'.cxd-Table': {
|
||||
'td,th': {
|
||||
color: 'red'
|
||||
}
|
||||
}
|
||||
},
|
||||
'\n.wrapperCustomStyle-test .cxd-Table td,.wrapperCustomStyle-test .cxd-Table th {\n color: red;\n}'
|
||||
]
|
||||
];
|
||||
|
||||
describe('formatCustomStyle', () => {
|
||||
test.each(customStyleCases)(
|
||||
'formatCustomStyle should return styles correctly',
|
||||
(customStyle, expected) => {
|
||||
const {content} = formatCustomStyle({customStyle, id: 'test'});
|
||||
expect(content).toBe(expected);
|
||||
}
|
||||
);
|
||||
});
|
||||
107
packages/amis-core/__tests__/utils/visitedCache.test.ts
Normal file
107
packages/amis-core/__tests__/utils/visitedCache.test.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import VisitedCache from '../../src/utils/visitedCache';
|
||||
|
||||
describe('VisitedCache', () => {
|
||||
let cache: VisitedCache<string, number>;
|
||||
|
||||
beforeEach(() => {
|
||||
cache = new VisitedCache<string, number>(5);
|
||||
});
|
||||
|
||||
it('should set and get values correctly', () => {
|
||||
cache.set('a', 1);
|
||||
cache.set('b', 2);
|
||||
cache.set('c', 3);
|
||||
|
||||
expect(cache.get('a')).toBe(1);
|
||||
expect(cache.get('b')).toBe(2);
|
||||
expect(cache.get('c')).toBe(3);
|
||||
});
|
||||
|
||||
it('should evict the least visited entry when cache is full', () => {
|
||||
cache.set('a', 1);
|
||||
cache.set('b', 2);
|
||||
cache.set('c', 3);
|
||||
cache.set('d', 4);
|
||||
cache.set('e', 5);
|
||||
|
||||
// Access 'a' to increase its visit count
|
||||
cache.get('a');
|
||||
|
||||
cache.set('f', 6);
|
||||
|
||||
expect(cache.get('a')).toBe(1);
|
||||
expect(cache.get('b')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle cache misses correctly', () => {
|
||||
expect(cache.get('non-existent-key')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should handle multiple entries with the same visit count', () => {
|
||||
cache.set('a', 1);
|
||||
cache.set('b', 2);
|
||||
cache.set('c', 3);
|
||||
cache.set('d', 4);
|
||||
cache.set('e', 5);
|
||||
|
||||
// Access 'a', 'b', 'c' to make them have the same visit count
|
||||
cache.get('a');
|
||||
cache.get('b');
|
||||
cache.get('c');
|
||||
|
||||
cache.set('f', 6);
|
||||
|
||||
// 动态清理的个数为1,清理掉最少访问最旧的d项
|
||||
expect(cache.get('a')).toBe(1);
|
||||
expect(cache.get('b')).toBe(2);
|
||||
expect(cache.get('c')).toBe(3);
|
||||
expect(cache.get('d')).toBeUndefined();
|
||||
expect(cache.get('e')).toBe(5);
|
||||
expect(cache.get('f')).toBe(6);
|
||||
});
|
||||
|
||||
it('should handle dynamic release count', () => {
|
||||
cache = new VisitedCache<string, number>(10, 1 / 5);
|
||||
// 释放数量为 10 * 1/5 >> 0 || 1 = 2
|
||||
|
||||
cache.set('a', 1);
|
||||
cache.set('b', 2);
|
||||
cache.set('c', 3);
|
||||
cache.set('d', 4);
|
||||
cache.set('e', 5);
|
||||
cache.set('f', 6);
|
||||
cache.set('g', 7);
|
||||
cache.set('h', 8);
|
||||
cache.set('i', 9);
|
||||
cache.set('j', 10);
|
||||
|
||||
// 提升除了a之外的访问次数
|
||||
cache.get('b');
|
||||
cache.get('c');
|
||||
cache.get('d');
|
||||
cache.get('e');
|
||||
cache.get('f');
|
||||
cache.get('g');
|
||||
cache.get('h');
|
||||
cache.get('i');
|
||||
cache.get('j');
|
||||
|
||||
// 再次提升高b的访问次数
|
||||
cache.get('b');
|
||||
|
||||
// 此时应该清理掉两项,a和c
|
||||
cache.set('k', 11);
|
||||
|
||||
expect(cache.get('a')).toBeUndefined();
|
||||
expect(cache.get('b')).toBe(2);
|
||||
expect(cache.get('c')).toBeUndefined();
|
||||
expect(cache.get('d')).toBe(4);
|
||||
expect(cache.get('e')).toBe(5);
|
||||
expect(cache.get('f')).toBe(6);
|
||||
expect(cache.get('g')).toBe(7);
|
||||
expect(cache.get('h')).toBe(8);
|
||||
expect(cache.get('i')).toBe(9);
|
||||
expect(cache.get('j')).toBe(10);
|
||||
expect(cache.get('k')).toBe(11);
|
||||
});
|
||||
});
|
||||
124
packages/amis-core/package.json
Normal file
124
packages/amis-core/package.json
Normal file
@@ -0,0 +1,124 @@
|
||||
{
|
||||
"name": "amis-core",
|
||||
"version": "6.13.0",
|
||||
"description": "amis-core",
|
||||
"main": "lib/index.js",
|
||||
"module": "esm/index.js",
|
||||
"types": "lib/index.d.ts",
|
||||
"author": "fex",
|
||||
"license": "Apache-2.0",
|
||||
"exports": {
|
||||
".": {
|
||||
"require": "./lib/index.js",
|
||||
"import": "./esm/index.js"
|
||||
},
|
||||
"./lib/*": {
|
||||
"require": "./lib/*.js",
|
||||
"import": "./esm/*.js"
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rollup/plugin-commonjs": "^22.0.2",
|
||||
"@rollup/plugin-json": "^4.1.0",
|
||||
"@rollup/plugin-node-resolve": "^14.1.0",
|
||||
"@rollup/plugin-replace": "^5.0.1",
|
||||
"@rollup/plugin-typescript": "^8.3.4",
|
||||
"@testing-library/jest-dom": "^5.17.0",
|
||||
"@types/file-saver": "^2.0.1",
|
||||
"@types/hoist-non-react-statics": "^3.3.1",
|
||||
"@types/jest": "^28.1.0",
|
||||
"@types/react": "^18.0.24",
|
||||
"@types/react-dom": "^18.0.8",
|
||||
"@types/react-is": "^18.2.4",
|
||||
"immutable": "^4.1.0",
|
||||
"jest": "^29.0.3",
|
||||
"jest-environment-jsdom": "^29.0.3",
|
||||
"moment-timezone": "^0.5.34",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"resize-observer-polyfill": "^1.5.1",
|
||||
"rimraf": "^3.0.2",
|
||||
"rollup": "^2.79.1",
|
||||
"rollup-plugin-auto-external": "^2.0.0",
|
||||
"rollup-plugin-license": "^2.7.0",
|
||||
"ts-jest": "^29.0.2",
|
||||
"typescript": "^4.6.4"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "npm run clean-dist && cross-env NODE_ENV=production rollup -c ",
|
||||
"build-esm": "npm run clean-dist && cross-env NODE_ENV=production rollup -c rollup.esm.config.js",
|
||||
"dev": "rollup -c -w",
|
||||
"test": "jest",
|
||||
"update-snapshot": "jest --updateSnapshot",
|
||||
"coverage": "jest --coverage",
|
||||
"clean-dist": "rimraf lib/** esm/**"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"esm"
|
||||
],
|
||||
"dependencies": {
|
||||
"@rc-component/mini-decimal": "^1.0.1",
|
||||
"amis-formula": "^6.13.0",
|
||||
"classnames": "2.3.2",
|
||||
"cross-env": "^7.0.3",
|
||||
"file-saver": "^2.0.2",
|
||||
"hoist-non-react-statics": "^3.3.2",
|
||||
"lodash": "^4.17.15",
|
||||
"match-sorter": "^6.3.1",
|
||||
"mobx": "^4.5.0",
|
||||
"mobx-react": "^6.3.1",
|
||||
"mobx-state-tree": "^3.17.3",
|
||||
"moment": "^2.19.4",
|
||||
"papaparse": "^5.3.0",
|
||||
"path-to-regexp": "6.2.0",
|
||||
"qs": "6.9.7",
|
||||
"react-intersection-observer": "9.5.2",
|
||||
"react-json-view": "1.21.3",
|
||||
"react-overlays": "5.1.1",
|
||||
"tslib": "^2.3.1",
|
||||
"uncontrollable": "7.2.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"amis-formula": "*",
|
||||
"react": ">=16.8.6",
|
||||
"react-dom": ">=16.8.6",
|
||||
"react-is": ">=16.8.6"
|
||||
},
|
||||
"jest": {
|
||||
"testEnvironment": "jsdom",
|
||||
"coverageReporters": [
|
||||
"text",
|
||||
"cobertura"
|
||||
],
|
||||
"collectCoverageFrom": [
|
||||
"src/**/*"
|
||||
],
|
||||
"moduleFileExtensions": [
|
||||
"ts",
|
||||
"tsx",
|
||||
"js"
|
||||
],
|
||||
"transform": {
|
||||
"^.+\\.(t|j)sx?$": "@swc/jest"
|
||||
},
|
||||
"setupFiles": [
|
||||
"jest-canvas-mock"
|
||||
],
|
||||
"testRegex": "/.*\\.test\\.(ts|tsx|js)$",
|
||||
"moduleNameMapper": {
|
||||
"\\.(css|less|sass|scss)$": "<rootDir>/../../__mocks__/styleMock.js",
|
||||
"\\.(svg)$": "<rootDir>/../../__mocks__/svgMock.js",
|
||||
"^amis\\-core$": "<rootDir>/../../packages/amis-core/src/index.tsx",
|
||||
"^amis\\-formula$": "<rootDir>/../../packages/amis-formula/src/index.ts"
|
||||
},
|
||||
"setupFilesAfterEnv": [
|
||||
"<rootDir>/../amis-core/__tests__/jest.setup.js"
|
||||
],
|
||||
"testPathIgnorePatterns": [
|
||||
"/node_modules/",
|
||||
"/.rollup.cache/"
|
||||
]
|
||||
},
|
||||
"gitHead": "37d23b4a8eb1c663bc38e8dd9040889ea1526ec4"
|
||||
}
|
||||
226
packages/amis-core/rollup.config.js
Normal file
226
packages/amis-core/rollup.config.js
Normal file
@@ -0,0 +1,226 @@
|
||||
// rollup.config.js
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import json from '@rollup/plugin-json';
|
||||
import resolve from '@rollup/plugin-node-resolve';
|
||||
import typescript from '@rollup/plugin-typescript';
|
||||
import license from 'rollup-plugin-license';
|
||||
import autoExternal from 'rollup-plugin-auto-external';
|
||||
import replace from '@rollup/plugin-replace';
|
||||
import {
|
||||
name,
|
||||
version,
|
||||
author,
|
||||
main,
|
||||
module,
|
||||
dependencies
|
||||
} from './package.json';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
const isDev = process.env.NODE_ENV !== 'production';
|
||||
|
||||
const settings = {
|
||||
globals: {}
|
||||
};
|
||||
|
||||
const pkgs = [];
|
||||
// 读取所有的node_modules目录,获取所有的包名
|
||||
[
|
||||
path.join(__dirname, './node_modules'),
|
||||
path.join(__dirname, '../../node_modules')
|
||||
].forEach(dir => {
|
||||
if (fs.existsSync(dir)) {
|
||||
fs.readdirSync(dir).forEach(item => {
|
||||
if (item.startsWith('.')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (item.startsWith('@')) {
|
||||
fs.readdirSync(path.join(dir, item)).forEach(subItem => {
|
||||
pkgs.push(item + '/' + subItem);
|
||||
});
|
||||
}
|
||||
|
||||
return pkgs.push(item);
|
||||
});
|
||||
}
|
||||
});
|
||||
const external = id =>
|
||||
pkgs.some(pkg => id.startsWith(pkg) || ~id.indexOf(`node_modules/${pkg}`));
|
||||
const input = './src/index.tsx';
|
||||
|
||||
/** 获取子包编译后的入口路径,需要使用相对路径 */
|
||||
const getCompiledEntryPath = (repo, format) =>
|
||||
path.join(
|
||||
'..',
|
||||
repo,
|
||||
repo === 'amis-formula' || format === 'cjs' ? 'lib' : 'esm',
|
||||
'index.js'
|
||||
);
|
||||
|
||||
export default [
|
||||
{
|
||||
input,
|
||||
|
||||
output: [
|
||||
{
|
||||
...settings,
|
||||
dir: path.dirname(main),
|
||||
format: 'cjs',
|
||||
exports: 'named',
|
||||
preserveModulesRoot: './src',
|
||||
preserveModules: true // Keep directory structure and files
|
||||
}
|
||||
],
|
||||
external,
|
||||
plugins: getPlugins('cjs')
|
||||
},
|
||||
|
||||
isDev
|
||||
? null
|
||||
: {
|
||||
input,
|
||||
|
||||
output: [
|
||||
{
|
||||
...settings,
|
||||
dir: path.dirname(module),
|
||||
format: 'esm',
|
||||
exports: 'named',
|
||||
preserveModulesRoot: './src',
|
||||
preserveModules: true // Keep directory structure and files
|
||||
}
|
||||
],
|
||||
external,
|
||||
plugins: getPlugins('esm')
|
||||
}
|
||||
].filter(item => item);
|
||||
|
||||
function transpileDynamicImportForCJS(options) {
|
||||
return {
|
||||
name: 'transpile-dynamic-import-for-cjs',
|
||||
renderDynamicImport({format, targetModuleId}) {
|
||||
if (format !== 'cjs') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
left: 'Promise.resolve().then(function() {return new Promise(function(fullfill) {require([',
|
||||
right:
|
||||
', "tslib"], function(mod, tslib) {fullfill(tslib.__importStar(mod))})})})'
|
||||
};
|
||||
|
||||
// return {
|
||||
// left: 'Promise.resolve().then(function() {return new Promise(function(fullfill) {require.ensure([',
|
||||
// right:
|
||||
// '], function(r) {fullfill(_interopDefaultLegacy(r("' +
|
||||
// targetModuleId +
|
||||
// '")))})})})'
|
||||
// };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// 参考:https://github.com/theKashey/jsx-compress-loader/blob/master/src/index.js
|
||||
function transpileReactCreateElement() {
|
||||
return {
|
||||
name: 'transpile-react-create-element',
|
||||
enforce: 'post',
|
||||
transform: (code, id) => {
|
||||
if (
|
||||
/\.(?:tsx|jsx|svg)$/.test(id) &&
|
||||
code.indexOf('React.createElement') !== -1
|
||||
) {
|
||||
const separator = '\n\n;';
|
||||
const appendText =
|
||||
`\n` +
|
||||
`var __react_jsx__ = require('react');\n` +
|
||||
`var _J$X_ = (__react_jsx__["default"] || __react_jsx__).createElement;\n` +
|
||||
`var _J$F_ = (__react_jsx__["default"] || __react_jsx__).Fragment;\n`;
|
||||
|
||||
const newSource = code
|
||||
.replace(/React\.createElement\(/g, '_J$X_(')
|
||||
.replace(/React\.createElement\(/g, '_J$F_(');
|
||||
|
||||
code = [appendText, newSource].join(separator);
|
||||
}
|
||||
|
||||
return {
|
||||
code
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function getPlugins(format = 'esm') {
|
||||
const overridePaths = ['amis-formula'].reduce(
|
||||
(prev, current) => ({
|
||||
...prev,
|
||||
[current]: [getCompiledEntryPath(current, format)]
|
||||
}),
|
||||
{}
|
||||
);
|
||||
const typeScriptOptions = {
|
||||
typescript: require('typescript'),
|
||||
sourceMap: false,
|
||||
outputToFilesystem: true,
|
||||
|
||||
...(format === 'esm'
|
||||
? {
|
||||
compilerOptions: {
|
||||
rootDir: './src',
|
||||
outDir: path.dirname(module),
|
||||
/** 覆盖继承自顶层tsconfig的paths配置,编译时应该去掉,避免报错@rollup/plugin-typescript TS6305 */
|
||||
paths: overridePaths
|
||||
}
|
||||
}
|
||||
: {
|
||||
compilerOptions: {
|
||||
rootDir: './src',
|
||||
outDir: path.dirname(main),
|
||||
paths: overridePaths
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
return [
|
||||
transpileDynamicImportForCJS(),
|
||||
autoExternal(),
|
||||
json(),
|
||||
resolve({
|
||||
jsnext: true,
|
||||
main: true
|
||||
}),
|
||||
replace({
|
||||
preventAssignment: true,
|
||||
__buildVersion: version,
|
||||
__buildTime: () => new Date().toISOString()
|
||||
}),
|
||||
typescript(typeScriptOptions),
|
||||
commonjs({
|
||||
sourceMap: false
|
||||
}),
|
||||
format === 'esm' ? null : transpileReactCreateElement(),
|
||||
license({
|
||||
banner: `
|
||||
${name} v${version}
|
||||
Copyright 2018<%= moment().format('YYYY') > 2018 ? '-' + moment().format('YYYY') : null %> ${author}
|
||||
`
|
||||
}),
|
||||
{
|
||||
name: 'disable-treeshake',
|
||||
transform(code, id) {
|
||||
if (/\/src\/renderers\//.test(id)) {
|
||||
// Disable tree shake for modules under `src/renderers`
|
||||
return {
|
||||
code,
|
||||
map: null,
|
||||
moduleSideEffects: 'no-treeshake'
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
].filter(item => item);
|
||||
}
|
||||
5
packages/amis-core/rollup.esm.config.js
Normal file
5
packages/amis-core/rollup.esm.config.js
Normal file
@@ -0,0 +1,5 @@
|
||||
import config from "./rollup.config";
|
||||
|
||||
const esmConfig = config[1];
|
||||
|
||||
export default esmConfig;
|
||||
256
packages/amis-core/src/Root.tsx
Normal file
256
packages/amis-core/src/Root.tsx
Normal file
@@ -0,0 +1,256 @@
|
||||
import React from 'react';
|
||||
import isPlainObject from 'lodash/isPlainObject';
|
||||
import {RendererEnv} from './env';
|
||||
import {RendererProps} from './factory';
|
||||
import {LocaleContext, TranslateFn} from './locale';
|
||||
import {RootRenderer} from './RootRenderer';
|
||||
import {SchemaRenderer} from './SchemaRenderer';
|
||||
import Scoped from './Scoped';
|
||||
import {IRendererStore} from './store';
|
||||
import {ThemeContext} from './theme';
|
||||
import {Schema, SchemaNode} from './types';
|
||||
import {autobind, isEmpty} from './utils/helper';
|
||||
import {RootStoreContext} from './WithRootStore';
|
||||
import {
|
||||
StatusScoped,
|
||||
StatusScopedWrapper,
|
||||
StatusScopedProps
|
||||
} from './StatusScoped';
|
||||
import {GlobalVariableItem} from './globalVar';
|
||||
|
||||
export interface RootRenderProps {
|
||||
globalVars?: Array<GlobalVariableItem>;
|
||||
location?: Location;
|
||||
theme?: string;
|
||||
data?: Record<string, any>;
|
||||
context?: Record<string, any>;
|
||||
locale?: string;
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
export interface RootProps extends StatusScopedProps {
|
||||
schema: SchemaNode;
|
||||
rootStore: IRendererStore;
|
||||
env: RendererEnv;
|
||||
theme: string;
|
||||
pathPrefix?: string;
|
||||
locale?: string;
|
||||
translate?: TranslateFn;
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
export interface RootWrapperProps {
|
||||
env: RendererEnv;
|
||||
children: React.ReactNode | Array<React.ReactNode>;
|
||||
schema: SchemaNode;
|
||||
rootStore: IRendererStore;
|
||||
theme: string;
|
||||
data?: Record<string, any>;
|
||||
context?: Record<string, any>;
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
const rootWrappers: Array<(props: RootWrapperProps) => React.ReactNode> = [];
|
||||
|
||||
export function addRootWrapper(
|
||||
fn: (props: RootWrapperProps) => React.ReactNode
|
||||
) {
|
||||
rootWrappers.push(fn);
|
||||
}
|
||||
|
||||
export class Root extends React.Component<RootProps> {
|
||||
@autobind
|
||||
resolveDefinitions(name: string) {
|
||||
const definitions = (this.props.schema as Schema).definitions;
|
||||
if (!name || isEmpty(definitions)) {
|
||||
return {};
|
||||
}
|
||||
return definitions && definitions[name];
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
schema,
|
||||
rootStore,
|
||||
env,
|
||||
pathPrefix,
|
||||
location,
|
||||
data,
|
||||
context,
|
||||
locale,
|
||||
translate,
|
||||
...rest
|
||||
} = this.props;
|
||||
const theme = env.theme;
|
||||
let themeName = this.props.theme || 'cxd';
|
||||
|
||||
if (themeName === 'default') {
|
||||
themeName = 'cxd';
|
||||
}
|
||||
|
||||
return (
|
||||
<RootStoreContext.Provider value={rootStore}>
|
||||
<ThemeContext.Provider value={themeName}>
|
||||
<LocaleContext.Provider value={this.props.locale!}>
|
||||
{
|
||||
rootWrappers.reduce(
|
||||
(props: RootWrapperProps, wrapper) => {
|
||||
return {
|
||||
...props,
|
||||
children: wrapper(props)
|
||||
};
|
||||
},
|
||||
{
|
||||
pathPrefix: pathPrefix || '',
|
||||
schema: isPlainObject(schema)
|
||||
? {
|
||||
type: 'page',
|
||||
...(schema as any)
|
||||
}
|
||||
: schema,
|
||||
...rest,
|
||||
render: renderChild,
|
||||
rootStore: rootStore,
|
||||
resolveDefinitions: this.resolveDefinitions,
|
||||
location: location,
|
||||
data,
|
||||
env: env,
|
||||
classnames: theme.classnames,
|
||||
classPrefix: theme.classPrefix,
|
||||
locale: locale,
|
||||
translate: translate,
|
||||
children: (
|
||||
<RootRenderer
|
||||
pathPrefix={pathPrefix || ''}
|
||||
schema={
|
||||
isPlainObject(schema)
|
||||
? {
|
||||
type: 'page',
|
||||
...(schema as any)
|
||||
}
|
||||
: schema
|
||||
}
|
||||
{...rest}
|
||||
render={renderChild}
|
||||
rootStore={rootStore}
|
||||
resolveDefinitions={this.resolveDefinitions}
|
||||
location={location}
|
||||
data={data}
|
||||
context={context}
|
||||
env={env}
|
||||
classnames={theme.classnames}
|
||||
classPrefix={theme.classPrefix}
|
||||
locale={locale}
|
||||
translate={translate}
|
||||
/>
|
||||
)
|
||||
} as RootWrapperProps
|
||||
).children
|
||||
}
|
||||
</LocaleContext.Provider>
|
||||
</ThemeContext.Provider>
|
||||
</RootStoreContext.Provider>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export interface renderChildProps
|
||||
extends Partial<Omit<RendererProps, 'statusStore'>>,
|
||||
StatusScopedProps {
|
||||
env: RendererEnv;
|
||||
}
|
||||
export type ReactElement = React.ReactNode[] | JSX.Element | null | false;
|
||||
|
||||
export function renderChildren(
|
||||
prefix: string,
|
||||
node: SchemaNode,
|
||||
props: renderChildProps
|
||||
): ReactElement {
|
||||
if (Array.isArray(node)) {
|
||||
var elemKey = props.key || props.propKey || props.id || '';
|
||||
|
||||
return node.map((node, index) =>
|
||||
renderChild(`${prefix}/${index}`, node, {
|
||||
...props,
|
||||
key: `${elemKey ? `${elemKey}-` : ''}${index}`
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
return renderChild(prefix, node, props);
|
||||
}
|
||||
|
||||
export function renderChild(
|
||||
prefix: string,
|
||||
node: SchemaNode,
|
||||
props: renderChildProps
|
||||
): ReactElement {
|
||||
if (Array.isArray(node)) {
|
||||
return renderChildren(prefix, node, props);
|
||||
}
|
||||
|
||||
const typeofnode = typeof node;
|
||||
|
||||
if (typeofnode === 'undefined' || node === null) {
|
||||
return null;
|
||||
} else if (React.isValidElement(node)) {
|
||||
return node;
|
||||
}
|
||||
|
||||
let schema: Schema =
|
||||
typeofnode === 'string' || typeofnode === 'number'
|
||||
? {type: 'tpl', tpl: String(node)}
|
||||
: (node as Schema);
|
||||
|
||||
const transform = props.propsTransform;
|
||||
|
||||
if (transform) {
|
||||
props = {...props};
|
||||
delete props.propsTransform;
|
||||
|
||||
props = transform(props);
|
||||
}
|
||||
|
||||
const Comp = props.env.SchemaRenderer || SchemaRenderer;
|
||||
|
||||
if (
|
||||
['dialog', 'drawer'].includes(schema?.type) &&
|
||||
!schema?.component &&
|
||||
!schema?.children
|
||||
) {
|
||||
// 因为状态判断实在 SchemaRenderer 里面判断的
|
||||
// 找渲染器也是在那,所以没办法在之前根据渲染器信息来包裹个组件下发 statusStore
|
||||
// 所以这里先根据 type 来处理一下
|
||||
// 等后续把状态处理再抽一层,可以把此处放到 SchemaRenderer 里面去
|
||||
return (
|
||||
<StatusScopedWrapper>
|
||||
{({statusStore}) => (
|
||||
<Comp
|
||||
render={renderChild as any}
|
||||
{...props}
|
||||
key={props.key ?? schema.key}
|
||||
schema={schema}
|
||||
propKey={schema.key}
|
||||
$path={`${prefix ? `${prefix}/` : ''}${
|
||||
(schema && schema.type) || ''
|
||||
}`}
|
||||
statusStore={statusStore}
|
||||
/>
|
||||
)}
|
||||
</StatusScopedWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Comp
|
||||
render={renderChild as any}
|
||||
{...props}
|
||||
key={props.key ?? schema.key}
|
||||
schema={schema}
|
||||
propKey={schema.key}
|
||||
$path={`${prefix ? `${prefix}/` : ''}${(schema && schema.type) || ''}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default StatusScoped(Scoped(Root));
|
||||
585
packages/amis-core/src/RootRenderer.tsx
Normal file
585
packages/amis-core/src/RootRenderer.tsx
Normal file
@@ -0,0 +1,585 @@
|
||||
import {observer} from 'mobx-react';
|
||||
import React from 'react';
|
||||
import type {RootProps} from './Root';
|
||||
import {IScopedContext, ScopedContext, filterTarget} from './Scoped';
|
||||
import {IRootStore, RootStore} from './store/root';
|
||||
import {ActionObject} from './types';
|
||||
import {bulkBindFunctions, guid, isVisible, JSONTraverse} from './utils/helper';
|
||||
import {filter} from './utils/tpl';
|
||||
import qs from 'qs';
|
||||
import pick from 'lodash/pick';
|
||||
import mapValues from 'lodash/mapValues';
|
||||
import {saveAs} from 'file-saver';
|
||||
import {normalizeApi} from './utils/api';
|
||||
import {findDOMNode} from 'react-dom';
|
||||
import LazyComponent from './components/LazyComponent';
|
||||
import {hasAsyncRenderers, loadAsyncRenderersByType} from './factory';
|
||||
import {dispatchEvent} from './utils/renderer-event';
|
||||
|
||||
export interface RootRendererProps extends RootProps {
|
||||
location?: any;
|
||||
data?: Record<string, any>;
|
||||
context?: Record<string, any>;
|
||||
render: (region: string, schema: any, props: any) => React.ReactNode;
|
||||
}
|
||||
|
||||
@observer
|
||||
export class RootRenderer extends React.Component<RootRendererProps> {
|
||||
store: IRootStore;
|
||||
static contextType = ScopedContext;
|
||||
|
||||
constructor(props: RootRendererProps) {
|
||||
super(props);
|
||||
this.store = props.rootStore.addStore({
|
||||
id: guid(),
|
||||
path: this.props.$path,
|
||||
storeType: RootStore.name,
|
||||
parentId: ''
|
||||
}) as IRootStore;
|
||||
this.store.updateContext(props.context, true);
|
||||
this.store.initData(props.data);
|
||||
this.store.updateLocation(props.location, this.props.env?.parseLocation);
|
||||
|
||||
// 将数据里面的函数批量的绑定到 this 上
|
||||
bulkBindFunctions<RootRenderer /*为毛 this 的类型自动识别不出来?*/>(this, [
|
||||
'handleAction',
|
||||
'dispatchEvent',
|
||||
'handleDialogConfirm',
|
||||
'handleDialogClose',
|
||||
'handleDrawerConfirm',
|
||||
'handleDrawerClose',
|
||||
'handlePageVisibilityChange'
|
||||
]);
|
||||
|
||||
this.store.init(() => {
|
||||
if (!hasAsyncRenderers()) {
|
||||
return;
|
||||
}
|
||||
const schema = props.schema;
|
||||
const types: Array<string> = [
|
||||
'tpl',
|
||||
'dialog',
|
||||
'drawer',
|
||||
'cell',
|
||||
'spinner',
|
||||
'group',
|
||||
'container',
|
||||
'dropdown-button',
|
||||
'plain'
|
||||
];
|
||||
JSONTraverse(schema, (value: any, key: string) => {
|
||||
if (key === 'type') {
|
||||
types.push(value);
|
||||
|
||||
// form 依赖 panel
|
||||
if (value === 'form') {
|
||||
types.push('panel');
|
||||
}
|
||||
}
|
||||
});
|
||||
return hasAsyncRenderers(types)
|
||||
? loadAsyncRenderersByType(types, true)
|
||||
: undefined;
|
||||
});
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
// 不要设置太早,否则组件内部的监控可能会监控不到,因为初始值可能在监控之前就设置了。
|
||||
// 以至于监控不到变化。
|
||||
this.store.setGlobalVars(this.props.globalVars);
|
||||
document.addEventListener(
|
||||
'visibilitychange',
|
||||
this.handlePageVisibilityChange
|
||||
);
|
||||
|
||||
// 兼容 affixOffsetTop 和 affixOffsetBottom
|
||||
if (
|
||||
typeof this.props.env.affixOffsetTop !== 'undefined' ||
|
||||
typeof this.props.env.affixOffsetBottom !== 'undefined'
|
||||
) {
|
||||
// top: var(--affix-offset-top);
|
||||
const dom = findDOMNode(this);
|
||||
if (dom?.parentElement) {
|
||||
dom.parentElement.style.cssText += `--affix-offset-top: ${
|
||||
this.props.env.affixOffsetTop || 0
|
||||
}px; --affix-offset-bottom: ${
|
||||
this.props.env.affixOffsetBottom || 0
|
||||
}px;`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: RootRendererProps) {
|
||||
const props = this.props;
|
||||
|
||||
// 更新全局变量
|
||||
if (props.globalVars !== prevProps.globalVars) {
|
||||
this.store.setGlobalVars(props.globalVars);
|
||||
}
|
||||
|
||||
if (props.location !== prevProps.location) {
|
||||
this.store.updateLocation(props.location, this.props.env?.parseLocation);
|
||||
}
|
||||
|
||||
let contextChanged = false;
|
||||
if (props.context !== prevProps.context) {
|
||||
contextChanged = true;
|
||||
this.store.updateContext(props.context);
|
||||
}
|
||||
|
||||
// 一定要最后处理,否则 downStream 里面的上层数据 context 还是老的。
|
||||
if (props.data !== prevProps.data || contextChanged) {
|
||||
// context 依赖 data 变化才能触发变动,所以不管 data 变没变都更新一下
|
||||
this.store.initData(props.data);
|
||||
}
|
||||
}
|
||||
|
||||
componentDidCatch(error: any, errorInfo: any) {
|
||||
this.props.env?.errorCatcher?.(error, errorInfo);
|
||||
this.store.setRuntimeError(error, errorInfo);
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.props.rootStore.removeStore(this.store);
|
||||
document.removeEventListener(
|
||||
'visibilitychange',
|
||||
this.handlePageVisibilityChange
|
||||
);
|
||||
}
|
||||
|
||||
handlePageVisibilityChange() {
|
||||
const env = this.props.env;
|
||||
if (document.visibilityState === 'hidden') {
|
||||
env?.tracker({
|
||||
eventType: 'pageHidden'
|
||||
});
|
||||
} else if (document.visibilityState === 'visible') {
|
||||
env?.tracker({
|
||||
eventType: 'pageVisible'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
handleAction(
|
||||
e: React.UIEvent<any> | void,
|
||||
action: ActionObject,
|
||||
ctx: object,
|
||||
throwErrors: boolean = false,
|
||||
delegate?: IScopedContext
|
||||
): any {
|
||||
const {env, messages, onAction, mobileUI, render} = this.props;
|
||||
const store = this.store;
|
||||
|
||||
if (
|
||||
onAction?.(e, action, ctx, throwErrors, delegate || this.context) ===
|
||||
false
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const scoped = delegate || (this.context as IScopedContext);
|
||||
if (action.actionType === 'reload') {
|
||||
action.target && scoped.reload(action.target, ctx);
|
||||
} else if (action.target) {
|
||||
action.target.split(',').forEach(name => {
|
||||
let target = scoped.getComponentByName(name);
|
||||
target &&
|
||||
target.doAction &&
|
||||
target.doAction(
|
||||
{
|
||||
...action,
|
||||
target: undefined
|
||||
},
|
||||
ctx
|
||||
);
|
||||
});
|
||||
} else if (
|
||||
action.actionType === 'url' ||
|
||||
action.actionType === 'link' ||
|
||||
action.actionType === 'jump'
|
||||
) {
|
||||
if (!env || !env.jumpTo) {
|
||||
throw new Error('env.jumpTo is required!');
|
||||
}
|
||||
|
||||
env.jumpTo(
|
||||
filter(
|
||||
(action.to || action.url || action.link) as string,
|
||||
ctx,
|
||||
'| raw'
|
||||
),
|
||||
action,
|
||||
ctx
|
||||
);
|
||||
} else if (action.actionType === 'email') {
|
||||
const mailTo = filter(action.to, ctx);
|
||||
const mailInfo = mapValues(
|
||||
pick(action, 'to', 'cc', 'bcc', 'subject', 'body'),
|
||||
val => filter(val, ctx)
|
||||
);
|
||||
const mailStr = qs.stringify(mailInfo);
|
||||
const mailto = `mailto:${mailTo}?${mailStr}`;
|
||||
|
||||
window.open(mailto);
|
||||
} else if (action.actionType === 'dialog') {
|
||||
store.setCurrentAction(action, this.props.resolveDefinitions);
|
||||
return new Promise<any>(resolve => {
|
||||
store.openDialog(
|
||||
ctx,
|
||||
undefined,
|
||||
(confirmed: any, value: any) => {
|
||||
action.callback?.(confirmed, value);
|
||||
resolve({
|
||||
confirmed,
|
||||
value
|
||||
});
|
||||
},
|
||||
delegate || (this.context as any)
|
||||
);
|
||||
});
|
||||
} else if (action.actionType === 'drawer') {
|
||||
store.setCurrentAction(action, this.props.resolveDefinitions);
|
||||
return new Promise<any>(resolve => {
|
||||
store.openDrawer(
|
||||
ctx,
|
||||
undefined,
|
||||
(confirmed: any, value: any) => {
|
||||
action.callback?.(confirmed, value);
|
||||
resolve({
|
||||
confirmed,
|
||||
value
|
||||
});
|
||||
},
|
||||
delegate
|
||||
);
|
||||
});
|
||||
} else if (action.actionType === 'toast') {
|
||||
action.toast?.items?.forEach(({level, body, title, ...item}: any) => {
|
||||
env.notify(
|
||||
level || 'info',
|
||||
body
|
||||
? render('body', body, {
|
||||
...this.props,
|
||||
data: ctx,
|
||||
context: store.context
|
||||
})
|
||||
: '',
|
||||
{
|
||||
...action.toast,
|
||||
...item,
|
||||
title: title
|
||||
? render('title', title, {
|
||||
...this.props,
|
||||
data: ctx,
|
||||
context: store.context
|
||||
})
|
||||
: null,
|
||||
mobileUI: mobileUI
|
||||
}
|
||||
);
|
||||
});
|
||||
} else if (action.actionType === 'ajax') {
|
||||
store.setCurrentAction(action, this.props.resolveDefinitions);
|
||||
store
|
||||
.saveRemote(action.api as string, ctx, {
|
||||
successMessage:
|
||||
(action.messages && action.messages.success) ||
|
||||
(messages && messages.saveSuccess),
|
||||
errorMessage:
|
||||
(action.messages && action.messages.failed) ||
|
||||
(messages && messages.saveSuccess)
|
||||
})
|
||||
.then(async () => {
|
||||
if (action.feedback && isVisible(action.feedback, store.data)) {
|
||||
await this.openFeedback(action.feedback, store.data);
|
||||
}
|
||||
|
||||
const redirect =
|
||||
action.redirect && filter(action.redirect, store.data);
|
||||
redirect && env.jumpTo(redirect, action, store.data);
|
||||
action.reload &&
|
||||
this.reloadTarget(
|
||||
delegate || (this.context as IScopedContext),
|
||||
filterTarget(action.reload, ctx),
|
||||
store.data
|
||||
);
|
||||
})
|
||||
.catch(e => {
|
||||
if (throwErrors || action.countDown) {
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
} else if (
|
||||
action.actionType === 'copy' &&
|
||||
(action.content || action.copy)
|
||||
) {
|
||||
env.copy &&
|
||||
env.copy(filter(action.content || action.copy, ctx, '| raw'), {
|
||||
format: action.copyFormat
|
||||
});
|
||||
} else if (action.actionType === 'saveAs') {
|
||||
// 使用 saveAs 实现下载
|
||||
// 不支持 env,除非以后将 saveAs 代码拷过来改
|
||||
const api = normalizeApi((action as any).api);
|
||||
if (typeof api.url === 'string') {
|
||||
let fileName = action.fileName || 'data.txt';
|
||||
if (!action.fileName && api.url.indexOf('.') !== -1) {
|
||||
fileName = api.url.split('/').pop();
|
||||
}
|
||||
saveAs(api.url, fileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dispatchEvent(
|
||||
e: string | React.MouseEvent<any>,
|
||||
data: any,
|
||||
renderer?: React.Component<any>,
|
||||
scoped?: IScopedContext
|
||||
) {
|
||||
return dispatchEvent(e, renderer!, scoped!, data);
|
||||
}
|
||||
|
||||
handleDialogConfirm(
|
||||
values: object[],
|
||||
action: ActionObject,
|
||||
...args: Array<any>
|
||||
) {
|
||||
const store = this.store;
|
||||
|
||||
if (action.mergeData && values.length === 1 && values[0]) {
|
||||
store.updateData(values[0]);
|
||||
}
|
||||
|
||||
const dialog = store.action.dialog as any;
|
||||
if (
|
||||
dialog &&
|
||||
dialog.onConfirm &&
|
||||
dialog.onConfirm(values, action, ...args) === false
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const dialogAction = store.action as ActionObject;
|
||||
const reload = action.reload ?? dialogAction.reload;
|
||||
const scoped = store.getDialogScoped() || (this.context as IScopedContext);
|
||||
|
||||
store.closeDialog(true, values);
|
||||
|
||||
if (reload) {
|
||||
scoped.reload(reload, store.data);
|
||||
}
|
||||
}
|
||||
|
||||
handleDialogClose(confirmed = false) {
|
||||
const store = this.store;
|
||||
store.closeDialog(confirmed);
|
||||
}
|
||||
|
||||
handleDrawerConfirm(
|
||||
values: object[],
|
||||
action: ActionObject,
|
||||
...args: Array<any>
|
||||
) {
|
||||
const store = this.store;
|
||||
|
||||
if (action.mergeData && values.length === 1 && values[0]) {
|
||||
store.updateData(values[0]);
|
||||
}
|
||||
|
||||
const drawer = store.action.drawer as any;
|
||||
if (
|
||||
drawer &&
|
||||
drawer.onConfirm &&
|
||||
drawer.onConfirm(values, action, ...args) === false
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const drawerAction = store.action as ActionObject;
|
||||
const reload = action.reload ?? drawerAction.reload;
|
||||
const scoped = store.getDrawerScoped() || (this.context as IScopedContext);
|
||||
|
||||
store.closeDrawer(true, values);
|
||||
|
||||
// 稍等会,等动画结束。
|
||||
setTimeout(() => {
|
||||
if (reload) {
|
||||
scoped.reload(reload, store.data);
|
||||
}
|
||||
}, 300);
|
||||
}
|
||||
|
||||
handleDrawerClose() {
|
||||
const store = this.store;
|
||||
store.closeDrawer(false);
|
||||
}
|
||||
|
||||
openFeedback(dialog: any, ctx: any) {
|
||||
return new Promise(resolve => {
|
||||
const store = this.store;
|
||||
store.setCurrentAction(
|
||||
{
|
||||
type: 'button',
|
||||
actionType: 'dialog',
|
||||
dialog: dialog
|
||||
},
|
||||
this.props.resolveDefinitions
|
||||
);
|
||||
store.openDialog(
|
||||
ctx,
|
||||
undefined,
|
||||
confirmed => {
|
||||
resolve(confirmed);
|
||||
},
|
||||
this.context as any
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
reloadTarget(scoped: IScopedContext, target: string, data?: any) {
|
||||
scoped.reload(target, data);
|
||||
}
|
||||
|
||||
renderRuntimeError() {
|
||||
const {render, ...rest} = this.props;
|
||||
const {store} = this;
|
||||
return render(
|
||||
'error',
|
||||
{
|
||||
type: 'alert',
|
||||
level: 'danger'
|
||||
},
|
||||
{
|
||||
...rest,
|
||||
topStore: store,
|
||||
body: (
|
||||
<>
|
||||
<h3>{store.runtimeError?.toString()}</h3>
|
||||
<pre>
|
||||
<code>{store.runtimeErrorStack.componentStack}</code>
|
||||
</pre>
|
||||
</>
|
||||
)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
renderSpinner() {
|
||||
const {render, ...rest} = this.props;
|
||||
const {store} = this;
|
||||
return render(
|
||||
'spinner',
|
||||
{
|
||||
type: 'spinner'
|
||||
},
|
||||
{
|
||||
...rest,
|
||||
topStore: store,
|
||||
show: store.loading
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
renderError() {
|
||||
const {render, ...rest} = this.props;
|
||||
const store = this.store;
|
||||
return store.error
|
||||
? render(
|
||||
'error',
|
||||
{
|
||||
type: 'alert'
|
||||
},
|
||||
{
|
||||
...rest,
|
||||
topStore: this.store,
|
||||
body: store.msg,
|
||||
showCloseButton: true,
|
||||
onClose: store.clearMessage
|
||||
}
|
||||
)
|
||||
: null;
|
||||
}
|
||||
|
||||
renderDialog() {
|
||||
const {render, ...rest} = this.props;
|
||||
const store = this.store;
|
||||
return render(
|
||||
'dialog',
|
||||
{
|
||||
...store.dialogSchema,
|
||||
type: 'dialog'
|
||||
},
|
||||
{
|
||||
...rest,
|
||||
key: 'dialog',
|
||||
topStore: this.store,
|
||||
data: store.dialogData,
|
||||
context: store.context,
|
||||
onConfirm: this.handleDialogConfirm,
|
||||
onClose: this.handleDialogClose,
|
||||
show: store.dialogOpen,
|
||||
onAction: this.handleAction,
|
||||
dispatchEvent: this.dispatchEvent
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
renderDrawer() {
|
||||
const {render, ...rest} = this.props;
|
||||
const store = this.store;
|
||||
return render(
|
||||
'drawer',
|
||||
{
|
||||
...store.drawerSchema,
|
||||
type: 'drawer'
|
||||
},
|
||||
{
|
||||
...rest,
|
||||
key: 'drawer',
|
||||
topStore: this.store,
|
||||
data: store.drawerData,
|
||||
context: store.context,
|
||||
onConfirm: this.handleDrawerConfirm,
|
||||
onClose: this.handleDrawerClose,
|
||||
show: store.drawerOpen,
|
||||
onAction: this.handleAction,
|
||||
dispatchEvent: this.dispatchEvent
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const {pathPrefix, schema, render, globalVars, ...rest} = this.props;
|
||||
const store = this.store;
|
||||
|
||||
if (store.runtimeError) {
|
||||
return this.renderRuntimeError();
|
||||
} else if (!store.ready) {
|
||||
return <LazyComponent className="RootLoader" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{
|
||||
render(pathPrefix!, schema, {
|
||||
...rest,
|
||||
topStore: this.store,
|
||||
data: this.store.downStream,
|
||||
context: store.context,
|
||||
onAction: this.handleAction,
|
||||
dispatchEvent: this.dispatchEvent
|
||||
}) as JSX.Element
|
||||
}
|
||||
|
||||
{this.renderSpinner()}
|
||||
|
||||
{this.renderError()}
|
||||
|
||||
{this.renderDialog()}
|
||||
|
||||
{this.renderDrawer()}
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
685
packages/amis-core/src/SchemaRenderer.tsx
Normal file
685
packages/amis-core/src/SchemaRenderer.tsx
Normal file
@@ -0,0 +1,685 @@
|
||||
import difference from 'lodash/difference';
|
||||
import findLastIndex from 'lodash/findLastIndex';
|
||||
import omit from 'lodash/omit';
|
||||
import React from 'react';
|
||||
import {isValidElementType} from 'react-is';
|
||||
import LazyComponent from './components/LazyComponent';
|
||||
import {
|
||||
filterSchema,
|
||||
loadRendererError,
|
||||
loadAsyncRenderer,
|
||||
registerRenderer,
|
||||
RendererConfig,
|
||||
RendererEnv,
|
||||
RendererProps,
|
||||
resolveRenderer
|
||||
} from './factory';
|
||||
import {asFormItem} from './renderers/Item';
|
||||
import {IScopedContext, ScopedContext} from './Scoped';
|
||||
import {Schema, SchemaNode} from './types';
|
||||
import {DebugWrapper} from './utils/debug';
|
||||
import getExprProperties from './utils/filter-schema';
|
||||
import {
|
||||
anyChanged,
|
||||
chainEvents,
|
||||
autobind,
|
||||
TestIdBuilder,
|
||||
formateId
|
||||
} from './utils/helper';
|
||||
import {SimpleMap} from './utils/SimpleMap';
|
||||
import {
|
||||
bindEvent,
|
||||
bindGlobalEventForRenderer as bindGlobalEvent,
|
||||
dispatchEvent,
|
||||
RendererEvent
|
||||
} from './utils/renderer-event';
|
||||
import {isAlive} from 'mobx-state-tree';
|
||||
import {reaction} from 'mobx';
|
||||
import {resolveVariableAndFilter} from './utils/tpl-builtin';
|
||||
import {buildStyle, mergeStyle} from './utils/style';
|
||||
import {isExpression} from './utils/formula';
|
||||
import {StatusScopedProps} from './StatusScoped';
|
||||
import {evalExpression, filter} from './utils/tpl';
|
||||
import Animations from './components/Animations';
|
||||
import {cloneObject} from './utils/object';
|
||||
import {observeGlobalVars} from './globalVar';
|
||||
import type {IRootStore} from './store/root';
|
||||
import {createObjectFromChain, extractObjectChain} from './utils';
|
||||
import {IIRendererStore} from './store/index';
|
||||
|
||||
interface SchemaRendererProps
|
||||
extends Partial<Omit<RendererProps, 'statusStore'>>,
|
||||
StatusScopedProps {
|
||||
schema: Schema;
|
||||
$path: string;
|
||||
env: RendererEnv;
|
||||
}
|
||||
|
||||
export const RENDERER_TRANSMISSION_OMIT_PROPS = [
|
||||
'type',
|
||||
'name',
|
||||
'$ref',
|
||||
'className',
|
||||
'style',
|
||||
'data',
|
||||
'originData',
|
||||
'children',
|
||||
'ref',
|
||||
'visible',
|
||||
'loading',
|
||||
'visibleOn',
|
||||
'hidden',
|
||||
'hiddenOn',
|
||||
'disabled',
|
||||
'disabledOn',
|
||||
'static',
|
||||
'staticOn',
|
||||
'component',
|
||||
'detectField',
|
||||
'defaultValue',
|
||||
'defaultData',
|
||||
'required',
|
||||
'requiredOn',
|
||||
'syncSuperStore',
|
||||
'mode',
|
||||
'body',
|
||||
'id',
|
||||
'inputOnly',
|
||||
'label',
|
||||
'renderLabel',
|
||||
'trackExpression',
|
||||
'editorSetting',
|
||||
'updatePristineAfterStoreDataReInit',
|
||||
'source'
|
||||
];
|
||||
|
||||
const componentCache: SimpleMap = new SimpleMap();
|
||||
|
||||
export class SchemaRenderer extends React.Component<SchemaRendererProps, any> {
|
||||
static displayName: string = 'Renderer';
|
||||
static contextType = ScopedContext;
|
||||
|
||||
rendererKey = '';
|
||||
renderer: RendererConfig | null;
|
||||
ref: any;
|
||||
cRef: any;
|
||||
|
||||
schema: any;
|
||||
path: string;
|
||||
|
||||
tmpData: any;
|
||||
|
||||
toDispose: Array<() => any> = [];
|
||||
unbindEvent: (() => void) | undefined = undefined;
|
||||
unbindGlobalEvent: (() => void) | undefined = undefined;
|
||||
isStatic: any = undefined;
|
||||
|
||||
subStore?: IIRendererStore | null;
|
||||
|
||||
constructor(props: SchemaRendererProps) {
|
||||
super(props);
|
||||
|
||||
this.refFn = this.refFn.bind(this);
|
||||
this.renderChild = this.renderChild.bind(this);
|
||||
this.reRender = this.reRender.bind(this);
|
||||
this.resolveRenderer(this.props);
|
||||
this.dispatchEvent = this.dispatchEvent.bind(this);
|
||||
this.storeRef = this.storeRef.bind(this);
|
||||
this.handleGlobalVarChange = this.handleGlobalVarChange.bind(this);
|
||||
|
||||
const schema = props.schema;
|
||||
|
||||
// 监听statusStore更新
|
||||
this.toDispose.push(
|
||||
reaction(
|
||||
() => {
|
||||
const id = filter(schema.id, props.data);
|
||||
const name = filter(schema.name, props.data);
|
||||
return `${
|
||||
props.statusStore.visibleState[id] ??
|
||||
props.statusStore.visibleState[name]
|
||||
}${
|
||||
props.statusStore.disableState[id] ??
|
||||
props.statusStore.disableState[name]
|
||||
}${
|
||||
props.statusStore.staticState[id] ??
|
||||
props.statusStore.staticState[name]
|
||||
}`;
|
||||
},
|
||||
() => this.forceUpdate()
|
||||
)
|
||||
);
|
||||
|
||||
this.toDispose.push(
|
||||
observeGlobalVars(schema, props.topStore, this.handleGlobalVarChange)
|
||||
);
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.toDispose.forEach(fn => fn());
|
||||
this.toDispose = [];
|
||||
this.unbindEvent?.();
|
||||
this.unbindGlobalEvent?.();
|
||||
}
|
||||
|
||||
// 限制:只有 schema 除外的 props 变化,或者 schema 里面的某个成员值发生变化才更新。
|
||||
shouldComponentUpdate(nextProps: SchemaRendererProps) {
|
||||
const props = this.props;
|
||||
const list: Array<string> = difference(Object.keys(nextProps), [
|
||||
'schema',
|
||||
'scope'
|
||||
]);
|
||||
|
||||
if (
|
||||
difference(Object.keys(props), ['schema', 'scope']).length !==
|
||||
list.length ||
|
||||
anyChanged(list, this.props, nextProps)
|
||||
) {
|
||||
return true;
|
||||
} else {
|
||||
const list: Array<string> = Object.keys(nextProps.schema);
|
||||
|
||||
if (
|
||||
Object.keys(props.schema).length !== list.length ||
|
||||
anyChanged(list, props.schema, nextProps.schema)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
storeRef(store: IIRendererStore | null) {
|
||||
this.subStore = store;
|
||||
}
|
||||
|
||||
handleGlobalVarChange() {
|
||||
const handler = this.renderer?.onGlobalVarChanged;
|
||||
const topStore: IRootStore = this.props.topStore;
|
||||
const chain = extractObjectChain(this.props.data).filter(
|
||||
(item: any) => !item.hasOwnProperty('__isTempGlobalLayer')
|
||||
);
|
||||
const globalLayerIdx = findLastIndex(
|
||||
chain,
|
||||
item =>
|
||||
item.hasOwnProperty('global') || item.hasOwnProperty('globalState')
|
||||
);
|
||||
|
||||
const globalData = {
|
||||
global: topStore.nextGlobalData.global,
|
||||
globalState: topStore.nextGlobalData.globalState,
|
||||
// 兼容旧的全局变量
|
||||
__page: topStore.nextGlobalData.__page,
|
||||
appVariables: topStore.nextGlobalData.appVariables,
|
||||
__isTempGlobalLayer: true
|
||||
};
|
||||
|
||||
if (globalLayerIdx !== -1) {
|
||||
chain.splice(globalLayerIdx + 1, 0, globalData);
|
||||
}
|
||||
const newData = createObjectFromChain(chain);
|
||||
|
||||
// 如果渲染器自己做了实现,且返回 false,则不再继续往下执行
|
||||
if (handler?.(this.cRef, this.props.schema, newData) === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 强制刷新并通过一个临时对象让下发给组件的全局变量更新
|
||||
// 等 react 完成一轮渲染后,将临时渲染切成正式渲染
|
||||
// 也就是说删掉临时对象,后续渲染读取真正变更后的全局变量
|
||||
//
|
||||
|
||||
// 为什么这么做?因为很多组件内部都会 diff this.props.data 和 prevProps.data
|
||||
// 如果对应的数据没有发生变化,则会跳过组件状态的更新
|
||||
this.tmpData = newData;
|
||||
this.subStore?.temporaryUpdateGlobalVars(globalData);
|
||||
topStore.addSyncGlobalVarStatePendingTask(
|
||||
callback => this.forceUpdate(callback),
|
||||
() => {
|
||||
delete this.tmpData;
|
||||
this.subStore?.unDoTemporaryUpdateGlobalVars();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
resolveRenderer(props: SchemaRendererProps, force = false): any {
|
||||
let schema = props.schema;
|
||||
let path = props.$path;
|
||||
|
||||
if (schema && schema.$ref) {
|
||||
schema = {
|
||||
...props.resolveDefinitions(schema.$ref),
|
||||
...schema
|
||||
};
|
||||
|
||||
path = path.replace(/(?!.*\/).*/, schema.type);
|
||||
}
|
||||
|
||||
if (
|
||||
schema?.type &&
|
||||
(force ||
|
||||
!this.renderer ||
|
||||
this.rendererKey !== `${schema.type}-${schema.$$id}`)
|
||||
) {
|
||||
const rendererResolver = props.env.rendererResolver || resolveRenderer;
|
||||
this.renderer = rendererResolver(path, schema, props);
|
||||
this.rendererKey = `${schema.type}-${schema.$$id}`;
|
||||
} else {
|
||||
// 自定义组件如果在节点设置了 label name 什么的,就用 formItem 包一层
|
||||
// 至少自动支持了 valdiations, label, description 等逻辑。
|
||||
if (schema.children && !schema.component && schema.asFormItem) {
|
||||
schema.component = PlaceholderComponent;
|
||||
schema.renderChildren = schema.children;
|
||||
delete schema.children;
|
||||
}
|
||||
|
||||
if (
|
||||
schema.component &&
|
||||
!schema.component.wrapedAsFormItem &&
|
||||
schema.asFormItem
|
||||
) {
|
||||
const cache = componentCache.get(schema.component);
|
||||
|
||||
if (cache) {
|
||||
schema.component = cache;
|
||||
} else {
|
||||
const cache = asFormItem({
|
||||
strictMode: false,
|
||||
...schema.asFormItem
|
||||
})(schema.component);
|
||||
componentCache.set(schema.component, cache);
|
||||
cache.wrapedAsFormItem = true;
|
||||
schema.component = cache;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {path, schema};
|
||||
}
|
||||
|
||||
getWrappedInstance() {
|
||||
return this.cRef;
|
||||
}
|
||||
|
||||
refFn(ref: any) {
|
||||
this.ref = ref;
|
||||
}
|
||||
|
||||
@autobind
|
||||
childRef(ref: any) {
|
||||
// todo 这里有个问题,就是注意以下的这段注释
|
||||
// > // 原来表单项的 visible: false 和 hidden: true 表单项的值和验证是有效的
|
||||
// > 而 visibleOn 和 hiddenOn 是无效的,
|
||||
// > 这个本来就是个bug,但是已经被广泛使用了
|
||||
// > 我只能继续实现这个bug了
|
||||
// 这样会让子组件去根据是 hidden 的情况去渲染个 null,这样会导致这里 ref 有值,但是 ref.getWrappedInstance() 为 null
|
||||
// 这样会和直接渲染的组件时有些区别,至少 cRef 的指向是不一样的
|
||||
while (ref?.getWrappedInstance?.()) {
|
||||
ref = ref.getWrappedInstance();
|
||||
}
|
||||
|
||||
if (ref && !ref.props) {
|
||||
Object.defineProperty(ref, 'props', {
|
||||
get: () => this.props
|
||||
});
|
||||
}
|
||||
|
||||
if (ref) {
|
||||
// 这里无法区分监听的是不是广播,所以又bind一下,主要是为了绑广播
|
||||
this.unbindEvent?.();
|
||||
this.unbindGlobalEvent?.();
|
||||
|
||||
this.unbindEvent = bindEvent(ref);
|
||||
this.unbindGlobalEvent = bindGlobalEvent(ref);
|
||||
}
|
||||
this.cRef = ref;
|
||||
}
|
||||
|
||||
dispatchEvent(
|
||||
e: React.MouseEvent<any>,
|
||||
data: any,
|
||||
renderer?: React.Component<RendererProps>, // for didmount
|
||||
scoped?: IScopedContext
|
||||
): Promise<RendererEvent<any> | void> {
|
||||
return this.props.dispatchEvent(
|
||||
e,
|
||||
data,
|
||||
renderer || this.cRef,
|
||||
scoped || (this.context as IScopedContext)
|
||||
);
|
||||
}
|
||||
|
||||
renderChild(
|
||||
region: string,
|
||||
node?: SchemaNode,
|
||||
subProps: {
|
||||
data?: object;
|
||||
[propName: string]: any;
|
||||
} = {}
|
||||
) {
|
||||
let {schema: _, $path: __, env, render, ...rest} = this.props;
|
||||
let {path: $path} = this.resolveRenderer(this.props);
|
||||
|
||||
const omitList = RENDERER_TRANSMISSION_OMIT_PROPS.concat();
|
||||
if (this.renderer) {
|
||||
const Component = this.renderer.component;
|
||||
Component?.propsList &&
|
||||
omitList.push.apply(omitList, Component.propsList as Array<string>);
|
||||
}
|
||||
|
||||
return render!(`${$path}${region ? `/${region}` : ''}`, node || '', {
|
||||
...omit(rest, omitList),
|
||||
defaultStatic:
|
||||
(this.renderer?.type &&
|
||||
['drawer', 'dialog'].includes(this.renderer.type)
|
||||
? false
|
||||
: undefined) ??
|
||||
this.isStatic ??
|
||||
(_.staticOn
|
||||
? evalExpression(_.staticOn, rest.data)
|
||||
: _.static ?? rest.defaultStatic),
|
||||
...subProps,
|
||||
data:
|
||||
this.tmpData && subProps.data === this.props.data
|
||||
? this.tmpData
|
||||
: subProps.data || rest.data,
|
||||
env: env
|
||||
});
|
||||
}
|
||||
|
||||
reRender() {
|
||||
this.resolveRenderer(this.props, true);
|
||||
this.forceUpdate();
|
||||
}
|
||||
|
||||
render(): JSX.Element | null {
|
||||
let {
|
||||
$path: _,
|
||||
schema: __,
|
||||
rootStore,
|
||||
statusStore,
|
||||
render,
|
||||
...rest
|
||||
} = this.props;
|
||||
|
||||
if (__ == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let {path: $path, schema} = this.resolveRenderer(this.props);
|
||||
const theme = this.props.env.theme;
|
||||
|
||||
if (Array.isArray(schema)) {
|
||||
return render!($path, schema as any, rest) as JSX.Element;
|
||||
}
|
||||
|
||||
// 用于全局变量刷新
|
||||
(rest as any).data = this.tmpData || rest.data;
|
||||
|
||||
const detectData =
|
||||
schema &&
|
||||
(schema.detectField === '&' ? rest : rest[schema.detectField || 'data']);
|
||||
let exprProps: any = detectData
|
||||
? getExprProperties(schema, detectData, undefined, rest)
|
||||
: {};
|
||||
|
||||
// 控制显隐
|
||||
const id = filter(schema.id, rest.data);
|
||||
const name = filter(schema.name, rest.data);
|
||||
const visible = isAlive(statusStore)
|
||||
? statusStore.visibleState[id] ?? statusStore.visibleState[name]
|
||||
: undefined;
|
||||
const disable = isAlive(statusStore)
|
||||
? statusStore.disableState[id] ?? statusStore.disableState[name]
|
||||
: undefined;
|
||||
const isStatic = isAlive(statusStore)
|
||||
? statusStore.staticState[id] ?? statusStore.staticState[name]
|
||||
: undefined;
|
||||
this.isStatic = isStatic;
|
||||
|
||||
if (
|
||||
visible === false ||
|
||||
(visible !== true &&
|
||||
exprProps &&
|
||||
(exprProps.hidden ||
|
||||
exprProps.visible === false ||
|
||||
schema.hidden ||
|
||||
schema.visible === false ||
|
||||
rest.hidden ||
|
||||
rest.visible === false))
|
||||
) {
|
||||
(rest as any).invisible = true;
|
||||
}
|
||||
|
||||
if (schema.children) {
|
||||
return rest.invisible
|
||||
? null
|
||||
: React.isValidElement(schema.children)
|
||||
? schema.children
|
||||
: typeof schema.children !== 'function'
|
||||
? null
|
||||
: (schema.children as Function)({
|
||||
...rest,
|
||||
...exprProps,
|
||||
$path: $path,
|
||||
$schema: schema,
|
||||
render: this.renderChild,
|
||||
forwardedRef: this.refFn,
|
||||
rootStore,
|
||||
statusStore,
|
||||
dispatchEvent: this.dispatchEvent
|
||||
});
|
||||
} else if (schema.component && isValidElementType(schema.component)) {
|
||||
const isSFC = !(schema.component.prototype instanceof React.Component);
|
||||
const {
|
||||
data: defaultData,
|
||||
value: defaultValue, // render时的value改放defaultValue中
|
||||
activeKey: defaultActiveKey,
|
||||
key: propKey,
|
||||
...restSchema
|
||||
} = schema;
|
||||
return rest.invisible
|
||||
? null
|
||||
: React.createElement(schema.component as any, {
|
||||
...rest,
|
||||
...restSchema,
|
||||
...exprProps,
|
||||
// value: defaultValue, // 备注: 此处并没有将value传递给渲染器
|
||||
defaultData,
|
||||
defaultValue,
|
||||
defaultActiveKey,
|
||||
propKey,
|
||||
$path: $path,
|
||||
$schema: schema,
|
||||
ref: isSFC ? undefined : this.refFn,
|
||||
forwardedRef: isSFC ? this.refFn : undefined,
|
||||
render: this.renderChild,
|
||||
rootStore,
|
||||
statusStore,
|
||||
dispatchEvent: this.dispatchEvent
|
||||
});
|
||||
} else if (Object.keys(schema).length === 0) {
|
||||
return null;
|
||||
} else if (!this.renderer) {
|
||||
return rest.invisible ? null : (
|
||||
<LazyComponent
|
||||
defaultVisible={true}
|
||||
getComponent={async () => {
|
||||
const result = await rest.env.loadRenderer(
|
||||
schema,
|
||||
$path,
|
||||
this.reRender
|
||||
);
|
||||
if (result && typeof result === 'function') {
|
||||
return result;
|
||||
} else if (result && React.isValidElement(result)) {
|
||||
return () => result;
|
||||
}
|
||||
|
||||
this.reRender();
|
||||
return () => loadRendererError(schema, $path);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
} else if (this.renderer.getComponent && !this.renderer.component) {
|
||||
// 处理异步渲染器
|
||||
return rest.invisible ? null : (
|
||||
<LazyComponent
|
||||
defaultVisible={true}
|
||||
getComponent={async () => {
|
||||
await loadAsyncRenderer(this.renderer as RendererConfig);
|
||||
this.reRender();
|
||||
return () => null;
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const renderer = this.renderer as RendererConfig;
|
||||
schema = filterSchema(schema, renderer, rest);
|
||||
const {
|
||||
data: defaultData,
|
||||
value: defaultValue,
|
||||
activeKey: defaultActiveKey,
|
||||
key: propKey,
|
||||
...restSchema
|
||||
} = schema;
|
||||
const Component = renderer.component!;
|
||||
|
||||
let animationShow = true;
|
||||
|
||||
// 原来表单项的 visible: false 和 hidden: true 表单项的值和验证是有效的
|
||||
// 而 visibleOn 和 hiddenOn 是无效的,
|
||||
// 这个本来就是个bug,但是已经被广泛使用了
|
||||
// 我只能继续实现这个bug了
|
||||
if (
|
||||
rest.invisible &&
|
||||
(exprProps.hidden ||
|
||||
exprProps.visible === false ||
|
||||
!renderer.isFormItem ||
|
||||
(schema.visible !== false && !schema.hidden))
|
||||
) {
|
||||
if (schema.animations) {
|
||||
animationShow = false;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// withStore 里面会处理,而且会实时处理
|
||||
// 这里处理反而导致了问题
|
||||
if (renderer.storeType) {
|
||||
exprProps = {};
|
||||
}
|
||||
|
||||
const supportRef =
|
||||
Component.prototype?.isReactComponent ||
|
||||
(Component as any).$$typeof === Symbol.for('react.forward_ref');
|
||||
let props: any = {
|
||||
...renderer.defaultProps?.(schema.type, schema),
|
||||
...theme.getRendererConfig(renderer.name),
|
||||
...restSchema,
|
||||
...chainEvents(rest, restSchema),
|
||||
...exprProps,
|
||||
// value: defaultValue, // 备注: 此处并没有将value传递给渲染器
|
||||
defaultData: restSchema.defaultData ?? defaultData,
|
||||
defaultValue: restSchema.defaultValue ?? defaultValue,
|
||||
defaultActiveKey: defaultActiveKey,
|
||||
propKey: propKey,
|
||||
$path: $path,
|
||||
$schema: schema,
|
||||
render: this.renderChild,
|
||||
rootStore,
|
||||
statusStore,
|
||||
dispatchEvent: this.dispatchEvent,
|
||||
mobileUI: schema.useMobileUI === false ? false : rest.mobileUI
|
||||
};
|
||||
|
||||
// style 支持公式
|
||||
if (schema.style) {
|
||||
(props as any).style = mergeStyle(
|
||||
(props as any).style,
|
||||
buildStyle(schema.style, detectData)
|
||||
);
|
||||
}
|
||||
|
||||
if (disable !== undefined) {
|
||||
(props as any).disabled = disable;
|
||||
}
|
||||
|
||||
if (isStatic !== undefined) {
|
||||
(props as any).static = isStatic;
|
||||
}
|
||||
|
||||
// 优先使用组件自己的testid或者id,这个解决不了table行内的一些子元素
|
||||
// 每一行都会出现这个testid的元素,只在测试工具中直接使用nth拿序号
|
||||
if (rest.env.enableTestid) {
|
||||
if (props.testid || props.id || props.testIdBuilder == null) {
|
||||
if (!(props.testIdBuilder instanceof TestIdBuilder)) {
|
||||
props.testIdBuilder = new TestIdBuilder(props.testid || props.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 自动解析变量模式,主要是方便直接引入第三方组件库,无需为了支持变量封装一层
|
||||
if (renderer.autoVar) {
|
||||
for (const key of Object.keys(schema)) {
|
||||
if (typeof props[key] === 'string' && isExpression(props[key])) {
|
||||
props[key] = resolveVariableAndFilter(
|
||||
props[key],
|
||||
props.data,
|
||||
'| raw'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let component = supportRef ? (
|
||||
<Component {...props} ref={this.childRef} storeRef={this.storeRef} />
|
||||
) : (
|
||||
<Component
|
||||
{...props}
|
||||
forwardedRef={this.childRef}
|
||||
storeRef={this.storeRef}
|
||||
/>
|
||||
);
|
||||
|
||||
if (schema.animations) {
|
||||
component = (
|
||||
<Animations
|
||||
schema={schema}
|
||||
component={component}
|
||||
show={animationShow}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return this.props.env.enableAMISDebug ? (
|
||||
<DebugWrapper renderer={renderer}>{component}</DebugWrapper>
|
||||
) : (
|
||||
component
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class PlaceholderComponent extends React.Component {
|
||||
childRef = React.createRef<any>();
|
||||
|
||||
getWrappedInstance() {
|
||||
return this.childRef.current;
|
||||
}
|
||||
|
||||
render() {
|
||||
const {renderChildren, ...rest} = this.props as any;
|
||||
|
||||
if (typeof renderChildren === 'function') {
|
||||
return renderChildren({
|
||||
...rest,
|
||||
ref: this.childRef
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
585
packages/amis-core/src/Scoped.tsx
Normal file
585
packages/amis-core/src/Scoped.tsx
Normal file
@@ -0,0 +1,585 @@
|
||||
/**
|
||||
* @file 用来创建一个域,在这个域里面会把里面的运行时实例注册进来,方便组件之间的通信。
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import find from 'lodash/find';
|
||||
import values from 'lodash/values';
|
||||
import hoistNonReactStatic from 'hoist-non-react-statics';
|
||||
import {dataMapping, registerFunction} from './utils/tpl-builtin';
|
||||
import {RendererEnv, RendererProps} from './factory';
|
||||
import {
|
||||
autobind,
|
||||
qsstringify,
|
||||
qsparse,
|
||||
eachTree,
|
||||
findTree,
|
||||
TreeItem,
|
||||
parseQuery,
|
||||
getVariable
|
||||
} from './utils/helper';
|
||||
import {RendererData, ActionObject} from './types';
|
||||
import {isPureVariable} from './utils/isPureVariable';
|
||||
import {createObject, createRendererEvent, filter, memoParse} from './utils';
|
||||
import {ListenerAction, runActions} from './actions';
|
||||
|
||||
/**
|
||||
* target 里面可能包含 ?xxx=xxx,这种情况下,需要把 ?xxx=xxx 保留下来,然后对前面的部分进行 filter
|
||||
* 因为后面会对 query 部分做不一样的处理。会保留原始的值。而不是会转成字符串。
|
||||
* @param target
|
||||
* @param data
|
||||
* @returns
|
||||
*/
|
||||
export function filterTarget(target: string, data: Record<string, any>) {
|
||||
const idx = target.indexOf('?');
|
||||
|
||||
if (~idx) {
|
||||
return filter(target.slice(0, idx), data) + target.slice(idx);
|
||||
}
|
||||
|
||||
return filter(target, data, '| raw');
|
||||
}
|
||||
|
||||
/**
|
||||
* 分割目标,如果里面有表达式,不要跟表达式里面的逗号冲突。
|
||||
* @param target
|
||||
* @returns
|
||||
*/
|
||||
export function splitTarget(target: string): Array<string> {
|
||||
try {
|
||||
const ast = memoParse(target);
|
||||
const pos: Array<number> = [];
|
||||
ast.body.forEach((item: any) => {
|
||||
// 不要处理表达式里面的东西。
|
||||
if (item.type === 'raw') {
|
||||
const parts = (item.value as string).split(',');
|
||||
if (parts.length > 1) {
|
||||
parts.pop();
|
||||
let start = item.start.index;
|
||||
parts.forEach(part => {
|
||||
pos.push(start + part.length);
|
||||
start += part.length + 1;
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
if (pos.length) {
|
||||
let parts: Array<string> = [];
|
||||
|
||||
pos.reduceRight((arr: Array<string>, index) => {
|
||||
arr.unshift(target.slice(index + 1)?.trim());
|
||||
target = target.slice(0, index);
|
||||
return arr;
|
||||
}, parts);
|
||||
parts.unshift(target);
|
||||
|
||||
return parts;
|
||||
}
|
||||
} catch (e) {}
|
||||
return [target];
|
||||
}
|
||||
|
||||
export interface ScopedComponentType extends React.Component<RendererProps> {
|
||||
focus?: () => void;
|
||||
doAction?: (
|
||||
action: ActionObject,
|
||||
data: RendererData,
|
||||
throwErrors?: boolean,
|
||||
args?: any
|
||||
) => void;
|
||||
receive?: (values: RendererData, subPath?: string, replace?: boolean) => void;
|
||||
reload?: (
|
||||
subpath?: string,
|
||||
query?: any,
|
||||
ctx?: RendererData,
|
||||
silent?: boolean,
|
||||
replace?: boolean,
|
||||
args?: any
|
||||
) => void;
|
||||
context: any;
|
||||
setData?: (value?: object, replace?: boolean, index?: number) => void;
|
||||
}
|
||||
|
||||
export interface IScopedContext {
|
||||
rendererType?: string;
|
||||
component?: ScopedComponentType;
|
||||
parent?: AliasIScopedContext;
|
||||
children?: AliasIScopedContext[];
|
||||
registerComponent: (component: ScopedComponentType) => void;
|
||||
unRegisterComponent: (component: ScopedComponentType) => void;
|
||||
getComponentByName: (name: string) => ScopedComponentType;
|
||||
getComponentById: (id: string) => ScopedComponentType | undefined;
|
||||
getComponentByIdUnderCurrentScope: (
|
||||
id: string,
|
||||
ignoreScope?: IScopedContext
|
||||
) => ScopedComponentType | undefined;
|
||||
getComponents: () => Array<ScopedComponentType>;
|
||||
reload: (target: string, ctx: RendererData) => void | Promise<void>;
|
||||
send: (target: string, ctx: RendererData) => void;
|
||||
close: (target: string) => void;
|
||||
closeById: (target: string) => void;
|
||||
getComponentsByRefPath: (
|
||||
session: string,
|
||||
path: string
|
||||
) => ScopedComponentType[];
|
||||
doAction: (actions: ListenerAction | ListenerAction[], ctx: any) => void;
|
||||
}
|
||||
type AliasIScopedContext = IScopedContext;
|
||||
|
||||
const rootScopedContext = createScopedTools('');
|
||||
export const ScopedContext = React.createContext(rootScopedContext);
|
||||
|
||||
function createScopedTools(
|
||||
path?: string,
|
||||
parent?: AliasIScopedContext,
|
||||
env?: RendererEnv,
|
||||
rendererType?: string
|
||||
): IScopedContext {
|
||||
const components: Array<ScopedComponentType> = [];
|
||||
const self: IScopedContext = {
|
||||
rendererType,
|
||||
component: undefined,
|
||||
parent,
|
||||
registerComponent(component: ScopedComponentType) {
|
||||
// 不要把自己注册在自己的 Scoped 上,自己的 Scoped 是给子节点们注册的。
|
||||
if (component.props.$path === path && parent) {
|
||||
self.component = component;
|
||||
return parent.registerComponent(component);
|
||||
}
|
||||
|
||||
if (!~components.indexOf(component)) {
|
||||
components.push(component);
|
||||
}
|
||||
},
|
||||
|
||||
unRegisterComponent(component: ScopedComponentType) {
|
||||
// 自己本身实际上注册在父级 Scoped 上。
|
||||
if (component.props.$path === path && parent) {
|
||||
// 如果是自己,尝试把自己从父级 Scoped 上移除,否则在某些场景下会导致父级的 children 一直增长。
|
||||
const idx = parent.children!.indexOf(self);
|
||||
~idx && parent.children!.splice(idx, 1);
|
||||
return parent.unRegisterComponent(component);
|
||||
}
|
||||
|
||||
const idx = components.indexOf(component);
|
||||
|
||||
if (~idx) {
|
||||
components.splice(idx, 1);
|
||||
}
|
||||
},
|
||||
|
||||
getComponentByName(name: string) {
|
||||
if (~name.indexOf('.')) {
|
||||
const paths = name.split('.');
|
||||
const len = paths.length;
|
||||
|
||||
return paths.reduce((scope, name, idx) => {
|
||||
if (scope && scope.getComponentByName) {
|
||||
const result: ScopedComponentType = scope.getComponentByName(name);
|
||||
return result && idx < len - 1 ? result.context : result;
|
||||
}
|
||||
|
||||
return null;
|
||||
}, this);
|
||||
}
|
||||
|
||||
const resolved = find(
|
||||
components,
|
||||
component =>
|
||||
filter(component.props.name, component.props.data) === name ||
|
||||
component.props.id === name
|
||||
);
|
||||
return resolved || (parent && parent.getComponentByName(name));
|
||||
},
|
||||
|
||||
getComponentByIdUnderCurrentScope(
|
||||
id: string,
|
||||
ignoreScope?: IScopedContext
|
||||
) {
|
||||
let component = undefined;
|
||||
findTree(
|
||||
[this],
|
||||
(item: TreeItem) =>
|
||||
item !== ignoreScope &&
|
||||
item.getComponents().find((cmpt: ScopedComponentType) => {
|
||||
if (filter(cmpt.props.id, cmpt.props.data) === id) {
|
||||
component = cmpt;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})
|
||||
) as ScopedComponentType | undefined;
|
||||
|
||||
return component;
|
||||
},
|
||||
|
||||
getComponentById(id: string) {
|
||||
let root: AliasIScopedContext = this;
|
||||
let ignoreScope: AliasIScopedContext | undefined = undefined;
|
||||
|
||||
// 找到顶端scoped
|
||||
while (root) {
|
||||
// 优先从当前scope查找
|
||||
// 直接跑到顶层查找,对于有历史标签一次渲染多个页面的情况,会有问题
|
||||
const component = root.getComponentByIdUnderCurrentScope(
|
||||
id,
|
||||
ignoreScope
|
||||
);
|
||||
|
||||
if (component) {
|
||||
return component;
|
||||
}
|
||||
|
||||
if (!root.parent || root.parent === rootScopedContext) {
|
||||
break;
|
||||
}
|
||||
|
||||
ignoreScope = root;
|
||||
root = root.parent;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
},
|
||||
|
||||
/**
|
||||
* 基于绑定的变量名称查找组件
|
||||
* 支持形如${xxx}的格式
|
||||
*
|
||||
* @param session store的session, 默认为全局的
|
||||
* @param path 变量路径, 包含命名空间
|
||||
*/
|
||||
getComponentsByRefPath(
|
||||
session: string,
|
||||
path: string
|
||||
): ScopedComponentType[] {
|
||||
if (!path || typeof path !== 'string') {
|
||||
return [];
|
||||
}
|
||||
|
||||
const cmptMaps: Record<string, ScopedComponentType> = {};
|
||||
let root: AliasIScopedContext = this;
|
||||
|
||||
while (root.parent) {
|
||||
root = root.parent;
|
||||
}
|
||||
|
||||
eachTree([root], (item: TreeItem) => {
|
||||
const scopedCmptList: ScopedComponentType[] =
|
||||
item.getComponents() || [];
|
||||
|
||||
if (Array.isArray(scopedCmptList)) {
|
||||
for (const cmpt of scopedCmptList) {
|
||||
const pathKey = cmpt?.props?.$path ?? 'unknown';
|
||||
const schema = cmpt?.props?.$schema ?? {};
|
||||
const cmptSession = cmpt?.props.env?.session ?? 'global';
|
||||
|
||||
/** 仅查找当前session的组件 */
|
||||
if (cmptMaps[pathKey] || session !== cmptSession) {
|
||||
continue;
|
||||
}
|
||||
|
||||
/** 非Scoped组件, 查找其所属的父容器 */
|
||||
if (cmpt?.setData && typeof cmpt.setData === 'function') {
|
||||
cmptMaps[pathKey] = cmpt;
|
||||
continue;
|
||||
}
|
||||
|
||||
/** 查找Scoped组件中的引用 */
|
||||
for (const key of Object.keys(schema)) {
|
||||
const expression = schema[key];
|
||||
|
||||
if (
|
||||
typeof expression === 'string' &&
|
||||
isPureVariable(expression)
|
||||
) {
|
||||
/** 考虑到数据映射函数的情况,将宿主变量提取出来 */
|
||||
const host = expression
|
||||
.substring(2, expression.length - 1)
|
||||
.split('|')[0];
|
||||
|
||||
if (host && host === path) {
|
||||
cmptMaps[pathKey] = cmpt;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return values(cmptMaps);
|
||||
},
|
||||
|
||||
getComponents() {
|
||||
return components.concat();
|
||||
},
|
||||
|
||||
reload(target: string | Array<string>, ctx: any) {
|
||||
const scoped = this;
|
||||
|
||||
let targets = typeof target === 'string' ? splitTarget(target) : target;
|
||||
targets.forEach(name => {
|
||||
const idx2 = name.indexOf('?');
|
||||
let query = null;
|
||||
|
||||
if (~idx2) {
|
||||
const queryObj = qsparse(
|
||||
name
|
||||
.substring(idx2 + 1)
|
||||
.replace(
|
||||
/\$\{(.*?)\}/,
|
||||
(_, match) => '${' + encodeURIComponent(match) + '}'
|
||||
)
|
||||
);
|
||||
query = dataMapping(queryObj, ctx);
|
||||
name = name.substring(0, idx2);
|
||||
}
|
||||
|
||||
const idx = name.indexOf('.');
|
||||
let subPath = '';
|
||||
|
||||
if (~idx) {
|
||||
subPath = name.substring(1 + idx);
|
||||
name = name.substring(0, idx);
|
||||
}
|
||||
|
||||
if (name === 'window') {
|
||||
if (query) {
|
||||
const link = location.pathname + '?' + qsstringify(query);
|
||||
env ? env.updateLocation(link, true) : location.replace(link);
|
||||
} else {
|
||||
location.reload();
|
||||
}
|
||||
} else {
|
||||
const component =
|
||||
scoped.getComponentByName(name) || scoped.getComponentById(name);
|
||||
component &&
|
||||
component.reload &&
|
||||
component.reload(subPath, query, ctx);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
send(receive: string | Array<string>, values: object) {
|
||||
const scoped = this;
|
||||
let receives =
|
||||
typeof receive === 'string' ? splitTarget(receive) : receive;
|
||||
|
||||
// todo 没找到做提示!
|
||||
receives.forEach(name => {
|
||||
const askIdx = name.indexOf('?');
|
||||
if (~askIdx) {
|
||||
const query = name.substring(askIdx + 1);
|
||||
const queryObj = qsparse(
|
||||
query.replace(
|
||||
/\$\{(.*?)\}/,
|
||||
(_, match) => '${' + encodeURIComponent(match) + '}'
|
||||
)
|
||||
);
|
||||
|
||||
name = name.substring(0, askIdx);
|
||||
values = dataMapping(queryObj, values);
|
||||
}
|
||||
|
||||
const idx = name.indexOf('.');
|
||||
let subPath = '';
|
||||
|
||||
if (~idx) {
|
||||
subPath = name.substring(1 + idx);
|
||||
name = name.substring(0, idx);
|
||||
}
|
||||
|
||||
const component = scoped.getComponentByName(name);
|
||||
|
||||
if (component && component.receive) {
|
||||
component.receive(values, subPath);
|
||||
} else if (name === 'window' && env && env.updateLocation) {
|
||||
const query = {
|
||||
...parseQuery(location),
|
||||
...values
|
||||
};
|
||||
const link = location.pathname + '?' + qsstringify(query);
|
||||
env.updateLocation(link, true);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* 主要是用来关闭指定弹框的
|
||||
*
|
||||
* @param target 目标 name
|
||||
*/
|
||||
close(target: string | boolean) {
|
||||
const scoped = this;
|
||||
|
||||
if (typeof target === 'string') {
|
||||
// 过滤已经关掉的,当用户 close 配置多个弹框 name 时会出现这种情况
|
||||
splitTarget(target)
|
||||
.map(name => scoped.getComponentByName(name))
|
||||
.filter(component => component && component.props.show)
|
||||
.forEach(closeDialog);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 关闭指定id的弹窗
|
||||
* @param id
|
||||
*/
|
||||
closeById(id: string) {
|
||||
const scoped = this;
|
||||
const component: any = scoped.getComponentById(id);
|
||||
if (component && component.props.show) {
|
||||
closeDialog(component);
|
||||
}
|
||||
},
|
||||
|
||||
async doAction(actions: ListenerAction | ListenerAction[], ctx: any) {
|
||||
const renderer = this.getComponents()[0]; // 直接拿最顶层
|
||||
const rendererEvent = createRendererEvent('embed', {
|
||||
env,
|
||||
nativeEvent: undefined,
|
||||
data: createObject(renderer.props.data, ctx),
|
||||
scoped: this
|
||||
});
|
||||
|
||||
await runActions(actions, renderer, rendererEvent);
|
||||
|
||||
if (rendererEvent.prevented) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
registerFunction(
|
||||
'GETRENDERERDATA',
|
||||
(componentId: string, path?: string, scoped: any = self) => {
|
||||
const component = scoped.getComponentById(componentId);
|
||||
const data = component?.getData?.();
|
||||
if (path) {
|
||||
const variable = getVariable(data, path);
|
||||
return variable;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
);
|
||||
|
||||
registerFunction(
|
||||
'GETRENDERERPROP',
|
||||
(componentId: string, path?: string, scoped: any = self) => {
|
||||
const component = scoped.getComponentById(componentId);
|
||||
const props = component?.props;
|
||||
if (path) {
|
||||
const variable = getVariable(props, path);
|
||||
return variable;
|
||||
}
|
||||
return props;
|
||||
}
|
||||
);
|
||||
|
||||
if (!parent) {
|
||||
return self;
|
||||
}
|
||||
|
||||
!parent.children && (parent.children = []);
|
||||
|
||||
// 把孩子带上
|
||||
parent.children!.push(self);
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
function closeDialog(component: ScopedComponentType) {
|
||||
(component.context as IScopedContext)
|
||||
.getComponents()
|
||||
.filter(
|
||||
item =>
|
||||
item &&
|
||||
(item.props.type === 'dialog' || item.props.type === 'drawer') &&
|
||||
item.props.show
|
||||
)
|
||||
.forEach(closeDialog);
|
||||
component.props.onClose && component.props.onClose();
|
||||
}
|
||||
|
||||
export function HocScoped<
|
||||
T extends {
|
||||
$path?: string;
|
||||
env: RendererEnv;
|
||||
}
|
||||
>(
|
||||
ComposedComponent: React.ComponentType<T>,
|
||||
rendererType?: string
|
||||
): React.ComponentType<
|
||||
T & {
|
||||
scopeRef?: (ref: any) => void;
|
||||
}
|
||||
> & {
|
||||
ComposedComponent: React.ComponentType<T>;
|
||||
} {
|
||||
type ScopedProps = T & {
|
||||
scopeRef?: (ref: any) => void;
|
||||
};
|
||||
class ScopedComponent extends React.Component<ScopedProps> {
|
||||
static displayName = `Scoped(${
|
||||
ComposedComponent.displayName || ComposedComponent.name
|
||||
})`;
|
||||
static contextType = ScopedContext;
|
||||
static ComposedComponent = ComposedComponent;
|
||||
ref: any;
|
||||
scoped?: IScopedContext;
|
||||
|
||||
constructor(props: ScopedProps, context: IScopedContext) {
|
||||
super(props);
|
||||
|
||||
this.scoped = createScopedTools(
|
||||
this.props.$path,
|
||||
context,
|
||||
this.props.env,
|
||||
rendererType
|
||||
);
|
||||
|
||||
const scopeRef = props.scopeRef;
|
||||
scopeRef && scopeRef(this.scoped);
|
||||
}
|
||||
|
||||
getWrappedInstance() {
|
||||
return this.ref;
|
||||
}
|
||||
|
||||
@autobind
|
||||
childRef(ref: any) {
|
||||
while (ref && ref.getWrappedInstance) {
|
||||
ref = ref.getWrappedInstance();
|
||||
}
|
||||
|
||||
this.ref = ref;
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
const scopeRef = this.props.scopeRef;
|
||||
scopeRef && scopeRef(null);
|
||||
delete this.scoped;
|
||||
}
|
||||
|
||||
render() {
|
||||
const {scopeRef, ...rest} = this.props;
|
||||
|
||||
return (
|
||||
<ScopedContext.Provider value={this.scoped!}>
|
||||
<ComposedComponent
|
||||
{
|
||||
...(rest as any) /* todo */
|
||||
}
|
||||
ref={this.childRef}
|
||||
/>
|
||||
</ScopedContext.Provider>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
hoistNonReactStatic(ScopedComponent, ComposedComponent);
|
||||
return ScopedComponent;
|
||||
}
|
||||
|
||||
export default HocScoped;
|
||||
50
packages/amis-core/src/StatusScoped.tsx
Normal file
50
packages/amis-core/src/StatusScoped.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
// 多语言支持
|
||||
import React from 'react';
|
||||
import hoistNonReactStatic from 'hoist-non-react-statics';
|
||||
import {IStatusStore, StatusStore} from './store/status';
|
||||
import {destroy} from 'mobx-state-tree';
|
||||
|
||||
export interface StatusScopedProps {
|
||||
statusStore: IStatusStore;
|
||||
}
|
||||
|
||||
export interface StatusScopedWrapperProps {
|
||||
children: (props: {statusStore: IStatusStore}) => JSX.Element;
|
||||
}
|
||||
|
||||
export function StatusScopedWrapper({children}: StatusScopedWrapperProps) {
|
||||
const store = React.useMemo(() => StatusStore.create({}), []);
|
||||
React.useEffect(() => {
|
||||
return () => {
|
||||
destroy(store);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return children({statusStore: store});
|
||||
}
|
||||
|
||||
export function StatusScoped<
|
||||
T extends React.ComponentType<React.ComponentProps<T> & StatusScopedProps>
|
||||
>(ComposedComponent: T) {
|
||||
const wrapped = (
|
||||
props: JSX.LibraryManagedAttributes<
|
||||
T,
|
||||
Omit<React.ComponentProps<T>, keyof StatusScopedProps>
|
||||
> & {},
|
||||
ref: any
|
||||
) => {
|
||||
return (
|
||||
<StatusScopedWrapper>
|
||||
{({statusStore}) => (
|
||||
<ComposedComponent
|
||||
{...(props as any)}
|
||||
statusStore={statusStore}
|
||||
ref={ref}
|
||||
/>
|
||||
)}
|
||||
</StatusScopedWrapper>
|
||||
);
|
||||
};
|
||||
|
||||
return React.forwardRef(wrapped as any) as typeof wrapped;
|
||||
}
|
||||
63
packages/amis-core/src/StyleManager.ts
Normal file
63
packages/amis-core/src/StyleManager.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import kebabCase from 'lodash/kebabCase';
|
||||
|
||||
interface Style {
|
||||
[id: string]: {
|
||||
[className: string]: {
|
||||
[propName: string]: string | number;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
class StyleManager {
|
||||
styles: Style;
|
||||
styleDom: HTMLStyleElement;
|
||||
styleText: string;
|
||||
|
||||
constructor() {
|
||||
this.styles = {};
|
||||
this.styleDom = document.createElement('style');
|
||||
this.styleDom.id = 'amis-styles';
|
||||
document.head.appendChild(this.styleDom);
|
||||
}
|
||||
|
||||
updateStyle(style: Style) {
|
||||
Object.keys(style).forEach(className => {
|
||||
if (!this.styles[className]) {
|
||||
this.styles[className] = style[className];
|
||||
} else {
|
||||
this.styles[className] = {
|
||||
...this.styles[className],
|
||||
...style[className]
|
||||
};
|
||||
}
|
||||
});
|
||||
this.updateStyleDom();
|
||||
}
|
||||
|
||||
removeStyles(id: string) {
|
||||
delete this.styles[id];
|
||||
this.updateStyleDom();
|
||||
}
|
||||
|
||||
updateStyleDom() {
|
||||
const styleText = Object.keys(this.styles)
|
||||
.map(id => {
|
||||
const style = this.styles[id];
|
||||
return Object.keys(style)
|
||||
.map(className => {
|
||||
return `${className} {${Object.keys(style[className])
|
||||
.map(propName => {
|
||||
return `${kebabCase(propName)}: ${style[className][propName]};`;
|
||||
})
|
||||
.join('')}}`;
|
||||
})
|
||||
.join('');
|
||||
})
|
||||
.join('');
|
||||
|
||||
this.styleDom.innerHTML = styleText;
|
||||
this.styleText = styleText;
|
||||
}
|
||||
}
|
||||
|
||||
export default new StyleManager();
|
||||
69
packages/amis-core/src/WithRootStore.tsx
Normal file
69
packages/amis-core/src/WithRootStore.tsx
Normal file
@@ -0,0 +1,69 @@
|
||||
import React from 'react';
|
||||
import {IRendererStore} from './store';
|
||||
import hoistNonReactStatic from 'hoist-non-react-statics';
|
||||
|
||||
export const RootStoreContext = React.createContext<IRendererStore>(
|
||||
undefined as any
|
||||
);
|
||||
|
||||
export function withRootStore<
|
||||
T extends React.ComponentType<
|
||||
React.ComponentProps<T> & {
|
||||
rootStore: IRendererStore;
|
||||
}
|
||||
>
|
||||
>(ComposedComponent: T) {
|
||||
type OuterProps = JSX.LibraryManagedAttributes<
|
||||
T,
|
||||
Omit<React.ComponentProps<T>, 'rootStore'>
|
||||
>;
|
||||
|
||||
const result = hoistNonReactStatic(
|
||||
class extends React.Component<OuterProps> {
|
||||
static displayName: string = `WithRootStore(${
|
||||
ComposedComponent.displayName || ComposedComponent.name
|
||||
})`;
|
||||
static contextType = RootStoreContext;
|
||||
static ComposedComponent = ComposedComponent as React.ComponentType<T>;
|
||||
ref: any;
|
||||
|
||||
constructor(props: OuterProps) {
|
||||
super(props);
|
||||
this.refFn = this.refFn.bind(this);
|
||||
}
|
||||
|
||||
getWrappedInstance() {
|
||||
return this.ref.control;
|
||||
}
|
||||
|
||||
refFn(ref: any) {
|
||||
this.ref = ref;
|
||||
}
|
||||
|
||||
render() {
|
||||
const rootStore: IRendererStore = this.context as any;
|
||||
const injectedProps: {
|
||||
rootStore: IRendererStore;
|
||||
} = {
|
||||
rootStore
|
||||
};
|
||||
|
||||
return (
|
||||
<ComposedComponent
|
||||
{...(this.props as JSX.LibraryManagedAttributes<
|
||||
T,
|
||||
React.ComponentProps<T>
|
||||
> as any)}
|
||||
{...injectedProps}
|
||||
ref={this.refFn}
|
||||
/>
|
||||
);
|
||||
}
|
||||
},
|
||||
ComposedComponent
|
||||
);
|
||||
|
||||
return result as typeof result & {
|
||||
ComposedComponent: T;
|
||||
};
|
||||
}
|
||||
464
packages/amis-core/src/WithStore.tsx
Normal file
464
packages/amis-core/src/WithStore.tsx
Normal file
@@ -0,0 +1,464 @@
|
||||
import hoistNonReactStatic from 'hoist-non-react-statics';
|
||||
import {reaction} from 'mobx';
|
||||
import {observer} from 'mobx-react';
|
||||
import {isAlive} from 'mobx-state-tree';
|
||||
import React from 'react';
|
||||
import {RendererProps} from './factory';
|
||||
import {IIRendererStore, IRendererStore} from './store';
|
||||
import {RendererData, SchemaNode} from './types';
|
||||
import getExprProperties, {
|
||||
hasExprPropertiesChanged
|
||||
} from './utils/filter-schema';
|
||||
import {
|
||||
createObject,
|
||||
extendObject,
|
||||
guid,
|
||||
isObjectShallowModified,
|
||||
syncDataFromSuper,
|
||||
isSuperDataModified
|
||||
} from './utils/helper';
|
||||
import {dataMapping, tokenize} from './utils/tpl-builtin';
|
||||
import {RootStoreContext} from './WithRootStore';
|
||||
import {extractObjectChain} from './utils/object';
|
||||
|
||||
/**
|
||||
* 忽略静态数据中的 schema 属性
|
||||
*
|
||||
* 比如 https://github.com/baidu/amis/issues/8972 中的用法
|
||||
*/
|
||||
function ignoreSchemaProps(key: string, value: any) {
|
||||
if (['clickAction'].includes(key) && typeof value !== 'string') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function HocStoreFactory(renderer: {
|
||||
storeType: string;
|
||||
extendsData?: boolean | ((props: any) => boolean);
|
||||
shouldSyncSuperStore?: (
|
||||
store: any,
|
||||
props: any,
|
||||
prevProps: any
|
||||
) => boolean | undefined;
|
||||
}): any {
|
||||
return function <T extends React.ComponentType<RendererProps>>(Component: T) {
|
||||
type Props = Omit<
|
||||
RendererProps,
|
||||
'store' | 'data' | 'dataUpdatedAt' | 'scope'
|
||||
> & {
|
||||
store?: IIRendererStore;
|
||||
data?: RendererData;
|
||||
scope?: RendererData;
|
||||
storeRef?: (store: IIRendererStore | null) => void;
|
||||
rootStore: any;
|
||||
topStore: any;
|
||||
};
|
||||
|
||||
@observer
|
||||
class StoreFactory extends React.Component<Props> {
|
||||
static displayName = `WithStore(${
|
||||
Component.displayName || Component.name
|
||||
})`;
|
||||
static ComposedComponent = Component;
|
||||
static contextType = RootStoreContext;
|
||||
store: IIRendererStore;
|
||||
context!: React.ContextType<typeof RootStoreContext>;
|
||||
ref: any;
|
||||
state: any;
|
||||
unReaction: any;
|
||||
|
||||
constructor(
|
||||
props: Props,
|
||||
context: React.ContextType<typeof RootStoreContext>
|
||||
) {
|
||||
super(props);
|
||||
|
||||
const rootStore = context;
|
||||
this.renderChild = this.renderChild.bind(this);
|
||||
this.refFn = this.refFn.bind(this);
|
||||
|
||||
const store = rootStore.addStore({
|
||||
id: guid(),
|
||||
path: this.props.$path,
|
||||
storeType: renderer.storeType,
|
||||
parentId: this.props.store ? this.props.store.id : ''
|
||||
}) as IIRendererStore;
|
||||
store.setTopStore(props.topStore);
|
||||
|
||||
props.storeRef?.(store);
|
||||
|
||||
this.store = store;
|
||||
|
||||
const extendsData =
|
||||
typeof renderer.extendsData === 'function'
|
||||
? renderer.extendsData(props)
|
||||
: renderer.extendsData;
|
||||
|
||||
if (extendsData === false) {
|
||||
store.initData(
|
||||
createObject(
|
||||
(this.props.data as any)
|
||||
? (this.props.data as any).__super
|
||||
: null,
|
||||
{
|
||||
...this.formatData(
|
||||
dataMapping(
|
||||
this.props.defaultData,
|
||||
this.props.data,
|
||||
ignoreSchemaProps
|
||||
)
|
||||
),
|
||||
...this.formatData(this.props.data)
|
||||
}
|
||||
)
|
||||
);
|
||||
} else if (
|
||||
this.props.scope ||
|
||||
(this.props.data && (this.props.data as any).__super)
|
||||
) {
|
||||
if (this.props.store && this.props.data === this.props.scope) {
|
||||
store.initData(
|
||||
createObject(this.props.store.data, {
|
||||
...this.formatData(
|
||||
dataMapping(
|
||||
this.props.defaultData,
|
||||
this.props.data,
|
||||
ignoreSchemaProps
|
||||
)
|
||||
)
|
||||
})
|
||||
);
|
||||
} else {
|
||||
store.initData(
|
||||
createObject(
|
||||
(this.props.data as any).__super || this.props.scope,
|
||||
{
|
||||
...this.formatData(
|
||||
dataMapping(
|
||||
this.props.defaultData,
|
||||
this.props.data,
|
||||
ignoreSchemaProps
|
||||
)
|
||||
),
|
||||
...this.formatData(this.props.data)
|
||||
}
|
||||
)
|
||||
);
|
||||
}
|
||||
} else {
|
||||
store.initData({
|
||||
...this.formatData(
|
||||
dataMapping(
|
||||
this.props.defaultData,
|
||||
this.props.data,
|
||||
ignoreSchemaProps
|
||||
)
|
||||
),
|
||||
...this.formatData(this.props.data)
|
||||
});
|
||||
}
|
||||
|
||||
this.state = {};
|
||||
const {detectField, ...rest} = props;
|
||||
let exprProps: any = {};
|
||||
|
||||
if (!detectField || detectField === 'data') {
|
||||
exprProps = getExprProperties(rest, store.data);
|
||||
|
||||
this.state = {
|
||||
...exprProps
|
||||
};
|
||||
|
||||
this.unReaction = reaction(
|
||||
() => JSON.stringify(getExprProperties(this.props, store.data)),
|
||||
() =>
|
||||
this.setState({
|
||||
...getExprProperties(this.props, store.data)
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
getWrappedInstance() {
|
||||
return this.ref;
|
||||
}
|
||||
|
||||
refFn(ref: any) {
|
||||
this.ref = ref;
|
||||
}
|
||||
|
||||
formatData(data: any): object {
|
||||
if (Array.isArray(data)) {
|
||||
return {
|
||||
items: data
|
||||
};
|
||||
}
|
||||
|
||||
return data as object;
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: Props) {
|
||||
const props = this.props;
|
||||
const store = this.store;
|
||||
|
||||
// dialog 场景下 schema 是显示的时候更新的,
|
||||
// 所以 schema 里面有表达式属性其实是监听不到变化的
|
||||
// 所以这里需要根据新属性重新 reaction 一下
|
||||
if (
|
||||
(!props.detectField || props.detectField === 'data') &&
|
||||
hasExprPropertiesChanged(this.props, prevProps)
|
||||
) {
|
||||
const state = getExprProperties(this.props, store.data);
|
||||
isObjectShallowModified(state, this.state) && this.setState(state);
|
||||
// 需要重新监听
|
||||
this.unReaction?.();
|
||||
this.unReaction = reaction(
|
||||
() => getExprProperties(this.props, store.data),
|
||||
(exprProps: any) => this.setState(exprProps)
|
||||
);
|
||||
}
|
||||
|
||||
const shouldSync = renderer.shouldSyncSuperStore?.(
|
||||
store,
|
||||
props,
|
||||
prevProps
|
||||
);
|
||||
|
||||
if (shouldSync === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
const extendsData =
|
||||
typeof renderer.extendsData === 'function'
|
||||
? renderer.extendsData(props)
|
||||
: renderer.extendsData;
|
||||
if (extendsData === false) {
|
||||
if (
|
||||
shouldSync === true ||
|
||||
prevProps.defaultData !== props.defaultData ||
|
||||
(props.trackExpression
|
||||
? tokenize(props.trackExpression, props.data!) !==
|
||||
tokenize(props.trackExpression, prevProps.data!)
|
||||
: isObjectShallowModified(prevProps.data, props.data) ||
|
||||
//
|
||||
// 特殊处理 CRUD。
|
||||
// CRUD 中 toolbar 里面的 data 是空对象,但是 __super 会不一样
|
||||
(props.data &&
|
||||
prevProps.data &&
|
||||
props.data.__super !== prevProps.data.__super))
|
||||
) {
|
||||
store.initData(
|
||||
extendObject(props.data, {
|
||||
...this.formatData(
|
||||
dataMapping(
|
||||
this.props.defaultData,
|
||||
this.props.data,
|
||||
ignoreSchemaProps
|
||||
)
|
||||
),
|
||||
...(store.hasRemoteData ? store.data : null), // todo 只保留 remote 数据
|
||||
...this.formatData(props.data)
|
||||
}),
|
||||
(props.updatePristineAfterStoreDataReInit ??
|
||||
props.dataUpdatedAt !== prevProps.dataUpdatedAt) === false,
|
||||
props.data?.__changeReason
|
||||
);
|
||||
}
|
||||
} else if (
|
||||
shouldSync === true ||
|
||||
(props.trackExpression
|
||||
? tokenize(props.trackExpression, props.data!) !==
|
||||
tokenize(props.trackExpression, prevProps.data!)
|
||||
: isObjectShallowModified(prevProps.data, props.data) ||
|
||||
(props.syncSuperStore !== false &&
|
||||
isSuperDataModified(props.data, prevProps.data, store)))
|
||||
) {
|
||||
if (props.store && props.scope === props.data) {
|
||||
store.initData(
|
||||
createObject(props.store.data, {
|
||||
...this.formatData(
|
||||
dataMapping(
|
||||
this.props.defaultData,
|
||||
this.props.data,
|
||||
ignoreSchemaProps
|
||||
)
|
||||
),
|
||||
...(props.syncSuperStore === false
|
||||
? {
|
||||
...store.data
|
||||
}
|
||||
: syncDataFromSuper(
|
||||
store.data,
|
||||
props.store.data,
|
||||
prevProps.scope,
|
||||
store,
|
||||
props.syncSuperStore === true
|
||||
))
|
||||
}),
|
||||
(props.updatePristineAfterStoreDataReInit ??
|
||||
props.dataUpdatedAt !== prevProps.dataUpdatedAt) === false,
|
||||
|
||||
props.data?.__changeReason
|
||||
);
|
||||
} else if (props.data && (props.data as any).__super) {
|
||||
store.initData(
|
||||
extendObject(props.data, {
|
||||
...this.formatData(
|
||||
dataMapping(
|
||||
this.props.defaultData,
|
||||
this.props.data,
|
||||
ignoreSchemaProps
|
||||
)
|
||||
),
|
||||
...// 有远程数据
|
||||
// 或者顶级 store
|
||||
(store.hasRemoteData || !store.path.includes('/')
|
||||
? {
|
||||
...store.data,
|
||||
...props.data
|
||||
}
|
||||
: // combo 不需要同步,如果要同步,在 Combo.tsx 里面已经实现了相关逻辑
|
||||
// 目前主要的问题是,如果 combo 中表单项名字和 combo 本身的名字一样,会导致里面的值会被覆盖成数组
|
||||
props.store?.storeType === 'ComboStore'
|
||||
? undefined
|
||||
: syncDataFromSuper(
|
||||
{...store.pristineDiff, ...props.data},
|
||||
(props.data as any).__super,
|
||||
(prevProps.data as any).__super,
|
||||
store,
|
||||
false
|
||||
))
|
||||
}),
|
||||
(props.updatePristineAfterStoreDataReInit ??
|
||||
props.dataUpdatedAt !== prevProps.dataUpdatedAt) === false,
|
||||
props.data?.__changeReason
|
||||
);
|
||||
} else {
|
||||
store.initData(
|
||||
createObject(props.scope, props.data),
|
||||
(props.updatePristineAfterStoreDataReInit ??
|
||||
props.dataUpdatedAt !== prevProps.dataUpdatedAt) === false,
|
||||
props.data?.__changeReason
|
||||
);
|
||||
}
|
||||
} else if (
|
||||
!props.trackExpression &&
|
||||
(!props.store || props.data !== props.scope) &&
|
||||
props.data &&
|
||||
props.data.__super
|
||||
) {
|
||||
// 这个用法很少,当 data.__super 值发生变化时,更新 store.data
|
||||
if (
|
||||
!prevProps.data ||
|
||||
isObjectShallowModified(
|
||||
props.data.__super,
|
||||
prevProps.data.__super,
|
||||
false
|
||||
)
|
||||
) {
|
||||
store.initData(
|
||||
createObject(props.data.__super, {
|
||||
...props.data,
|
||||
...store.data
|
||||
}),
|
||||
|
||||
(props.updatePristineAfterStoreDataReInit ??
|
||||
props.dataUpdatedAt !== prevProps.dataUpdatedAt) === false ||
|
||||
(store.storeType === 'FormStore' &&
|
||||
prevProps.store?.storeType === 'CRUDStore'),
|
||||
|
||||
props.data?.__changeReason
|
||||
);
|
||||
}
|
||||
// nextProps.data.__super !== props.data.__super) &&
|
||||
} else if (
|
||||
!props.trackExpression &&
|
||||
props.scope &&
|
||||
props.data === props.store!.data &&
|
||||
prevProps.data !== props.data
|
||||
) {
|
||||
// 只有父级数据变动的时候才应该进来,
|
||||
// 目前看来这个 case 很少有情况下能进来
|
||||
store.initData(
|
||||
createObject(props.scope, {
|
||||
// ...nextProps.data,
|
||||
...store.data
|
||||
}),
|
||||
(props.updatePristineAfterStoreDataReInit ??
|
||||
props.dataUpdatedAt !== prevProps.dataUpdatedAt) === false,
|
||||
|
||||
props.data?.__changeReason
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
const rootStore = this.context as IRendererStore;
|
||||
const store = this.store;
|
||||
|
||||
this.unReaction?.();
|
||||
if (isAlive(store)) {
|
||||
store.setTopStore(null);
|
||||
rootStore.removeStore(store);
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
delete this.store;
|
||||
this.props.storeRef?.(null);
|
||||
}
|
||||
|
||||
renderChild(
|
||||
region: string,
|
||||
node: SchemaNode,
|
||||
subProps: {
|
||||
data?: object;
|
||||
[propName: string]: any;
|
||||
} = {}
|
||||
) {
|
||||
let {render} = this.props;
|
||||
|
||||
return render(region, node, {
|
||||
data: this.store.data,
|
||||
dataUpdatedAt: this.store.updatedAt,
|
||||
...subProps,
|
||||
scope: this.store.data,
|
||||
store: this.store
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
const {detectField, storeRef, ...rest} = this.props;
|
||||
|
||||
if (this.state.hidden || this.state.visible === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const refConfig =
|
||||
Component.prototype?.isReactComponent ||
|
||||
(Component as any).$$typeof === Symbol.for('react.forward_ref')
|
||||
? {ref: this.refFn}
|
||||
: {forwardedRef: this.refFn};
|
||||
|
||||
return (
|
||||
<Component
|
||||
{
|
||||
...(rest as any) /* todo */
|
||||
}
|
||||
{...this.state}
|
||||
{...refConfig}
|
||||
data={this.store.data}
|
||||
dataUpdatedAt={this.store.updatedAt}
|
||||
store={this.store}
|
||||
scope={this.store.data}
|
||||
render={this.renderChild}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
hoistNonReactStatic(StoreFactory, Component);
|
||||
|
||||
return StoreFactory;
|
||||
};
|
||||
}
|
||||
467
packages/amis-core/src/actions/Action.ts
Normal file
467
packages/amis-core/src/actions/Action.ts
Normal file
@@ -0,0 +1,467 @@
|
||||
import omit from 'lodash/omit';
|
||||
import {RendererProps} from '../factory';
|
||||
import {ConditionGroupValue} from '../types';
|
||||
import {createObject} from '../utils/helper';
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import {evalExpressionWithConditionBuilderAsync} from '../utils/tpl';
|
||||
import {dataMapping} from '../utils/tpl-builtin';
|
||||
import {IBreakAction} from './BreakAction';
|
||||
import {IContinueAction} from './ContinueAction';
|
||||
import {ILoopAction} from './LoopAction';
|
||||
import {IParallelAction} from './ParallelAction';
|
||||
import {ISwitchAction} from './SwitchAction';
|
||||
import {debug} from '../utils/debug';
|
||||
import {injectObjectChain} from '../utils';
|
||||
|
||||
// 循环动作执行状态
|
||||
export enum LoopStatus {
|
||||
NORMAL,
|
||||
BREAK,
|
||||
CONTINUE
|
||||
}
|
||||
|
||||
// 监听器动作定义
|
||||
export interface ListenerAction {
|
||||
actionType: string; // 动作类型 逻辑动作|自定义(脚本支撑)|reload|url|ajax|dialog|drawer 其他扩充的组件动作
|
||||
description?: string; // 事件描述,actionType: broadcast
|
||||
componentId?: string; // 组件ID,用于直接执行指定组件的动作,指定多个组件时使用英文逗号分隔
|
||||
componentName?: string; // 组件Name,用于直接执行指定组件的动作,指定多个组件时使用英文逗号分隔
|
||||
ignoreError?: boolean; // 当执行动作发生错误时,是否忽略并继续执行
|
||||
args?: Record<string, any>; // 动作配置,可以配置数据映射。注意:存在schema配置的动作都不能放在args里面,避免数据域不同导致的解析错误问题
|
||||
data?: Record<string, any> | null; // 动作数据参数,可以配置数据映射
|
||||
dataMergeMode?: 'merge' | 'override'; // 参数模式,合并或者覆盖
|
||||
outputVar?: string; // 输出数据变量名
|
||||
preventDefault?: boolean; // 阻止原有组件的动作行为
|
||||
stopPropagation?: boolean; // 阻止后续的事件处理器执行
|
||||
expression?: string | ConditionGroupValue; // 执行条件
|
||||
execOn?: string; // 执行条件,1.9.0废弃
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
export interface ILogicAction extends ListenerAction {
|
||||
children?: ListenerAction[]; // 子动作
|
||||
}
|
||||
|
||||
// 逻辑动作类型,支持并行、排他(switch)、循环(支持continue和break)
|
||||
export type LogicAction =
|
||||
| IParallelAction
|
||||
| ISwitchAction
|
||||
| ILoopAction
|
||||
| IContinueAction
|
||||
| IBreakAction;
|
||||
|
||||
export interface ListenerContext extends React.Component<RendererProps> {
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
interface MappingIgnoreMap {
|
||||
[propName: string]: string[];
|
||||
}
|
||||
|
||||
// Action 基础接口
|
||||
export interface RendererAction {
|
||||
// 运行这个 Action,每个类型的 Action 都只有一个实例,run 函数是个可重入的函数
|
||||
run: (
|
||||
action: ListenerAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>,
|
||||
mergeData?: any // 有些Action内部需要通过上下文数据处理专有逻辑,这里的数据是事件数据+渲染器数据
|
||||
) => Promise<RendererEvent<any> | void>;
|
||||
}
|
||||
|
||||
// 存储 Action 和类型的映射关系,用于后续查找
|
||||
const ActionTypeMap: {[key: string]: RendererAction} = {};
|
||||
// 存储动作属性排除列表
|
||||
const ActionIgnoreKey: MappingIgnoreMap = {};
|
||||
// 存储组件专有动作的属性排除列表
|
||||
const CmptIgnoreMap: MappingIgnoreMap = {};
|
||||
|
||||
// 注册 Action
|
||||
export const registerAction = (type: string, action: RendererAction) => {
|
||||
ActionTypeMap[type] = action;
|
||||
};
|
||||
|
||||
// 通过类型获取 Action 实例
|
||||
export const getActionByType = (type: string) => {
|
||||
return ActionTypeMap[type];
|
||||
};
|
||||
|
||||
// 根据动作类型获取属性排除列表
|
||||
const getOmitActionProp = (type: string) => {
|
||||
let omitList: string[] = [];
|
||||
switch (type) {
|
||||
case 'toast':
|
||||
omitList = [
|
||||
'msgType',
|
||||
'msg',
|
||||
'position',
|
||||
'closeButton',
|
||||
'showIcon',
|
||||
'timeout',
|
||||
'title'
|
||||
];
|
||||
break;
|
||||
case 'alert':
|
||||
omitList = ['msg'];
|
||||
break;
|
||||
case 'confirm':
|
||||
omitList = ['msg', 'title'];
|
||||
break;
|
||||
case 'ajax':
|
||||
case 'download':
|
||||
omitList = ['api', 'messages', 'options'];
|
||||
break;
|
||||
case 'setValue':
|
||||
omitList = ['value', 'index'];
|
||||
break;
|
||||
case 'copy':
|
||||
omitList = ['content', 'copyFormat'];
|
||||
break;
|
||||
case 'email':
|
||||
omitList = ['to', 'cc', 'bcc', 'subject', 'body'];
|
||||
break;
|
||||
case 'link':
|
||||
omitList = ['link', 'blank', 'params'];
|
||||
break;
|
||||
case 'url':
|
||||
omitList = ['url', 'blank', 'params'];
|
||||
break;
|
||||
case 'for':
|
||||
omitList = ['loopName'];
|
||||
break;
|
||||
case 'goPage':
|
||||
omitList = ['delta'];
|
||||
break;
|
||||
case 'custom':
|
||||
omitList = ['script'];
|
||||
break;
|
||||
case 'broadcast':
|
||||
omitList = ['eventName'];
|
||||
break;
|
||||
case 'dialog':
|
||||
omitList = ['dialog'];
|
||||
break;
|
||||
case 'drawer':
|
||||
omitList = ['drawer'];
|
||||
break;
|
||||
case 'confirmDialog':
|
||||
omitList = ['dialog'];
|
||||
break;
|
||||
case 'reload':
|
||||
omitList = ['resetPage'];
|
||||
break;
|
||||
}
|
||||
return omitList;
|
||||
};
|
||||
|
||||
export const getTargetComponent = (
|
||||
action: ListenerAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>,
|
||||
key?: string
|
||||
) => {
|
||||
let targetComponent = renderer;
|
||||
if (key && event.context.scoped) {
|
||||
const func = action.componentId ? 'getComponentById' : 'getComponentByName';
|
||||
if (typeof event.context.scoped[func] === 'function') {
|
||||
targetComponent = event.context.scoped[func](key);
|
||||
}
|
||||
}
|
||||
|
||||
return targetComponent;
|
||||
};
|
||||
|
||||
export const runActions = async (
|
||||
actions: ListenerAction | ListenerAction[],
|
||||
renderer: ListenerContext,
|
||||
event: any
|
||||
) => {
|
||||
if (!Array.isArray(actions)) {
|
||||
actions = [actions];
|
||||
}
|
||||
|
||||
for (const actionConfig of actions) {
|
||||
let actionInstrance = getActionByType(actionConfig.actionType);
|
||||
|
||||
// 如果存在指定组件ID,说明是组件专有动作
|
||||
if (
|
||||
!actionInstrance &&
|
||||
(actionConfig.componentId || actionConfig.componentName)
|
||||
) {
|
||||
actionInstrance = [
|
||||
'static',
|
||||
'nonstatic',
|
||||
'show',
|
||||
'visibility',
|
||||
'hidden',
|
||||
'enabled',
|
||||
'disabled',
|
||||
'usability'
|
||||
].includes(actionConfig.actionType)
|
||||
? getActionByType('status')
|
||||
: getActionByType('component');
|
||||
} else if (['url', 'link', 'jump'].includes(actionConfig.actionType)) {
|
||||
// 打开页面动作
|
||||
actionInstrance = getActionByType('openlink');
|
||||
}
|
||||
|
||||
// 找不到就通过组件专有动作完成
|
||||
if (!actionInstrance) {
|
||||
actionInstrance = getActionByType('component');
|
||||
}
|
||||
|
||||
try {
|
||||
// 这些节点的子节点运行逻辑由节点内部实现
|
||||
await runAction(actionInstrance, actionConfig, renderer, event);
|
||||
} catch (e) {
|
||||
const ignore = actionConfig.ignoreError ?? false;
|
||||
if (!ignore) {
|
||||
// 通过标记 stop 来阻止后续动作执行
|
||||
// 不要抛出,避免后续的代码逻辑不执行,同时避免 unhandled promise rejection
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
console.error(
|
||||
`${actionConfig.actionType} 动作执行失败,原因:${
|
||||
e.message || '未知'
|
||||
}`
|
||||
);
|
||||
// throw Error(
|
||||
// `${actionConfig.actionType} 动作执行失败,原因:${
|
||||
// e.message || '未知'
|
||||
// }`
|
||||
// );
|
||||
}
|
||||
}
|
||||
|
||||
if (event.stoped) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 执行动作,与原有动作处理打通
|
||||
export const runAction = async (
|
||||
actionInstrance: RendererAction,
|
||||
actionConfig: ListenerAction,
|
||||
renderer: ListenerContext,
|
||||
event: any
|
||||
) => {
|
||||
// 追加数据
|
||||
let additional: any = {
|
||||
event
|
||||
};
|
||||
let action: ListenerAction = {...actionConfig};
|
||||
action.args = {...actionConfig.args};
|
||||
|
||||
const rendererProto = renderer.props.getData?.() ?? renderer.props.data;
|
||||
|
||||
// __rendererData默认为renderer.props.data,兼容表单项值变化时的data读取
|
||||
if (!event.data?.__rendererData) {
|
||||
additional = {
|
||||
event,
|
||||
__rendererData: rendererProto // 部分组件交互后会有更新,如果想要获取那部分数据,可以通过事件数据获取
|
||||
};
|
||||
}
|
||||
|
||||
// 用户可能,需要用到事件数据和当前域的数据,因此merge事件数据和当前渲染器数据
|
||||
// 需要保持渲染器数据链完整
|
||||
// 注意:并行ajax请求结果必须通过event取值
|
||||
const mergeData = injectObjectChain(event.data, additional);
|
||||
// createObject(
|
||||
// createObject(
|
||||
// rendererProto.__super
|
||||
// ? createObject(rendererProto.__super, additional)
|
||||
// : additional,
|
||||
// rendererProto
|
||||
// ),
|
||||
// event.data
|
||||
// );
|
||||
// 兼容一下1.9.0之前的版本
|
||||
const expression = action.expression ?? action.execOn;
|
||||
// 执行条件
|
||||
let isStop = false;
|
||||
|
||||
if (expression) {
|
||||
isStop = !(await evalExpressionWithConditionBuilderAsync(
|
||||
expression,
|
||||
mergeData,
|
||||
true
|
||||
));
|
||||
}
|
||||
|
||||
if (isStop) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 支持表达式 >=1.10.0
|
||||
let preventDefault = false;
|
||||
if (action.preventDefault) {
|
||||
preventDefault = await evalExpressionWithConditionBuilderAsync(
|
||||
action.preventDefault,
|
||||
mergeData,
|
||||
false
|
||||
);
|
||||
}
|
||||
|
||||
let key = {
|
||||
componentId: dataMapping(action.componentId, mergeData),
|
||||
componentName: dataMapping(action.componentName, mergeData)
|
||||
};
|
||||
|
||||
// 兼容args包裹的用法
|
||||
if (action.actionType === 'dialog') {
|
||||
action.dialog = {...(action.dialog ?? action.args?.dialog)};
|
||||
delete action.args?.dialog;
|
||||
} else if (action.actionType === 'drawer') {
|
||||
action.drawer = {...(action.drawer ?? action.args?.drawer)};
|
||||
delete action.args?.drawer;
|
||||
} else if (['ajax', 'download'].includes(action.actionType)) {
|
||||
const api = action.api ?? action.args?.api;
|
||||
action.api = typeof api === 'string' ? api : {...api};
|
||||
action.options = {...(action.options ?? action.args?.options)};
|
||||
action.messages = {...(action.messages ?? action.args?.messages)};
|
||||
delete action.args?.api;
|
||||
delete action.args?.options;
|
||||
delete action.args?.messages;
|
||||
}
|
||||
const cmptFlag = key.componentId || key.componentName;
|
||||
const targetComponent = getTargetComponent(action, renderer, event, cmptFlag);
|
||||
// 动作配置
|
||||
const args = dataMapping(action.args, mergeData, (key: string) => {
|
||||
const curCmptType: string = targetComponent?.props?.type;
|
||||
const curActionType: string = action.actionType;
|
||||
const ignoreKey = [
|
||||
...(ActionIgnoreKey[curActionType] || []),
|
||||
...(CmptIgnoreMap[curCmptType] || [])
|
||||
];
|
||||
return ignoreKey.includes(key);
|
||||
});
|
||||
const afterMappingData = dataMapping(action.data, mergeData);
|
||||
|
||||
// 动作数据
|
||||
const actionData =
|
||||
args && Object.keys(args).length
|
||||
? omit(
|
||||
{
|
||||
...args, // 兼容历史(动作配置与数据混在一起的情况)
|
||||
...(afterMappingData ?? {})
|
||||
},
|
||||
getOmitActionProp(action.actionType)
|
||||
)
|
||||
: afterMappingData;
|
||||
|
||||
// 默认为当前数据域
|
||||
const data =
|
||||
actionData !== undefined &&
|
||||
!['ajax', 'download', 'dialog', 'drawer'].includes(action.actionType) // 避免非法配置影响对actionData的判断,导致动作配置中的数据映射失败
|
||||
? actionData
|
||||
: mergeData;
|
||||
|
||||
console.group?.(`run action ${action.actionType}`);
|
||||
console.debug(`[${action.actionType}] action args, data`, args, data);
|
||||
|
||||
debug('action', `run action ${action.actionType} with args`, args);
|
||||
debug('action', `run action ${action.actionType} with data`, data);
|
||||
|
||||
try {
|
||||
let stopped = false;
|
||||
const actionResult = await actionInstrance.run(
|
||||
{
|
||||
...action,
|
||||
args,
|
||||
rawData: actionConfig.data,
|
||||
data: action.actionType === 'reload' ? actionData : data, // 如果是刷新动作,则只传action.data
|
||||
...key
|
||||
},
|
||||
renderer,
|
||||
event,
|
||||
mergeData
|
||||
);
|
||||
// 二次确认弹窗如果取消,则终止后续动作
|
||||
if (action?.actionType === 'confirmDialog' && !actionResult) {
|
||||
stopped = true;
|
||||
preventDefault = true; // 这种对表单项change比较有意义,例如switch切换时弹确认弹窗,如果取消后不能把switch修改了
|
||||
}
|
||||
|
||||
let stopPropagation = false;
|
||||
if (action.stopPropagation) {
|
||||
stopPropagation = await evalExpressionWithConditionBuilderAsync(
|
||||
action.stopPropagation,
|
||||
mergeData,
|
||||
false
|
||||
);
|
||||
}
|
||||
// 阻止原有动作执行
|
||||
preventDefault && event.preventDefault();
|
||||
// 阻止后续动作执行
|
||||
(stopPropagation || stopped) && event.stopPropagation();
|
||||
} finally {
|
||||
console.debug(`[${action.actionType}] action end event`, event);
|
||||
console.groupEnd?.();
|
||||
}
|
||||
};
|
||||
|
||||
// 注册动作参数映射忽略键
|
||||
export const registerActionMappingIgnoreKey = (
|
||||
actionType: string,
|
||||
ignoreKey: string[],
|
||||
replace: boolean = true
|
||||
) => {
|
||||
if (replace) {
|
||||
ActionIgnoreKey[actionType] = ignoreKey;
|
||||
return;
|
||||
}
|
||||
ActionIgnoreKey[actionType] = [
|
||||
...(ActionIgnoreKey[actionType] || []),
|
||||
...ignoreKey
|
||||
];
|
||||
};
|
||||
|
||||
// 注册多个动作参数映射忽略键
|
||||
export const registerActionMappingIgnoreMap = (
|
||||
maps: MappingIgnoreMap,
|
||||
replace: boolean = true
|
||||
) => {
|
||||
Object.keys(maps).forEach(key => {
|
||||
registerActionMappingIgnoreKey(key, maps[key], replace);
|
||||
});
|
||||
};
|
||||
|
||||
// 注册组件动作参数映射忽略键
|
||||
export const registerComponentActionMappingIgnoreKey = (
|
||||
cmptType: string,
|
||||
ignoreKey: string[],
|
||||
replace: boolean = true
|
||||
) => {
|
||||
if (replace) {
|
||||
CmptIgnoreMap[cmptType] = ignoreKey;
|
||||
return;
|
||||
}
|
||||
CmptIgnoreMap[cmptType] = [...(CmptIgnoreMap[cmptType] || []), ...ignoreKey];
|
||||
};
|
||||
|
||||
// 注册多个组件动作参数映射忽略键
|
||||
export const registerComponentActionMappingIgnoreMap = (
|
||||
maps: MappingIgnoreMap,
|
||||
replace: boolean = true
|
||||
) => {
|
||||
Object.keys(maps).forEach(key => {
|
||||
registerComponentActionMappingIgnoreKey(key, maps[key], replace);
|
||||
});
|
||||
};
|
||||
|
||||
// 注册默认忽略键(将来是否需要移到相应的模块中)
|
||||
registerActionMappingIgnoreMap({
|
||||
ajax: ['adaptor', 'responseAdaptor', 'requestAdaptor', 'responseData']
|
||||
});
|
||||
|
||||
// 注册组件默认忽略键(将来是否需要移到相应的渲染器中)
|
||||
registerComponentActionMappingIgnoreMap({
|
||||
'input-table': ['condition'],
|
||||
'table': ['condition'],
|
||||
'table2': ['condition'],
|
||||
'crud': ['condition'],
|
||||
'combo': ['condition'],
|
||||
'list': ['condition'],
|
||||
'cards': ['condition']
|
||||
});
|
||||
162
packages/amis-core/src/actions/AjaxAction.ts
Normal file
162
packages/amis-core/src/actions/AjaxAction.ts
Normal file
@@ -0,0 +1,162 @@
|
||||
import {Api, ApiObject} from '../types';
|
||||
import {normalizeApi, normalizeApiResponseData} from '../utils/api';
|
||||
import {ServerError} from '../utils/errors';
|
||||
import {createObject, isEmpty} from '../utils/helper';
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import {evalExpressionWithConditionBuilderAsync} from '../utils/tpl';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerAction,
|
||||
ListenerContext,
|
||||
registerAction
|
||||
} from './Action';
|
||||
|
||||
export interface IAjaxAction extends ListenerAction {
|
||||
action: 'ajax';
|
||||
api: Api;
|
||||
messages?: {
|
||||
success: string;
|
||||
failed: string;
|
||||
};
|
||||
options?: Record<string, any>;
|
||||
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送请求动作
|
||||
*
|
||||
* @export
|
||||
* @class AjaxAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class AjaxAction implements RendererAction {
|
||||
fetcherType: string;
|
||||
|
||||
constructor(fetcherType: string = 'ajax') {
|
||||
this.fetcherType = fetcherType;
|
||||
}
|
||||
|
||||
async run(
|
||||
action: IAjaxAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
if (!event.context.env?.fetcher) {
|
||||
throw new Error('env.fetcher is required!');
|
||||
}
|
||||
|
||||
if (!action.api) {
|
||||
throw new Error('api is required!');
|
||||
}
|
||||
|
||||
if (this.fetcherType === 'download' && action.actionType === 'download') {
|
||||
if ((action as any).api) {
|
||||
(action as any).api.responseType = 'blob';
|
||||
}
|
||||
}
|
||||
|
||||
const env = event.context.env;
|
||||
const silent = action?.options?.silent || (action?.api as ApiObject).silent;
|
||||
const messages = (action?.api as ApiObject)?.messages;
|
||||
let api = normalizeApi(action.api);
|
||||
|
||||
if (api.sendOn) {
|
||||
// 发送请求前,判断是否需要发送
|
||||
const sendOn = await evalExpressionWithConditionBuilderAsync(
|
||||
api.sendOn,
|
||||
action.data ?? {},
|
||||
false
|
||||
);
|
||||
|
||||
if (!sendOn) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没配置data数据映射,则给一个空对象,避免将当前数据域作为接口请求参数
|
||||
if ((api as any)?.data == undefined) {
|
||||
api = {
|
||||
...api,
|
||||
data: {}
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await env.fetcher(
|
||||
api,
|
||||
action.data ?? {},
|
||||
action?.options ?? {}
|
||||
);
|
||||
const responseData =
|
||||
!isEmpty(result.data) || result.ok
|
||||
? normalizeApiResponseData(result.data)
|
||||
: null;
|
||||
|
||||
// 记录请求返回的数据
|
||||
event.setData(
|
||||
createObject(event.data, {
|
||||
...event.data,
|
||||
...responseData, // 兼容历史配置
|
||||
responseData: responseData,
|
||||
[action.outputVar || 'responseResult']: {
|
||||
...responseData,
|
||||
responseData,
|
||||
responseStatus: result.status,
|
||||
responseMsg: result.msg
|
||||
}
|
||||
})
|
||||
);
|
||||
if (!silent) {
|
||||
if (!result.ok) {
|
||||
throw new ServerError(
|
||||
messages?.failed ?? action.messages?.failed ?? result.msg,
|
||||
result
|
||||
);
|
||||
} else {
|
||||
const msg =
|
||||
messages?.success ??
|
||||
action.messages?.success ??
|
||||
result.msg ??
|
||||
result.defaultMsg;
|
||||
msg &&
|
||||
env.notify(
|
||||
'success',
|
||||
msg,
|
||||
result.msgTimeout !== undefined
|
||||
? {
|
||||
closeButton: true,
|
||||
timeout: result.msgTimeout
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return result.data;
|
||||
} catch (e) {
|
||||
if (!silent) {
|
||||
if (e.type === 'ServerError') {
|
||||
const result = (e as ServerError).response;
|
||||
env.notify(
|
||||
'error',
|
||||
e.message,
|
||||
result.msgTimeout !== undefined
|
||||
? {
|
||||
closeButton: true,
|
||||
timeout: result.msgTimeout
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
} else {
|
||||
env.notify('error', e.message);
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('ajax', new AjaxAction());
|
||||
|
||||
registerAction('download', new AjaxAction('download'));
|
||||
31
packages/amis-core/src/actions/BreakAction.ts
Normal file
31
packages/amis-core/src/actions/BreakAction.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { RendererEvent } from '../utils/renderer-event';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerContext,
|
||||
LoopStatus,
|
||||
registerAction,
|
||||
ILogicAction
|
||||
} from './Action';
|
||||
|
||||
export interface IBreakAction extends ILogicAction {
|
||||
actionType: 'break';
|
||||
}
|
||||
|
||||
/**
|
||||
* breach
|
||||
*
|
||||
* @export
|
||||
* @class BreakAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class BreakAction implements RendererAction {
|
||||
async run(
|
||||
action: IBreakAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
renderer.loopStatus = LoopStatus.BREAK;
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('break', new BreakAction());
|
||||
55
packages/amis-core/src/actions/BroadcastAction.ts
Normal file
55
packages/amis-core/src/actions/BroadcastAction.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import {createObject} from '../utils/helper';
|
||||
import {
|
||||
RendererEvent,
|
||||
dispatchGlobalEventForRenderer
|
||||
} from '../utils/renderer-event';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerAction,
|
||||
ListenerContext,
|
||||
registerAction
|
||||
} from './Action';
|
||||
|
||||
export interface IBroadcastAction extends ListenerAction {
|
||||
actionType: 'broadcast';
|
||||
args: {
|
||||
eventName: string; // 事件名称,actionType: broadcast
|
||||
};
|
||||
eventName?: string; // 兼容历史
|
||||
}
|
||||
|
||||
/**
|
||||
* broadcast
|
||||
*
|
||||
* @export
|
||||
* @class BroadcastAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class BroadcastAction implements RendererAction {
|
||||
async run(
|
||||
action: IBroadcastAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
if (!action.args?.eventName && !action.eventName) {
|
||||
console.error('eventName 未定义,请定义事件名称');
|
||||
return;
|
||||
}
|
||||
|
||||
// 作为一个新的事件,需要把广播动作的args参数追加到事件数据中
|
||||
event.setData(createObject(event.data, action.data ?? {}));
|
||||
|
||||
const eventName = action.args?.eventName || action.eventName!;
|
||||
|
||||
// 直接触发对应的动作
|
||||
return await dispatchGlobalEventForRenderer(
|
||||
eventName,
|
||||
renderer,
|
||||
event.context.scoped,
|
||||
action.data,
|
||||
event
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('broadcast', new BroadcastAction());
|
||||
194
packages/amis-core/src/actions/CmptAction.ts
Normal file
194
packages/amis-core/src/actions/CmptAction.ts
Normal file
@@ -0,0 +1,194 @@
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import {createObject, extendObject} from '../utils/helper';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerAction,
|
||||
ListenerContext,
|
||||
registerAction,
|
||||
getTargetComponent
|
||||
} from './Action';
|
||||
import {getRendererByName} from '../factory';
|
||||
|
||||
export interface ICmptAction extends ListenerAction {
|
||||
actionType: string;
|
||||
args: {
|
||||
resetPage?: boolean; // reload时,是否重置分页
|
||||
path?: string; // setValue时,目标变量的path
|
||||
value?: string | {[key: string]: string}; // setValue时,目标变量的值
|
||||
index?: number; // setValue时,支持更新指定索引的数据,一般用于数组类型
|
||||
condition?: any; // setValue时,支持更新指定条件的数据,一般用于数组类型
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 组件动作
|
||||
*
|
||||
* @export
|
||||
* @class CmptAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class CmptAction implements RendererAction {
|
||||
async run(
|
||||
action: ICmptAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
/**
|
||||
* 根据唯一ID查找指定组件
|
||||
* 触发组件未指定id或未指定响应组件componentId,则使用触发组件响应
|
||||
*/
|
||||
const key = action.componentId || action.componentName;
|
||||
const dataMergeMode = action.dataMergeMode || 'merge';
|
||||
const path = action.args?.path;
|
||||
|
||||
/** 如果args中携带path参数, 则认为是全局变量赋值, 否则认为是组件变量赋值 */
|
||||
if (action.actionType === 'setValue' && path && typeof path === 'string') {
|
||||
if (path.startsWith('global.')) {
|
||||
const topStore = renderer.props.topStore;
|
||||
topStore?.updateGlobalVarValue(path.substring(7), action.args.value);
|
||||
}
|
||||
|
||||
const beforeSetData = event?.context?.env?.beforeSetData;
|
||||
if (beforeSetData && typeof beforeSetData === 'function') {
|
||||
const res = await beforeSetData(renderer, action, event);
|
||||
|
||||
if (res === false) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 如果key没指定,则默认是当前组件
|
||||
const component = getTargetComponent(action, renderer, event, key);
|
||||
// 如果key指定了,但是没找到组件,则报错
|
||||
if (key && !component) {
|
||||
const msg = `尝试执行一个不存在的目标组件动作(${key}),请检查目标组件非隐藏状态,且正确指定了componentId或componentName`;
|
||||
|
||||
// cmpAction 可以容忍错误,除非 ignoreError 强制设置成了 false
|
||||
if (action.ignoreError === false) {
|
||||
throw Error(msg);
|
||||
} else {
|
||||
console.warn(msg);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (action.actionType === 'setValue') {
|
||||
if (component?.setData) {
|
||||
return component?.setData(
|
||||
action.args?.value,
|
||||
dataMergeMode === 'override',
|
||||
action.args?.index,
|
||||
action.args?.condition
|
||||
);
|
||||
} else {
|
||||
return component?.props.onChange?.(action.args?.value);
|
||||
}
|
||||
}
|
||||
|
||||
// 刷新
|
||||
if (action.actionType === 'reload') {
|
||||
const result = await component?.reload?.(
|
||||
undefined,
|
||||
action.data,
|
||||
event.data,
|
||||
undefined,
|
||||
dataMergeMode === 'override',
|
||||
{
|
||||
...action.args,
|
||||
resetPage: action.args?.resetPage ?? action.resetPage
|
||||
}
|
||||
);
|
||||
|
||||
if (result && action.outputVar) {
|
||||
event.setData(
|
||||
extendObject(event.data, {
|
||||
[action.outputVar]: result
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// 校验表单项
|
||||
if (
|
||||
action.actionType === 'validateFormItem' &&
|
||||
getRendererByName(component?.props?.type)?.isFormItem
|
||||
) {
|
||||
try {
|
||||
const valid =
|
||||
(await component?.props.onValidate?.()) && // wrapControl 里面的 validate 是,返回校验是否有问题
|
||||
!(await component?.validate?.()); // 组件里面的 validate 方法是,如果有问题返回错误信息,没有问题返回空
|
||||
|
||||
if (valid) {
|
||||
event.setData(
|
||||
createObject(event.data, {
|
||||
[action.outputVar || `${action.actionType}Result`]: {
|
||||
error: '',
|
||||
value: component?.props?.formItem?.value
|
||||
}
|
||||
})
|
||||
);
|
||||
} else {
|
||||
event.setData(
|
||||
createObject(event.data, {
|
||||
[action.outputVar || `${action.actionType}Result`]: {
|
||||
error:
|
||||
typeof valid === 'string'
|
||||
? valid
|
||||
: (component?.props?.formItem?.errors || []).join(','),
|
||||
value: component?.props?.formItem?.value
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
event.setData(
|
||||
createObject(event.data, {
|
||||
[action.outputVar || `${action.actionType}Result`]: {
|
||||
error: e.message || '未知错误',
|
||||
value: component?.props?.formItem?.value
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 执行组件动作
|
||||
try {
|
||||
const result = await component?.doAction?.(
|
||||
action,
|
||||
event.data,
|
||||
true,
|
||||
action.args
|
||||
);
|
||||
|
||||
if (['validate', 'submit'].includes(action.actionType)) {
|
||||
event.setData(
|
||||
createObject(event.data, {
|
||||
[action.outputVar || `${action.actionType}Result`]: {
|
||||
error: '',
|
||||
payload: result?.__payload ?? component?.props?.store?.data,
|
||||
responseData: result?.__response
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
return result;
|
||||
} catch (e) {
|
||||
event.setData(
|
||||
createObject(event.data, {
|
||||
[action.outputVar || `${action.actionType}Result`]: {
|
||||
error: e.message,
|
||||
errors: e.name === 'ValidateError' ? e.detail : e,
|
||||
payload: component?.props?.store?.data
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('component', new CmptAction());
|
||||
31
packages/amis-core/src/actions/ContinueAction.ts
Normal file
31
packages/amis-core/src/actions/ContinueAction.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { RendererEvent } from '../utils/renderer-event';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerContext,
|
||||
LoopStatus,
|
||||
registerAction,
|
||||
ILogicAction
|
||||
} from './Action';
|
||||
|
||||
export interface IContinueAction extends ILogicAction {
|
||||
actionType: 'continue';
|
||||
}
|
||||
|
||||
/**
|
||||
* continue
|
||||
*
|
||||
* @export
|
||||
* @class ContinueAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class ContinueAction implements RendererAction {
|
||||
async run(
|
||||
action: IContinueAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
renderer.loopStatus = LoopStatus.CONTINUE;
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('continue', new ContinueAction());
|
||||
43
packages/amis-core/src/actions/CopyAction.ts
Normal file
43
packages/amis-core/src/actions/CopyAction.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerAction,
|
||||
ListenerContext,
|
||||
registerAction
|
||||
} from './Action';
|
||||
|
||||
export interface ICopyAction extends ListenerAction {
|
||||
actionType: 'copy';
|
||||
args: {
|
||||
content: string;
|
||||
copyFormat?: string;
|
||||
[propName: string]: any;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制动作
|
||||
*
|
||||
* @export
|
||||
* @class CopyAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class CopyAction implements RendererAction {
|
||||
async run(
|
||||
action: ICopyAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
if (!event.context.env?.copy) {
|
||||
throw new Error('env.copy is required!');
|
||||
}
|
||||
|
||||
if (action.args?.content) {
|
||||
event.context.env?.copy?.(action.args.content, {
|
||||
format: action.args?.copyFormat
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('copy', new CopyAction());
|
||||
81
packages/amis-core/src/actions/CustomAction.ts
Normal file
81
packages/amis-core/src/actions/CustomAction.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import isPlainObject from 'lodash/isPlainObject';
|
||||
import {ActionObject} from '../types';
|
||||
import {promisify, str2AsyncFunction} from '../utils';
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerAction,
|
||||
ListenerContext,
|
||||
registerAction,
|
||||
runActions
|
||||
} from './Action';
|
||||
|
||||
type ScriptType =
|
||||
| string
|
||||
| ((
|
||||
renderer: any,
|
||||
doAction: (action: ActionObject, data: Record<string, any>) => void,
|
||||
event: RendererEvent<any>,
|
||||
action: ListenerAction
|
||||
) => void); // 自定义JS,actionType: custom
|
||||
|
||||
export interface ICustomAction extends ListenerAction {
|
||||
actionType: 'custom';
|
||||
args: {
|
||||
script: ScriptType;
|
||||
};
|
||||
script?: ScriptType; // 兼容历史
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义动作,JS脚本
|
||||
*
|
||||
* @export
|
||||
* @class CustomAction
|
||||
* @implements {ActionObject}
|
||||
*/
|
||||
export class CustomAction implements RendererAction {
|
||||
async run(
|
||||
action: ICustomAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
// 执行自定义编排脚本
|
||||
let scriptFunc = action.args?.script ?? action.script;
|
||||
|
||||
if (typeof scriptFunc === 'string') {
|
||||
scriptFunc = str2AsyncFunction(
|
||||
scriptFunc,
|
||||
'context',
|
||||
'doAction',
|
||||
'event'
|
||||
) as any;
|
||||
}
|
||||
const proxy = new Proxy(
|
||||
{},
|
||||
{
|
||||
get(target: {}, p: string | symbol, receiver: any): any {
|
||||
if (typeof p === 'string') {
|
||||
return event.context.scoped?.getComponentByName?.(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
// 外部可以直接调用doAction来完成动作调用
|
||||
// 可以通过上下文直接编排动作调用,通过event来进行动作干预
|
||||
let result = await (scriptFunc as any)?.call(
|
||||
proxy,
|
||||
renderer,
|
||||
(action: ListenerAction) => runActions(action, renderer, event),
|
||||
event,
|
||||
action
|
||||
);
|
||||
|
||||
// 交给外部处理
|
||||
// if (isPlainObject(result)) {
|
||||
// event.setData({...event.data, ...result});
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('custom', new CustomAction());
|
||||
258
packages/amis-core/src/actions/DialogAction.ts
Normal file
258
packages/amis-core/src/actions/DialogAction.ts
Normal file
@@ -0,0 +1,258 @@
|
||||
import {Schema, SchemaNode} from '../types';
|
||||
import {extendObject} from '../utils';
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import {filter} from '../utils/tpl';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerAction,
|
||||
ListenerContext,
|
||||
registerAction
|
||||
} from './Action';
|
||||
|
||||
export interface IAlertAction extends ListenerAction {
|
||||
actionType: 'alert';
|
||||
dialog?: Schema;
|
||||
// 兼容历史,保留。为了和其他弹窗保持一致
|
||||
args: {
|
||||
msg: string;
|
||||
[propName: string]: any;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IConfirmAction extends ListenerAction {
|
||||
actionType: 'confirm';
|
||||
args: {
|
||||
title: string;
|
||||
msg: string;
|
||||
[propName: string]: any;
|
||||
};
|
||||
}
|
||||
|
||||
export interface IDialogAction extends ListenerAction {
|
||||
actionType: 'dialog';
|
||||
// 兼容历史,保留。不建议用args
|
||||
args: {
|
||||
dialog: SchemaNode;
|
||||
};
|
||||
dialog?: SchemaNode;
|
||||
|
||||
/**
|
||||
* 是否等待确认结果
|
||||
*/
|
||||
waitForAction?: boolean;
|
||||
|
||||
/**
|
||||
* 如果等待结果,将弹窗结果保存到此处变量
|
||||
*/
|
||||
outputVar?: string;
|
||||
}
|
||||
|
||||
export interface IConfirmDialogAction extends ListenerAction {
|
||||
actionType: 'confirmDialog';
|
||||
dialog?: Schema;
|
||||
|
||||
// 兼容历史,保留。不建议用args
|
||||
args: {
|
||||
msg: string;
|
||||
title: string;
|
||||
body?: Schema;
|
||||
closeOnEsc?: boolean;
|
||||
size?: '' | 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'full';
|
||||
confirmText?: string;
|
||||
cancelText?: string;
|
||||
confirmBtnLevel?: string;
|
||||
cancelBtnLevel?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开弹窗动作
|
||||
*
|
||||
* @export
|
||||
* @class DialogAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class DialogAction implements RendererAction {
|
||||
async run(
|
||||
action: IDialogAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
// 防止editor preview模式下执行
|
||||
if ((action as any).$$id !== undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
let ret = renderer.handleAction
|
||||
? renderer.handleAction(
|
||||
event,
|
||||
{
|
||||
actionType: 'dialog',
|
||||
dialog: action.dialog,
|
||||
reload: 'none',
|
||||
data: action.rawData
|
||||
},
|
||||
action.data
|
||||
)
|
||||
: renderer.props.onAction?.(
|
||||
event,
|
||||
{
|
||||
actionType: 'dialog',
|
||||
dialog: action.dialog,
|
||||
reload: 'none',
|
||||
data: action.rawData
|
||||
},
|
||||
action.data
|
||||
);
|
||||
|
||||
event.pendingPromise.push(ret);
|
||||
if (action.waitForAction) {
|
||||
const {confirmed, value} = await ret;
|
||||
|
||||
event.setData(
|
||||
extendObject(event.data, {
|
||||
[action.outputVar || 'dialogResponse']: {
|
||||
confirmed,
|
||||
value
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface ICloseDialogAction extends ListenerAction {
|
||||
actionType: 'closeDialog';
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭弹窗动作
|
||||
*
|
||||
* @export
|
||||
* @class CloseDialogAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class CloseDialogAction implements RendererAction {
|
||||
async run(
|
||||
action: ListenerAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
// todo 支持 waitForAction,等待弹窗关闭后再执行后续动作
|
||||
if (action.componentId) {
|
||||
// 关闭指定弹窗
|
||||
event.context.scoped.closeById(action.componentId);
|
||||
} else {
|
||||
// 关闭当前弹窗
|
||||
renderer.props.onAction?.(
|
||||
event,
|
||||
{
|
||||
...action,
|
||||
actionType: 'close'
|
||||
},
|
||||
action.data
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* alert提示动作
|
||||
*/
|
||||
export class AlertAction implements RendererAction {
|
||||
async run(
|
||||
action: IAlertAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
event.context.env.alert?.(
|
||||
filter(action.dialog?.msg, event.data) ?? action.args?.msg,
|
||||
filter(action.dialog?.title, event.data) ?? action.args?.title,
|
||||
filter(action.dialog?.className, event.data) ?? ''
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* confirm确认提示动作
|
||||
*/
|
||||
export class ConfirmAction implements RendererAction {
|
||||
async run(
|
||||
action: IConfirmDialogAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
let modal: any = action.dialog ?? action.args;
|
||||
|
||||
if (modal.$ref && renderer.props.resolveDefinitions) {
|
||||
modal = {
|
||||
...renderer.props.resolveDefinitions(modal.$ref),
|
||||
...modal
|
||||
};
|
||||
}
|
||||
|
||||
const type = modal?.type;
|
||||
|
||||
if (!type) {
|
||||
const confirmed = await event.context.env.confirm?.(
|
||||
filter(modal?.msg, event.data) || action.args?.msg,
|
||||
filter(action.dialog?.title, event.data) || action.args?.title,
|
||||
{
|
||||
closeOnEsc:
|
||||
filter(action.dialog?.closeOnEsc, event.data) ||
|
||||
action.args?.closeOnEsc,
|
||||
size: filter(action.dialog?.size, event.data) || action.args?.size,
|
||||
confirmText:
|
||||
filter(action.dialog?.confirmText, event.data) ||
|
||||
action.args?.confirmText,
|
||||
cancelText:
|
||||
filter(action.dialog?.cancelText, event.data) ||
|
||||
action.args?.cancelText,
|
||||
confirmBtnLevel:
|
||||
filter(action.dialog?.confirmBtnLevel, event.data) ||
|
||||
action.args?.confirmBtnLevel,
|
||||
cancelBtnLevel:
|
||||
filter(action.dialog?.cancelBtnLevel, event.data) ||
|
||||
action.args?.cancelBtnLevel,
|
||||
className: filter(action.dialog?.className, event.data) || ''
|
||||
}
|
||||
);
|
||||
|
||||
return confirmed;
|
||||
}
|
||||
|
||||
// 自定义弹窗内容
|
||||
const confirmed = await new Promise((resolve, reject) => {
|
||||
renderer.handleAction
|
||||
? renderer.handleAction(
|
||||
event,
|
||||
{
|
||||
actionType: 'dialog',
|
||||
dialog: modal,
|
||||
data: action.rawData,
|
||||
reload: 'none',
|
||||
callback: (result: boolean) => resolve(result)
|
||||
},
|
||||
action.data
|
||||
)
|
||||
: renderer.props.onAction?.(
|
||||
event,
|
||||
{
|
||||
actionType: 'dialog',
|
||||
dialog: modal,
|
||||
data: action.rawData,
|
||||
reload: 'none',
|
||||
callback: (result: boolean) => resolve(result)
|
||||
},
|
||||
action.data
|
||||
);
|
||||
});
|
||||
|
||||
return confirmed;
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('dialog', new DialogAction());
|
||||
registerAction('closeDialog', new CloseDialogAction());
|
||||
registerAction('alert', new AlertAction());
|
||||
registerAction('confirmDialog', new ConfirmAction());
|
||||
117
packages/amis-core/src/actions/DrawerAction.ts
Normal file
117
packages/amis-core/src/actions/DrawerAction.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import {SchemaNode} from '../types';
|
||||
import {extendObject} from '../utils';
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerAction,
|
||||
ListenerContext,
|
||||
registerAction
|
||||
} from './Action';
|
||||
|
||||
export interface IDrawerAction extends ListenerAction {
|
||||
actionType: 'drawer';
|
||||
// 兼容历史,保留。不建议用args
|
||||
args: {
|
||||
drawer: SchemaNode;
|
||||
};
|
||||
drawer?: SchemaNode;
|
||||
|
||||
/**
|
||||
* 是否等待确认结果
|
||||
*/
|
||||
waitForAction?: boolean;
|
||||
|
||||
outputVar?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开抽屉动作
|
||||
*
|
||||
* @export
|
||||
* @class DrawerAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class DrawerAction implements RendererAction {
|
||||
async run(
|
||||
action: IDrawerAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
// 防止editor preview模式下执行
|
||||
if ((action as any).$$id !== undefined) {
|
||||
return;
|
||||
}
|
||||
let ret = renderer.handleAction
|
||||
? renderer.handleAction(
|
||||
event,
|
||||
{
|
||||
actionType: 'drawer',
|
||||
drawer: action.drawer,
|
||||
reload: 'none',
|
||||
data: action.rawData
|
||||
},
|
||||
action.data
|
||||
)
|
||||
: renderer.props.onAction?.(
|
||||
event,
|
||||
{
|
||||
actionType: 'drawer',
|
||||
drawer: action.drawer,
|
||||
reload: 'none',
|
||||
data: action.rawData
|
||||
},
|
||||
action.data
|
||||
);
|
||||
|
||||
event.pendingPromise.push(ret);
|
||||
if (action.waitForAction) {
|
||||
const {confirmed, value} = await ret;
|
||||
|
||||
event.setData(
|
||||
extendObject(event.data, {
|
||||
[action.outputVar || 'drawerResponse']: {
|
||||
confirmed,
|
||||
value
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface ICloseDrawerAction extends ListenerAction {
|
||||
actionType: 'closeDrawer';
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭抽屉动作
|
||||
*
|
||||
* @export
|
||||
* @class CloseDrawerAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class CloseDrawerAction implements RendererAction {
|
||||
async run(
|
||||
action: ListenerAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
if (action.componentId) {
|
||||
// 关闭指定抽屉
|
||||
event.context.scoped.closeById(action.componentId);
|
||||
} else {
|
||||
// 关闭当前抽屉
|
||||
renderer.props.onAction?.(
|
||||
event,
|
||||
{
|
||||
...action,
|
||||
actionType: 'close'
|
||||
},
|
||||
action.data
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('drawer', new DrawerAction());
|
||||
registerAction('closeDrawer', new CloseDrawerAction());
|
||||
45
packages/amis-core/src/actions/EmailAction.ts
Normal file
45
packages/amis-core/src/actions/EmailAction.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import pick from 'lodash/pick';
|
||||
import qs from 'qs';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerContext,
|
||||
registerAction,
|
||||
ListenerAction
|
||||
} from './Action';
|
||||
|
||||
export interface IEmailAction extends ListenerAction {
|
||||
actionType: 'email';
|
||||
args: {
|
||||
to: string;
|
||||
cc: string;
|
||||
bcc: string;
|
||||
subject: string;
|
||||
body: string;
|
||||
[propName: string]: any;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 邮件动作
|
||||
*
|
||||
* @export
|
||||
* @class EmailAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class EmailAction implements RendererAction {
|
||||
async run(
|
||||
action: IEmailAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
const mailTo = action.args?.to;
|
||||
const mailInfo = pick(action.args ?? {}, 'cc', 'bcc', 'subject', 'body');
|
||||
const mailStr = qs.stringify(mailInfo);
|
||||
const mailto = `mailto:${mailTo}?${mailStr}`;
|
||||
|
||||
window.open(mailto);
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('email', new EmailAction());
|
||||
63
packages/amis-core/src/actions/EventAction.ts
Normal file
63
packages/amis-core/src/actions/EventAction.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import {isExpression, resolveVariableAndFilterForAsync} from '../utils';
|
||||
import {cloneObject, setVariable} from '../utils/object';
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerContext,
|
||||
registerAction,
|
||||
ListenerAction
|
||||
} from './Action';
|
||||
|
||||
export interface IEventAction extends ListenerAction {
|
||||
actionType: 'setEventData' | 'preventDefault' | 'stopPropagation';
|
||||
args: {
|
||||
key?: string;
|
||||
value?: any;
|
||||
[propName: string]: any;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 事件本身相关动作
|
||||
*
|
||||
* @export
|
||||
* @class EventAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class EventAction implements RendererAction {
|
||||
async run(
|
||||
action: IEventAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
switch (action.actionType) {
|
||||
case 'setEventData':
|
||||
if (typeof action.args?.key === 'string') {
|
||||
const data = cloneObject(event.data);
|
||||
let value = action.args.value;
|
||||
|
||||
if (isExpression(value)) {
|
||||
value = await resolveVariableAndFilterForAsync(
|
||||
value,
|
||||
event.data,
|
||||
'| raw'
|
||||
);
|
||||
}
|
||||
|
||||
setVariable(data, action.args.key, value);
|
||||
event.setData(data);
|
||||
}
|
||||
break;
|
||||
case 'preventDefault':
|
||||
event.preventDefault();
|
||||
break;
|
||||
case 'stopPropagation':
|
||||
event.stopPropagation();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('setEventData', new EventAction());
|
||||
registerAction('preventDefault', new EventAction());
|
||||
registerAction('stopPropagation', new EventAction());
|
||||
75
packages/amis-core/src/actions/LinkAction.ts
Normal file
75
packages/amis-core/src/actions/LinkAction.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import {buildApi} from '../utils/api';
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import omit from 'lodash/omit';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerContext,
|
||||
registerAction,
|
||||
ListenerAction
|
||||
} from './Action';
|
||||
|
||||
export interface ILinkAction extends ListenerAction {
|
||||
actionType: 'link' | 'url' | 'jump';
|
||||
args: {
|
||||
link?: string;
|
||||
url?: string;
|
||||
blank?: boolean;
|
||||
params?: {
|
||||
[key: string]: string;
|
||||
};
|
||||
[propName: string]: any;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开页面动作
|
||||
*
|
||||
* @export
|
||||
* @class LinkAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class LinkAction implements RendererAction {
|
||||
async run(
|
||||
action: ILinkAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
if (!event.context.env?.jumpTo) {
|
||||
throw new Error('env.jumpTo is required!');
|
||||
}
|
||||
|
||||
let apiParams = {
|
||||
...(action.args?.params ?? {}),
|
||||
...(action.data ?? {})
|
||||
};
|
||||
|
||||
if (action?.actionType === 'link' && apiParams?.targetType) {
|
||||
// link动作新增打开方式targetType,buildApi不需要该参数
|
||||
delete apiParams.targetType;
|
||||
}
|
||||
|
||||
// 通过buildApi兼容较复杂的url情况
|
||||
let urlObj = buildApi(
|
||||
{
|
||||
url: (action.args?.url || action.args?.link) as string,
|
||||
method: 'get'
|
||||
},
|
||||
apiParams,
|
||||
{
|
||||
autoAppend: true
|
||||
}
|
||||
);
|
||||
|
||||
event.context.env?.jumpTo(
|
||||
urlObj.url,
|
||||
{
|
||||
actionType: action.actionType,
|
||||
type: 'button',
|
||||
...action.args
|
||||
},
|
||||
action.data ?? {}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('openlink', new LinkAction());
|
||||
86
packages/amis-core/src/actions/LoopAction.ts
Normal file
86
packages/amis-core/src/actions/LoopAction.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import {createObject} from '../utils/helper';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerContext,
|
||||
LoopStatus,
|
||||
registerAction,
|
||||
runActions,
|
||||
ILogicAction
|
||||
} from './Action';
|
||||
import {resolveVariable} from '../utils/tpl-builtin';
|
||||
|
||||
export interface ILoopAction extends ILogicAction {
|
||||
actionType: 'loop';
|
||||
args: {
|
||||
loopName: string;
|
||||
[propName: string]: any;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 循环动作
|
||||
*
|
||||
* @export
|
||||
* @class LoopAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class LoopAction implements RendererAction {
|
||||
async run(
|
||||
action: ILoopAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>,
|
||||
mergeData: any
|
||||
) {
|
||||
const loopName = action.args?.loopName;
|
||||
if (typeof loopName !== 'string') {
|
||||
console.error('loopName 必须是字符串类型');
|
||||
return;
|
||||
}
|
||||
|
||||
const loopData = resolveVariable(loopName, mergeData) || [];
|
||||
|
||||
// 必须是数组
|
||||
if (!loopData) {
|
||||
console.error(`没有找到数据 ${loopName}`);
|
||||
} else if (!Array.isArray(loopData)) {
|
||||
console.error(`${loopName} 数据不是数组`);
|
||||
} else if (action.children?.length) {
|
||||
// 暂存一下
|
||||
const protoData = event.data;
|
||||
|
||||
for (const data of loopData) {
|
||||
renderer.loopStatus = LoopStatus.NORMAL;
|
||||
// 追加逻辑处理中的数据,事件数据优先,用完还要还原
|
||||
event.setData(createObject(event.data, data));
|
||||
|
||||
for (const subAction of action.children) {
|
||||
// @ts-ignore
|
||||
if (renderer.loopStatus === LoopStatus.CONTINUE) {
|
||||
continue;
|
||||
}
|
||||
await runActions(subAction, renderer, event);
|
||||
|
||||
// @ts-ignore
|
||||
if (renderer.loopStatus === LoopStatus.BREAK || event.stoped) {
|
||||
// 还原事件数据
|
||||
event.setData(protoData);
|
||||
event.stopPropagation();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (event.stoped) {
|
||||
// 还原事件数据
|
||||
event.setData(protoData);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
renderer.loopStatus = LoopStatus.NORMAL;
|
||||
event.setData(protoData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('loop', new LoopAction());
|
||||
70
packages/amis-core/src/actions/PageAction.ts
Normal file
70
packages/amis-core/src/actions/PageAction.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerAction,
|
||||
ListenerContext,
|
||||
registerAction
|
||||
} from './Action';
|
||||
|
||||
export interface IPageGoAction extends ListenerAction {
|
||||
actionType: 'goBack' | 'refresh' | 'goPage';
|
||||
args: {
|
||||
delta?: number;
|
||||
[propName: string]: any;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回上个页面
|
||||
*
|
||||
* @export
|
||||
* @class PageGoBackAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class PageGoBackAction implements RendererAction {
|
||||
async run(
|
||||
action: IPageGoAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
window.history.back();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 到指定页面
|
||||
*
|
||||
* @export
|
||||
* @class PageGoAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class PageGoAction implements RendererAction {
|
||||
async run(
|
||||
action: IPageGoAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
window.history.go(action.args?.delta || 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 浏览器刷新
|
||||
*
|
||||
* @export
|
||||
* @class PageRefreshAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class PageRefreshAction implements RendererAction {
|
||||
async run(
|
||||
action: IPageGoAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
window.location.reload();
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('goBack', new PageGoBackAction());
|
||||
registerAction('refresh', new PageRefreshAction());
|
||||
registerAction('goPage', new PageGoAction());
|
||||
31
packages/amis-core/src/actions/ParallelAction.ts
Normal file
31
packages/amis-core/src/actions/ParallelAction.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { RendererEvent } from '../utils/renderer-event';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerContext,
|
||||
ILogicAction,
|
||||
LogicAction,
|
||||
registerAction,
|
||||
runActions
|
||||
} from './Action';
|
||||
|
||||
export interface IParallelAction extends ILogicAction {
|
||||
actionType: 'parallel';
|
||||
}
|
||||
|
||||
export class ParallelAction implements RendererAction {
|
||||
async run(
|
||||
action: IParallelAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
if (action.children && action.children.length) {
|
||||
const childActions = action.children.map((child: LogicAction) => {
|
||||
// 并行动作互不干扰,但不管哪个存在干预都对后续动作生效
|
||||
return runActions(child, renderer, event);
|
||||
});
|
||||
await Promise.all(childActions);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('parallel', new ParallelAction());
|
||||
58
packages/amis-core/src/actions/PrintAction.ts
Normal file
58
packages/amis-core/src/actions/PrintAction.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import {printElements} from '../utils/printElement';
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerAction,
|
||||
ListenerContext,
|
||||
registerAction
|
||||
} from './Action';
|
||||
|
||||
export interface IPrintAction extends ListenerAction {
|
||||
actionType: 'print';
|
||||
args: {
|
||||
id?: string;
|
||||
ids?: string[];
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 打印动作
|
||||
*
|
||||
* @export
|
||||
* @class PrintAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class PrintAction implements RendererAction {
|
||||
async run(
|
||||
action: IPrintAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
// 兼容之前的 word 打印
|
||||
if (action.componentId) {
|
||||
const targetComponent = event.context.scoped?.getComponentById(
|
||||
action.componentId
|
||||
);
|
||||
targetComponent?.doAction?.(action, event.data, true, action.args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action.args?.id) {
|
||||
const element = document.querySelector(`[data-id='${action.args.id}']`);
|
||||
if (element) {
|
||||
printElements([element]);
|
||||
}
|
||||
} else if (action.args?.ids) {
|
||||
const elements: Element[] = [];
|
||||
action.args.ids.forEach(id => {
|
||||
const element = document.querySelector(`[data-id='${id}']`);
|
||||
if (element) {
|
||||
elements.push(element);
|
||||
}
|
||||
});
|
||||
printElements(elements);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('print', new PrintAction());
|
||||
64
packages/amis-core/src/actions/StatusAction.ts
Normal file
64
packages/amis-core/src/actions/StatusAction.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerAction,
|
||||
ListenerContext,
|
||||
registerAction
|
||||
} from './Action';
|
||||
|
||||
export interface IStatusAction extends ListenerAction {
|
||||
actionType:
|
||||
| 'static'
|
||||
| 'nonstatic'
|
||||
| 'show'
|
||||
| 'visibility'
|
||||
| 'hidden'
|
||||
| 'enabled'
|
||||
| 'disabled'
|
||||
| 'usability';
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态更新动作
|
||||
*
|
||||
* @export
|
||||
* @class StatusAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class StatusAction implements RendererAction {
|
||||
async run(
|
||||
action: IStatusAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
/**
|
||||
* 根据唯一ID查找指定组件
|
||||
* 触发组件未指定id或未指定响应组件componentId,则使用触发组件响应
|
||||
*/
|
||||
const key = action.componentId || action.componentName;
|
||||
|
||||
// 显隐&状态控制
|
||||
if (['show', 'hidden', 'visibility'].includes(action.actionType)) {
|
||||
let visibility =
|
||||
action.actionType === 'visibility'
|
||||
? action.args?.value
|
||||
: action.actionType === 'show';
|
||||
return renderer.props.statusStore.setVisible(key!, visibility as any);
|
||||
} else if (['static', 'nonstatic'].includes(action.actionType)) {
|
||||
return renderer.props.statusStore.setStatic(
|
||||
key!,
|
||||
action.actionType === 'static'
|
||||
);
|
||||
} else if (
|
||||
['enabled', 'disabled', 'usability'].includes(action.actionType)
|
||||
) {
|
||||
let usability =
|
||||
action.actionType === 'usability'
|
||||
? !action.args?.value
|
||||
: action.actionType === 'disabled';
|
||||
return renderer.props.statusStore.setDisable(key!, usability);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('status', new StatusAction());
|
||||
44
packages/amis-core/src/actions/SwitchAction.ts
Normal file
44
packages/amis-core/src/actions/SwitchAction.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import {evalExpressionWithConditionBuilderAsync} from '../utils/tpl';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerContext,
|
||||
registerAction,
|
||||
runActions,
|
||||
ILogicAction
|
||||
} from './Action';
|
||||
|
||||
export interface ISwitchAction extends ILogicAction {
|
||||
actionType: 'switch';
|
||||
}
|
||||
|
||||
/**
|
||||
* 排他动作
|
||||
*/
|
||||
export class SwitchAction implements RendererAction {
|
||||
async run(
|
||||
action: ISwitchAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>,
|
||||
mergeData: any
|
||||
) {
|
||||
for (const branch of action.children || []) {
|
||||
if (!branch.expression) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const isPass = await evalExpressionWithConditionBuilderAsync(
|
||||
branch.expression,
|
||||
mergeData
|
||||
);
|
||||
|
||||
if (isPass) {
|
||||
await runActions(branch, renderer, event);
|
||||
// 去掉runAllMatch,这里只做排他,多个可以直接通过expression
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('switch', new SwitchAction());
|
||||
49
packages/amis-core/src/actions/ToastAction.ts
Normal file
49
packages/amis-core/src/actions/ToastAction.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerContext,
|
||||
registerAction,
|
||||
ListenerAction
|
||||
} from './Action';
|
||||
|
||||
export interface IToastAction extends ListenerAction {
|
||||
actionType: 'toast';
|
||||
args: {
|
||||
msg: string;
|
||||
msgType?: string;
|
||||
position?:
|
||||
| 'top-right'
|
||||
| 'top-center'
|
||||
| 'top-left'
|
||||
| 'bottom-center'
|
||||
| 'bottom-left'
|
||||
| 'bottom-right'
|
||||
| 'center';
|
||||
closeButton?: boolean;
|
||||
showIcon?: boolean;
|
||||
timeout?: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 全局toast
|
||||
*/
|
||||
export class ToastAction implements RendererAction {
|
||||
async run(
|
||||
action: IToastAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
if (!event.context.env?.notify) {
|
||||
throw new Error('env.notify is required!');
|
||||
}
|
||||
|
||||
event.context.env?.notify?.(
|
||||
action.args?.msgType || 'info',
|
||||
String(action.args?.msg),
|
||||
{...action.args, mobileUI: renderer.props.mobileUI}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('toast', new ToastAction());
|
||||
37
packages/amis-core/src/actions/WaitAction.ts
Normal file
37
packages/amis-core/src/actions/WaitAction.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import {RendererEvent} from '../utils/renderer-event';
|
||||
import {
|
||||
RendererAction,
|
||||
ListenerContext,
|
||||
registerAction,
|
||||
ListenerAction
|
||||
} from './Action';
|
||||
|
||||
export interface IWaitAction extends ListenerAction {
|
||||
actionType: 'wait';
|
||||
args: {
|
||||
time: number;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 事件本身相关动作
|
||||
*
|
||||
* @export
|
||||
* @class EventAction
|
||||
* @implements {Action}
|
||||
*/
|
||||
export class WaitAction implements RendererAction {
|
||||
async run(
|
||||
action: IWaitAction,
|
||||
renderer: ListenerContext,
|
||||
event: RendererEvent<any>
|
||||
) {
|
||||
const time = action.args?.time;
|
||||
|
||||
if (typeof time === 'number') {
|
||||
await new Promise(resolve => setTimeout(resolve, time));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerAction('wait', new WaitAction());
|
||||
26
packages/amis-core/src/actions/index.ts
Normal file
26
packages/amis-core/src/actions/index.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* @file 导入所有动作
|
||||
*/
|
||||
|
||||
import './LoopAction';
|
||||
import './BreakAction';
|
||||
import './ContinueAction';
|
||||
import './SwitchAction';
|
||||
import './ParallelAction';
|
||||
import './CustomAction';
|
||||
import './BroadcastAction';
|
||||
import './CmptAction';
|
||||
import './StatusAction';
|
||||
import './AjaxAction';
|
||||
import './CopyAction';
|
||||
import './DialogAction';
|
||||
import './DrawerAction';
|
||||
import './EmailAction';
|
||||
import './EventAction';
|
||||
import './LinkAction';
|
||||
import './ToastAction';
|
||||
import './WaitAction';
|
||||
import './PageAction';
|
||||
import './PrintAction';
|
||||
|
||||
export * from './Action';
|
||||
168
packages/amis-core/src/components/Animations.tsx
Normal file
168
packages/amis-core/src/components/Animations.tsx
Normal file
@@ -0,0 +1,168 @@
|
||||
import React, {useEffect, useMemo, useState, useCallback} from 'react';
|
||||
import {CSSTransition} from 'react-transition-group';
|
||||
import {Schema} from '../types';
|
||||
import {formateId} from '../utils';
|
||||
import {createAnimationStyle} from '../utils/animations';
|
||||
import styleManager from '../StyleManager';
|
||||
|
||||
function Animations({
|
||||
schema,
|
||||
component,
|
||||
show
|
||||
}: {
|
||||
schema: Schema;
|
||||
component: any;
|
||||
show: boolean;
|
||||
}) {
|
||||
const {enter} = schema.animations || {};
|
||||
const [animationShow, setAnimationShow] = useState(!enter?.inView);
|
||||
const [placeholderShow, setPlaceholderShow] = useState(!!enter?.inView);
|
||||
|
||||
const id = useMemo(() => formateId(schema.id), []);
|
||||
const observer = useMemo(newObserver, []);
|
||||
const animationClassNames = useMemo(initAnimationClassNames, []);
|
||||
const animationTimeout = useMemo(initAnimationTimeout, []);
|
||||
|
||||
useEffect(() => {
|
||||
createAnimationStyle(id, schema.animations!);
|
||||
return () => {
|
||||
if (schema.animations) {
|
||||
styleManager.removeStyles(id);
|
||||
}
|
||||
observer.disconnect();
|
||||
};
|
||||
}, []);
|
||||
|
||||
function newObserver() {
|
||||
return new IntersectionObserver(
|
||||
(entries, observer) => {
|
||||
entries.forEach(entry => {
|
||||
if (
|
||||
entry.target.getAttribute('data-role') === 'animation-placeholder'
|
||||
) {
|
||||
if (entry.isIntersecting) {
|
||||
setAnimationShow(true);
|
||||
setPlaceholderShow(false);
|
||||
observer.unobserve(entry.target);
|
||||
}
|
||||
} else {
|
||||
if (!entry.isIntersecting) {
|
||||
setAnimationShow(false);
|
||||
observer.unobserve(entry.target);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
{
|
||||
root: null,
|
||||
rootMargin: '0px',
|
||||
threshold: 0.1
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
function initAnimationClassNames() {
|
||||
const animations = schema?.animations;
|
||||
const animationClassNames = {
|
||||
appear: '',
|
||||
enter: '',
|
||||
exit: ''
|
||||
};
|
||||
if (animations) {
|
||||
if (animations.enter) {
|
||||
animationClassNames.enter = `${animations.enter.type}-${id}-enter`;
|
||||
animationClassNames.appear = animationClassNames.enter;
|
||||
}
|
||||
if (animations.exit) {
|
||||
animationClassNames.exit = `${animations.exit.type}-${id}-exit`;
|
||||
}
|
||||
}
|
||||
return animationClassNames;
|
||||
}
|
||||
|
||||
function initAnimationTimeout() {
|
||||
const animations = schema?.animations;
|
||||
const animationTimeout = {
|
||||
enter: 0,
|
||||
exit: 0
|
||||
};
|
||||
if (animations) {
|
||||
if (animations.enter) {
|
||||
animationTimeout.enter =
|
||||
((animations.enter.duration || 1) + (animations.enter.delay || 0)) *
|
||||
1000;
|
||||
}
|
||||
if (animations.exit) {
|
||||
animationTimeout.exit =
|
||||
((animations.exit.duration || 1) + (animations.exit.delay || 0)) *
|
||||
1000;
|
||||
}
|
||||
}
|
||||
return animationTimeout;
|
||||
}
|
||||
|
||||
function refFn(ref: HTMLElement | null) {
|
||||
if (ref) {
|
||||
observer.observe(ref);
|
||||
}
|
||||
}
|
||||
|
||||
const handleEntered = useCallback((node: HTMLElement) => {
|
||||
const {attention, exit, enter, hover} = schema.animations || {};
|
||||
if (attention) {
|
||||
node.classList.add(`${attention.type}-${id}-attention`);
|
||||
}
|
||||
|
||||
if (hover) {
|
||||
node.classList.add(`${hover.type}-${id}-hover`);
|
||||
node.classList.add(`amis-${hover.type}`);
|
||||
}
|
||||
|
||||
if (exit?.outView || enter?.repeat) {
|
||||
observer.observe(node);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleExit = useCallback((node: HTMLElement) => {
|
||||
const {attention, hover} = schema.animations || {};
|
||||
if (attention) {
|
||||
node.classList.remove(`${attention.type}-${id}-attention`);
|
||||
}
|
||||
if (hover) {
|
||||
node.classList.remove(`${hover.type}-${id}-hover`);
|
||||
node.classList.remove(`amis-${hover.type}`);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleExited = useCallback(() => {
|
||||
setPlaceholderShow(true);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
{!animationShow && show && placeholderShow && (
|
||||
<div
|
||||
ref={refFn}
|
||||
className="amis-animation-placeholder"
|
||||
data-role="animation-placeholder"
|
||||
>
|
||||
{component}
|
||||
</div>
|
||||
)}
|
||||
<CSSTransition
|
||||
in={animationShow && show}
|
||||
timeout={animationTimeout}
|
||||
classNames={animationClassNames}
|
||||
onEntered={handleEntered}
|
||||
onExit={handleExit}
|
||||
onExited={handleExited}
|
||||
appear
|
||||
unmountOnExit
|
||||
>
|
||||
{component}
|
||||
</CSSTransition>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default Animations;
|
||||
90
packages/amis-core/src/components/CustomStyle.tsx
Normal file
90
packages/amis-core/src/components/CustomStyle.tsx
Normal file
@@ -0,0 +1,90 @@
|
||||
import {useEffect, useRef} from 'react';
|
||||
import type {RendererEnv} from '../env';
|
||||
import {
|
||||
removeCustomStyle,
|
||||
type InsertCustomStyle,
|
||||
insertCustomStyle,
|
||||
insertEditCustomStyle
|
||||
} from '../utils/style-helper';
|
||||
|
||||
interface CustomStyleProps {
|
||||
config: {
|
||||
wrapperCustomStyle?: any;
|
||||
componentId?: string;
|
||||
} & InsertCustomStyle;
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
export const styleIdCount = new Map();
|
||||
|
||||
export default function (props: CustomStyleProps) {
|
||||
const {config, env, data} = props;
|
||||
const {themeCss, classNames, defaultData, wrapperCustomStyle} = config;
|
||||
const id = config.id ? `${config.id}` : config.id;
|
||||
|
||||
useEffect(() => {
|
||||
if (styleIdCount.has(id)) {
|
||||
styleIdCount.set(id, styleIdCount.get(id) + 1);
|
||||
} else if (id) {
|
||||
styleIdCount.set(id, 1);
|
||||
}
|
||||
return () => {
|
||||
if (styleIdCount.has(id)) {
|
||||
styleIdCount.set(id, styleIdCount.get(id) - 1);
|
||||
if (styleIdCount.get(id) === 0) {
|
||||
styleIdCount.delete(id);
|
||||
}
|
||||
}
|
||||
};
|
||||
}, [id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (themeCss && id) {
|
||||
insertCustomStyle({
|
||||
themeCss,
|
||||
classNames,
|
||||
id,
|
||||
defaultData,
|
||||
customStyleClassPrefix: env?.customStyleClassPrefix,
|
||||
doc: env?.getModalContainer?.()?.ownerDocument,
|
||||
data
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (id && !styleIdCount.get(id)) {
|
||||
removeCustomStyle(
|
||||
'',
|
||||
id,
|
||||
env?.getModalContainer?.()?.ownerDocument,
|
||||
data
|
||||
);
|
||||
}
|
||||
};
|
||||
}, [themeCss, id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (wrapperCustomStyle && id) {
|
||||
insertEditCustomStyle({
|
||||
customStyle: wrapperCustomStyle,
|
||||
id,
|
||||
customStyleClassPrefix: env?.customStyleClassPrefix,
|
||||
doc: env?.getModalContainer?.()?.ownerDocument,
|
||||
data
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (id && !styleIdCount.get(id)) {
|
||||
removeCustomStyle(
|
||||
'wrapperCustomStyle',
|
||||
id,
|
||||
env?.getModalContainer?.()?.ownerDocument,
|
||||
data
|
||||
);
|
||||
}
|
||||
};
|
||||
}, [wrapperCustomStyle, id]);
|
||||
|
||||
return null;
|
||||
}
|
||||
58
packages/amis-core/src/components/ErrorBoundary.tsx
Normal file
58
packages/amis-core/src/components/ErrorBoundary.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* @file ErrorBoundary
|
||||
* @description 捕获发生在其子组件树任何位置的 JavaScript 错误,并打印这些错误
|
||||
* @author wibetter
|
||||
*/
|
||||
import React from 'react';
|
||||
|
||||
interface ErrorBoundaryProps {
|
||||
// 自定义错误信息,控制台输出
|
||||
customErrorMsg?: string;
|
||||
fallback?: () => void;
|
||||
children: any;
|
||||
}
|
||||
|
||||
interface ErrorBoundaryStates {
|
||||
hasError: boolean;
|
||||
}
|
||||
|
||||
export default class ErrorBoundary extends React.Component<
|
||||
ErrorBoundaryProps,
|
||||
ErrorBoundaryStates
|
||||
> {
|
||||
constructor(props: any) {
|
||||
super(props);
|
||||
this.state = {hasError: false};
|
||||
}
|
||||
|
||||
componentDidCatch(error: any, errorInfo: any) {
|
||||
const {customErrorMsg} = this.props;
|
||||
if (customErrorMsg) {
|
||||
console.warn(customErrorMsg);
|
||||
}
|
||||
|
||||
console.warn('错误对象:', error);
|
||||
console.warn('错误信息:', errorInfo);
|
||||
this.setState({
|
||||
hasError: true
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
const {fallback} = this.props;
|
||||
if (this.state.hasError) {
|
||||
if (fallback) {
|
||||
return fallback();
|
||||
}
|
||||
|
||||
// 默认渲染错误信息
|
||||
return (
|
||||
<div className="renderer-error-boundary">
|
||||
渲染发生错误,详细错误信息请查看控制台输出。
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
158
packages/amis-core/src/components/LazyComponent.tsx
Normal file
158
packages/amis-core/src/components/LazyComponent.tsx
Normal file
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* @file LazyComponent
|
||||
* @description
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {InView} from 'react-intersection-observer';
|
||||
import {themeable, ThemeProps} from '../theme';
|
||||
|
||||
export interface LazyComponentProps extends ThemeProps {
|
||||
component?: React.ElementType;
|
||||
getComponent?: () => Promise<React.ElementType>;
|
||||
placeholder?: React.ReactNode;
|
||||
unMountOnHidden?: boolean;
|
||||
childProps?: object;
|
||||
defaultVisible?: boolean;
|
||||
className?: string;
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
export interface LazyComponentState {
|
||||
visible: boolean;
|
||||
component?: React.ElementType;
|
||||
}
|
||||
|
||||
export class LazyComponent extends React.Component<
|
||||
LazyComponentProps,
|
||||
LazyComponentState
|
||||
> {
|
||||
static defaultProps = {
|
||||
placeholder: <span>Loading...</span>,
|
||||
unMountOnHidden: false,
|
||||
partialVisibility: true
|
||||
};
|
||||
|
||||
mounted: boolean = false;
|
||||
constructor(props: LazyComponentProps) {
|
||||
super(props);
|
||||
|
||||
this.handleVisibleChange = this.handleVisibleChange.bind(this);
|
||||
this.mounted = true;
|
||||
|
||||
this.state = {
|
||||
visible: props.defaultVisible ?? false,
|
||||
component: props.component as React.ElementType
|
||||
};
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
// jest 里面有点异常,先手动让它总是可见
|
||||
if (typeof jest !== 'undefined' || this.state.visible) {
|
||||
this.handleVisibleChange(true);
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.mounted = false;
|
||||
}
|
||||
|
||||
handleVisibleChange(visible: boolean, entry?: any) {
|
||||
this.setState({
|
||||
visible: visible
|
||||
});
|
||||
|
||||
if (!visible || this.state.component || !this.props.getComponent) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.props
|
||||
.getComponent()
|
||||
.then(
|
||||
component =>
|
||||
this.mounted &&
|
||||
typeof component === 'function' &&
|
||||
this.setState({
|
||||
component: component
|
||||
})
|
||||
)
|
||||
.catch(
|
||||
reason =>
|
||||
this.mounted &&
|
||||
this.setState({
|
||||
component: () => (
|
||||
<div className="alert alert-danger">{String(reason)}</div>
|
||||
)
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
render(): React.ReactNode {
|
||||
const {
|
||||
placeholder,
|
||||
unMountOnHidden,
|
||||
childProps,
|
||||
partialVisibility,
|
||||
children,
|
||||
className,
|
||||
...rest
|
||||
} = this.props;
|
||||
const cx = this.props.classnames;
|
||||
|
||||
const {visible, component: Component} = this.state;
|
||||
|
||||
// 需要监听从可见到不可见。
|
||||
if (unMountOnHidden) {
|
||||
return (
|
||||
<InView
|
||||
onChange={this.handleVisibleChange}
|
||||
threshold={partialVisibility ? 0 : 1}
|
||||
>
|
||||
{({ref}) => {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={`visibility-sensor ${visible ? 'in' : ''}`}
|
||||
>
|
||||
{Component && visible ? (
|
||||
<Component {...rest} {...childProps} />
|
||||
) : children && visible ? (
|
||||
children
|
||||
) : (
|
||||
placeholder
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
</InView>
|
||||
);
|
||||
}
|
||||
|
||||
if (!visible) {
|
||||
return (
|
||||
<InView
|
||||
onChange={this.handleVisibleChange}
|
||||
threshold={partialVisibility ? 0 : 1}
|
||||
>
|
||||
{({ref}) => (
|
||||
<div ref={ref} className="visibility-sensor">
|
||||
{placeholder}
|
||||
</div>
|
||||
)}
|
||||
</InView>
|
||||
);
|
||||
} else if (Component) {
|
||||
// 只监听不可见到可见,一旦可见了,就销毁检查。
|
||||
return <Component {...rest} {...childProps} />;
|
||||
} else if (children) {
|
||||
return children;
|
||||
}
|
||||
|
||||
return <div className={cx('LazyComponent', className)}>{placeholder}</div>;
|
||||
}
|
||||
}
|
||||
|
||||
const themedLazyComponent = themeable(LazyComponent);
|
||||
(themedLazyComponent as any).defaultProps = LazyComponent.defaultProps;
|
||||
export default themedLazyComponent;
|
||||
380
packages/amis-core/src/components/Overlay.tsx
Normal file
380
packages/amis-core/src/components/Overlay.tsx
Normal file
@@ -0,0 +1,380 @@
|
||||
/**
|
||||
* @file Overlay
|
||||
* @description
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import Portal from 'react-overlays/Portal';
|
||||
import classNames from 'classnames';
|
||||
import ReactDOM, {findDOMNode} from 'react-dom';
|
||||
import React, {cloneElement} from 'react';
|
||||
import {
|
||||
autobind,
|
||||
calculatePosition,
|
||||
getComputedStyle,
|
||||
getContainer,
|
||||
getScrollParent,
|
||||
noop,
|
||||
ownerDocument,
|
||||
resizeSensor,
|
||||
RootClose,
|
||||
uuid
|
||||
} from '../utils';
|
||||
import {EnvContext} from '../env';
|
||||
|
||||
export const SubPopoverDisplayedID = 'data-sub-popover-displayed';
|
||||
|
||||
function onScroll(elem: HTMLElement, callback: () => void) {
|
||||
const handler = () => {
|
||||
requestAnimationFrame(callback);
|
||||
};
|
||||
elem.addEventListener('scroll', handler);
|
||||
return function () {
|
||||
elem.removeEventListener('scroll', handler);
|
||||
};
|
||||
}
|
||||
|
||||
class Position extends React.Component<any, any> {
|
||||
props: any;
|
||||
_lastTarget: any;
|
||||
resizeDispose: Array<() => void>;
|
||||
watchedTarget: any;
|
||||
parentPopover: any;
|
||||
// setState: (state: any) => void;
|
||||
componentId: string;
|
||||
overlay: HTMLDivElement;
|
||||
|
||||
static defaultProps = {
|
||||
containerPadding: 0,
|
||||
placement: 'right',
|
||||
shouldUpdatePosition: false
|
||||
};
|
||||
|
||||
constructor(props: any) {
|
||||
super(props);
|
||||
|
||||
this.state = {
|
||||
ready: false,
|
||||
positionLeft: 0,
|
||||
positionTop: 0,
|
||||
arrowOffsetLeft: null,
|
||||
arrowOffsetTop: null
|
||||
};
|
||||
|
||||
this._lastTarget = null;
|
||||
this.componentId = uuid();
|
||||
}
|
||||
|
||||
updatePosition(target: any) {
|
||||
this._lastTarget = target;
|
||||
|
||||
/** 标记宿主元素的PopOver祖先,用于后续判断PopOver 是否可以 root close */
|
||||
if (target) {
|
||||
const parentPopover = target?.closest?.('[role=popover]');
|
||||
|
||||
if (!this.parentPopover && parentPopover) {
|
||||
this.parentPopover = parentPopover;
|
||||
this.parentPopover.setAttribute(
|
||||
SubPopoverDisplayedID + '-' + this.componentId,
|
||||
true
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (!target || !target.offsetWidth) {
|
||||
// 靠这个 re-render 来重置 position
|
||||
return this.setState({});
|
||||
}
|
||||
|
||||
const watchTargetSizeChange = this.props.watchTargetSizeChange;
|
||||
const overlay = this.overlay;
|
||||
const container = getContainer(
|
||||
this.props.container,
|
||||
ownerDocument(this).body
|
||||
);
|
||||
|
||||
if (!this.watchedTarget || this.watchedTarget !== target) {
|
||||
this.resizeDispose?.forEach(fn => fn());
|
||||
this.watchedTarget = target;
|
||||
this.resizeDispose = [
|
||||
watchTargetSizeChange !== false
|
||||
? resizeSensor(target, () => this.updatePosition(target))
|
||||
: noop,
|
||||
resizeSensor(overlay, () => this.updatePosition(target))
|
||||
];
|
||||
|
||||
const scrollParent = getScrollParent(target);
|
||||
if (scrollParent && container.contains(scrollParent)) {
|
||||
this.resizeDispose.push(
|
||||
onScroll(scrollParent, () => {
|
||||
this.updatePosition(target);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
this.setState({
|
||||
...calculatePosition(
|
||||
this.props.placement,
|
||||
overlay,
|
||||
target,
|
||||
container,
|
||||
this.props.containerPadding,
|
||||
this.props.offset
|
||||
),
|
||||
ready: true
|
||||
});
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this.overlay = findDOMNode(this) as HTMLDivElement;
|
||||
this.updatePosition(this.getTarget());
|
||||
}
|
||||
|
||||
getTarget = () => {
|
||||
const {target} = this.props;
|
||||
const targetElement = typeof target === 'function' ? target() : target;
|
||||
return (targetElement && ReactDOM.findDOMNode(targetElement)) || null;
|
||||
};
|
||||
|
||||
componentDidUpdate(prevProps: any) {
|
||||
this.maybeUpdatePosition(this.props.placement !== prevProps.placement);
|
||||
}
|
||||
|
||||
maybeUpdatePosition = (placementChanged: any) => {
|
||||
const target = this.getTarget();
|
||||
|
||||
if (
|
||||
!this.props.shouldUpdatePosition &&
|
||||
target === this._lastTarget &&
|
||||
!placementChanged
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.updatePosition(target);
|
||||
};
|
||||
|
||||
componentWillUnmount() {
|
||||
// 一个 PopOver 关闭时,需把挂载父 PopOver 的标记去掉
|
||||
// 这里可能会存在多个子 PopOver 的情况,所以需要加上 componentId
|
||||
if (
|
||||
this.parentPopover &&
|
||||
this.parentPopover.getAttribute(
|
||||
SubPopoverDisplayedID + '-' + this.componentId
|
||||
)
|
||||
) {
|
||||
this.parentPopover.removeAttribute(
|
||||
SubPopoverDisplayedID + '-' + this.componentId
|
||||
);
|
||||
this.parentPopover = null;
|
||||
}
|
||||
|
||||
this.resizeDispose?.forEach(fn => fn());
|
||||
}
|
||||
|
||||
render() {
|
||||
const {children, className, ...props} = this.props;
|
||||
const {ready, positionLeft, positionTop, ...arrowPosition} = this.state;
|
||||
|
||||
// These should not be forwarded to the child.
|
||||
delete props.target;
|
||||
delete props.container;
|
||||
delete props.containerPadding;
|
||||
delete props.shouldUpdatePosition;
|
||||
|
||||
const child = React.Children.only(children);
|
||||
return cloneElement(child, {
|
||||
...props,
|
||||
...arrowPosition,
|
||||
// 防止 child offset 被 Overlay offset 覆盖
|
||||
...(child.props.offset ? {offset: child.props.offset} : {}),
|
||||
// FIXME: Don't forward `positionLeft` and `positionTop` via both props
|
||||
// and `props.style`.
|
||||
positionLeft,
|
||||
positionTop,
|
||||
className: classNames(className, child.props.className),
|
||||
style: {
|
||||
...child.props.style,
|
||||
left: positionLeft,
|
||||
top: positionTop,
|
||||
visibility: ready ? undefined : 'hidden'
|
||||
},
|
||||
componentId: this.componentId
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
interface OverlayProps {
|
||||
placement?: string;
|
||||
show?: boolean;
|
||||
transition?: React.ElementType;
|
||||
containerPadding?: number;
|
||||
children?: any;
|
||||
shouldUpdatePosition?: boolean;
|
||||
rootClose?: boolean;
|
||||
onHide?(props: any, ...args: any[]): any;
|
||||
container?:
|
||||
| HTMLElement
|
||||
| React.ReactNode
|
||||
| (() => HTMLElement | React.ReactNode | null | undefined);
|
||||
containerSelector?: string;
|
||||
target?: React.ReactNode | HTMLElement | Function;
|
||||
watchTargetSizeChange?: boolean;
|
||||
offset?: [number, number];
|
||||
onEnter?(node: HTMLElement): any;
|
||||
onEntering?(node: HTMLElement): any;
|
||||
onEntered?(node: HTMLElement): any;
|
||||
onExit?(node: HTMLElement): any;
|
||||
onExiting?(node: HTMLElement): any;
|
||||
onExited?(node: HTMLElement): any;
|
||||
}
|
||||
interface OverlayState {
|
||||
exited: boolean;
|
||||
}
|
||||
export default class Overlay extends React.Component<
|
||||
OverlayProps,
|
||||
OverlayState
|
||||
> {
|
||||
static defaultProps = {
|
||||
placement: 'auto'
|
||||
};
|
||||
static contextType = EnvContext;
|
||||
declare context: React.ContextType<typeof EnvContext>;
|
||||
constructor(props: OverlayProps) {
|
||||
super(props as any);
|
||||
|
||||
this.state = {
|
||||
exited: !props.show
|
||||
};
|
||||
}
|
||||
|
||||
position: any = null;
|
||||
positionRef = (position: any) => {
|
||||
this.position = position;
|
||||
};
|
||||
|
||||
updatePosition() {
|
||||
this.position?.maybeUpdatePosition(true);
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: OverlayProps, prevState: OverlayState) {
|
||||
const props = this.props;
|
||||
if (prevProps.show !== props.show && props.show) {
|
||||
this.setState({exited: false});
|
||||
} else if (props.transition !== prevProps.transition && !props.transition) {
|
||||
// Otherwise let handleHidden take care of marking exited.
|
||||
this.setState({exited: true});
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
onHiddenListener(node: HTMLElement) {
|
||||
this.setState({exited: true});
|
||||
|
||||
if (this.props.onExited) {
|
||||
this.props.onExited(node);
|
||||
}
|
||||
}
|
||||
|
||||
@autobind
|
||||
getContainerSelector() {
|
||||
const containerSelector = this.props.containerSelector;
|
||||
let container = null;
|
||||
|
||||
if (typeof containerSelector === 'string') {
|
||||
container = document.querySelector(containerSelector);
|
||||
}
|
||||
|
||||
return container;
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
containerPadding,
|
||||
target,
|
||||
placement,
|
||||
shouldUpdatePosition,
|
||||
rootClose,
|
||||
children,
|
||||
watchTargetSizeChange,
|
||||
transition: Transition,
|
||||
offset,
|
||||
...props
|
||||
} = this.props;
|
||||
const container =
|
||||
(this.getContainerSelector()
|
||||
? this.getContainerSelector
|
||||
: this.props.container) || this.context?.getModalContainer;
|
||||
const mountOverlay = props.show || (Transition && !this.state.exited);
|
||||
if (!mountOverlay) {
|
||||
// Don't bother showing anything if we don't have to.
|
||||
return null;
|
||||
}
|
||||
|
||||
let child = children;
|
||||
|
||||
// Position is be inner-most because it adds inline styles into the child,
|
||||
// which the other wrappers don't forward correctly.
|
||||
child = (
|
||||
// @ts-ignore
|
||||
<Position
|
||||
{...{
|
||||
container,
|
||||
containerPadding,
|
||||
target,
|
||||
placement,
|
||||
shouldUpdatePosition,
|
||||
offset
|
||||
}}
|
||||
ref={this.positionRef}
|
||||
>
|
||||
{child}
|
||||
</Position>
|
||||
);
|
||||
|
||||
if (Transition) {
|
||||
let {onExit, onExiting, onEnter, onEntering, onEntered} = props;
|
||||
|
||||
// This animates the child node by injecting props, so it must precede
|
||||
// anything that adds a wrapping div.
|
||||
child = (
|
||||
<Transition
|
||||
in={props.show}
|
||||
appear
|
||||
onExit={onExit}
|
||||
onExiting={onExiting}
|
||||
onExited={this.onHiddenListener}
|
||||
onEnter={onEnter}
|
||||
onEntering={onEntering}
|
||||
onEntered={onEntered}
|
||||
>
|
||||
{child}
|
||||
</Transition>
|
||||
);
|
||||
}
|
||||
|
||||
// This goes after everything else because it adds a wrapping div.
|
||||
if (rootClose) {
|
||||
return (
|
||||
// @ts-ignore
|
||||
<Portal container={container}>
|
||||
<RootClose onRootClose={props.onHide}>
|
||||
{(ref: any) => {
|
||||
if (React.isValidElement(child)) {
|
||||
return React.cloneElement(child as React.ReactElement, {
|
||||
ref: ref
|
||||
});
|
||||
}
|
||||
|
||||
return <div ref={ref}>{child}</div>;
|
||||
}}
|
||||
</RootClose>
|
||||
</Portal>
|
||||
);
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
return <Portal container={container}>{child}</Portal>;
|
||||
}
|
||||
}
|
||||
254
packages/amis-core/src/components/PopOver.tsx
Normal file
254
packages/amis-core/src/components/PopOver.tsx
Normal file
@@ -0,0 +1,254 @@
|
||||
/**
|
||||
* @file PopOver
|
||||
* @description
|
||||
* @author fex
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {findDOMNode} from 'react-dom';
|
||||
import {ClassNamesFn, themeable} from '../theme';
|
||||
import {autobind, camel, preventDefault, TestIdBuilder} from '../utils';
|
||||
import {SubPopoverDisplayedID} from './Overlay';
|
||||
|
||||
export interface Offset {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export interface PopOverProps {
|
||||
className?: string;
|
||||
placement?: string;
|
||||
positionTop?: number;
|
||||
positionLeft?: number;
|
||||
arrowOffsetLeft?: number;
|
||||
arrowOffsetTop?: number;
|
||||
offset?: ((clip: object, offset: object) => Offset) | Offset;
|
||||
style?: object;
|
||||
overlay?: boolean;
|
||||
onHide?: () => void;
|
||||
onClick?: (e: React.MouseEvent<any>) => void;
|
||||
classPrefix: string;
|
||||
classnames: ClassNamesFn;
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
interface PopOverState {
|
||||
xOffset: number;
|
||||
yOffset: number;
|
||||
}
|
||||
|
||||
export class PopOver extends React.PureComponent<PopOverProps, PopOverState> {
|
||||
static defaultProps = {
|
||||
className: '',
|
||||
offset: {
|
||||
x: 0,
|
||||
y: 0
|
||||
},
|
||||
overlay: false,
|
||||
placement: 'auto'
|
||||
};
|
||||
|
||||
state = {
|
||||
xOffset: 0,
|
||||
yOffset: 0
|
||||
};
|
||||
|
||||
parent: HTMLElement;
|
||||
wrapperRef: React.RefObject<HTMLDivElement> = React.createRef();
|
||||
isRootClosed = false;
|
||||
|
||||
componentDidMount() {
|
||||
this.mayUpdateOffset();
|
||||
const dom = findDOMNode(this) as HTMLElement;
|
||||
this.parent = dom.parentNode as HTMLElement;
|
||||
this.parent.classList.add('has-popover');
|
||||
|
||||
if (this.wrapperRef && this.wrapperRef.current) {
|
||||
// https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/addEventListener#使用_passive_改善的滚屏性能
|
||||
this.wrapperRef.current.addEventListener('touchmove', preventDefault, {
|
||||
passive: false,
|
||||
capture: false
|
||||
});
|
||||
}
|
||||
|
||||
// 从弹窗中处理复制过来的,如果要修改,请同步修改
|
||||
// 因为 overlay 功能其实是用 postion: fixed 来实现的
|
||||
// 目的是加一个蒙层监听蒙层点击然后关闭弹窗。意图就是 closeOnOutside
|
||||
// 但是如果上层有个 translateZ 之类的样式就会影响 fixed 的定位,导致功能失效
|
||||
// 所以这里兜底加了个 closeOnOutside 的功能
|
||||
document.body.addEventListener(
|
||||
'mousedown',
|
||||
this.handleRootMouseDownCapture,
|
||||
true
|
||||
);
|
||||
document.body.addEventListener(
|
||||
'mouseup',
|
||||
this.handleRootMouseUpCapture,
|
||||
true
|
||||
);
|
||||
document.body.addEventListener('mouseup', this.handleRootMouseUp);
|
||||
}
|
||||
|
||||
componentDidUpdate() {
|
||||
this.mayUpdateOffset();
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.parent && this.parent.classList.remove('has-popover');
|
||||
|
||||
if (this.wrapperRef && this.wrapperRef.current) {
|
||||
this.wrapperRef.current.removeEventListener('touchmove', preventDefault);
|
||||
}
|
||||
|
||||
document.body.removeEventListener('mouseup', this.handleRootMouseUp);
|
||||
document.body.removeEventListener(
|
||||
'mousedown',
|
||||
this.handleRootMouseDownCapture,
|
||||
true
|
||||
);
|
||||
document.body.removeEventListener(
|
||||
'mouseup',
|
||||
this.handleRootMouseUpCapture,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleRootMouseDownCapture(e: MouseEvent) {
|
||||
const target = e.target as HTMLElement;
|
||||
const {overlay: closeOnOutside, classPrefix: ns} = this.props;
|
||||
const isLeftButton =
|
||||
(e.button === 1 && window.event !== null) || e.button === 0;
|
||||
|
||||
this.isRootClosed = !!(
|
||||
isLeftButton &&
|
||||
closeOnOutside &&
|
||||
target &&
|
||||
this.wrapperRef.current &&
|
||||
// 要可见,不可见就不处理了,通常是打开了新页签
|
||||
this.wrapperRef.current.offsetHeight &&
|
||||
!this.wrapperRef.current
|
||||
.getAttributeNames()
|
||||
.find(n => n.startsWith(SubPopoverDisplayedID)) &&
|
||||
((!this.wrapperRef.current.contains(target) &&
|
||||
!target.closest('[role=dialog]')) ||
|
||||
(target.matches(`.${ns}Modal`) && target === this.wrapperRef.current))
|
||||
); // 干脆过滤掉来自弹框里面的点击
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleRootMouseUpCapture(e: MouseEvent) {
|
||||
// mousedown 的时候不在弹窗里面,则不需要判断了
|
||||
if (!this.isRootClosed) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 再判断 mouseup 的时候是不是在弹窗里面
|
||||
this.handleRootMouseDownCapture(e);
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleRootMouseUp(e: MouseEvent) {
|
||||
const {onHide} = this.props;
|
||||
if (this.isRootClosed && !e.defaultPrevented) {
|
||||
// 因为原来 overlay 是不会让别的部分还有点击事件的,所以这里要阻止默认事件
|
||||
// 参考:https://stackoverflow.com/questions/8643739/cancel-click-event-in-the-mouseup-event-handler
|
||||
let captureClick = (e: Event) => {
|
||||
e.stopPropagation();
|
||||
window.removeEventListener('click', captureClick, true);
|
||||
};
|
||||
window.addEventListener('click', captureClick, true);
|
||||
onHide?.();
|
||||
}
|
||||
}
|
||||
|
||||
mayUpdateOffset() {
|
||||
let offset: Offset;
|
||||
let getOffset = this.props.offset;
|
||||
|
||||
if (getOffset && typeof getOffset === 'function') {
|
||||
const {placement, positionTop: y, positionLeft: x} = this.props;
|
||||
|
||||
offset = getOffset(
|
||||
(findDOMNode(this) as HTMLElement).getBoundingClientRect(),
|
||||
{
|
||||
x,
|
||||
y,
|
||||
placement
|
||||
}
|
||||
);
|
||||
} else {
|
||||
offset = getOffset as Offset;
|
||||
}
|
||||
this.setState({
|
||||
xOffset: offset && offset.x ? (offset as Offset).x : 0,
|
||||
yOffset: offset && offset.y ? (offset as Offset).y : 0
|
||||
});
|
||||
}
|
||||
|
||||
@autobind
|
||||
handleOverlayClick(e: React.MouseEvent<HTMLDivElement>) {
|
||||
e.preventDefault();
|
||||
this.props.onHide?.();
|
||||
}
|
||||
|
||||
render() {
|
||||
const {
|
||||
placement,
|
||||
activePlacement,
|
||||
positionTop,
|
||||
positionLeft,
|
||||
arrowOffsetLeft,
|
||||
arrowOffsetTop,
|
||||
style,
|
||||
children,
|
||||
offset,
|
||||
overlay,
|
||||
onHide,
|
||||
classPrefix: ns,
|
||||
classnames: cx,
|
||||
className,
|
||||
componentId,
|
||||
testIdBuilder,
|
||||
...rest
|
||||
} = this.props;
|
||||
|
||||
const {xOffset, yOffset} = this.state;
|
||||
const outerStyle = {
|
||||
display: 'block',
|
||||
...style,
|
||||
top: (positionTop as number) + yOffset,
|
||||
left: (positionLeft as number) + xOffset
|
||||
};
|
||||
const placements =
|
||||
typeof activePlacement === 'string' ? activePlacement.split('-') : [];
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={this.wrapperRef}
|
||||
role="popover"
|
||||
className={cx(
|
||||
`PopOver`,
|
||||
className,
|
||||
activePlacement ? `PopOver--${camel(activePlacement)}` : '',
|
||||
placements[3] ? `PopOver--v-${placements[3]}` : ''
|
||||
)}
|
||||
style={outerStyle}
|
||||
{...testIdBuilder?.getTestId()}
|
||||
{...rest}
|
||||
>
|
||||
{overlay ? (
|
||||
<div
|
||||
className={`${ns}PopOver-overlay`}
|
||||
onClick={this.handleOverlayClick}
|
||||
{...testIdBuilder?.getChild('overlay').getTestId()}
|
||||
/>
|
||||
) : null}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default themeable(PopOver);
|
||||
230
packages/amis-core/src/env.tsx
Normal file
230
packages/amis-core/src/env.tsx
Normal file
@@ -0,0 +1,230 @@
|
||||
/**
|
||||
* @file 组件 Env,包括如何发送 ajax,如何通知,如何跳转等等。。
|
||||
*/
|
||||
import React from 'react';
|
||||
import {RendererConfig} from './factory';
|
||||
import {ThemeInstance} from './theme';
|
||||
import {
|
||||
ActionObject,
|
||||
Api,
|
||||
EventTrack,
|
||||
Payload,
|
||||
PlainObject,
|
||||
Schema,
|
||||
ToastConf,
|
||||
ToastLevel
|
||||
} from './types';
|
||||
import hoistNonReactStatic from 'hoist-non-react-statics';
|
||||
|
||||
import type {IScopedContext} from './Scoped';
|
||||
import type {RendererEvent} from './utils/renderer-event';
|
||||
import type {ListenerContext} from './actions/Action';
|
||||
import type {ICmptAction} from './actions/CmptAction';
|
||||
|
||||
export interface WsObject {
|
||||
url: string;
|
||||
responseKey?: string;
|
||||
body?: any;
|
||||
}
|
||||
|
||||
export interface RendererEnv {
|
||||
/* 强制隐藏组件内部的报错信息,会覆盖组件内部属性 */
|
||||
forceSilenceInsideError?: boolean;
|
||||
session?: string;
|
||||
fetcher: (api: Api, data?: any, options?: object) => Promise<Payload>;
|
||||
isCancel: (val: any) => boolean;
|
||||
wsFetcher: (
|
||||
ws: WsObject,
|
||||
onMessage: (data: any) => void,
|
||||
onError: (error: any) => void
|
||||
) => void;
|
||||
notify: (type: ToastLevel, msg: any, conf?: ToastConf) => void;
|
||||
jumpTo: (to: string, action?: ActionObject, ctx?: object) => void;
|
||||
alert: (msg: string, title?: string) => void;
|
||||
confirm: (msg: string, title?: string) => Promise<boolean>;
|
||||
updateLocation: (location: any, replace?: boolean) => void;
|
||||
|
||||
/**
|
||||
* 阻止路由跳转,有时候 form 没有保存,但是路由跳转了,导致页面没有更新,
|
||||
* 所以先让用户确认一下。
|
||||
*
|
||||
* 单页模式需要这个,如果非单页模式,不需要处理这个。
|
||||
*/
|
||||
blockRouting?: (fn: (targetLocation: any) => void | string) => () => void;
|
||||
isCurrentUrl: (link: string, ctx?: any) => boolean | {params?: object};
|
||||
|
||||
/**
|
||||
* 监控路由变化,如果 jssdk 需要做单页跳转需要实现这个。
|
||||
*/
|
||||
watchRouteChange?: (fn: () => void) => () => void;
|
||||
// 用于跟踪用户在界面中的各种操作
|
||||
tracker: (eventTrack: EventTrack, props?: PlainObject) => void;
|
||||
/**
|
||||
* 捕获amis执行中的错误信息
|
||||
*/
|
||||
errorCatcher?: (error: any, errorInfo: any) => void;
|
||||
/**
|
||||
* 自定义样式前缀
|
||||
*/
|
||||
customStyleClassPrefix?: string;
|
||||
rendererResolver?: (
|
||||
path: string,
|
||||
schema: Schema,
|
||||
props: any
|
||||
) => null | RendererConfig;
|
||||
copy?: (contents: string, format?: any) => void;
|
||||
getModalContainer?: () => HTMLElement;
|
||||
theme: ThemeInstance;
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
* 请通过外层设置 `--affix-offset-top` css 变量设置
|
||||
*/
|
||||
affixOffsetTop?: number;
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
* 请通过外层设置 `--affix-offset-bottom` css 变量设置
|
||||
*/
|
||||
affixOffsetBottom?: number;
|
||||
|
||||
richTextToken: string;
|
||||
|
||||
/**
|
||||
* 默认的选址组件提供商,目前支持仅 baidu
|
||||
*/
|
||||
locationPickerVendor?: string;
|
||||
|
||||
/**
|
||||
* 选址组件的 ak
|
||||
*/
|
||||
locationPickerAK?: string;
|
||||
loadRenderer: (
|
||||
schema: Schema,
|
||||
path: string,
|
||||
reRender: Function
|
||||
) => Promise<React.ElementType> | React.ElementType | JSX.Element | void;
|
||||
loadChartExtends?: () => void | Promise<void>;
|
||||
loadTinymcePlugin?: (tinymce: any) => void | Promise<void>;
|
||||
useMobileUI?: boolean;
|
||||
isMobile: () => boolean;
|
||||
/**
|
||||
* 过滤 html 标签,可用来添加 xss 保护逻辑
|
||||
*/
|
||||
filterHtml: (input: string) => string;
|
||||
beforeDispatchEvent: (
|
||||
e:
|
||||
| string
|
||||
| React.ClipboardEvent<any>
|
||||
| React.DragEvent<any>
|
||||
| React.ChangeEvent<any>
|
||||
| React.KeyboardEvent<any>
|
||||
| React.TouchEvent<any>
|
||||
| React.WheelEvent<any>
|
||||
| React.AnimationEvent<any>
|
||||
| React.TransitionEvent<any>
|
||||
| React.MouseEvent<any>,
|
||||
context: any,
|
||||
scoped: IScopedContext,
|
||||
data: any,
|
||||
broadcast?: RendererEvent<any>
|
||||
) => void;
|
||||
|
||||
/**
|
||||
* 是否开启 amis 调试
|
||||
*/
|
||||
enableAMISDebug?: boolean;
|
||||
|
||||
/**
|
||||
* 是否开启 testid 定位
|
||||
*/
|
||||
enableTestid?: boolean;
|
||||
|
||||
/**
|
||||
* 替换文本,用于实现 URL 替换、语言替换等
|
||||
*/
|
||||
replaceText?: {[propName: string]: any};
|
||||
|
||||
/**
|
||||
* 文本替换的黑名单,因为属性太多了所以改成黑名单的 flags
|
||||
*/
|
||||
replaceTextIgnoreKeys?:
|
||||
| String[]
|
||||
| ((key: string, value: any, object: any) => boolean);
|
||||
|
||||
/**
|
||||
* 解析url参数
|
||||
*/
|
||||
parseLocation?: (location: any) => Object;
|
||||
|
||||
/** 数据更新前触发的Hook */
|
||||
beforeSetData?: (
|
||||
renderer: ListenerContext,
|
||||
action: ICmptAction,
|
||||
event: RendererEvent<any, any>
|
||||
) => Promise<void | boolean>;
|
||||
|
||||
/**
|
||||
* 渲染器包裹组件可以外部指定
|
||||
*/
|
||||
SchemaRenderer?: React.ComponentType<any>;
|
||||
|
||||
/**
|
||||
* 获取当前页面标识
|
||||
*/
|
||||
getPageId?: () => string;
|
||||
}
|
||||
|
||||
export const EnvContext = React.createContext<RendererEnv | void>(undefined);
|
||||
|
||||
export interface EnvProps {
|
||||
env: RendererEnv;
|
||||
}
|
||||
|
||||
export function withRendererEnv<
|
||||
T extends React.ComponentType<React.ComponentProps<T> & EnvProps>
|
||||
>(ComposedComponent: T) {
|
||||
type OuterProps = JSX.LibraryManagedAttributes<
|
||||
T,
|
||||
Omit<React.ComponentProps<T>, keyof EnvProps>
|
||||
> & {
|
||||
env?: RendererEnv;
|
||||
};
|
||||
|
||||
const result = hoistNonReactStatic(
|
||||
class extends React.Component<OuterProps> {
|
||||
static displayName: string = `WithEnv(${
|
||||
ComposedComponent.displayName || ComposedComponent.name
|
||||
})`;
|
||||
static contextType = EnvContext;
|
||||
static ComposedComponent = ComposedComponent as React.ComponentType<T>;
|
||||
|
||||
render() {
|
||||
const injectedProps: {
|
||||
env: RendererEnv;
|
||||
} = {
|
||||
env: this.props.env! || this.context
|
||||
};
|
||||
|
||||
if (!injectedProps.env) {
|
||||
throw new Error('Env 信息获取失败,组件用法不正确');
|
||||
}
|
||||
|
||||
return (
|
||||
<ComposedComponent
|
||||
{...(this.props as JSX.LibraryManagedAttributes<
|
||||
T,
|
||||
React.ComponentProps<T>
|
||||
> as any)}
|
||||
{...injectedProps}
|
||||
/>
|
||||
);
|
||||
}
|
||||
},
|
||||
ComposedComponent
|
||||
);
|
||||
|
||||
return result as typeof result & {
|
||||
ComposedComponent: T;
|
||||
};
|
||||
}
|
||||
33
packages/amis-core/src/envOverwrite.ts
Normal file
33
packages/amis-core/src/envOverwrite.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* @file 用于在移动端或不同语言环境下使用不同配置
|
||||
*/
|
||||
|
||||
import {JSONValueMap} from './utils/helper';
|
||||
import isPlainObject from 'lodash/isPlainObject';
|
||||
const isMobile = (window as any).matchMedia?.('(max-width: 768px)').matches
|
||||
? true
|
||||
: false;
|
||||
|
||||
// 这里不能用 addSchemaFilter 是因为还需要更深层的替换,比如 select 里的 options
|
||||
export const envOverwrite = (schema: any, locale?: string, device?: string) => {
|
||||
const isMobileDevice = device === 'mobile' || isMobile;
|
||||
return JSONValueMap(
|
||||
schema,
|
||||
(value: any) => {
|
||||
if (!isPlainObject(value)) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (locale && value[locale]) {
|
||||
const newValue = Object.assign({}, value, value[locale]);
|
||||
delete newValue[locale];
|
||||
return newValue;
|
||||
} else if (isMobileDevice && value.mobile) {
|
||||
const newValue = Object.assign({}, value, value.mobile);
|
||||
delete newValue.mobile;
|
||||
return newValue;
|
||||
}
|
||||
},
|
||||
true
|
||||
);
|
||||
};
|
||||
698
packages/amis-core/src/factory.tsx
Normal file
698
packages/amis-core/src/factory.tsx
Normal file
@@ -0,0 +1,698 @@
|
||||
import React from 'react';
|
||||
import {RendererStore, IRendererStore, IIRendererStore} from './store/index';
|
||||
import {getEnv, destroy} from 'mobx-state-tree';
|
||||
import {wrapFetcher} from './utils/api';
|
||||
import {normalizeLink} from './utils/normalizeLink';
|
||||
import {
|
||||
findIndex,
|
||||
promisify,
|
||||
qsparse,
|
||||
string2regExp,
|
||||
parseQuery,
|
||||
isMobile,
|
||||
TestIdBuilder
|
||||
} from './utils/helper';
|
||||
import {
|
||||
fetcherResult,
|
||||
SchemaNode,
|
||||
Schema,
|
||||
EventTrack,
|
||||
PlainObject
|
||||
} from './types';
|
||||
import {observer} from 'mobx-react';
|
||||
import Scoped from './Scoped';
|
||||
import {ThemeProps} from './theme';
|
||||
import find from 'lodash/find';
|
||||
import {LocaleProps} from './locale';
|
||||
import {HocStoreFactory} from './WithStore';
|
||||
import type {RendererEnv} from './env';
|
||||
import {OnEventProps, RendererEvent} from './utils/renderer-event';
|
||||
import {Placeholder} from './renderers/Placeholder';
|
||||
import {StatusScopedProps} from './StatusScoped';
|
||||
import type {IScopedContext} from './Scoped';
|
||||
import {getPageId} from './utils/getPageId';
|
||||
export interface TestFunc {
|
||||
(
|
||||
path: string,
|
||||
schema?: Schema,
|
||||
resolveRenderer?: (
|
||||
path: string,
|
||||
schema?: Schema,
|
||||
props?: any
|
||||
) => null | RendererConfig
|
||||
): boolean;
|
||||
}
|
||||
|
||||
export interface RendererBasicConfig {
|
||||
test?: RegExp | TestFunc;
|
||||
type?: string;
|
||||
alias?: Array<string>; // 别名, 可以绑定多个类型,命中其中一个即可。
|
||||
name?: string;
|
||||
origin?: RendererBasicConfig;
|
||||
storeType?: string;
|
||||
defaultProps?: (type: string, schema: any) => any;
|
||||
shouldSyncSuperStore?: (
|
||||
store: any,
|
||||
props: any,
|
||||
prevProps: any
|
||||
) => boolean | undefined;
|
||||
storeExtendsData?: boolean | ((props: any) => boolean); // 是否需要继承上层数据。
|
||||
// 当全局渲染器关联的全局变量发生变化时执行
|
||||
// 因为全局变量永远都是最新的,有些组件是 didUpdate 的时候比对有变化才更新
|
||||
// 这里给组件一个自定义更新的机会
|
||||
onGlobalVarChanged?: (
|
||||
instance: React.Component,
|
||||
schema: any,
|
||||
data: any
|
||||
) => void | boolean;
|
||||
weight?: number; // 权重,值越低越优先命中。
|
||||
isolateScope?: boolean;
|
||||
isFormItem?: boolean;
|
||||
autoVar?: boolean; // 自动解析变量
|
||||
// 如果要替换系统渲染器,则需要设置这个为 true
|
||||
override?: boolean;
|
||||
// [propName:string]:any;
|
||||
}
|
||||
|
||||
export interface RendererProps
|
||||
extends ThemeProps,
|
||||
LocaleProps,
|
||||
OnEventProps,
|
||||
StatusScopedProps {
|
||||
render: (
|
||||
region: string,
|
||||
node: SchemaNode,
|
||||
props?: PlainObject
|
||||
) => JSX.Element;
|
||||
env: RendererEnv;
|
||||
$path: string; // 当前组件所在的层级信息
|
||||
$schema: any; // 原始 schema 配置
|
||||
testIdBuilder?: TestIdBuilder;
|
||||
store?: IIRendererStore;
|
||||
syncSuperStore?: boolean;
|
||||
data: {
|
||||
[propName: string]: any;
|
||||
};
|
||||
defaultData?: object;
|
||||
className?: any;
|
||||
style?: {
|
||||
[propName: string]: any;
|
||||
};
|
||||
onBroadcast?: (type: string, rawEvent: RendererEvent<any>, ctx: any) => any;
|
||||
dispatchEvent: (
|
||||
e: string | React.MouseEvent<any>,
|
||||
data: any,
|
||||
renderer?: React.Component<RendererProps>,
|
||||
scoped?: IScopedContext
|
||||
) => Promise<RendererEvent<any>>;
|
||||
mobileUI?: boolean;
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
export type RendererComponent = React.ComponentType<RendererProps> & {
|
||||
propsList?: Array<any>;
|
||||
};
|
||||
|
||||
export interface RendererConfig extends RendererBasicConfig {
|
||||
// 渲染器组件,与 Renderer 的区别是,这个可能是包裹了 store 的。
|
||||
component?: RendererComponent;
|
||||
// 异步渲染器
|
||||
getComponent?: () => Promise<{default: RendererComponent} | any>;
|
||||
|
||||
// 原始组件
|
||||
Renderer?: RendererComponent;
|
||||
}
|
||||
|
||||
export interface RenderSchemaFilter {
|
||||
(schema: Schema, renderer: RendererConfig, props?: any): Schema;
|
||||
}
|
||||
|
||||
export interface WsObject {
|
||||
url: string;
|
||||
responseKey?: string;
|
||||
body?: any;
|
||||
}
|
||||
|
||||
export interface FetcherConfig {
|
||||
url: string;
|
||||
method?: 'get' | 'post' | 'put' | 'patch' | 'delete' | 'jsonp' | 'js';
|
||||
data?: any;
|
||||
config?: any;
|
||||
}
|
||||
|
||||
export interface RenderOptions
|
||||
extends Partial<Omit<RendererEnv, 'fetcher' | 'theme'>> {
|
||||
session?: string;
|
||||
theme?: string;
|
||||
fetcher?: (config: FetcherConfig) => Promise<fetcherResult>;
|
||||
}
|
||||
|
||||
const renderers: Array<RendererConfig> = [];
|
||||
// type 与 RendererConfig 的映射关系
|
||||
const renderersTypeMap: {
|
||||
[propName: string]: RendererConfig;
|
||||
} = {};
|
||||
export const renderersMap: {
|
||||
[propName: string]: boolean;
|
||||
} = {};
|
||||
const schemaFilters: Array<RenderSchemaFilter> = [];
|
||||
let anonymousIndex = 1;
|
||||
|
||||
export function addSchemaFilter(fn: RenderSchemaFilter) {
|
||||
schemaFilters.push(fn);
|
||||
}
|
||||
|
||||
export function filterSchema(
|
||||
schema: Schema,
|
||||
render: RendererConfig,
|
||||
props?: any
|
||||
) {
|
||||
return schemaFilters.reduce(
|
||||
(schema, filter) => filter(schema, render, props),
|
||||
schema
|
||||
) as Schema;
|
||||
}
|
||||
|
||||
export function Renderer(config: RendererBasicConfig) {
|
||||
return function <T extends RendererComponent>(component: T): T {
|
||||
const renderer = registerRenderer({
|
||||
...config,
|
||||
component: component
|
||||
});
|
||||
return renderer.component as T;
|
||||
};
|
||||
}
|
||||
|
||||
// mobx-react 的 observer 会修改原型链的 render 方法
|
||||
// 如果想继承覆盖组件的 render 方法,需要把原型链 render 还原回来
|
||||
// 否则无法调用 super.render 方法
|
||||
function fixMobxInjectRender<T extends Function>(klass: T): T {
|
||||
const target = klass.prototype;
|
||||
|
||||
// mobx-react 篡改之前先记录原始 render
|
||||
if (target?.render) {
|
||||
target.__originRender = target.render;
|
||||
}
|
||||
|
||||
// 将父级类上面被 mobx 篡改的 render 方法还原回来
|
||||
// 而且当前类的 render 也是会被篡改的,所以父级上的其实不需要篡改
|
||||
if (target?.__proto__?.hasOwnProperty('__originRender')) {
|
||||
const originProto = target.__proto__;
|
||||
target.__proto__ = Object.create(originProto.__proto__ || Object);
|
||||
Object.assign(target.__proto__, originProto);
|
||||
target.__proto__.render = originProto.__originRender;
|
||||
}
|
||||
|
||||
return klass;
|
||||
}
|
||||
|
||||
// 将 renderer 转成组件
|
||||
function rendererToComponent(
|
||||
component: RendererComponent,
|
||||
config: RendererConfig
|
||||
): RendererComponent {
|
||||
if (config.storeType && config.component) {
|
||||
component = HocStoreFactory({
|
||||
storeType: config.storeType,
|
||||
extendsData: config.storeExtendsData,
|
||||
shouldSyncSuperStore: config.shouldSyncSuperStore
|
||||
})(observer(fixMobxInjectRender(component)));
|
||||
}
|
||||
|
||||
if (config.isolateScope) {
|
||||
component = Scoped(component, config.type);
|
||||
}
|
||||
return component;
|
||||
}
|
||||
|
||||
export function registerRenderer(config: RendererConfig): RendererConfig {
|
||||
if (!config.test && !config.type) {
|
||||
throw new TypeError('please set config.type or config.test');
|
||||
} else if (!config.type && config.name !== 'static') {
|
||||
// todo static 目前还没办法不用 test 来实现
|
||||
console.warn(
|
||||
`config.type is recommended for register renderer(${config.test})`
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof config.type === 'string' && config.type) {
|
||||
config.type = config.type.toLowerCase();
|
||||
config.test =
|
||||
config.test ||
|
||||
new RegExp(
|
||||
`(^|\/)(?:${(config.alias || [])
|
||||
.concat(config.type)
|
||||
.map(type => string2regExp(type))
|
||||
.join('|')})$`,
|
||||
'i'
|
||||
);
|
||||
}
|
||||
|
||||
const exists = renderersTypeMap[config.type || ''];
|
||||
let renderer = {...config};
|
||||
if (
|
||||
exists &&
|
||||
exists.component &&
|
||||
exists.component !== Placeholder &&
|
||||
config.component &&
|
||||
!exists.origin &&
|
||||
!config.override
|
||||
) {
|
||||
throw new Error(
|
||||
`The renderer with type "${config.type}" has already exists, please try another type!`
|
||||
);
|
||||
} else if (exists) {
|
||||
// 如果已经存在,合并配置,并用合并后的配置
|
||||
renderer = Object.assign(exists, config);
|
||||
// 如果已存在的配置有占位组件,并且新的配置是异步渲染器,在把占位组件删除
|
||||
// 避免遇到设置了 visibleOn/hiddenOn 条件的 Schema 无法渲染的问题
|
||||
if (
|
||||
exists.component === Placeholder &&
|
||||
!config.component &&
|
||||
config.getComponent
|
||||
) {
|
||||
delete renderer.component;
|
||||
delete renderer.Renderer;
|
||||
}
|
||||
}
|
||||
|
||||
renderer.weight = renderer.weight || 0;
|
||||
renderer.name =
|
||||
renderer.name || renderer.type || `anonymous-${anonymousIndex++}`;
|
||||
|
||||
if (config.component) {
|
||||
renderer.Renderer = config.component;
|
||||
renderer.component = rendererToComponent(config.component, renderer);
|
||||
}
|
||||
|
||||
if (!exists) {
|
||||
const idx = findIndex(
|
||||
renderers,
|
||||
item => (config.weight as number) < item.weight
|
||||
);
|
||||
~idx ? renderers.splice(idx, 0, renderer) : renderers.push(renderer);
|
||||
}
|
||||
renderersMap[renderer.name] = !!(
|
||||
renderer.component && renderer.component !== Placeholder
|
||||
);
|
||||
renderer.type && (renderersTypeMap[renderer.type] = renderer);
|
||||
(renderer.alias || []).forEach(alias => {
|
||||
const fork = {
|
||||
...renderer,
|
||||
type: alias,
|
||||
name: alias,
|
||||
alias: undefined,
|
||||
origin: renderer
|
||||
};
|
||||
|
||||
const idx = renderers.findIndex(item => item.name === alias);
|
||||
if (~idx) {
|
||||
Object.assign(renderers[idx], fork);
|
||||
} else {
|
||||
renderers.push(fork);
|
||||
}
|
||||
renderersTypeMap[alias] = fork;
|
||||
renderersMap[alias] = true;
|
||||
});
|
||||
return renderer;
|
||||
}
|
||||
|
||||
export function unRegisterRenderer(config: RendererConfig | string) {
|
||||
const name = (typeof config === 'string' ? config : config.name)!;
|
||||
const idx = renderers.findIndex(item => item.name === name);
|
||||
if (~idx) {
|
||||
const renderer = renderers[idx];
|
||||
renderers.splice(idx, 1);
|
||||
|
||||
delete renderersMap[name];
|
||||
delete renderersTypeMap[renderer.type || ''];
|
||||
renderer.alias?.forEach(alias => {
|
||||
const idx = renderers.findIndex(item => item.name === alias);
|
||||
idx > -1 && renderers.splice(idx, 1);
|
||||
delete renderersTypeMap[alias];
|
||||
delete renderersMap[alias];
|
||||
});
|
||||
|
||||
// 清空渲染器定位缓存
|
||||
Object.keys(cache).forEach(key => {
|
||||
const value = cache[key];
|
||||
if (value === renderer) {
|
||||
delete cache[key];
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function loadRendererError(schema: Schema, path: string) {
|
||||
return (
|
||||
<div className="RuntimeError">
|
||||
<p>Error: 找不到对应的渲染器</p>
|
||||
<p>Path: {path}</p>
|
||||
<pre>
|
||||
<code>{JSON.stringify(schema, null, 2)}</code>
|
||||
</pre>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export async function loadAsyncRenderer(renderer: RendererConfig) {
|
||||
if (!isAsyncRenderer(renderer)) {
|
||||
// already loaded
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await renderer.getComponent!();
|
||||
|
||||
// 如果异步加载的组件没有注册渲染器
|
||||
// 同时默认导出了一个组件,则自动注册
|
||||
if (!renderer.component && result.default) {
|
||||
registerRenderer({
|
||||
...renderer,
|
||||
component: result.default
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function isAsyncRenderer(item: RendererConfig) {
|
||||
return (
|
||||
item &&
|
||||
(!item.component || item.component === Placeholder) &&
|
||||
item.getComponent
|
||||
);
|
||||
}
|
||||
|
||||
export function hasAsyncRenderers(types?: Array<string>) {
|
||||
return (
|
||||
Array.isArray(types)
|
||||
? renderers.filter(item => item.type && types.includes(item.type))
|
||||
: renderers
|
||||
).some(isAsyncRenderer);
|
||||
}
|
||||
|
||||
export async function loadAsyncRenderersByType(
|
||||
type: string | Array<string>,
|
||||
ignore = false
|
||||
) {
|
||||
const types = Array.isArray(type) ? type : [type];
|
||||
const asyncRenderers = types
|
||||
.map(type => {
|
||||
const renderer = renderersTypeMap[type];
|
||||
if (!renderer && !ignore) {
|
||||
throw new Error(`Can not find the renderer by type: ${type}`);
|
||||
}
|
||||
return renderer;
|
||||
})
|
||||
.filter(isAsyncRenderer);
|
||||
|
||||
if (asyncRenderers.length) {
|
||||
await Promise.all(asyncRenderers.map(item => loadAsyncRenderer(item)));
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadAllAsyncRenderers() {
|
||||
const asyncRenderers = renderers.filter(isAsyncRenderer);
|
||||
if (asyncRenderers.length) {
|
||||
await Promise.all(
|
||||
renderers.map(async renderer => {
|
||||
await loadAsyncRenderer(renderer);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const defaultOptions: RenderOptions = {
|
||||
session: 'global',
|
||||
richTextToken: '',
|
||||
useMobileUI: true, // 是否启用移动端原生 UI
|
||||
enableAMISDebug:
|
||||
(window as any).enableAMISDebug ??
|
||||
location.search.indexOf('amisDebug=1') !== -1 ??
|
||||
false,
|
||||
loadRenderer: loadRendererError,
|
||||
fetcher() {
|
||||
return Promise.reject('fetcher is required');
|
||||
},
|
||||
// 使用 WebSocket 来实时获取数据
|
||||
wsFetcher(
|
||||
ws: WsObject,
|
||||
onMessage: (data: any) => void,
|
||||
onError: (error: any) => void
|
||||
) {
|
||||
if (ws) {
|
||||
const socket = new WebSocket(ws.url);
|
||||
socket.onopen = event => {
|
||||
if (ws.body) {
|
||||
socket.send(JSON.stringify(ws.body));
|
||||
}
|
||||
};
|
||||
socket.onmessage = event => {
|
||||
if (event.data) {
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(event.data);
|
||||
} catch (error) {}
|
||||
if (typeof data !== 'object') {
|
||||
let key = ws.responseKey || 'data';
|
||||
data = {
|
||||
[key]: event.data
|
||||
};
|
||||
}
|
||||
|
||||
onMessage(data);
|
||||
}
|
||||
};
|
||||
socket.onerror = onError;
|
||||
return {
|
||||
close: socket.close
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
close: () => {}
|
||||
};
|
||||
}
|
||||
},
|
||||
isCancel() {
|
||||
console.error(
|
||||
'Please implement isCancel. see https://aisuda.bce.baidu.com/amis/zh-CN/start/getting-started#%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97'
|
||||
);
|
||||
return false;
|
||||
},
|
||||
updateLocation() {
|
||||
console.error(
|
||||
'Please implement updateLocation. see https://aisuda.bce.baidu.com/amis/zh-CN/start/getting-started#%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97'
|
||||
);
|
||||
},
|
||||
|
||||
jumpTo: (to: string, action?: any) => {
|
||||
if (to === 'goBack') {
|
||||
return window.history.back();
|
||||
}
|
||||
to = normalizeLink(to);
|
||||
if (action && action.actionType === 'url') {
|
||||
action.blank === false ? (window.location.href = to) : window.open(to);
|
||||
return;
|
||||
}
|
||||
// link动作新增了targetType属性,默认是内容区打开(page),在新窗口打开(blank);在当前页签打开(self)
|
||||
if (
|
||||
action?.actionType === 'link' &&
|
||||
['blank', 'self'].includes(action?.targetType)
|
||||
) {
|
||||
if (action.targetType === 'self') {
|
||||
// 当前页签打开,需要刷新页面
|
||||
window.history.pushState(null, '', to);
|
||||
location.reload();
|
||||
} else {
|
||||
window.open(to);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (/^https?:\/\//.test(to)) {
|
||||
window.location.replace(to);
|
||||
} else {
|
||||
location.href = to;
|
||||
}
|
||||
},
|
||||
isCurrentUrl: (to: string) => {
|
||||
if (!to) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const link = normalizeLink(to);
|
||||
const location = window.location;
|
||||
let pathname = link;
|
||||
let search = '';
|
||||
const idx = link.indexOf('?');
|
||||
if (~idx) {
|
||||
pathname = link.substring(0, idx);
|
||||
search = link.substring(idx);
|
||||
}
|
||||
if (search) {
|
||||
if (pathname !== location.pathname || !location.search) {
|
||||
return false;
|
||||
}
|
||||
const query = qsparse(search.substring(1));
|
||||
const currentQuery = parseQuery(location);
|
||||
return Object.keys(query).every(key => query[key] === currentQuery[key]);
|
||||
} else if (pathname === location.pathname) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
copy(contents: string) {
|
||||
console.error('copy contents', contents);
|
||||
},
|
||||
// 用于跟踪用户在界面中的各种操作
|
||||
tracker(eventTrack: EventTrack, props: PlainObject) {},
|
||||
rendererResolver: resolveRenderer,
|
||||
replaceTextIgnoreKeys: [
|
||||
'type',
|
||||
'name',
|
||||
'mode',
|
||||
'target',
|
||||
'reload',
|
||||
'persistData'
|
||||
],
|
||||
/**
|
||||
* 过滤 html 标签,可用来添加 xss 保护逻辑
|
||||
*/
|
||||
filterHtml: (input: string) => input,
|
||||
isMobile: isMobile,
|
||||
getPageId: getPageId
|
||||
};
|
||||
|
||||
export const stores: {
|
||||
[propName: string]: IRendererStore;
|
||||
} = {};
|
||||
|
||||
// 默认 env 会被缓存,所以新传入的 env 不会替换旧的。
|
||||
// 除非先删了旧的,新的才会生效。
|
||||
export function clearStoresCache(
|
||||
sessions: Array<string> | string = Object.keys(stores)
|
||||
) {
|
||||
if (!Array.isArray(sessions)) {
|
||||
sessions = [sessions];
|
||||
}
|
||||
|
||||
sessions.forEach(key => {
|
||||
const store = stores[key];
|
||||
|
||||
// @ts-ignore
|
||||
delete stores[key];
|
||||
|
||||
store && destroy(store);
|
||||
});
|
||||
}
|
||||
|
||||
// 当然也可以直接这样更新。
|
||||
// 主要是有时候第一次创建的时候并没有准备多少接口,
|
||||
// 可以后续补充点,比如 amis 自己实现的,prompt 里面的表单。
|
||||
export function updateEnv(options: Partial<RenderOptions>, session = 'global') {
|
||||
options = {
|
||||
...options
|
||||
};
|
||||
|
||||
if (options.fetcher) {
|
||||
options.fetcher = wrapFetcher(options.fetcher, options.tracker) as any;
|
||||
}
|
||||
|
||||
if (options.confirm) {
|
||||
options.confirm = promisify(options.confirm);
|
||||
}
|
||||
|
||||
let store = stores[options.session || session];
|
||||
if (!store) {
|
||||
store = RendererStore.create(
|
||||
{},
|
||||
{
|
||||
...defaultOptions,
|
||||
...options
|
||||
}
|
||||
);
|
||||
stores[options.session || session] = store;
|
||||
} else {
|
||||
const env = getEnv(store);
|
||||
Object.assign(env, options);
|
||||
}
|
||||
}
|
||||
|
||||
// 扩充默认的 env ,这样使用方不需要指定都会有。
|
||||
export function extendDefaultEnv(env: Partial<RenderOptions>) {
|
||||
Object.assign(defaultOptions, env);
|
||||
}
|
||||
|
||||
let cache: {[propName: string]: RendererConfig} = {};
|
||||
export function resolveRenderer(
|
||||
path: string,
|
||||
schema?: Schema
|
||||
): null | RendererConfig {
|
||||
const type = typeof schema?.type == 'string' ? schema.type.toLowerCase() : '';
|
||||
|
||||
// 直接匹配类型,后续注册渲染都应该用这个方式而不是之前的判断路径。
|
||||
if (type && renderersTypeMap[type]) {
|
||||
return renderersTypeMap[type];
|
||||
} else if (cache[path]) {
|
||||
return cache[path];
|
||||
} else if (path && path.length > 3072) {
|
||||
throw new Error('Path太长是不是死循环了?');
|
||||
}
|
||||
|
||||
let renderer: null | RendererConfig = null;
|
||||
|
||||
renderers.some(item => {
|
||||
let matched = false;
|
||||
|
||||
if (typeof item.test === 'function') {
|
||||
// 不应该搞得这么复杂的,让每个渲染器唯一 id,自己不晕别人用起来也不晕。
|
||||
matched = item.test(path, schema, resolveRenderer);
|
||||
} else if (item.test instanceof RegExp) {
|
||||
matched = item.test.test(path);
|
||||
}
|
||||
|
||||
if (matched) {
|
||||
renderer = item;
|
||||
}
|
||||
|
||||
return matched;
|
||||
});
|
||||
|
||||
// 只能缓存纯正则表达式的后者方法中没有用到第二个参数的,
|
||||
// 因为自定义 test 函数的有可能依赖 schema 的结果
|
||||
if (
|
||||
renderer !== null &&
|
||||
(renderer as RendererConfig).component !== Placeholder &&
|
||||
((renderer as RendererConfig).type ||
|
||||
(renderer as RendererConfig).test instanceof RegExp ||
|
||||
(typeof (renderer as RendererConfig).test === 'function' &&
|
||||
((renderer as RendererConfig).test as Function).length < 2))
|
||||
) {
|
||||
cache[path] = renderer;
|
||||
}
|
||||
|
||||
return renderer;
|
||||
}
|
||||
|
||||
export function getRenderers() {
|
||||
return renderers.concat();
|
||||
}
|
||||
|
||||
export function getRendererByName(name: string) {
|
||||
return find(renderers, item => item.name === name);
|
||||
}
|
||||
|
||||
export {RendererEnv};
|
||||
|
||||
export interface IGlobalOptions {
|
||||
pdfjsWorkerSrc: string;
|
||||
}
|
||||
|
||||
const GlobalOptions: IGlobalOptions = {
|
||||
pdfjsWorkerSrc: ''
|
||||
};
|
||||
|
||||
export function setGlobalOptions(options: Partial<IGlobalOptions>) {
|
||||
Object.assign(GlobalOptions, options);
|
||||
}
|
||||
|
||||
export function getGlobalOptions() {
|
||||
return GlobalOptions;
|
||||
}
|
||||
362
packages/amis-core/src/globalVar.ts
Normal file
362
packages/amis-core/src/globalVar.ts
Normal file
@@ -0,0 +1,362 @@
|
||||
/**
|
||||
* 全局变量
|
||||
*
|
||||
* 用于实现跨组件、跨页面的数据共享,支持持久化。
|
||||
*/
|
||||
|
||||
import {JSONSchema} from './types';
|
||||
import {isExpression} from './utils/formula';
|
||||
import {reaction} from 'mobx';
|
||||
import {resolveVariableAndFilter} from './utils/resolveVariableAndFilter';
|
||||
import {IRootStore} from './store/root';
|
||||
import isPlainObject from 'lodash/isPlainObject';
|
||||
|
||||
/**
|
||||
* 全局变量的定义
|
||||
*/
|
||||
export interface GlobalVariableItem {
|
||||
// 标识,用于区分不同的变量,不可重复
|
||||
id?: string;
|
||||
|
||||
/**
|
||||
* 设计态属性。
|
||||
* 全局变量类型,不是数据体类型,而是用于区分不同的配置方式。
|
||||
* 这个字段运行时无含义,主要用于编辑器中的分类。
|
||||
*
|
||||
* 比如平台可能扩充:应用级别、页面级别、用户级别、数据字典关联、数据模型关联等。
|
||||
* amis 中内置了:builtin 为简单的客户端存储,服务端存储需要外部扩充。
|
||||
*
|
||||
* @default builtin
|
||||
*/
|
||||
type?: string | 'builtin';
|
||||
|
||||
/**
|
||||
* 变量名
|
||||
*/
|
||||
key: string;
|
||||
|
||||
/**
|
||||
* 变量标题
|
||||
*/
|
||||
label?: string;
|
||||
|
||||
/**
|
||||
* 变量描述
|
||||
*/
|
||||
description?: string;
|
||||
|
||||
/**
|
||||
* 默认值
|
||||
*/
|
||||
defaultValue?: string;
|
||||
|
||||
/**
|
||||
* 值的数据类型定义
|
||||
*/
|
||||
valueSchema?: JSONSchema;
|
||||
|
||||
/**
|
||||
* 数据作用域
|
||||
*/
|
||||
scope?: 'page' | 'app';
|
||||
|
||||
/**
|
||||
* 数据存储方式
|
||||
*/
|
||||
storageOn?: 'client' | 'server' | 'session';
|
||||
|
||||
/**
|
||||
* 是否只读,不允许修改,运行态属性。
|
||||
*/
|
||||
readonly?: boolean;
|
||||
|
||||
/**
|
||||
* @default true
|
||||
* 是否自动保存,如果不特殊配置,会自动保存
|
||||
*/
|
||||
autoSave?: boolean;
|
||||
|
||||
// todo: 以下是扩展字段,需要进一步定义
|
||||
validationErrors?: any;
|
||||
validations?: any;
|
||||
|
||||
// 其他扩充数据
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
export type GlobalVarGetter = (
|
||||
variable: GlobalVariableItem,
|
||||
context: GlobalVarContext
|
||||
) => Promise<any>;
|
||||
export type GlobalVarBulkGetter = (
|
||||
context: GlobalVarContext
|
||||
) => Promise<Record<string, any>> | Record<string, any>;
|
||||
export type GlobalVarSetter = (
|
||||
variable: GlobalVariableItem,
|
||||
value: Record<string, any>,
|
||||
context: GlobalVarContext
|
||||
) => Promise<any>;
|
||||
export type GlobalVarBulkSetter = (
|
||||
values: Record<string, any>,
|
||||
context: GlobalVarContext
|
||||
) => Promise<any> | any;
|
||||
|
||||
export interface GlobalVariableItemFull extends GlobalVariableItem {
|
||||
/**
|
||||
* 校验数值是否合法
|
||||
* @param value
|
||||
* @returns
|
||||
*/
|
||||
validate?: (value: any, values: Record<string, any>) => string | void;
|
||||
|
||||
/**
|
||||
* 权重,用于排序
|
||||
*/
|
||||
order?: number;
|
||||
|
||||
/**
|
||||
* 单个数据初始化获取
|
||||
* @returns
|
||||
*/
|
||||
getter?: GlobalVarGetter;
|
||||
|
||||
/**
|
||||
* 批量数据初始化获取
|
||||
* @returns
|
||||
*/
|
||||
bulkGetter?: GlobalVarBulkGetter;
|
||||
|
||||
/**
|
||||
* 当个数据修改保存
|
||||
* @param value
|
||||
* @returns
|
||||
*/
|
||||
setter?: GlobalVarSetter;
|
||||
|
||||
/**
|
||||
* 批量全局变量数据保存,多个变量一起保存
|
||||
* @param values
|
||||
* @returns
|
||||
*/
|
||||
bulkSetter?: GlobalVarBulkSetter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 全局变量的状态
|
||||
*/
|
||||
export interface GlobalVariableState {
|
||||
/**
|
||||
* 当前值
|
||||
*/
|
||||
value: any;
|
||||
|
||||
/**
|
||||
* 原始值
|
||||
*/
|
||||
pristine: any;
|
||||
|
||||
/**
|
||||
* 是否正在加载, 或者说正在获取
|
||||
*/
|
||||
busy?: boolean;
|
||||
|
||||
/**
|
||||
* 是否已经初始化
|
||||
*/
|
||||
initialized: boolean;
|
||||
|
||||
/**
|
||||
* 数据是否合法
|
||||
*/
|
||||
valid: boolean;
|
||||
|
||||
/**
|
||||
* 错误馨馨
|
||||
*/
|
||||
errorMessages: string[];
|
||||
|
||||
/**
|
||||
* 是否有变更
|
||||
*/
|
||||
touched: boolean;
|
||||
|
||||
/**
|
||||
* 是否有保存
|
||||
*/
|
||||
saved: boolean;
|
||||
}
|
||||
|
||||
export interface GlobalVarContext {
|
||||
variables: Array<GlobalVariableItem>;
|
||||
[propName: string]: any;
|
||||
}
|
||||
/**
|
||||
* 全局变量处理器, 可以处理全变量的初始化、校验、存储等操作
|
||||
*/
|
||||
export type GlobalVariableHandler = (
|
||||
variable: GlobalVariableItem | GlobalVariableItemFull,
|
||||
context: GlobalVarContext
|
||||
) =>
|
||||
| GlobalVariableItemFull
|
||||
| void
|
||||
| ((
|
||||
variable: GlobalVariableItem | GlobalVariableItemFull,
|
||||
context: GlobalVarContext
|
||||
) => GlobalVariableItemFull | void);
|
||||
|
||||
const handlers: Array<GlobalVariableHandler> = [];
|
||||
|
||||
/**
|
||||
* 注册全局变量处理器
|
||||
* @param handler
|
||||
*/
|
||||
export function registerGlobalVariableHandler(handler: GlobalVariableHandler) {
|
||||
handlers.push(handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过处理器构建全局变量细节对象,用于后续的初始化、校验、存储等操作
|
||||
* @param variable
|
||||
* @param context
|
||||
* @returns
|
||||
*/
|
||||
export function buildGlobalVariable(
|
||||
variable: GlobalVariableItem | GlobalVariableItemFull,
|
||||
context: GlobalVarContext
|
||||
): GlobalVariableItemFull {
|
||||
const postHandlers: Array<
|
||||
(
|
||||
variable: GlobalVariableItem | GlobalVariableItemFull,
|
||||
context: GlobalVarContext
|
||||
) => GlobalVariableItemFull | void
|
||||
> = [];
|
||||
|
||||
let result = handlers.reduce((item, handler) => {
|
||||
const result = handler(item, context);
|
||||
|
||||
if (typeof result === 'function') {
|
||||
postHandlers.push(result);
|
||||
}
|
||||
|
||||
return (result ?? item) as GlobalVariableItemFull;
|
||||
}, variable);
|
||||
|
||||
result = postHandlers.reduce(
|
||||
(item, handler) => handler(item, context) ?? item,
|
||||
result
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建变量初始状态
|
||||
* @returns
|
||||
*/
|
||||
export function createGlobalVarState(): GlobalVariableState {
|
||||
return {
|
||||
value: undefined,
|
||||
pristine: undefined,
|
||||
initialized: false,
|
||||
valid: true,
|
||||
errorMessages: [],
|
||||
touched: false,
|
||||
saved: false
|
||||
};
|
||||
}
|
||||
|
||||
// 前两个是历史遗留,后两个是新的
|
||||
const globalVarFields = ['__page.', 'appVariables.', 'global.', 'globalState.'];
|
||||
export function isGlobalVarExpression(value: string) {
|
||||
return (
|
||||
typeof value === 'string' &&
|
||||
isExpression(value) &&
|
||||
globalVarFields.some(k => value.includes(k))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 监控组件的全局变量
|
||||
* @param schema
|
||||
* @param topStore
|
||||
* @param callback
|
||||
* @returns
|
||||
*/
|
||||
export function observeGlobalVars(
|
||||
schema: any,
|
||||
topStore: IRootStore,
|
||||
callback: () => void
|
||||
) {
|
||||
let expressions: Array<{
|
||||
key: string;
|
||||
value: string;
|
||||
}> = [];
|
||||
Object.keys(schema).forEach(key => {
|
||||
const value = schema[key];
|
||||
|
||||
if (isGlobalVarExpression(value)) {
|
||||
expressions.push({
|
||||
key,
|
||||
value
|
||||
});
|
||||
} else if (isPlainObject(value) && !value.type) {
|
||||
// 最多支持两层,多了可能就会有性能问题了
|
||||
// 再多一层主要是为了支持某些 api 配置的是对象形式
|
||||
Object.keys(value).forEach(k => {
|
||||
if (isGlobalVarExpression(value[k])) {
|
||||
expressions.push({
|
||||
key: `${key}.${k}`,
|
||||
value: value[k]
|
||||
});
|
||||
}
|
||||
});
|
||||
} else if (
|
||||
[
|
||||
'items',
|
||||
'body',
|
||||
'buttons',
|
||||
'header',
|
||||
'columns',
|
||||
'tabs',
|
||||
'footer',
|
||||
'actions',
|
||||
'toolbar'
|
||||
].includes(key)
|
||||
) {
|
||||
const items = Array.isArray(value) ? value : [value];
|
||||
items.forEach(item => {
|
||||
if (isGlobalVarExpression(item?.visibleOn)) {
|
||||
expressions.push({
|
||||
key: `${key}.x.visibleOn`,
|
||||
value: item.visibleOn
|
||||
});
|
||||
} else if (isGlobalVarExpression(item?.hiddenOn)) {
|
||||
expressions.push({
|
||||
key: `${key}.x.hiddenOn`,
|
||||
value: item.hiddenOn
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
if (!expressions.length) {
|
||||
return () => {};
|
||||
}
|
||||
|
||||
const unReaction = reaction(
|
||||
() =>
|
||||
expressions
|
||||
.map(
|
||||
exp =>
|
||||
`${exp.key}:${resolveVariableAndFilter(
|
||||
exp.value,
|
||||
topStore.nextGlobalData,
|
||||
'| json' // 如果用了复杂对象,要靠这个来比较
|
||||
)}`
|
||||
)
|
||||
.join(','),
|
||||
callback
|
||||
);
|
||||
|
||||
return unReaction;
|
||||
}
|
||||
84
packages/amis-core/src/globalVarClientHandler.ts
Normal file
84
packages/amis-core/src/globalVarClientHandler.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import {
|
||||
registerGlobalVariableHandler,
|
||||
GlobalVariableItemFull,
|
||||
GlobalVarContext,
|
||||
GlobalVariableItem
|
||||
} from './globalVar';
|
||||
|
||||
function loadClientData(key: string, variables: Array<GlobalVariableItem>) {
|
||||
const str = localStorage.getItem(key);
|
||||
let data: any = {};
|
||||
|
||||
try {
|
||||
data = JSON.parse(str || '{}');
|
||||
} catch (e) {
|
||||
console.error(`parse localstorage "${key} error"`, e);
|
||||
}
|
||||
|
||||
let filterData: any = {};
|
||||
variables.forEach(item => {
|
||||
if (data.hasOwnProperty(item.key)) {
|
||||
filterData[item.key] = data[item.key];
|
||||
}
|
||||
});
|
||||
|
||||
return filterData;
|
||||
}
|
||||
|
||||
function saveClientData(
|
||||
key: string,
|
||||
values: any,
|
||||
variables: Array<GlobalVariableItem>
|
||||
) {
|
||||
const str = localStorage.getItem(key);
|
||||
let data: any = {};
|
||||
|
||||
try {
|
||||
data = JSON.parse(str || '{}');
|
||||
} catch (e) {
|
||||
console.error(`parse localstorage "${key} error"`, e);
|
||||
}
|
||||
Object.assign(data, values);
|
||||
localStorage.setItem(key, JSON.stringify(data));
|
||||
}
|
||||
|
||||
function bulkClientGetter({variables}: GlobalVarContext) {
|
||||
return loadClientData('amis-client-vars', variables);
|
||||
}
|
||||
|
||||
function bulkClientSetter(values: any, context: GlobalVarContext) {
|
||||
return saveClientData('amis-client-vars', values, context.variables);
|
||||
}
|
||||
|
||||
function pageBulkClientGetter(context: GlobalVarContext) {
|
||||
const variables = context.variables;
|
||||
const key = `amis-client-vars-${context.pageId || location.pathname}`;
|
||||
return loadClientData(key, variables);
|
||||
}
|
||||
|
||||
function pageBulkClientSetter(values: any, context: GlobalVarContext) {
|
||||
const key = `amis-client-vars-${context.pageId || location.pathname}`;
|
||||
return saveClientData(key, values, context.variables);
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册全局变量处理器,用来处理 storageOn 为 client 的变量
|
||||
*
|
||||
* 并且根据变量的 scope 来决定是 page 还是全局的
|
||||
*
|
||||
* 将数据存入 localStorage
|
||||
*/
|
||||
registerGlobalVariableHandler(function (
|
||||
variable,
|
||||
context
|
||||
): GlobalVariableItemFull | void {
|
||||
if (variable.storageOn === 'client') {
|
||||
return {
|
||||
...variable,
|
||||
bulkGetter:
|
||||
variable.scope === 'page' ? pageBulkClientGetter : bulkClientGetter,
|
||||
bulkSetter:
|
||||
variable.scope === 'page' ? pageBulkClientSetter : bulkClientSetter
|
||||
};
|
||||
}
|
||||
});
|
||||
30
packages/amis-core/src/globalVarDefaultValueHandler.ts
Normal file
30
packages/amis-core/src/globalVarDefaultValueHandler.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import {
|
||||
registerGlobalVariableHandler,
|
||||
GlobalVariableItemFull
|
||||
} from './globalVar';
|
||||
/**
|
||||
* 格式化默认值
|
||||
*/
|
||||
registerGlobalVariableHandler(function (
|
||||
variable,
|
||||
context
|
||||
): GlobalVariableItemFull | void {
|
||||
if (variable.defaultValue && typeof variable.defaultValue === 'string') {
|
||||
const defaultValue = variable.defaultValue;
|
||||
try {
|
||||
let value = defaultValue;
|
||||
const valueType = variable.valueSchema?.type as string;
|
||||
|
||||
if (valueType && ['number', 'array', 'object'].includes(valueType)) {
|
||||
value = JSON.parse(defaultValue);
|
||||
}
|
||||
|
||||
return {
|
||||
...variable,
|
||||
defaultValue: value
|
||||
};
|
||||
} catch (e) {
|
||||
// do nothing
|
||||
}
|
||||
}
|
||||
});
|
||||
400
packages/amis-core/src/index.tsx
Normal file
400
packages/amis-core/src/index.tsx
Normal file
@@ -0,0 +1,400 @@
|
||||
/** @license amis v@version
|
||||
*
|
||||
* Copyright Baidu
|
||||
*
|
||||
* This source code is licensed under the Apache license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import {
|
||||
Renderer,
|
||||
getRendererByName,
|
||||
getRenderers,
|
||||
loadAllAsyncRenderers,
|
||||
loadAsyncRenderersByType,
|
||||
loadAsyncRenderer,
|
||||
registerRenderer,
|
||||
unRegisterRenderer,
|
||||
resolveRenderer,
|
||||
filterSchema,
|
||||
clearStoresCache,
|
||||
updateEnv,
|
||||
stores,
|
||||
defaultOptions,
|
||||
addSchemaFilter,
|
||||
extendDefaultEnv,
|
||||
getGlobalOptions,
|
||||
setGlobalOptions
|
||||
} from './factory';
|
||||
import type {
|
||||
RenderOptions,
|
||||
RendererConfig,
|
||||
RendererProps,
|
||||
hasAsyncRenderers
|
||||
} from './factory';
|
||||
import './polyfills';
|
||||
import './renderers/builtin';
|
||||
import './renderers/register';
|
||||
export * from './utils/index';
|
||||
export * from './utils/animations';
|
||||
export * from './types';
|
||||
export * from './store';
|
||||
export * from './globalVar';
|
||||
import * as utils from './utils/helper';
|
||||
import './globalVarClientHandler';
|
||||
import './globalVarDefaultValueHandler';
|
||||
import {getEnv} from 'mobx-state-tree';
|
||||
|
||||
import {RegisterStore, registerStore, RendererStore} from './store';
|
||||
import type {IColumn, IColumn2, IRow, IRow2} from './store';
|
||||
import {
|
||||
setDefaultLocale,
|
||||
getDefaultLocale,
|
||||
makeTranslator,
|
||||
register as registerLocale,
|
||||
extendLocale,
|
||||
removeLocaleData,
|
||||
localeable,
|
||||
format as localeFormatter
|
||||
} from './locale';
|
||||
import type {LocaleProps, TranslateFn} from './locale';
|
||||
|
||||
import Scoped, {ScopedContext, filterTarget, splitTarget} from './Scoped';
|
||||
import type {ScopedComponentType, IScopedContext} from './Scoped';
|
||||
|
||||
import {
|
||||
classnames,
|
||||
getClassPrefix,
|
||||
setDefaultTheme,
|
||||
theme,
|
||||
getTheme,
|
||||
themeable,
|
||||
makeClassnames
|
||||
} from './theme';
|
||||
import type {ClassNamesFn, ThemeProps} from './theme';
|
||||
const classPrefix = getClassPrefix();
|
||||
|
||||
export * from './actions';
|
||||
import FormItem, {
|
||||
FormItemWrap,
|
||||
registerFormItem,
|
||||
getFormItemByName
|
||||
} from './renderers/Item';
|
||||
import type {
|
||||
FormBaseControl,
|
||||
FormBaseControlWithoutSize,
|
||||
FormControlProps,
|
||||
FormItemProps
|
||||
} from './renderers/Item';
|
||||
import {
|
||||
OptionsControl,
|
||||
registerOptionsControl,
|
||||
OptionsControlBase
|
||||
} from './renderers/Options';
|
||||
import type {OptionsControlProps} from './renderers/Options';
|
||||
import type {
|
||||
FormOptionsControl,
|
||||
FormOptionsControlSelf
|
||||
} from './renderers/Options';
|
||||
import {Schema} from './types';
|
||||
import ScopedRootRenderer, {addRootWrapper, RootRenderProps} from './Root';
|
||||
import {envOverwrite} from './envOverwrite';
|
||||
import {EnvContext} from './env';
|
||||
import type {RendererEnv} from './env';
|
||||
import React from 'react';
|
||||
import {
|
||||
evaluate,
|
||||
evaluateForAsync,
|
||||
Evaluator,
|
||||
AsyncEvaluator,
|
||||
extendsFilters,
|
||||
filters,
|
||||
getFilters,
|
||||
lexer,
|
||||
parse,
|
||||
registerFilter,
|
||||
registerFunction
|
||||
} from 'amis-formula';
|
||||
import type {FilterContext} from 'amis-formula';
|
||||
import LazyComponent from './components/LazyComponent';
|
||||
import Overlay from './components/Overlay';
|
||||
import PopOver from './components/PopOver';
|
||||
import ErrorBoundary from './components/ErrorBoundary';
|
||||
import {FormRenderer} from './renderers/Form';
|
||||
import type {FormHorizontal, FormSchemaBase} from './renderers/Form';
|
||||
import {
|
||||
enableDebug,
|
||||
disableDebug,
|
||||
promisify,
|
||||
replaceText,
|
||||
wrapFetcher,
|
||||
resolveVariableAndFilter,
|
||||
resolveVariableAndFilterForAsync
|
||||
} from './utils/index';
|
||||
import type {OnEventProps} from './utils/index';
|
||||
import {valueMap as styleMap} from './utils/style-helper';
|
||||
import {
|
||||
RENDERER_TRANSMISSION_OMIT_PROPS,
|
||||
SchemaRenderer
|
||||
} from './SchemaRenderer';
|
||||
import type {IItem} from './store/list';
|
||||
import CustomStyle from './components/CustomStyle';
|
||||
import {StatusScoped} from './StatusScoped';
|
||||
|
||||
import styleManager from './StyleManager';
|
||||
|
||||
import {bindGlobalEvent, dispatchGlobalEvent} from './utils/renderer-event';
|
||||
|
||||
import {getCustomVendor, registerCustomVendor} from './utils/icon';
|
||||
|
||||
// @ts-ignore
|
||||
export const version = '__buildVersion';
|
||||
(window as any).amisVersionInfo = {
|
||||
version: '__buildVersion',
|
||||
buildTime: '__buildTime'
|
||||
};
|
||||
|
||||
export {
|
||||
styleManager,
|
||||
clearStoresCache,
|
||||
updateEnv,
|
||||
Renderer,
|
||||
RendererProps,
|
||||
RenderOptions,
|
||||
RendererEnv,
|
||||
EnvContext,
|
||||
RegisterStore,
|
||||
registerStore,
|
||||
FormItem,
|
||||
FormItemWrap,
|
||||
FormItemProps,
|
||||
OptionsControl,
|
||||
FormRenderer,
|
||||
FormHorizontal,
|
||||
// 其他功能类方法
|
||||
utils,
|
||||
getRendererByName,
|
||||
registerRenderer,
|
||||
unRegisterRenderer,
|
||||
getRenderers,
|
||||
loadAllAsyncRenderers,
|
||||
loadAsyncRenderersByType,
|
||||
loadAsyncRenderer,
|
||||
hasAsyncRenderers,
|
||||
registerFormItem,
|
||||
getFormItemByName,
|
||||
registerOptionsControl,
|
||||
resolveRenderer,
|
||||
filterSchema,
|
||||
Scoped,
|
||||
ScopedContext,
|
||||
IScopedContext,
|
||||
StatusScoped,
|
||||
setDefaultTheme,
|
||||
theme,
|
||||
themeable,
|
||||
ThemeProps,
|
||||
getTheme,
|
||||
classPrefix,
|
||||
getClassPrefix,
|
||||
classnames,
|
||||
makeClassnames,
|
||||
// 全局广播事件
|
||||
bindGlobalEvent,
|
||||
dispatchGlobalEvent,
|
||||
// 多语言相关
|
||||
getDefaultLocale,
|
||||
setDefaultLocale,
|
||||
registerLocale,
|
||||
makeTranslator,
|
||||
extendLocale,
|
||||
removeLocaleData,
|
||||
localeable,
|
||||
localeFormatter,
|
||||
LocaleProps,
|
||||
TranslateFn,
|
||||
ClassNamesFn,
|
||||
// amis-formula 相关
|
||||
parse,
|
||||
lexer,
|
||||
Evaluator,
|
||||
AsyncEvaluator,
|
||||
FilterContext,
|
||||
filters,
|
||||
getFilters,
|
||||
registerFilter,
|
||||
extendsFilters,
|
||||
registerFunction,
|
||||
evaluate,
|
||||
evaluateForAsync,
|
||||
// 其他
|
||||
LazyComponent,
|
||||
Overlay,
|
||||
PopOver,
|
||||
ErrorBoundary,
|
||||
addSchemaFilter,
|
||||
OptionsControlProps,
|
||||
OptionsControlBase,
|
||||
FormOptionsControl,
|
||||
FormOptionsControlSelf,
|
||||
FormControlProps,
|
||||
FormBaseControl,
|
||||
FormBaseControlWithoutSize,
|
||||
extendDefaultEnv,
|
||||
addRootWrapper,
|
||||
RendererConfig,
|
||||
styleMap,
|
||||
RENDERER_TRANSMISSION_OMIT_PROPS,
|
||||
ScopedComponentType,
|
||||
IItem,
|
||||
IColumn,
|
||||
IRow,
|
||||
IColumn2,
|
||||
IRow2,
|
||||
OnEventProps,
|
||||
FormSchemaBase,
|
||||
filterTarget,
|
||||
splitTarget,
|
||||
CustomStyle,
|
||||
enableDebug,
|
||||
disableDebug,
|
||||
envOverwrite,
|
||||
getGlobalOptions,
|
||||
setGlobalOptions,
|
||||
wrapFetcher,
|
||||
SchemaRenderer,
|
||||
getCustomVendor,
|
||||
registerCustomVendor,
|
||||
resolveVariableAndFilter,
|
||||
resolveVariableAndFilterForAsync
|
||||
};
|
||||
|
||||
export function render(
|
||||
schema: Schema,
|
||||
{key, ...props}: RootRenderProps = {},
|
||||
options: RenderOptions = {},
|
||||
pathPrefix: string = ''
|
||||
): JSX.Element {
|
||||
return (
|
||||
<AMISRenderer
|
||||
{...props}
|
||||
key={key}
|
||||
schema={schema}
|
||||
pathPrefix={pathPrefix}
|
||||
options={options}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AMISRenderer({
|
||||
schema,
|
||||
options,
|
||||
pathPrefix,
|
||||
...props
|
||||
}: RootRenderProps & {
|
||||
schema: Schema;
|
||||
options: RenderOptions;
|
||||
pathPrefix: string;
|
||||
}) {
|
||||
let locale = props.locale || getDefaultLocale();
|
||||
// 兼容 locale 的不同写法
|
||||
locale =
|
||||
locale === 'en'
|
||||
? 'en-US'
|
||||
: locale === 'zh' || locale === 'cn'
|
||||
? 'zh-CN'
|
||||
: locale.replace('_', '-');
|
||||
|
||||
const translate = React.useCallback(
|
||||
function () {
|
||||
const fn = props.translate || makeTranslator(locale);
|
||||
return fn.apply(null, arguments);
|
||||
},
|
||||
[locale, props.translate]
|
||||
);
|
||||
const store = React.useMemo(() => {
|
||||
let store = stores[options.session || 'global'];
|
||||
|
||||
if (!store) {
|
||||
options = {
|
||||
...defaultOptions,
|
||||
...options,
|
||||
fetcher: options.fetcher
|
||||
? wrapFetcher(options.fetcher, options.tracker)
|
||||
: defaultOptions.fetcher,
|
||||
confirm: promisify(
|
||||
options.confirm || defaultOptions.confirm || window.confirm
|
||||
),
|
||||
locale,
|
||||
translate
|
||||
} as any;
|
||||
|
||||
store = RendererStore.create({}, options);
|
||||
stores[options.session || 'global'] = store;
|
||||
} else {
|
||||
// 更新 env
|
||||
const env = getEnv(store);
|
||||
Object.assign(env, {
|
||||
...options,
|
||||
fetcher: options.fetcher
|
||||
? wrapFetcher(options.fetcher, options.tracker)
|
||||
: env.fetcher,
|
||||
confirm: options.confirm ? promisify(options.confirm) : env.confirm,
|
||||
locale,
|
||||
translate
|
||||
});
|
||||
}
|
||||
|
||||
(window as any).amisStore = store; // 为了方便 debug.
|
||||
return store;
|
||||
}, Object.keys(options).concat(Object.values(options)).concat(locale));
|
||||
|
||||
const env = getEnv(store);
|
||||
let theme = props.theme || options.theme || 'cxd';
|
||||
if (theme === 'default') {
|
||||
theme = 'cxd';
|
||||
}
|
||||
env.theme = getTheme(theme);
|
||||
|
||||
React.useEffect(() => {
|
||||
env.enableAMISDebug ? enableDebug() : disableDebug();
|
||||
return () => env.enableAMISDebug || disableDebug();
|
||||
}, [env.enableAMISDebug]);
|
||||
|
||||
if (props.locale !== undefined) {
|
||||
env.translate = translate;
|
||||
env.locale = locale;
|
||||
}
|
||||
|
||||
// 默认将开启移动端原生 UI
|
||||
if (options.useMobileUI !== false) {
|
||||
props.mobileUI = env.isMobile();
|
||||
}
|
||||
|
||||
// 根据环境覆盖 schema,这个要在最前面做,不然就无法覆盖 validations
|
||||
schema = React.useMemo(() => {
|
||||
schema = envOverwrite(schema, locale, env.isMobile() ? 'mobile' : 'pc');
|
||||
// todo 和 envOverwrite 一起处理,减少循环次数
|
||||
schema = replaceText(
|
||||
schema,
|
||||
options.replaceText,
|
||||
env.replaceTextIgnoreKeys
|
||||
);
|
||||
return schema;
|
||||
}, [schema, locale, options.replaceText]);
|
||||
|
||||
return (
|
||||
<EnvContext.Provider value={env}>
|
||||
<ScopedRootRenderer
|
||||
{...props}
|
||||
schema={schema}
|
||||
pathPrefix={pathPrefix}
|
||||
rootStore={store}
|
||||
env={env}
|
||||
theme={theme}
|
||||
locale={locale}
|
||||
translate={translate}
|
||||
/>
|
||||
</EnvContext.Provider>
|
||||
);
|
||||
}
|
||||
208
packages/amis-core/src/locale.tsx
Normal file
208
packages/amis-core/src/locale.tsx
Normal file
@@ -0,0 +1,208 @@
|
||||
// 多语言支持
|
||||
import React from 'react';
|
||||
import hoistNonReactStatic from 'hoist-non-react-statics';
|
||||
import moment from 'moment';
|
||||
import {resolveVariable} from './utils/tpl-builtin';
|
||||
|
||||
export type TranslateFn<T = any> = (str: T, data?: object) => T;
|
||||
|
||||
interface LocaleConfig {
|
||||
[propsName: string]: string;
|
||||
}
|
||||
|
||||
let defaultLocale: string = 'zh-CN';
|
||||
|
||||
const momentLocaleMap: Record<string, string> = {
|
||||
'zh-CN': 'zh-cn',
|
||||
'en-US': 'en',
|
||||
'de-DE': 'de'
|
||||
};
|
||||
|
||||
const locales: {
|
||||
[propName: string]: LocaleConfig;
|
||||
} = {};
|
||||
|
||||
export function register(name: string, config: LocaleConfig) {
|
||||
// 修改为扩展,防止已注册的语料被覆盖
|
||||
extendLocale(name, config);
|
||||
}
|
||||
|
||||
export function extendLocale(
|
||||
name: string,
|
||||
config: LocaleConfig,
|
||||
cover: boolean = true
|
||||
) {
|
||||
if (cover) {
|
||||
// 覆盖式扩展语料
|
||||
locales[name] = {
|
||||
...(locales[name] || {}),
|
||||
...config
|
||||
};
|
||||
} else {
|
||||
locales[name] = {
|
||||
...config,
|
||||
...(locales[name] || {})
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** 删除语料数据 */
|
||||
export function removeLocaleData(name: string, key: Array<string> | string) {
|
||||
if (Array.isArray(key)) {
|
||||
key.forEach(item => {
|
||||
removeLocaleData(name, item);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (locales?.[name]?.[key]) {
|
||||
delete locales[name][key];
|
||||
}
|
||||
}
|
||||
|
||||
const fns: {
|
||||
[propName: string]: TranslateFn;
|
||||
} = {};
|
||||
|
||||
export function format(str: string, data?: object) {
|
||||
if (!str.includes('{{')) return str; // 先快速检查,避免无谓的正则执行
|
||||
|
||||
return str.replace(/(\\)?\{\{([^{}]+?)\}\}/g, (_, escape, key) => {
|
||||
if (escape) {
|
||||
return _.substring(1);
|
||||
}
|
||||
|
||||
return resolveVariable(key, data || {});
|
||||
});
|
||||
}
|
||||
|
||||
export function makeTranslator(locale?: string): TranslateFn {
|
||||
if (locale && fns[locale]) {
|
||||
return fns[locale];
|
||||
}
|
||||
|
||||
const fn = (str: any, ...args: any[]) => {
|
||||
if (!str || typeof str !== 'string') {
|
||||
return str;
|
||||
}
|
||||
|
||||
const value =
|
||||
locales[locale!]?.[str] ||
|
||||
locales[defaultLocale]?.[str] ||
|
||||
locales['zh-CN']?.[str] ||
|
||||
str;
|
||||
return format(value, ...args);
|
||||
};
|
||||
|
||||
locale && (fns[locale] = fn);
|
||||
return fn;
|
||||
}
|
||||
|
||||
export function getDefaultLocale() {
|
||||
return defaultLocale;
|
||||
}
|
||||
|
||||
export function setDefaultLocale(locale: string) {
|
||||
defaultLocale = locale;
|
||||
}
|
||||
|
||||
export interface LocaleProps {
|
||||
locale: string;
|
||||
translate: TranslateFn;
|
||||
}
|
||||
|
||||
export const LocaleContext = React.createContext('');
|
||||
|
||||
export function localeable<
|
||||
T extends React.ComponentType<React.ComponentProps<T> & LocaleProps>
|
||||
>(ComposedComponent: T, methods?: Array<string>) {
|
||||
type OuterProps = JSX.LibraryManagedAttributes<
|
||||
T,
|
||||
Omit<React.ComponentProps<T>, keyof LocaleProps>
|
||||
> & {
|
||||
locale?: string;
|
||||
translate?: (str: string, ...args: any[]) => string;
|
||||
};
|
||||
|
||||
const result = hoistNonReactStatic(
|
||||
class extends React.Component<OuterProps> {
|
||||
static displayName: string = `I18N(${
|
||||
ComposedComponent.displayName || ComposedComponent.name
|
||||
})`;
|
||||
static contextType = LocaleContext;
|
||||
static ComposedComponent = ComposedComponent as React.ComponentType<T>;
|
||||
|
||||
constructor(props: OuterProps) {
|
||||
super(props);
|
||||
|
||||
this.childRef = this.childRef.bind(this);
|
||||
this.getWrappedInstance = this.getWrappedInstance.bind(this);
|
||||
}
|
||||
|
||||
ref: any;
|
||||
|
||||
childRef(ref: any) {
|
||||
while (ref && ref.getWrappedInstance) {
|
||||
ref = ref.getWrappedInstance();
|
||||
}
|
||||
|
||||
this.ref = ref;
|
||||
}
|
||||
|
||||
getWrappedInstance() {
|
||||
return this.ref;
|
||||
}
|
||||
|
||||
render() {
|
||||
const locale: string =
|
||||
this.props.locale || (this.context as string) || defaultLocale;
|
||||
const translate = this.props.translate || makeTranslator(locale);
|
||||
const injectedProps: {
|
||||
locale: string;
|
||||
translate: TranslateFn;
|
||||
} = {
|
||||
locale,
|
||||
translate: translate!
|
||||
};
|
||||
moment.locale(momentLocaleMap?.[locale] ?? locale);
|
||||
const refConfig =
|
||||
ComposedComponent.prototype?.isReactComponent ||
|
||||
(ComposedComponent as any).$$typeof ===
|
||||
Symbol.for('react.forward_ref')
|
||||
? {ref: this.childRef}
|
||||
: {forwardedRef: this.childRef};
|
||||
|
||||
const body = (
|
||||
<ComposedComponent
|
||||
{...(this.props as JSX.LibraryManagedAttributes<
|
||||
T,
|
||||
React.ComponentProps<T>
|
||||
> as any)}
|
||||
{...injectedProps}
|
||||
{...refConfig}
|
||||
/>
|
||||
);
|
||||
return this.context ? (
|
||||
body
|
||||
) : (
|
||||
<LocaleContext.Provider value={locale}>{body}</LocaleContext.Provider>
|
||||
);
|
||||
}
|
||||
},
|
||||
ComposedComponent
|
||||
);
|
||||
|
||||
if (Array.isArray(methods)) {
|
||||
methods.forEach(method => {
|
||||
if (ComposedComponent.prototype[method]) {
|
||||
(result as any).prototype[method] = function () {
|
||||
const fn = this.ref?.[method];
|
||||
return fn ? fn.apply(this.ref, arguments) : undefined;
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return result as typeof result & {
|
||||
ComposedComponent: T;
|
||||
};
|
||||
}
|
||||
10
packages/amis-core/src/polyfills.ts
Normal file
10
packages/amis-core/src/polyfills.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* 用于放一些关键的 polyfill
|
||||
*/
|
||||
|
||||
// ios 老版本没有这个会报错
|
||||
if (!('DragEvent' in window)) {
|
||||
Object.defineProperty(window, 'DragEvent', {
|
||||
value: class DragEvent {}
|
||||
});
|
||||
}
|
||||
2615
packages/amis-core/src/renderers/Form.tsx
Normal file
2615
packages/amis-core/src/renderers/Form.tsx
Normal file
File diff suppressed because it is too large
Load Diff
2407
packages/amis-core/src/renderers/Item.tsx
Normal file
2407
packages/amis-core/src/renderers/Item.tsx
Normal file
File diff suppressed because it is too large
Load Diff
1453
packages/amis-core/src/renderers/Options.tsx
Normal file
1453
packages/amis-core/src/renderers/Options.tsx
Normal file
File diff suppressed because it is too large
Load Diff
12
packages/amis-core/src/renderers/Placeholder.tsx
Normal file
12
packages/amis-core/src/renderers/Placeholder.tsx
Normal file
@@ -0,0 +1,12 @@
|
||||
import React from 'react';
|
||||
import {RendererProps} from '../factory';
|
||||
|
||||
export class Placeholder extends React.Component<RendererProps> {
|
||||
componentDidMount() {
|
||||
console.warn(`Please implement this renderer(${this.props.type})`);
|
||||
}
|
||||
|
||||
render() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
23
packages/amis-core/src/renderers/builtin.tsx
Normal file
23
packages/amis-core/src/renderers/builtin.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import {Placeholder} from './Placeholder';
|
||||
import './Form.tsx';
|
||||
import {registerRenderer} from '../factory';
|
||||
|
||||
registerRenderer({
|
||||
type: 'spinner',
|
||||
component: Placeholder
|
||||
});
|
||||
|
||||
registerRenderer({
|
||||
type: 'alert',
|
||||
component: Placeholder
|
||||
});
|
||||
|
||||
registerRenderer({
|
||||
type: 'dialog',
|
||||
component: Placeholder
|
||||
});
|
||||
|
||||
registerRenderer({
|
||||
type: 'drawer',
|
||||
component: Placeholder
|
||||
});
|
||||
95
packages/amis-core/src/renderers/register.ts
Normal file
95
packages/amis-core/src/renderers/register.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import {renderersMap, Renderer} from '../factory';
|
||||
import {OptionsControl} from './Options';
|
||||
import FormItem from './Item';
|
||||
|
||||
declare const window: Window & {
|
||||
AmisCustomRenderers: {
|
||||
[props: string]: any;
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 提供两种特殊的注册渲染器的方式
|
||||
* 1、自动加载预先注册的自定义渲染器:自动加载并注册 window.AmisCustomRenderers 中的渲染器
|
||||
* 2、通过 postMessage 告知 amis 注册一个新的渲染器:间接注册渲染器,无需直接依赖 amis。
|
||||
*/
|
||||
|
||||
// 自动加载预先注册的自定义渲染器
|
||||
export function autoPreRegisterAmisCustomRenderers() {
|
||||
if (window.AmisCustomRenderers) {
|
||||
Object.keys(window.AmisCustomRenderers).forEach(rendererType => {
|
||||
if (renderersMap[rendererType]) {
|
||||
console.warn(`[amis-core]:预注册渲染器失败,当前已存在重名渲染器(${rendererType})。`);
|
||||
} else {
|
||||
const curAmisRenderer = window.AmisCustomRenderers[rendererType];
|
||||
if (curAmisRenderer) {
|
||||
registerAmisRendererByUsage(rendererType, curAmisRenderer);
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 自动加载并注册 window.AmisCustomRenderers 中的渲染器
|
||||
autoPreRegisterAmisCustomRenderers();
|
||||
|
||||
// postMessage 渲染器动态注册机制
|
||||
window.addEventListener(
|
||||
'message',
|
||||
(event: any) => {
|
||||
if (!event.data) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
event.data?.type === 'amis-renderer-register-event' &&
|
||||
event.data?.amisRenderer &&
|
||||
event.data.amisRenderer.type
|
||||
) {
|
||||
const curAmisRenderer = event.data?.amisRenderer;
|
||||
const curUsage = curAmisRenderer?.usage || 'renderer';
|
||||
if (renderersMap[curAmisRenderer.type]) {
|
||||
console.warn(`[amis-core]:动态注册渲染器失败,当前已存在重名渲染器(${curAmisRenderer.type})。`);
|
||||
} else {
|
||||
console.info(
|
||||
'[amis-core]响应动态注册渲染器事件:',
|
||||
curAmisRenderer.type
|
||||
);
|
||||
registerAmisRendererByUsage(curUsage, curAmisRenderer);
|
||||
}
|
||||
}
|
||||
},
|
||||
false
|
||||
);
|
||||
|
||||
// 根据类型(usage)进行注册 amis渲染器
|
||||
function registerAmisRendererByUsage(curUsage: string, curAmisRenderer: any) {
|
||||
// 当前支持注册的渲染器类型
|
||||
const registerMap: {
|
||||
[props: string]: Function
|
||||
} = {
|
||||
renderer: Renderer,
|
||||
formitem: FormItem,
|
||||
options: OptionsControl,
|
||||
};
|
||||
let curAmisRendererComponent = curAmisRenderer.component;
|
||||
if (
|
||||
!curAmisRendererComponent &&
|
||||
window.AmisCustomRenderers &&
|
||||
window.AmisCustomRenderers[curAmisRenderer.type] &&
|
||||
window.AmisCustomRenderers[curAmisRenderer.type].component
|
||||
) {
|
||||
curAmisRendererComponent = window.AmisCustomRenderers[curAmisRenderer.type].component;
|
||||
}
|
||||
if (
|
||||
curAmisRendererComponent &&
|
||||
['renderer', 'formitem', 'options'].includes(curUsage) &&
|
||||
registerMap[curUsage]
|
||||
) {
|
||||
registerMap[curUsage as keyof typeof registerMap]({
|
||||
...(curAmisRenderer.config || {}),
|
||||
type: curAmisRenderer.type,
|
||||
weight: curAmisRenderer.weight || 0,
|
||||
autoVar: curAmisRenderer.autoVar || false
|
||||
})(curAmisRendererComponent);
|
||||
}
|
||||
}
|
||||
1039
packages/amis-core/src/renderers/wrapControl.tsx
Normal file
1039
packages/amis-core/src/renderers/wrapControl.tsx
Normal file
File diff suppressed because it is too large
Load Diff
253
packages/amis-core/src/store/app.ts
Normal file
253
packages/amis-core/src/store/app.ts
Normal file
@@ -0,0 +1,253 @@
|
||||
import {Instance, SnapshotIn, types} from 'mobx-state-tree';
|
||||
import {RendererEnv} from '../factory';
|
||||
import {NavigationObject} from '../types';
|
||||
import {
|
||||
createObject,
|
||||
filterTree,
|
||||
replaceUrlParams,
|
||||
findTree,
|
||||
guid,
|
||||
mapTree
|
||||
} from '../utils/helper';
|
||||
import {ServiceStore} from './service';
|
||||
import {filter, isVisible, resolveVariableAndFilter} from '../utils';
|
||||
|
||||
export const AppStore = ServiceStore.named('AppStore')
|
||||
.props({
|
||||
pages: types.frozen(),
|
||||
activePage: types.frozen(),
|
||||
folded: false,
|
||||
offScreen: false
|
||||
})
|
||||
.views(self => ({
|
||||
get navigations(): Array<NavigationObject> {
|
||||
if (Array.isArray(self.pages)) {
|
||||
return mapTree(self.pages, item => {
|
||||
let visible = isVisible(item, self.data);
|
||||
|
||||
if (
|
||||
visible !== false &&
|
||||
item.path &&
|
||||
!~item.path.indexOf('http') &&
|
||||
~item.path.indexOf(':')
|
||||
) {
|
||||
visible = false;
|
||||
}
|
||||
|
||||
return {
|
||||
label: item.label,
|
||||
icon: item.icon,
|
||||
path: item.path,
|
||||
children: item.children,
|
||||
className: item.className,
|
||||
visible,
|
||||
badge:
|
||||
typeof item.badge === 'string'
|
||||
? filter(item.badge, self.data)
|
||||
: item.badge,
|
||||
badgeClassName: filter(item.badgeClassName, self.data)
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
label: self.__('App.navigation'),
|
||||
children: []
|
||||
}
|
||||
];
|
||||
},
|
||||
get bcn() {
|
||||
return self.activePage?.bcn || [];
|
||||
},
|
||||
|
||||
get pageData() {
|
||||
return createObject(self.data, {
|
||||
params: self.activePage?.params || {}
|
||||
});
|
||||
}
|
||||
}))
|
||||
.actions(self => ({
|
||||
toggleFolded() {
|
||||
self.folded = !self.folded;
|
||||
},
|
||||
toggleOffScreen() {
|
||||
self.offScreen = !self.offScreen;
|
||||
},
|
||||
updateOffScreen(value: boolean) {
|
||||
self.offScreen = value;
|
||||
},
|
||||
|
||||
setPages(pages: any) {
|
||||
if (pages && !Array.isArray(pages)) {
|
||||
pages = [pages];
|
||||
} else if (!Array.isArray(pages)) {
|
||||
return;
|
||||
}
|
||||
|
||||
pages = mapTree(pages, (item, index, level, paths) => {
|
||||
let path = item.link || item.url;
|
||||
|
||||
if (item.schema || item.schemaApi) {
|
||||
path =
|
||||
item.url ||
|
||||
`/${paths
|
||||
.map(item => item.index)
|
||||
.concat(index)
|
||||
.map(index => `page-${index + 1}`)
|
||||
.join('/')}`;
|
||||
|
||||
if (path && path[0] !== '/') {
|
||||
let parentPath = '/';
|
||||
let index = paths.length;
|
||||
while (index > 0) {
|
||||
const item = paths[index - 1];
|
||||
|
||||
if (item?.path) {
|
||||
parentPath = item.path + '/';
|
||||
break;
|
||||
}
|
||||
index--;
|
||||
}
|
||||
|
||||
path = parentPath + path;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...item,
|
||||
index,
|
||||
id: item.id || guid(),
|
||||
label: item.label,
|
||||
icon: item.icon,
|
||||
path
|
||||
};
|
||||
});
|
||||
self.pages = pages;
|
||||
},
|
||||
|
||||
rewrite(to: string, env: RendererEnv) {
|
||||
let page = findTree(self.pages, item => {
|
||||
if (item.path === to) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
if (page) {
|
||||
this.setActivePage(page, env);
|
||||
}
|
||||
},
|
||||
|
||||
setActivePage(
|
||||
page: any,
|
||||
env: RendererEnv & {
|
||||
showFullBreadcrumbPath?: boolean;
|
||||
showBreadcrumbHomePath?: boolean;
|
||||
},
|
||||
params?: any
|
||||
) {
|
||||
// 同一个页面直接返回。
|
||||
if (self.activePage?.id === page.id) {
|
||||
if (params !== undefined) {
|
||||
self.activePage = {
|
||||
...self.activePage,
|
||||
params: params
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let bcn: Array<any> = [];
|
||||
|
||||
findTree(self.pages, (item, index, level, paths) => {
|
||||
if (item.id === page.id) {
|
||||
bcn = paths
|
||||
.filter(item => item.path && item.label)
|
||||
.map(item => ({
|
||||
...item,
|
||||
path: replaceUrlParams(item.path, params)
|
||||
}));
|
||||
if (env.showFullBreadcrumbPath) {
|
||||
bcn = paths.filter(item => item.label);
|
||||
}
|
||||
bcn.push({
|
||||
...item,
|
||||
path: ''
|
||||
});
|
||||
self.__;
|
||||
if (env.showBreadcrumbHomePath && bcn[0].path !== '/') {
|
||||
bcn.unshift({
|
||||
label: self.__('App.home'),
|
||||
path: '/'
|
||||
});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
self.activePage = {
|
||||
...page,
|
||||
params: params || {},
|
||||
bcn
|
||||
};
|
||||
|
||||
if (page.label) {
|
||||
document.title = page.label;
|
||||
}
|
||||
|
||||
if (page.schema) {
|
||||
self.schema = page.schema;
|
||||
self.schemaKey = '' + Date.now();
|
||||
} else if (page.schemaApi) {
|
||||
self.schema = null;
|
||||
self.fetchSchema(page.schemaApi, self.activePage, {method: 'get'});
|
||||
} else if (page.redirect) {
|
||||
env.jumpTo(page.redirect, undefined, self.data);
|
||||
return;
|
||||
} else if (page.rewrite) {
|
||||
this.rewrite(page.rewrite, env);
|
||||
} else {
|
||||
self.schema = null;
|
||||
self.schemaKey = '';
|
||||
}
|
||||
},
|
||||
|
||||
updateActivePage(env: RendererEnv) {
|
||||
if (!Array.isArray(self.pages)) {
|
||||
return;
|
||||
}
|
||||
let matched: any;
|
||||
|
||||
let page = findTree(self.pages, item => {
|
||||
if (item.path) {
|
||||
matched = env.isCurrentUrl(item.path, item);
|
||||
|
||||
if (matched) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
if (page) {
|
||||
this.setActivePage(
|
||||
page,
|
||||
env,
|
||||
typeof matched === 'object' ? matched.params : undefined
|
||||
);
|
||||
} else {
|
||||
const page = findTree(self.pages, item => item.isDefaultPage);
|
||||
|
||||
if (page) {
|
||||
this.setActivePage(page, env);
|
||||
} else {
|
||||
self.activePage = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
export type IAppStore = Instance<typeof AppStore>;
|
||||
export type SAppStore = SnapshotIn<typeof AppStore>;
|
||||
219
packages/amis-core/src/store/combo.ts
Normal file
219
packages/amis-core/src/store/combo.ts
Normal file
@@ -0,0 +1,219 @@
|
||||
import {types, SnapshotIn, Instance} from 'mobx-state-tree';
|
||||
import {iRendererStore} from './iRenderer';
|
||||
import type {IFormStore, IFormItemStore} from './form';
|
||||
import {getStoreById} from './manager';
|
||||
import {countTree} from '../utils/helper';
|
||||
|
||||
export const UniqueGroup = types
|
||||
.model('UniqueGroup', {
|
||||
name: types.identifier,
|
||||
itemsRef: types.array(types.string)
|
||||
})
|
||||
.views(self => ({
|
||||
get items() {
|
||||
return self.itemsRef.map(id => getStoreById(id) as any as IFormItemStore);
|
||||
}
|
||||
}))
|
||||
.actions(self => ({
|
||||
removeItem(item: IFormItemStore) {
|
||||
self.itemsRef.replace(self.itemsRef.filter(id => id !== item.id));
|
||||
},
|
||||
|
||||
addItem(item: IFormItemStore) {
|
||||
self.itemsRef.push(item.id);
|
||||
}
|
||||
}));
|
||||
|
||||
export type IUniqueGroup = typeof UniqueGroup.Type;
|
||||
|
||||
export const ComboStore = iRendererStore
|
||||
.named('ComboStore')
|
||||
.props({
|
||||
uniques: types.map(UniqueGroup),
|
||||
multiple: false,
|
||||
formsRef: types.optional(types.array(types.string), []),
|
||||
minLength: 0,
|
||||
maxLength: 0,
|
||||
length: 0,
|
||||
activeKey: 0,
|
||||
perPage: 0,
|
||||
page: 1,
|
||||
memberValidMap: types.optional(types.frozen(), {})
|
||||
})
|
||||
.views(self => {
|
||||
function getForms() {
|
||||
return self.formsRef.map(item => getStoreById(item) as IFormStore);
|
||||
}
|
||||
|
||||
return {
|
||||
get forms() {
|
||||
return getForms();
|
||||
},
|
||||
|
||||
get addable() {
|
||||
if (self.maxLength && self.length >= self.maxLength) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (self.uniques.size) {
|
||||
let isFull = false;
|
||||
self.uniques.forEach(item => {
|
||||
if (isFull || !item.items.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
let total = countTree(
|
||||
item.items[0].options,
|
||||
item => typeof item.value !== 'undefined'
|
||||
);
|
||||
let current = item.items.reduce((total, item) => {
|
||||
return total + item.selectedOptions.length;
|
||||
}, 0);
|
||||
|
||||
isFull = total && current >= total ? true : false;
|
||||
});
|
||||
|
||||
if (isFull) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
get removable() {
|
||||
if (self.minLength && self.minLength >= self.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
* name 值有两种类型:
|
||||
* 1. 数字索引,出现在多条模式下,这个时候,需要返回当前索引下的form,并且用于下一层的遍历搜索
|
||||
* 2. 普通的表单项 name 值,出现在单条模式下,当前这层查找已经结束,所以要返回当前找到的items,而不能返回form
|
||||
*
|
||||
* @param name 查找的name
|
||||
*/
|
||||
getItemsByName(name: string): any {
|
||||
const forms = getForms();
|
||||
return self.multiple
|
||||
? [forms[parseInt(name, 10)]]
|
||||
: forms[0].getItemsByName(name);
|
||||
},
|
||||
|
||||
get multiplePage() {
|
||||
return self.multiple && self.perPage > 0;
|
||||
},
|
||||
|
||||
get offset() {
|
||||
return (self.page - 1) * self.perPage;
|
||||
},
|
||||
|
||||
getRangeByPage(items: Array<any>) {
|
||||
if (self.perPage <= 0) {
|
||||
return items;
|
||||
}
|
||||
|
||||
const start = this.offset;
|
||||
const end = start + self.perPage;
|
||||
return items.slice(start, end);
|
||||
}
|
||||
};
|
||||
})
|
||||
.actions(self => {
|
||||
function config(setting: {
|
||||
multiple?: boolean;
|
||||
minLength?: number;
|
||||
maxLength?: number;
|
||||
length?: number;
|
||||
}) {
|
||||
typeof setting.multiple !== 'undefined' &&
|
||||
(self.multiple = setting.multiple);
|
||||
typeof setting.minLength !== 'undefined' &&
|
||||
(self.minLength = parseInt(setting.minLength as any, 10));
|
||||
typeof setting.maxLength !== 'undefined' &&
|
||||
(self.maxLength = parseInt(setting.maxLength as any, 10));
|
||||
typeof setting.length !== 'undefined' && (self.length = setting.length);
|
||||
}
|
||||
|
||||
function bindUniuqueItem(item: IFormItemStore) {
|
||||
if (!self.uniques.has(item.name)) {
|
||||
self.uniques.put({
|
||||
name: item.name
|
||||
});
|
||||
}
|
||||
let group: IUniqueGroup = self.uniques.get(item.name) as IUniqueGroup;
|
||||
group.addItem(item);
|
||||
}
|
||||
|
||||
function unBindUniuqueItem(item: IFormItemStore) {
|
||||
let group: IUniqueGroup = self.uniques.get(item.name) as IUniqueGroup;
|
||||
group.removeItem(item);
|
||||
if (!group.items.length) {
|
||||
self.uniques.delete(item.name);
|
||||
}
|
||||
}
|
||||
|
||||
function addForm(form: IFormStore) {
|
||||
self.formsRef.push(form.id);
|
||||
}
|
||||
|
||||
function onChildStoreDispose(child: IFormStore) {
|
||||
if (child.storeType === 'FormStore') {
|
||||
const idx = self.formsRef.indexOf(child.id);
|
||||
if (~idx) {
|
||||
self.formsRef.splice(idx, 1);
|
||||
child.items.forEach(item => {
|
||||
if (item.unique) {
|
||||
unBindUniuqueItem(item);
|
||||
}
|
||||
});
|
||||
|
||||
self.forms.forEach(form =>
|
||||
form.items.forEach(item => {
|
||||
if (item.unique) {
|
||||
item.syncOptions(undefined, form.data);
|
||||
|
||||
if (item.errors.length) {
|
||||
item.validate(item.tmpValue);
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
self.removeChildId(child.id);
|
||||
}
|
||||
|
||||
function setActiveKey(key: number) {
|
||||
self.activeKey = key;
|
||||
}
|
||||
|
||||
function setMemberValid(valid: boolean, index: number) {
|
||||
self.memberValidMap = {
|
||||
...self.memberValidMap,
|
||||
[index]: valid
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
config,
|
||||
setActiveKey,
|
||||
bindUniuqueItem,
|
||||
unBindUniuqueItem,
|
||||
addForm,
|
||||
onChildStoreDispose,
|
||||
setMemberValid,
|
||||
changePage: (page: number, perPage?: number) => {
|
||||
self.page = page || 1;
|
||||
if (typeof perPage === 'number') {
|
||||
self.perPage = perPage;
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
export type IComboStore = Instance<typeof ComboStore>;
|
||||
export type SComboStore = SnapshotIn<typeof ComboStore>;
|
||||
833
packages/amis-core/src/store/crud.ts
Normal file
833
packages/amis-core/src/store/crud.ts
Normal file
@@ -0,0 +1,833 @@
|
||||
import {saveAs} from 'file-saver';
|
||||
import {types, flow, getEnv, isAlive, Instance} from 'mobx-state-tree';
|
||||
import {IRendererStore} from './index';
|
||||
import {ServiceStore} from './service';
|
||||
import {
|
||||
extendObject,
|
||||
createObject,
|
||||
isObjectShallowModified,
|
||||
sortArray,
|
||||
applyFilters,
|
||||
isEmpty,
|
||||
qsstringify,
|
||||
findTreeIndex,
|
||||
getVariable
|
||||
} from '../utils/helper';
|
||||
import {Api, Payload, fetchOptions, ActionObject, ApiObject} from '../types';
|
||||
import pick from 'lodash/pick';
|
||||
import {resolveVariableAndFilter} from '../utils/tpl-builtin';
|
||||
import {normalizeApiResponseData} from '../utils/api';
|
||||
import {matchSorter} from 'match-sorter';
|
||||
import {filter} from '../utils/tpl';
|
||||
import {TableStore} from './table';
|
||||
|
||||
import type {ITableStore} from './table';
|
||||
import type {MatchSorterOptions} from 'match-sorter';
|
||||
|
||||
interface MatchFunc {
|
||||
(
|
||||
/* 当前列表的全量数据 */
|
||||
items: any,
|
||||
/* 最近一次接口返回的全量数据 */
|
||||
itemsRaw: any,
|
||||
/** 相关配置 */
|
||||
options?: {
|
||||
/* 查询参数 */
|
||||
query: Record<string, any>;
|
||||
/* 列配置 */
|
||||
columns: any;
|
||||
/**
|
||||
* match-sorter 匹配函数
|
||||
* @doc https://github.com/kentcdodds/match-sorter
|
||||
*/
|
||||
matchSorter: (
|
||||
items: any[],
|
||||
value: string,
|
||||
options?: MatchSorterOptions<any>
|
||||
) => any[];
|
||||
}
|
||||
): any;
|
||||
}
|
||||
|
||||
class ServerError extends Error {
|
||||
type = 'ServerError';
|
||||
readonly response: any;
|
||||
constructor(msg: string, response?: any) {
|
||||
super(msg);
|
||||
Object.setPrototypeOf(this, ServerError.prototype);
|
||||
this.response = response;
|
||||
}
|
||||
}
|
||||
|
||||
export const CRUDStore = ServiceStore.named('CRUDStore')
|
||||
.props({
|
||||
pristineQuery: types.optional(types.frozen(), {}),
|
||||
query: types.optional(types.frozen(), {}),
|
||||
prevPage: 1,
|
||||
page: 1,
|
||||
perPage: 10,
|
||||
total: 0,
|
||||
mode: 'normal',
|
||||
hasNext: false,
|
||||
selectedAction: types.frozen(),
|
||||
columns: types.frozen(),
|
||||
items: types.optional(types.array(types.frozen()), []),
|
||||
selectedItems: types.optional(types.array(types.frozen()), []),
|
||||
unSelectedItems: types.optional(types.array(types.frozen()), []),
|
||||
filterTogglable: false,
|
||||
filterVisible: true,
|
||||
hasInnerModalOpen: false
|
||||
})
|
||||
.views(self => ({
|
||||
get lastPage() {
|
||||
return Math.max(
|
||||
Math.ceil(self.total / (self.perPage < 1 ? 10 : self.perPage)),
|
||||
1
|
||||
);
|
||||
},
|
||||
|
||||
get filterData() {
|
||||
return createObject(self.data, {
|
||||
...self.query
|
||||
});
|
||||
},
|
||||
|
||||
get toolbarData() {
|
||||
// 包两层,主要是为了处理以下 case
|
||||
// 里面放了个 form,form 提交过来的时候不希望把 items 这些发送过来。
|
||||
// 因为会把数据呈现在地址栏上。
|
||||
return createObject(createObject(self.data, this.eventContext), {
|
||||
...self.query
|
||||
});
|
||||
},
|
||||
|
||||
get mergedData() {
|
||||
return extendObject(self.data, {
|
||||
...self.query,
|
||||
...this.eventContext,
|
||||
...self.data
|
||||
});
|
||||
},
|
||||
|
||||
get hasModalOpened() {
|
||||
return self.dialogOpen || self.drawerOpen || self.hasInnerModalOpen;
|
||||
},
|
||||
|
||||
get selectedItemsAsArray() {
|
||||
return self.selectedItems.concat();
|
||||
},
|
||||
|
||||
get itemsAsArray() {
|
||||
return self.items.concat();
|
||||
},
|
||||
|
||||
fetchCtxOf(
|
||||
data: any,
|
||||
options: {
|
||||
pageField?: string;
|
||||
perPageField?: string;
|
||||
}
|
||||
) {
|
||||
return createObject(data, {
|
||||
...self.query,
|
||||
[options.pageField || 'page']: self.page,
|
||||
[options.perPageField || 'perPage']: self.perPage,
|
||||
...data
|
||||
});
|
||||
},
|
||||
|
||||
get eventContext() {
|
||||
const context = {
|
||||
items: self.items.concat(),
|
||||
selectedItems: self.selectedItems.concat(),
|
||||
unSelectedItems: self.unSelectedItems.concat(),
|
||||
selectedIndexes: self.selectedItems.map(
|
||||
item =>
|
||||
findTreeIndex(
|
||||
self.items,
|
||||
i => (item.__pristine || item) === (i.__pristine || i)
|
||||
)?.join('.') || '-1'
|
||||
)
|
||||
};
|
||||
|
||||
return context;
|
||||
},
|
||||
|
||||
get offset() {
|
||||
return (self.page - 1) * self.perPage;
|
||||
}
|
||||
}))
|
||||
.actions(self => {
|
||||
let fetchCancel: Function | null = null;
|
||||
|
||||
function setPristineQuery() {
|
||||
self.pristineQuery = self.query;
|
||||
}
|
||||
|
||||
function updateQuery(
|
||||
values: object,
|
||||
updater?: Function,
|
||||
pageField: string = 'page',
|
||||
perPageField: string = 'perPage',
|
||||
replace: boolean = false
|
||||
) {
|
||||
const originQuery = self.query;
|
||||
const query: any = replace
|
||||
? {
|
||||
...values
|
||||
}
|
||||
: {
|
||||
...originQuery,
|
||||
...values
|
||||
};
|
||||
|
||||
/**
|
||||
* 非严格模式下也需要严格比较的CASE
|
||||
* @reference https://tc39.es/ecma262/#sec-islooselyequal
|
||||
*/
|
||||
const exceptedLooselyRules: [any, any][] = [
|
||||
[0, ''],
|
||||
[false, ''],
|
||||
[false, '0'],
|
||||
[false, 0],
|
||||
[true, 1],
|
||||
[true, '1']
|
||||
];
|
||||
|
||||
if (
|
||||
isObjectShallowModified(originQuery, query, (lhs: any, rhs: any) => {
|
||||
if (
|
||||
exceptedLooselyRules.some(
|
||||
rule => rule.includes(lhs) && rule.includes(rhs)
|
||||
)
|
||||
) {
|
||||
return lhs !== rhs;
|
||||
}
|
||||
|
||||
return lhs != rhs;
|
||||
})
|
||||
) {
|
||||
if (query[pageField || 'page']) {
|
||||
self.page = parseInt(query[pageField || 'page'], 10);
|
||||
}
|
||||
|
||||
if (query[perPageField || 'perPage']) {
|
||||
self.perPage = parseInt(query[perPageField || 'perPage'], 10);
|
||||
}
|
||||
|
||||
self.query = query;
|
||||
updater && setTimeout(updater.bind(null, `?${qsstringify(query)}`), 4);
|
||||
}
|
||||
}
|
||||
|
||||
const fetchInitData: (
|
||||
api: Api,
|
||||
data?: object,
|
||||
options?: fetchOptions & {
|
||||
forceReload?: boolean;
|
||||
loadDataOnce?: boolean; // 配置数据是否一次性加载,如果是这样,由前端来完成分页,排序等
|
||||
source?: string; // 支持自定义属于映射,默认不配置,读取 rows 或者 items
|
||||
loadDataMode?: boolean;
|
||||
syncResponse2Query?: boolean;
|
||||
columns?: Array<any>;
|
||||
matchFunc?: MatchFunc;
|
||||
filterOnAllColumns?: boolean; // 前端是否让所有字段参与过滤
|
||||
isTable2?: Boolean; // 是否是 CRUD2
|
||||
minLoadingTime?: number; // 最小加载时间
|
||||
dataAppendTo?: 'top' | 'bottom';
|
||||
totalField?: string;
|
||||
}
|
||||
) => Promise<any> = flow(function* getInitData(
|
||||
api: Api,
|
||||
data: object,
|
||||
options: fetchOptions & {
|
||||
forceReload?: boolean;
|
||||
loadDataOnce?: boolean; // 配置数据是否一次性加载,如果是这样,由前端来完成分页,排序等功能。
|
||||
source?: string; // 支持自定义属于映射,默认不配置,读取 rows 或者 items
|
||||
loadDataMode?: boolean;
|
||||
syncResponse2Query?: boolean;
|
||||
columns?: Array<any>;
|
||||
matchFunc?: MatchFunc;
|
||||
filterOnAllColumns?: boolean; // 前端是否让所有字段参与过滤
|
||||
minLoadingTime?: number; // 最小加载时间
|
||||
totalField?: string;
|
||||
} = {}
|
||||
) {
|
||||
try {
|
||||
const startTime = Date.now();
|
||||
let rawItems = options.source
|
||||
? resolveVariableAndFilter(
|
||||
options.source,
|
||||
createObject(self.mergedData, {
|
||||
items: self.data.itemsRaw,
|
||||
rows: self.data.itemsRaw
|
||||
}),
|
||||
'| raw'
|
||||
)
|
||||
: self.items.concat();
|
||||
|
||||
if (!options.forceReload && options.loadDataOnce && rawItems?.length) {
|
||||
const matchFunc = options.matchFunc;
|
||||
let items = rawItems;
|
||||
|
||||
items = applyFilters(items, {
|
||||
query: self.query,
|
||||
columns: options.columns,
|
||||
matchFunc: matchFunc,
|
||||
filterOnAllColumns: options.filterOnAllColumns
|
||||
});
|
||||
|
||||
if (self.query.orderBy) {
|
||||
const dir = /desc/i.test(self.query.orderDir) ? -1 : 1;
|
||||
items = sortArray(items, self.query.orderBy, dir);
|
||||
}
|
||||
|
||||
const data = {
|
||||
...self.data,
|
||||
count: items.length,
|
||||
[options.totalField || 'total']: items.length,
|
||||
items: items.slice(
|
||||
(self.page - 1) * self.perPage,
|
||||
self.page * self.perPage
|
||||
)
|
||||
};
|
||||
self.total =
|
||||
parseInt(data[options.totalField || 'total'] ?? data.count, 10) ||
|
||||
0;
|
||||
self.reInitData(data);
|
||||
return;
|
||||
}
|
||||
|
||||
if (fetchCancel) {
|
||||
fetchCancel();
|
||||
fetchCancel = null;
|
||||
self.fetching = false;
|
||||
}
|
||||
|
||||
options.silent || self.markFetching(true);
|
||||
const ctx: any = createObject(self.data, {
|
||||
...self.query,
|
||||
...data,
|
||||
[options.pageField || 'page']: self.page,
|
||||
[options.perPageField || 'perPage']: self.perPage
|
||||
});
|
||||
|
||||
// 一次性加载不要发送 perPage 属性
|
||||
if (options.loadDataOnce) {
|
||||
delete ctx[options.perPageField || 'perPage'];
|
||||
}
|
||||
|
||||
const json: Payload = yield getEnv(self).fetcher(api, ctx, {
|
||||
...options,
|
||||
cancelExecutor: (executor: Function) => (fetchCancel = executor)
|
||||
});
|
||||
fetchCancel = null;
|
||||
|
||||
if (!json.ok) {
|
||||
self.updateMessage(
|
||||
(api as ApiObject)?.messages?.failed ??
|
||||
json.msg ??
|
||||
options.errorMessage ??
|
||||
self.__('CRUD.fetchFailed'),
|
||||
true
|
||||
);
|
||||
!(api as ApiObject)?.silent &&
|
||||
getEnv(self).notify(
|
||||
'error',
|
||||
json.msg,
|
||||
json.msgTimeout !== undefined
|
||||
? {
|
||||
closeButton: true,
|
||||
timeout: json.msgTimeout
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
} else {
|
||||
if (!json.data) {
|
||||
throw new Error(self.__('CRUD.invalidData'));
|
||||
}
|
||||
|
||||
if (options.minLoadingTime) {
|
||||
const elapsedTime = Date.now() - startTime;
|
||||
const remainingTime = options.minLoadingTime - elapsedTime;
|
||||
if (remainingTime > 0) {
|
||||
yield new Promise(resolve => setTimeout(resolve, remainingTime));
|
||||
}
|
||||
}
|
||||
|
||||
self.updatedAt = Date.now();
|
||||
let result = normalizeApiResponseData(json.data);
|
||||
|
||||
const {
|
||||
total,
|
||||
count,
|
||||
page,
|
||||
hasNext,
|
||||
items: oItems,
|
||||
rows: oRows,
|
||||
columns,
|
||||
...rest
|
||||
} = result;
|
||||
|
||||
let items: Array<any>;
|
||||
if (options.source) {
|
||||
items = resolveVariableAndFilter(
|
||||
options.source,
|
||||
createObject(self.filterData, result),
|
||||
'| raw'
|
||||
);
|
||||
} else {
|
||||
items = result.items || result.rows;
|
||||
}
|
||||
|
||||
if (!Array.isArray(items)) {
|
||||
// 如果不按照 items 格式返回,就拿第一个数组当成 items
|
||||
for (const key of Object.keys(result)) {
|
||||
if (result.hasOwnProperty(key) && Array.isArray(result[key])) {
|
||||
items = result[key];
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (items == null) {
|
||||
items = [];
|
||||
}
|
||||
|
||||
if (!Array.isArray(items)) {
|
||||
throw new Error(self.__('CRUD.invalidArray'));
|
||||
} else {
|
||||
// 确保成员是对象。
|
||||
items.map((item: any) =>
|
||||
typeof item === 'string' ? {text: item} : item
|
||||
);
|
||||
}
|
||||
|
||||
// 点击加载更多数据
|
||||
let rowsData: Array<any> = [];
|
||||
if (options.loadDataMode && Array.isArray(self.data.items)) {
|
||||
if (options.dataAppendTo === 'top') {
|
||||
rowsData = items.concat(self.data.items);
|
||||
} else {
|
||||
rowsData = self.data.items.concat(items);
|
||||
}
|
||||
} else {
|
||||
// 第一次的时候就是直接加载请求的数据
|
||||
rowsData = items;
|
||||
}
|
||||
|
||||
const data = {
|
||||
...((api as ApiObject).replaceData ? {} : self.pristine),
|
||||
items: rowsData,
|
||||
count: count,
|
||||
total: total,
|
||||
...rest
|
||||
};
|
||||
|
||||
if (options.loadDataOnce) {
|
||||
/**
|
||||
* 1. 记录原始集合,后续可能基于原始数据做排序查找。
|
||||
* 2. 接口返回中没有 items 和 rows 字段,则直接用查到的数据。
|
||||
*/
|
||||
data.itemsRaw = oItems || oRows || rowsData.concat();
|
||||
let filteredItems = applyFilters(rowsData, {
|
||||
query: self.query,
|
||||
columns: options.columns,
|
||||
filterOnAllColumns: false,
|
||||
matchFunc: options.matchFunc
|
||||
});
|
||||
|
||||
if (self.query.orderBy) {
|
||||
const dir = /desc/i.test(self.query.orderDir) ? -1 : 1;
|
||||
filteredItems = sortArray(filteredItems, self.query.orderBy, dir);
|
||||
}
|
||||
data.items = filteredItems.slice(
|
||||
(self.page - 1) * self.perPage,
|
||||
self.page * self.perPage
|
||||
);
|
||||
data.count = data.total = filteredItems.length;
|
||||
}
|
||||
|
||||
if (Array.isArray(columns)) {
|
||||
self.columns = columns.concat();
|
||||
} else if (rest.isTable2) {
|
||||
self.columns = options.columns;
|
||||
}
|
||||
|
||||
self.items.replace(rowsData);
|
||||
self.reInitData(
|
||||
data,
|
||||
!!(api as ApiObject).replaceData,
|
||||
(api as ApiObject).concatDataFields
|
||||
);
|
||||
options.syncResponse2Query !== false &&
|
||||
updateQuery(
|
||||
pick(rest, Object.keys(self.query)),
|
||||
undefined,
|
||||
options.pageField || 'page',
|
||||
options.perPageField || 'perPage'
|
||||
);
|
||||
|
||||
self.total =
|
||||
parseInt(data[options.totalField || 'total'] ?? data.count, 10) ||
|
||||
0;
|
||||
typeof page !== 'undefined' && (self.page = parseInt(page, 10));
|
||||
|
||||
// 分页情况不清楚,只能知道有没有下一页。
|
||||
if (typeof hasNext !== 'undefined') {
|
||||
self.mode = 'simple';
|
||||
self.total = 0;
|
||||
self.hasNext = !!hasNext;
|
||||
}
|
||||
|
||||
self.updateMessage(
|
||||
(api as ApiObject).messages?.success ??
|
||||
json.msg ??
|
||||
options.successMessage ??
|
||||
json.defaultMsg
|
||||
);
|
||||
|
||||
// 配置了获取成功提示后提示,默认是空不会提示。
|
||||
options &&
|
||||
options.successMessage &&
|
||||
getEnv(self).notify('success', self.msg);
|
||||
}
|
||||
|
||||
self.markFetching(false);
|
||||
return json;
|
||||
} catch (e) {
|
||||
const env = getEnv(self) as IRendererStore;
|
||||
|
||||
if (!isAlive(self) || self.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.markFetching(false);
|
||||
|
||||
if (env.isCancel(e)) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.error(e);
|
||||
!(api as ApiObject)?.silent && env.notify('error', e.message);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
function changePage(page: number | string, perPage?: number | string) {
|
||||
const pageNum = typeof page !== 'number' ? parseInt(page, 10) : page;
|
||||
|
||||
self.page = isNaN(pageNum) ? 1 : pageNum;
|
||||
perPage && changePerPage(perPage);
|
||||
}
|
||||
|
||||
function changePerPage(perPage: number | string) {
|
||||
const perPageNum =
|
||||
typeof perPage !== 'number' ? parseInt(perPage, 10) : perPage;
|
||||
|
||||
self.perPage = isNaN(perPageNum) ? 10 : perPageNum;
|
||||
}
|
||||
|
||||
function selectAction(action: ActionObject) {
|
||||
self.selectedAction = action;
|
||||
}
|
||||
|
||||
const saveRemote: (
|
||||
api: Api,
|
||||
data?: object,
|
||||
options?: fetchOptions
|
||||
) => Promise<any> = flow(function* saveRemote(
|
||||
api: Api,
|
||||
data: object,
|
||||
options: fetchOptions = {}
|
||||
) {
|
||||
try {
|
||||
options = {
|
||||
method: 'post', // 默认走 post
|
||||
...options
|
||||
};
|
||||
|
||||
self.markSaving(true);
|
||||
const json: Payload = yield getEnv(self).fetcher(api, data, options);
|
||||
self.markSaving(false);
|
||||
|
||||
if (!isEmpty(json.data) || json.ok) {
|
||||
self.updateData(
|
||||
normalizeApiResponseData(json.data),
|
||||
{
|
||||
__saved: Date.now()
|
||||
},
|
||||
!!api && (api as ApiObject).replaceData,
|
||||
(api as ApiObject)?.concatDataFields
|
||||
);
|
||||
self.updatedAt = Date.now();
|
||||
}
|
||||
|
||||
if (!json.ok) {
|
||||
self.updateMessage(
|
||||
(api as ApiObject)?.messages?.failed ??
|
||||
json.msg ??
|
||||
options.errorMessage ??
|
||||
self.__('saveFailed'),
|
||||
true
|
||||
);
|
||||
!(api as ApiObject)?.silent &&
|
||||
getEnv(self).notify(
|
||||
'error',
|
||||
self.msg,
|
||||
json.msgTimeout !== undefined
|
||||
? {
|
||||
closeButton: true,
|
||||
timeout: json.msgTimeout
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
throw new ServerError(self.msg, json);
|
||||
} else {
|
||||
self.updateMessage(
|
||||
(api as ApiObject)?.messages?.success ??
|
||||
json.msg ??
|
||||
options.successMessage ??
|
||||
json.defaultMsg
|
||||
);
|
||||
self.msg &&
|
||||
getEnv(self).notify(
|
||||
'success',
|
||||
self.msg,
|
||||
json.msgTimeout !== undefined
|
||||
? {
|
||||
closeButton: true,
|
||||
timeout: json.msgTimeout
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
}
|
||||
// 补一个空对象是为了区别于被取消的请求
|
||||
// 请求被取消时会返回 undefined
|
||||
return json.data || {};
|
||||
} catch (e) {
|
||||
if (!isAlive(self) || self.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.markSaving(false);
|
||||
|
||||
if (getEnv(self).isCancel(e)) {
|
||||
return;
|
||||
}
|
||||
|
||||
!(api as ApiObject)?.silent &&
|
||||
e.type !== 'ServerError' &&
|
||||
getEnv(self).notify('error', e.message);
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
||||
const setFilterTogglable = (
|
||||
togglable: boolean,
|
||||
filterVisible?: boolean
|
||||
) => {
|
||||
self.filterTogglable = togglable;
|
||||
|
||||
filterVisible !== void 0 && (self.filterVisible = filterVisible);
|
||||
};
|
||||
|
||||
const setFilterVisible = (visible: boolean) => {
|
||||
self.filterVisible = visible;
|
||||
};
|
||||
|
||||
const setSelectedItems = (items: Array<any>) => {
|
||||
self.selectedItems.replace(items);
|
||||
};
|
||||
|
||||
const setUnSelectedItems = (items: Array<any>) => {
|
||||
self.unSelectedItems.replace(items);
|
||||
};
|
||||
|
||||
const updateSelectData = (selected: Array<any>, unSelected: Array<any>) => {
|
||||
self.selectedItems.replace(selected);
|
||||
self.unSelectedItems.replace(unSelected);
|
||||
// 同步到data中,使filter等部分也能拿到
|
||||
self.reInitData({
|
||||
selectedItems: selected,
|
||||
unSelectedItems: unSelected
|
||||
});
|
||||
};
|
||||
|
||||
const setInnerModalOpened = (value: boolean) => {
|
||||
self.hasInnerModalOpen = value;
|
||||
};
|
||||
|
||||
const initFromScope = function (
|
||||
scope: any,
|
||||
source: string,
|
||||
options: {
|
||||
columns?: Array<any>;
|
||||
matchFunc?: MatchFunc | null;
|
||||
totalField?: string;
|
||||
}
|
||||
) {
|
||||
let items: Array<any> = resolveVariableAndFilter(source, scope, '| raw');
|
||||
|
||||
if (!Array.isArray(items) && !self.items.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
items = applyFilters(Array.isArray(items) ? items : [], {
|
||||
query: self.query,
|
||||
columns: options.columns,
|
||||
matchFunc: options.matchFunc,
|
||||
filterOnAllColumns: true
|
||||
});
|
||||
|
||||
if (self.query.orderBy) {
|
||||
const dir = /desc/i.test(self.query.orderDir) ? -1 : 1;
|
||||
items = sortArray(items.concat(), self.query.orderBy, dir);
|
||||
}
|
||||
|
||||
const data = {
|
||||
...self.pristine,
|
||||
items:
|
||||
items.length > self.perPage
|
||||
? items.slice(
|
||||
(self.page - 1) * self.perPage,
|
||||
self.page * self.perPage
|
||||
)
|
||||
: items,
|
||||
count: items.length,
|
||||
total: items.length
|
||||
};
|
||||
|
||||
self.total =
|
||||
parseInt(data[options.totalField || 'total'] ?? data.count, 10) || 0;
|
||||
self.items.replace(items);
|
||||
self.reInitData(data);
|
||||
};
|
||||
|
||||
const exportAsCSV = async (
|
||||
options: {
|
||||
loadDataOnce?: boolean;
|
||||
api?: Api;
|
||||
data?: any;
|
||||
filename?: string;
|
||||
pageField?: string;
|
||||
perPageField?: string;
|
||||
} = {}
|
||||
) => {
|
||||
let items = options.loadDataOnce ? self.data.itemsRaw : self.data.items;
|
||||
const filename = options.filename
|
||||
? filter(options.filename, options.data, '| raw')
|
||||
: 'data';
|
||||
|
||||
if (options.api) {
|
||||
const pageField = options.pageField || 'page';
|
||||
const perPageField = options.perPageField || 'perPage';
|
||||
const env = getEnv(self);
|
||||
const ctx: any = createObject(self.data, {
|
||||
...self.query,
|
||||
...options.data,
|
||||
[pageField]: self.page || 1,
|
||||
[perPageField]: self.perPage || 10
|
||||
});
|
||||
const res = await env.fetcher(options.api, ctx, {
|
||||
autoAppend: true,
|
||||
pageField,
|
||||
perPageField
|
||||
});
|
||||
if (!res.data) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(res.data)) {
|
||||
items = res.data;
|
||||
} else {
|
||||
items = res.data.rows || res.data.items;
|
||||
}
|
||||
}
|
||||
|
||||
import('papaparse').then((papaparse: any) => {
|
||||
// 将数据里的对象转成 json 字符串,不然输出的 csv 没法显示
|
||||
const csvData = [];
|
||||
for (const row of items) {
|
||||
const rowData = {} as {[key: string]: any};
|
||||
for (const key in row) {
|
||||
const value = row[key];
|
||||
if (typeof value === 'object') {
|
||||
rowData[key] = JSON.stringify(value);
|
||||
} else {
|
||||
rowData[key] = value;
|
||||
}
|
||||
}
|
||||
csvData.push(rowData);
|
||||
}
|
||||
const csvText = papaparse.unparse(csvData);
|
||||
if (csvText) {
|
||||
const blob = new Blob(
|
||||
// 加上 BOM 这样 Excel 打开的时候就不会乱码
|
||||
[new Uint8Array([0xef, 0xbb, 0xbf]), csvText],
|
||||
{
|
||||
type: 'text/plain;charset=utf-8'
|
||||
}
|
||||
);
|
||||
saveAs(blob, `${filename}.csv`);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const getData = (superData: any): any => {
|
||||
return createObject(superData, {
|
||||
total: self.total,
|
||||
page: self.page,
|
||||
perPage: self.perPage,
|
||||
...self.eventContext
|
||||
});
|
||||
};
|
||||
|
||||
const updateColumns = (columns: Array<any>) => {
|
||||
self.columns = columns;
|
||||
};
|
||||
|
||||
const updateTotal = (total: number) => {
|
||||
self.total = total || 0;
|
||||
};
|
||||
|
||||
/** 非Picker模式下,重置当前CRUD的所有的已选择项目 */
|
||||
const resetSelection = (): void => {
|
||||
// 初始化CRUD记录的已选择项目和未选择项目
|
||||
setSelectedItems([]);
|
||||
setUnSelectedItems([]);
|
||||
|
||||
const tableStore = self?.children?.find?.(
|
||||
(s: any) => s.storeType === TableStore.name
|
||||
);
|
||||
|
||||
if (tableStore) {
|
||||
// 清空Table记录的已选择项目
|
||||
(tableStore as ITableStore).clear?.();
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
getData,
|
||||
updateSelectData,
|
||||
setPristineQuery,
|
||||
updateQuery,
|
||||
fetchInitData,
|
||||
changePage,
|
||||
changePerPage,
|
||||
selectAction,
|
||||
saveRemote,
|
||||
setFilterTogglable,
|
||||
setFilterVisible,
|
||||
setSelectedItems,
|
||||
setUnSelectedItems,
|
||||
setInnerModalOpened,
|
||||
initFromScope,
|
||||
exportAsCSV,
|
||||
updateColumns,
|
||||
updateTotal,
|
||||
resetSelection,
|
||||
replaceItems(items: Array<any>) {
|
||||
self.items.replace(items);
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
export type ICRUDStore = Instance<typeof CRUDStore>;
|
||||
869
packages/amis-core/src/store/form.ts
Normal file
869
packages/amis-core/src/store/form.ts
Normal file
@@ -0,0 +1,869 @@
|
||||
import {types, getEnv, flow, isAlive, Instance} from 'mobx-state-tree';
|
||||
import debounce from 'lodash/debounce';
|
||||
import throttle from 'lodash/throttle';
|
||||
import toPairs from 'lodash/toPairs';
|
||||
import pick from 'lodash/pick';
|
||||
import {ServiceStore} from './service';
|
||||
import type {IFormItemStore} from './formItem';
|
||||
import {
|
||||
Api,
|
||||
ApiObject,
|
||||
DataChangeReason,
|
||||
fetchOptions,
|
||||
Payload
|
||||
} from '../types';
|
||||
import {ServerError} from '../utils/errors';
|
||||
import {
|
||||
getVariable,
|
||||
setVariable,
|
||||
deleteVariable,
|
||||
cloneObject,
|
||||
createObject,
|
||||
difference,
|
||||
isEmpty,
|
||||
mapObject,
|
||||
keyToPath,
|
||||
isObject,
|
||||
ValidateError,
|
||||
extendObject
|
||||
} from '../utils/helper';
|
||||
import isEqual from 'lodash/isEqual';
|
||||
import flatten from 'lodash/flatten';
|
||||
import find from 'lodash/find';
|
||||
import {filter} from '../utils/tpl';
|
||||
import {isPureVariable} from '../utils/tpl-builtin';
|
||||
import {normalizeApiResponseData} from '../utils/api';
|
||||
|
||||
export const FormStore = ServiceStore.named('FormStore')
|
||||
.props({
|
||||
inited: false,
|
||||
validated: false,
|
||||
submited: false,
|
||||
submiting: false,
|
||||
savedData: types.frozen(),
|
||||
// items: types.optional(types.array(types.late(() => FormItemStore)), []),
|
||||
canAccessSuperData: true,
|
||||
persistData: types.optional(types.union(types.string, types.boolean), ''),
|
||||
restError: types.optional(types.array(types.string), []) // 没有映射到表达项上的 errors
|
||||
})
|
||||
.views(self => {
|
||||
function getItems() {
|
||||
const formItems: Array<IFormItemStore> = [];
|
||||
|
||||
// 查找孩子节点中是 formItem 的表单项
|
||||
const pool = self.children.concat();
|
||||
while (pool.length) {
|
||||
const current = pool.shift()!;
|
||||
|
||||
if (current.storeType === 'FormItemStore' && !current.isControlled) {
|
||||
formItems.push(current);
|
||||
} else if (
|
||||
!['ComboStore', 'TableStore', 'FormStore'].includes(current.storeType)
|
||||
) {
|
||||
pool.push(...current.children);
|
||||
}
|
||||
}
|
||||
|
||||
return formItems;
|
||||
}
|
||||
|
||||
return {
|
||||
get items() {
|
||||
return getItems();
|
||||
}
|
||||
};
|
||||
})
|
||||
.views(self => {
|
||||
return {
|
||||
get loading() {
|
||||
return self.saving || self.fetching;
|
||||
},
|
||||
|
||||
/** 获取InputGroup的子元素 */
|
||||
get inputGroupItems() {
|
||||
const formItems: Record<string, IFormItemStore[]> = {};
|
||||
const children: Array<any> = self.items.concat();
|
||||
|
||||
while (children.length) {
|
||||
const current = children.shift();
|
||||
|
||||
if (current.inputGroupControl && current.inputGroupControl?.name) {
|
||||
const controlName = current.inputGroupControl?.name as string;
|
||||
|
||||
if (formItems.hasOwnProperty(controlName)) {
|
||||
formItems[controlName].push(current);
|
||||
} else {
|
||||
formItems[controlName] = [current];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return formItems;
|
||||
},
|
||||
|
||||
get errors() {
|
||||
let errors: {
|
||||
[propName: string]: Array<string>;
|
||||
} = {};
|
||||
|
||||
self.items.forEach(item => {
|
||||
if (!item.valid) {
|
||||
errors[item.name] = Array.isArray(errors[item.name])
|
||||
? errors[item.name].concat(item.errors)
|
||||
: item.errors.concat();
|
||||
}
|
||||
});
|
||||
|
||||
return errors;
|
||||
},
|
||||
|
||||
getValueByName(
|
||||
name: string,
|
||||
canAccessSuperData = self.canAccessSuperData
|
||||
) {
|
||||
return getVariable(self.data, name, canAccessSuperData);
|
||||
},
|
||||
|
||||
getPristineValueByName(name: string) {
|
||||
return getVariable(self.pristine, name);
|
||||
},
|
||||
|
||||
getItemById(id: string) {
|
||||
return self.items.find(item => item.itemId === id);
|
||||
},
|
||||
|
||||
getItemByName(name: string) {
|
||||
return self.items.find(item => item.name === name);
|
||||
},
|
||||
|
||||
getItemsByName(name: string) {
|
||||
return self.items.filter(item => item.name === name);
|
||||
},
|
||||
|
||||
get valid() {
|
||||
return (
|
||||
self.items.every(item => item.valid) &&
|
||||
(!self.restError || !self.restError.length)
|
||||
);
|
||||
},
|
||||
|
||||
get validating() {
|
||||
return self.items.some(item => item.validating);
|
||||
},
|
||||
|
||||
get isPristine() {
|
||||
return isEqual(self.pristine, self.data);
|
||||
},
|
||||
|
||||
get modified() {
|
||||
if (self.savedData) {
|
||||
return self.savedData !== self.data;
|
||||
}
|
||||
|
||||
return !this.isPristine;
|
||||
},
|
||||
|
||||
get persistKey() {
|
||||
return `${location.pathname}/${self.path}/${
|
||||
typeof self.persistData === 'string'
|
||||
? filter(self.persistData, self.data)
|
||||
: self.persistData
|
||||
}`;
|
||||
}
|
||||
};
|
||||
})
|
||||
.actions(self => {
|
||||
function setValues(
|
||||
values: object,
|
||||
tag?: object,
|
||||
replace?: boolean,
|
||||
concatFields?: string | string[],
|
||||
changeReason?: DataChangeReason
|
||||
) {
|
||||
self.updateData(values, tag, replace, concatFields, changeReason);
|
||||
|
||||
// 如果数据域中有数据变化,就都reset一下,去掉之前残留的验证消息
|
||||
self.items.forEach(item => {
|
||||
if (item.extraName) {
|
||||
const value = [
|
||||
getVariable(values, item.name, false),
|
||||
getVariable(values, item.extraName, false)
|
||||
];
|
||||
if (
|
||||
value.some(item => item !== undefined) &&
|
||||
!isEqual(value, item.tmpValue)
|
||||
) {
|
||||
const origin = item.splitExtraValue(item.tmpValue);
|
||||
item.changeTmpValue(
|
||||
value.map((item, idx) => item ?? origin[idx]),
|
||||
'dataChanged'
|
||||
);
|
||||
item.changeEmitedValue(undefined);
|
||||
}
|
||||
} else {
|
||||
const value = getVariable(values, item.name, false);
|
||||
if (value !== undefined && value !== item.tmpValue) {
|
||||
item.changeTmpValue(value, 'dataChanged');
|
||||
item.changeEmitedValue(undefined);
|
||||
}
|
||||
}
|
||||
item.reset();
|
||||
self.inited && item.validateOnChange && item.validate(self.data);
|
||||
});
|
||||
|
||||
// 同步 options
|
||||
syncOptions();
|
||||
}
|
||||
|
||||
function setValueByName(
|
||||
name: string,
|
||||
value: any,
|
||||
isPristine: boolean = false,
|
||||
force: boolean = false,
|
||||
changeReason?: DataChangeReason
|
||||
) {
|
||||
// 没有变化就不跑了。
|
||||
const origin = getVariable(self.data, name, false);
|
||||
|
||||
const prev = self.data;
|
||||
const data = cloneObject(self.data);
|
||||
|
||||
if (value !== origin) {
|
||||
if (prev.hasOwnProperty('__prev')) {
|
||||
// 基于之前的 __prev 改
|
||||
const prevData = cloneObject(prev.__prev);
|
||||
setVariable(prevData, name, origin);
|
||||
Object.defineProperty(data, '__prev', {
|
||||
value: prevData,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
writable: false
|
||||
});
|
||||
} else {
|
||||
Object.defineProperty(data, '__prev', {
|
||||
value: {...prev},
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
writable: false
|
||||
});
|
||||
}
|
||||
} else if (!force) {
|
||||
return;
|
||||
}
|
||||
|
||||
setVariable(data, name, value);
|
||||
|
||||
if (isPristine) {
|
||||
const pristine = cloneObject(self.pristine);
|
||||
setVariable(pristine, name, value);
|
||||
self.pristine = pristine;
|
||||
}
|
||||
|
||||
if (!data.__pristine) {
|
||||
Object.defineProperty(data, '__pristine', {
|
||||
value: self.pristine,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
writable: false
|
||||
});
|
||||
}
|
||||
|
||||
changeReason &&
|
||||
Object.isExtensible(data) &&
|
||||
!data.__changeReason &&
|
||||
Object.defineProperty(data, '__changeReason', {
|
||||
value: changeReason,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
writable: false
|
||||
});
|
||||
|
||||
self.data = data;
|
||||
|
||||
// 同步 options
|
||||
syncOptions();
|
||||
}
|
||||
|
||||
function deleteValueByName(name: string, changeReason?: DataChangeReason) {
|
||||
const prev = self.data;
|
||||
const data = cloneObject(self.data);
|
||||
|
||||
if (prev.hasOwnProperty('__prev')) {
|
||||
// 基于之前的 __prev 改
|
||||
const prevData = cloneObject(prev.__prev);
|
||||
setVariable(prevData, name, getVariable(prev, name));
|
||||
Object.defineProperty(data, '__prev', {
|
||||
value: prevData,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
writable: false
|
||||
});
|
||||
} else {
|
||||
Object.defineProperty(data, '__prev', {
|
||||
value: {...prev},
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
writable: false
|
||||
});
|
||||
}
|
||||
|
||||
deleteVariable(data, name);
|
||||
|
||||
changeReason &&
|
||||
Object.isExtensible(data) &&
|
||||
!data.__changeReason &&
|
||||
Object.defineProperty(data, '__changeReason', {
|
||||
value: changeReason,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
writable: false
|
||||
});
|
||||
self.data = data;
|
||||
}
|
||||
|
||||
function trimValues() {
|
||||
let data = mapObject(self.data, (item: any) =>
|
||||
typeof item === 'string' ? item.trim() : item
|
||||
);
|
||||
self.updateData(data);
|
||||
}
|
||||
|
||||
const syncOptions = debounce(
|
||||
() => self.items.forEach(item => item.syncOptions(undefined, self.data)),
|
||||
250,
|
||||
{
|
||||
trailing: true,
|
||||
leading: false
|
||||
}
|
||||
);
|
||||
|
||||
function setRestError(errors: string[]) {
|
||||
self.restError.replace(errors);
|
||||
}
|
||||
|
||||
function addRestError(msg: string, name?: string | Array<string>) {
|
||||
const names = name
|
||||
? Array.isArray(name)
|
||||
? name.concat()
|
||||
: [name]
|
||||
: null;
|
||||
|
||||
if (Array.isArray(names)) {
|
||||
const errors: any = {};
|
||||
names.forEach(name => (errors[name] = msg));
|
||||
setFormItemErrors(errors, 'rules');
|
||||
} else {
|
||||
self.restError.push(msg);
|
||||
}
|
||||
}
|
||||
|
||||
function clearRestError() {
|
||||
setRestError([]);
|
||||
}
|
||||
|
||||
const saveRemote: (
|
||||
api: Api,
|
||||
data?: object,
|
||||
options?: fetchOptions
|
||||
) => Promise<any> = flow(function* saveRemote(
|
||||
api: Api,
|
||||
data: object,
|
||||
options: fetchOptions = {}
|
||||
) {
|
||||
clearRestError();
|
||||
|
||||
try {
|
||||
options = {
|
||||
method: 'post', // 默认走 post
|
||||
...options
|
||||
};
|
||||
|
||||
if (options && options.beforeSend) {
|
||||
let ret = options.beforeSend(data);
|
||||
|
||||
if (ret && ret.then) {
|
||||
ret = yield ret;
|
||||
}
|
||||
|
||||
if (ret === false) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
self.markSaving(true);
|
||||
const json: Payload = yield getEnv(self).fetcher(api, data, options);
|
||||
|
||||
// 失败也同样修改数据,如果有数据的话。
|
||||
if (!isEmpty(json.data) || json.ok) {
|
||||
self.updatedAt = Date.now();
|
||||
|
||||
setValues(
|
||||
normalizeApiResponseData(json.data),
|
||||
json.ok
|
||||
? {
|
||||
__saved: Date.now()
|
||||
}
|
||||
: undefined,
|
||||
!!(api as ApiObject).replaceData,
|
||||
(api as ApiObject).concatDataFields,
|
||||
{
|
||||
type: 'api'
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
if (!json.ok) {
|
||||
if (json.status === 422 && json.errors) {
|
||||
setFormItemErrors(json.errors);
|
||||
|
||||
self.updateMessage(
|
||||
(api as ApiObject)?.messages?.failed ??
|
||||
json.msg ??
|
||||
self.__(options && options.errorMessage) ??
|
||||
self.__('Form.validateFailed'),
|
||||
true
|
||||
);
|
||||
} else {
|
||||
self.updateMessage(
|
||||
(api as ApiObject)?.messages?.failed ??
|
||||
json.msg ??
|
||||
self.__(options && options.errorMessage),
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
throw new ServerError(self.msg, json);
|
||||
} else {
|
||||
updateSavedData();
|
||||
let ret = options?.onSuccess?.(json, json.data);
|
||||
if (ret?.then) {
|
||||
ret = yield ret;
|
||||
}
|
||||
if (ret?.cbResult?.then) {
|
||||
yield ret.cbResult;
|
||||
}
|
||||
self.markSaving(false);
|
||||
self.updateMessage(
|
||||
(api as ApiObject)?.messages?.success ??
|
||||
json.msg ??
|
||||
(options.successMessage === 'saveSuccess'
|
||||
? json.defaultMsg
|
||||
: self.__(options && options.successMessage)) ??
|
||||
json.defaultMsg
|
||||
);
|
||||
if (!ret?.dispatcher?.prevented) {
|
||||
self.msg &&
|
||||
getEnv(self).notify(
|
||||
'success',
|
||||
self.msg,
|
||||
json.msgTimeout !== undefined
|
||||
? {
|
||||
closeButton: true,
|
||||
timeout: json.msgTimeout
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
}
|
||||
return json.data;
|
||||
}
|
||||
} catch (e) {
|
||||
self.markSaving(false);
|
||||
let ret =
|
||||
options && options.onFailed && options.onFailed(e.response || {});
|
||||
if (ret?.then) {
|
||||
ret = yield ret;
|
||||
}
|
||||
if (!isAlive(self) || self.disposed) {
|
||||
return;
|
||||
}
|
||||
if (ret?.dispatcher?.prevented) {
|
||||
return;
|
||||
}
|
||||
if (!(api as ApiObject)?.silent) {
|
||||
if (e.type === 'ServerError') {
|
||||
const result = (e as ServerError).response;
|
||||
getEnv(self).notify(
|
||||
'error',
|
||||
e.message,
|
||||
result.msgTimeout !== undefined
|
||||
? {
|
||||
closeButton: true,
|
||||
timeout: result.msgTimeout
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
} else {
|
||||
getEnv(self).notify('error', e.message);
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
||||
function setFormItemErrors(
|
||||
errors: {[propName: string]: string},
|
||||
tag = 'remote'
|
||||
) {
|
||||
Object.keys(errors).forEach((key: string) => {
|
||||
const item = self.getItemById(key);
|
||||
const items = self.getItemsByName(key);
|
||||
|
||||
if (item) {
|
||||
item.setError(errors[key], tag);
|
||||
delete errors[key];
|
||||
} else if (items.length) {
|
||||
// 通过 name 直接找到的
|
||||
items.forEach(item => item.setError(errors[key], tag));
|
||||
delete errors[key];
|
||||
} else {
|
||||
// 尝试通过path寻找
|
||||
const items = getItemsByPath(key);
|
||||
|
||||
if (Array.isArray(items) && items.length) {
|
||||
items.forEach(item => item.setError(`${errors[key]}`, tag));
|
||||
delete errors[key];
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 没有映射上的error信息加在msg后显示出来
|
||||
!isEmpty(errors) &&
|
||||
setRestError(Object.keys(errors).map(key => String(errors[key])));
|
||||
}
|
||||
|
||||
const getItemsByPath = (key: string) => {
|
||||
const paths: Array<string> = keyToPath(key);
|
||||
const len = paths.length;
|
||||
|
||||
return paths.reduce(
|
||||
(stores: any[], path, idx) => {
|
||||
if (Array.isArray(stores) && stores.every(s => s.getItemsByName)) {
|
||||
const items = flatten(
|
||||
stores.map(s => s.getItemsByName(path))
|
||||
).filter(i => i);
|
||||
const subStores = items
|
||||
.map(item => item?.getSubStore?.())
|
||||
.filter(i => i);
|
||||
return subStores.length && idx < len - 1 ? subStores : items;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
[self]
|
||||
);
|
||||
};
|
||||
|
||||
// 5s 内不要重复弹同一个错误
|
||||
const toastValidateError = throttle(
|
||||
(msg, validateError?: ValidateError) => {
|
||||
const env = getEnv(self);
|
||||
env.notify('error', msg, {
|
||||
validateError
|
||||
});
|
||||
},
|
||||
5000,
|
||||
{
|
||||
trailing: false,
|
||||
leading: true
|
||||
}
|
||||
);
|
||||
|
||||
const submit: (
|
||||
fn?: (values: object) => Promise<any>,
|
||||
hooks?: Array<() => Promise<any>>,
|
||||
failedMessage?: string,
|
||||
validateErrCb?: () => void,
|
||||
throwErrors?: boolean
|
||||
) => Promise<any> = flow(function* submit(
|
||||
fn: any,
|
||||
hooks?: Array<() => Promise<any>>,
|
||||
failedMessage?: string,
|
||||
validateErrCb?: () => void,
|
||||
throwErrors?: boolean
|
||||
) {
|
||||
self.submited = true;
|
||||
self.submiting = true;
|
||||
|
||||
try {
|
||||
const valid = yield validate(
|
||||
hooks,
|
||||
true,
|
||||
true,
|
||||
failedMessage,
|
||||
validateErrCb
|
||||
);
|
||||
|
||||
if (fn) {
|
||||
const diff = difference(self.data, self.pristine);
|
||||
const result: any = yield fn(
|
||||
createObject(
|
||||
createObject(self.data.__super, {
|
||||
diff: diff,
|
||||
__diff: diff,
|
||||
pristine: self.pristine
|
||||
}),
|
||||
self.data
|
||||
)
|
||||
);
|
||||
return result ?? self.data;
|
||||
}
|
||||
|
||||
return self.data;
|
||||
} finally {
|
||||
self.submiting = false;
|
||||
}
|
||||
});
|
||||
|
||||
const validate: (
|
||||
hooks?: Array<() => Promise<any>>,
|
||||
forceValidate?: boolean,
|
||||
throwErrors?: boolean,
|
||||
failedMessage?: string,
|
||||
validateErrCb?: () => void
|
||||
) => Promise<boolean> = flow(function* validate(
|
||||
hooks?: Array<(data: any) => Promise<any>>,
|
||||
forceValidate?: boolean,
|
||||
throwErrors?: boolean,
|
||||
failedMessage?: string,
|
||||
validateErrCb?: () => void
|
||||
) {
|
||||
self.validated = true;
|
||||
const items = self.items.concat();
|
||||
for (let i = 0, len = items.length; i < len; i++) {
|
||||
let item = items[i] as IFormItemStore;
|
||||
|
||||
// 先清除组合校验的错误
|
||||
item.clearError('rules');
|
||||
|
||||
/* 日期类校验存在表单项联动的情况,需要在提交前重置校验状态,避免变量更新后联动校验结果未更新 */
|
||||
if (
|
||||
item.validated &&
|
||||
isObject(item.rules) &&
|
||||
toPairs(item.rules)
|
||||
.filter(([key, value]) => /^is(Date)?Time/.test(key))
|
||||
.some(([key, value]) =>
|
||||
Array.isArray(value)
|
||||
? value.some(item => isPureVariable(item))
|
||||
: isPureVariable(value)
|
||||
)
|
||||
) {
|
||||
item.resetValidationStatus();
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. 验证过,或者是 unique 的表单项,或者强制验证,或者有远端校验api
|
||||
* 2. 如果Schema的默认值为表达式,则需要基于联动计算结果重新校验
|
||||
*/
|
||||
if (
|
||||
!item.validated ||
|
||||
item.rules.equals ||
|
||||
item.rules.equalsField ||
|
||||
item.unique ||
|
||||
forceValidate ||
|
||||
!!item.validateApi ||
|
||||
item.isValueSchemaExp
|
||||
) {
|
||||
yield item.validate(self.data);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
if (hooks && hooks.length) {
|
||||
for (let i = 0, len = hooks.length; i < len; i++) {
|
||||
const msg = yield hooks[i](self.data);
|
||||
|
||||
if (typeof msg == 'string' && msg) {
|
||||
throw new Error(msg);
|
||||
} else if (msg === false) {
|
||||
// 不提示直接不通过校验
|
||||
throw new ValidateError(
|
||||
failedMessage || self.__('Form.validateFailed'),
|
||||
self.errors
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (throwErrors) {
|
||||
throw e;
|
||||
} else {
|
||||
toastValidateError(e.message);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!self.valid) {
|
||||
// 如果不是valid,而且有包含不是remote的报错的表单项时,不可提交
|
||||
if (
|
||||
self.items.some(item =>
|
||||
item.errorData.some(e => e.tag !== 'remote')
|
||||
) ||
|
||||
self.restError.length
|
||||
) {
|
||||
let msg = failedMessage ?? self.__('Form.validateFailed');
|
||||
let dispatcher: any = validateErrCb && validateErrCb();
|
||||
if (dispatcher?.then) {
|
||||
dispatcher = yield dispatcher;
|
||||
}
|
||||
if (!dispatcher?.prevented) {
|
||||
const validateError = new ValidateError(
|
||||
failedMessage || self.__('Form.validateFailed'),
|
||||
self.errors,
|
||||
{
|
||||
items: self.items,
|
||||
msg: {
|
||||
customMsg: failedMessage,
|
||||
defaultMsg: self.__('Form.validateFailed')
|
||||
}
|
||||
}
|
||||
);
|
||||
msg && toastValidateError(msg, validateError);
|
||||
}
|
||||
}
|
||||
|
||||
if (throwErrors) {
|
||||
throw new ValidateError(
|
||||
failedMessage || self.__('Form.validateFailed'),
|
||||
self.errors
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return self.valid;
|
||||
});
|
||||
|
||||
const validateFields: (
|
||||
fields: Array<string | {name: string; rules: {[propName: string]: any}}>
|
||||
) => Promise<boolean> = flow(function* validateFields(
|
||||
fields: Array<string | {name: string; rules: {[propName: string]: any}}>
|
||||
) {
|
||||
const items = self.items.concat();
|
||||
const normalizedfields = fields.map(field =>
|
||||
typeof field === 'string' ? {name: field, rules: {}} : field
|
||||
);
|
||||
let result: Array<boolean> = [];
|
||||
|
||||
for (let i = 0, len = items.length; i < len; i++) {
|
||||
let item = items[i] as IFormItemStore;
|
||||
const field = find(normalizedfields, field => field.name === item.name);
|
||||
|
||||
if (field) {
|
||||
result.push(yield item.validate(self.data, undefined, field.rules));
|
||||
}
|
||||
}
|
||||
return result.every(item => item);
|
||||
});
|
||||
|
||||
function clearErrors() {
|
||||
const items = self.items.concat();
|
||||
items.forEach(item => item.reset());
|
||||
}
|
||||
|
||||
function setPristine(data: object) {
|
||||
self.pristine = data;
|
||||
}
|
||||
|
||||
function reset(cb?: (data: any) => void, resetData: boolean = true) {
|
||||
if (resetData) {
|
||||
// 父级的数据可能已经被修改,__super不应该被修改
|
||||
self.data = createObject(self.data.__super, self.pristine);
|
||||
}
|
||||
|
||||
// 值可能变了,重新验证一次。
|
||||
self.validated = false;
|
||||
self.submited = false;
|
||||
self.items.forEach(item => item.reset());
|
||||
cb && cb(self.data);
|
||||
}
|
||||
|
||||
function clear(cb?: (data: any) => void) {
|
||||
const toClear: any = {};
|
||||
self.items.forEach(item => {
|
||||
if (item.name && item.type !== 'hidden') {
|
||||
setVariable(toClear, item.name, item.resetValue);
|
||||
}
|
||||
if (item.extraName && typeof item.extraName === 'string') {
|
||||
setVariable(toClear, item.extraName, item.resetValue);
|
||||
}
|
||||
});
|
||||
setValues(toClear);
|
||||
self.validated = false;
|
||||
self.submited = false;
|
||||
self.items.forEach(item => item.reset());
|
||||
cb && cb(self.data);
|
||||
}
|
||||
|
||||
function setCanAccessSuperData(value: boolean = true) {
|
||||
self.canAccessSuperData = value;
|
||||
}
|
||||
|
||||
function setInited(value: boolean) {
|
||||
self.inited = value;
|
||||
}
|
||||
|
||||
function setPersistData(value = '') {
|
||||
self.persistData = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将表单数据存入本地
|
||||
* @param keys 指定只存储某些 key
|
||||
*/
|
||||
const setLocalPersistData = (keys?: string[]) => {
|
||||
let data = self.data;
|
||||
if (keys && keys.length) {
|
||||
data = pick(data, keys);
|
||||
}
|
||||
localStorage.setItem(self.persistKey, JSON.stringify(data));
|
||||
};
|
||||
|
||||
function getLocalPersistData() {
|
||||
let data = localStorage.getItem(self.persistKey);
|
||||
if (data) {
|
||||
self.updateData(JSON.parse(data));
|
||||
}
|
||||
}
|
||||
|
||||
function clearLocalPersistData() {
|
||||
localStorage.removeItem(self.persistKey);
|
||||
}
|
||||
|
||||
function updateSavedData() {
|
||||
self.savedData = self.data;
|
||||
}
|
||||
|
||||
return {
|
||||
setInited,
|
||||
setValues,
|
||||
setValueByName,
|
||||
trimValues,
|
||||
submit,
|
||||
validate,
|
||||
validateFields,
|
||||
clearErrors,
|
||||
saveRemote,
|
||||
reset,
|
||||
syncOptions,
|
||||
setCanAccessSuperData,
|
||||
deleteValueByName,
|
||||
getLocalPersistData,
|
||||
setLocalPersistData,
|
||||
clearLocalPersistData,
|
||||
setPristine,
|
||||
setPersistData,
|
||||
clear,
|
||||
updateSavedData,
|
||||
setFormItemErrors,
|
||||
getItemsByPath,
|
||||
setRestError,
|
||||
addRestError,
|
||||
clearRestError,
|
||||
beforeDestroy() {
|
||||
syncOptions.cancel();
|
||||
toastValidateError.cancel();
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
export type IFormStore = Instance<typeof FormStore>;
|
||||
export {IFormItemStore};
|
||||
1641
packages/amis-core/src/store/formItem.ts
Normal file
1641
packages/amis-core/src/store/formItem.ts
Normal file
File diff suppressed because it is too large
Load Diff
395
packages/amis-core/src/store/iRenderer.ts
Normal file
395
packages/amis-core/src/store/iRenderer.ts
Normal file
@@ -0,0 +1,395 @@
|
||||
import {Instance, SnapshotIn, types} from 'mobx-state-tree';
|
||||
import {
|
||||
extendObject,
|
||||
createObject,
|
||||
getVariable,
|
||||
cloneObject,
|
||||
setVariable,
|
||||
deleteVariable
|
||||
} from '../utils/helper';
|
||||
import {dataMapping} from '../utils/tpl-builtin';
|
||||
import {SimpleMap} from '../utils/SimpleMap';
|
||||
import {StoreNode} from './node';
|
||||
import {IScopedContext} from '../Scoped';
|
||||
import {IRootStore} from './root';
|
||||
import {
|
||||
concatData,
|
||||
createObjectFromChain,
|
||||
extractObjectChain,
|
||||
injectObjectChain
|
||||
} from '../utils';
|
||||
import {DataChangeReason} from '../types';
|
||||
import findLastIndex from 'lodash/findLastIndex';
|
||||
|
||||
export const iRendererStore = StoreNode.named('iRendererStore')
|
||||
.props({
|
||||
hasRemoteData: types.optional(types.boolean, false),
|
||||
data: types.optional(types.frozen(), {}),
|
||||
initedAt: 0, // 初始 init 的时刻
|
||||
updatedAt: 0, // 从服务端更新时刻
|
||||
pristine: types.optional(types.frozen(), {}), // pristine 的数据可能会被表单项的默认值,form 的 initApi 等修改
|
||||
pristineRaw: types.optional(types.frozen(), {}), // pristine的原始值
|
||||
upStreamData: types.optional(types.frozen(), {}), // 最原始的数据,只有由上游同步下来时才更新。用来判断是否变化过
|
||||
action: types.optional(types.frozen(), undefined),
|
||||
dialogSchema: types.frozen(),
|
||||
dialogOpen: false,
|
||||
dialogData: types.optional(types.frozen(), undefined),
|
||||
drawerSchema: types.frozen(),
|
||||
drawerOpen: false,
|
||||
drawerData: types.optional(types.frozen(), undefined)
|
||||
})
|
||||
.views(self => ({
|
||||
getValueByName(name: string, canAccessSuper: boolean = true) {
|
||||
return getVariable(self.data, name, canAccessSuper);
|
||||
},
|
||||
|
||||
getPristineValueByName(name: string) {
|
||||
return getVariable(self.pristine, name, false);
|
||||
},
|
||||
|
||||
get pristineDiff() {
|
||||
const data: any = {};
|
||||
Object.keys(self.pristine).forEach(key => {
|
||||
if (self.pristine[key] !== self.pristineRaw[key]) {
|
||||
data[key] = self.pristine[key];
|
||||
}
|
||||
});
|
||||
return data;
|
||||
}
|
||||
}))
|
||||
.actions(self => {
|
||||
const dialogCallbacks = new SimpleMap<
|
||||
(confirmed?: any, value?: any) => void
|
||||
>();
|
||||
let dialogScoped: IScopedContext | null = null;
|
||||
let drawerScoped: IScopedContext | null = null;
|
||||
let top: IRootStore | null = null;
|
||||
|
||||
return {
|
||||
setTopStore(value: any) {
|
||||
top = value;
|
||||
},
|
||||
|
||||
initData(
|
||||
data: object = {},
|
||||
skipSetPristine = false,
|
||||
changeReason?: DataChangeReason
|
||||
) {
|
||||
self.initedAt = Date.now();
|
||||
|
||||
if (self.data.__tag) {
|
||||
data = injectObjectChain(data, self.data.__tag);
|
||||
}
|
||||
|
||||
if (!skipSetPristine) {
|
||||
self.pristine = data;
|
||||
self.pristineRaw = data;
|
||||
}
|
||||
|
||||
changeReason &&
|
||||
Object.isExtensible(data) &&
|
||||
!(data as any).__changeReason &&
|
||||
Object.defineProperty(data, '__changeReason', {
|
||||
value: changeReason,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
writable: false
|
||||
});
|
||||
|
||||
self.data = data;
|
||||
self.upStreamData = data;
|
||||
},
|
||||
|
||||
// 临时更新全局变量
|
||||
temporaryUpdateGlobalVars(globalVar: any) {
|
||||
const chain = extractObjectChain(self.data).filter(
|
||||
(item: any) => !item.hasOwnProperty('__isTempGlobalLayer')
|
||||
);
|
||||
const idx = findLastIndex(
|
||||
chain,
|
||||
item =>
|
||||
item.hasOwnProperty('global') || item.hasOwnProperty('globalState')
|
||||
);
|
||||
|
||||
if (idx !== -1) {
|
||||
chain.splice(idx + 1, 0, {
|
||||
...globalVar,
|
||||
__isTempGlobalLayer: true
|
||||
});
|
||||
}
|
||||
|
||||
self.data = createObjectFromChain(chain);
|
||||
},
|
||||
|
||||
// 撤销临时更新全局变量
|
||||
unDoTemporaryUpdateGlobalVars() {
|
||||
const chain = extractObjectChain(self.data).filter(
|
||||
(item: any) => !item.hasOwnProperty('__isTempGlobalLayer')
|
||||
);
|
||||
self.data = createObjectFromChain(chain);
|
||||
},
|
||||
|
||||
reset() {
|
||||
self.data = self.pristine;
|
||||
},
|
||||
|
||||
updateData(
|
||||
data: object = {},
|
||||
tag?: object,
|
||||
replace?: boolean,
|
||||
concatFields?: string | string[],
|
||||
changeReason?: DataChangeReason
|
||||
) {
|
||||
if (concatFields) {
|
||||
data = concatData(data, self.data, concatFields);
|
||||
}
|
||||
|
||||
const prev = self.data;
|
||||
let newData;
|
||||
if (tag) {
|
||||
let proto = createObject((self.data as any).__super || null, {
|
||||
...tag,
|
||||
__tag: tag
|
||||
});
|
||||
newData = createObject(proto, {
|
||||
...(replace ? {} : self.data),
|
||||
...data
|
||||
});
|
||||
} else {
|
||||
newData = extendObject(self.data, data, !replace);
|
||||
}
|
||||
|
||||
Object.defineProperty(newData, '__prev', {
|
||||
value: {...prev},
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
writable: false
|
||||
});
|
||||
|
||||
changeReason &&
|
||||
Object.isExtensible(newData) &&
|
||||
!(newData as any).__changeReason &&
|
||||
Object.defineProperty(newData, '__changeReason', {
|
||||
value: changeReason,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
writable: false
|
||||
});
|
||||
|
||||
self.data = newData;
|
||||
},
|
||||
|
||||
changeValue(
|
||||
name: string,
|
||||
value: any,
|
||||
changePristine?: boolean,
|
||||
force?: boolean,
|
||||
otherModifier?: (data: Object) => void,
|
||||
changeReason?: DataChangeReason
|
||||
) {
|
||||
if (!name) {
|
||||
return;
|
||||
}
|
||||
|
||||
const origin = getVariable(self.data, name, false);
|
||||
|
||||
if (value === origin && !force) {
|
||||
return;
|
||||
}
|
||||
|
||||
const prev = self.data;
|
||||
const data = cloneObject(self.data);
|
||||
if (prev.hasOwnProperty('__prev')) {
|
||||
// 基于之前的 __prev 改
|
||||
const prevData = cloneObject(prev.__prev);
|
||||
setVariable(prevData, name, origin);
|
||||
Object.defineProperty(data, '__prev', {
|
||||
value: prevData,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
writable: false
|
||||
});
|
||||
} else {
|
||||
Object.defineProperty(data, '__prev', {
|
||||
value: {...prev},
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
writable: false
|
||||
});
|
||||
}
|
||||
|
||||
if (value === undefined) {
|
||||
deleteVariable(data, name);
|
||||
} else {
|
||||
setVariable(data, name, value);
|
||||
}
|
||||
|
||||
otherModifier?.(data);
|
||||
|
||||
if (changePristine) {
|
||||
const pristine = cloneObject(self.pristine);
|
||||
setVariable(pristine, name, value);
|
||||
otherModifier?.(pristine);
|
||||
self.pristine = pristine;
|
||||
}
|
||||
|
||||
if (!data.__pristine) {
|
||||
Object.defineProperty(data, '__pristine', {
|
||||
value: self.pristine,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
writable: false
|
||||
});
|
||||
}
|
||||
|
||||
changeReason &&
|
||||
Object.isExtensible(data) &&
|
||||
!data.__changeReason &&
|
||||
Object.defineProperty(data, '__changeReason', {
|
||||
value: changeReason,
|
||||
enumerable: false,
|
||||
configurable: false,
|
||||
writable: false
|
||||
});
|
||||
|
||||
self.data = data;
|
||||
},
|
||||
|
||||
setCurrentAction(action: any, resolveDefinitions?: (schema: any) => any) {
|
||||
// 处理 $ref
|
||||
resolveDefinitions &&
|
||||
['dialog', 'drawer'].forEach(key => {
|
||||
if (action[key]?.$ref) {
|
||||
action = {
|
||||
...action,
|
||||
[key]: {
|
||||
...resolveDefinitions(action[key].$ref),
|
||||
...action[key]
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
self.action = action;
|
||||
},
|
||||
|
||||
openDialog(
|
||||
ctx: any,
|
||||
additonal?: object,
|
||||
callback?: (confirmed: boolean, values: any) => void,
|
||||
scoped?: IScopedContext
|
||||
) {
|
||||
const chain = extractObjectChain(ctx);
|
||||
chain.length === 1 && chain.unshift(self.data);
|
||||
if (additonal) {
|
||||
chain.splice(chain.length - 1, 0, additonal);
|
||||
}
|
||||
|
||||
const data = createObjectFromChain(chain);
|
||||
const mappingData = self.action.data ?? self.action.dialog?.data;
|
||||
if (mappingData) {
|
||||
self.dialogData = createObjectFromChain([
|
||||
top?.context,
|
||||
dataMapping(mappingData, data)
|
||||
]);
|
||||
|
||||
const clonedAction = {
|
||||
...self.action,
|
||||
dialog: {
|
||||
...self.action.dialog
|
||||
}
|
||||
};
|
||||
delete clonedAction.dialog.data;
|
||||
self.action = clonedAction;
|
||||
} else {
|
||||
self.dialogData = data;
|
||||
}
|
||||
self.dialogSchema = self.action.dialog;
|
||||
self.dialogOpen = true;
|
||||
callback && dialogCallbacks.set(self.dialogData, callback);
|
||||
dialogScoped = scoped || null;
|
||||
},
|
||||
|
||||
closeDialog(confirmed?: any, data?: any) {
|
||||
const callback = dialogCallbacks.get(self.dialogData);
|
||||
|
||||
// 不要过早的清空,否则内部组件提前销毁,会出现 store 异常读取问题
|
||||
// self.dialogSchema = null;
|
||||
self.dialogOpen = false;
|
||||
dialogScoped = null;
|
||||
|
||||
if (callback) {
|
||||
dialogCallbacks.delete(self.dialogData);
|
||||
setTimeout(() => callback(confirmed, data), 200);
|
||||
}
|
||||
},
|
||||
|
||||
openDrawer(
|
||||
ctx: any,
|
||||
additonal?: object,
|
||||
callback?: (confirmed: boolean, ret: any) => void,
|
||||
scoped?: IScopedContext
|
||||
) {
|
||||
const chain = extractObjectChain(ctx);
|
||||
chain.length === 1 && chain.unshift(self.data);
|
||||
if (additonal) {
|
||||
chain.splice(chain.length - 1, 0, additonal);
|
||||
}
|
||||
|
||||
const data = createObjectFromChain(chain);
|
||||
|
||||
const mappingData = self.action.data ?? self.action.drawer.data;
|
||||
if (mappingData) {
|
||||
self.drawerData = createObjectFromChain([
|
||||
top?.context,
|
||||
dataMapping(mappingData, data)
|
||||
]);
|
||||
|
||||
const clonedAction = {
|
||||
...self.action,
|
||||
drawer: {
|
||||
...self.action.drawer
|
||||
}
|
||||
};
|
||||
delete clonedAction.drawer.data;
|
||||
self.action = clonedAction;
|
||||
} else {
|
||||
self.drawerData = data;
|
||||
}
|
||||
self.drawerSchema = self.action.drawer;
|
||||
self.drawerOpen = true;
|
||||
|
||||
if (callback) {
|
||||
dialogCallbacks.set(self.drawerData, callback);
|
||||
}
|
||||
|
||||
drawerScoped = scoped || null;
|
||||
},
|
||||
|
||||
closeDrawer(confirmed?: any, data?: any) {
|
||||
const callback = dialogCallbacks.get(self.drawerData);
|
||||
|
||||
// 不要过早的清空,否则内部组件提前销毁,会出现 store 异常读取问题
|
||||
// self.drawerSchema = null;
|
||||
self.drawerOpen = false;
|
||||
drawerScoped = null;
|
||||
|
||||
if (callback) {
|
||||
dialogCallbacks.delete(self.drawerData);
|
||||
setTimeout(() => callback(confirmed, data), 200);
|
||||
}
|
||||
},
|
||||
|
||||
getDialogScoped() {
|
||||
return dialogScoped;
|
||||
},
|
||||
|
||||
getDrawerScoped() {
|
||||
return drawerScoped;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
export type IIRendererStore = Instance<typeof iRendererStore>;
|
||||
export type SIRendererStore = SnapshotIn<typeof iRendererStore>;
|
||||
// export type SIRendererStore = typeof iRendererStore.SnapshotType;
|
||||
150
packages/amis-core/src/store/index.ts
Normal file
150
packages/amis-core/src/store/index.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
import {
|
||||
types,
|
||||
getEnv,
|
||||
detach,
|
||||
setLivelinessChecking,
|
||||
isAlive,
|
||||
Instance
|
||||
} from 'mobx-state-tree';
|
||||
import {iRendererStore, SIRendererStore} from './iRenderer';
|
||||
import type {IIRendererStore} from './iRenderer';
|
||||
import {ServiceStore} from './service';
|
||||
import type {IServiceStore} from './service';
|
||||
import {ComboStore} from './combo';
|
||||
import type {IComboStore} from './combo';
|
||||
import {FormStore} from './form';
|
||||
import type {IFormStore} from './form';
|
||||
import {CRUDStore} from './crud';
|
||||
import type {ICRUDStore} from './crud';
|
||||
import {TableStore} from './table';
|
||||
import type {IColumn, IRow, ITableStore} from './table';
|
||||
import {TableStore2} from './table2';
|
||||
import type {IColumn2, IRow2, ITableStore2} from './table2';
|
||||
import {ListStore} from './list';
|
||||
import type {IListStore} from './list';
|
||||
import {ModalStore} from './modal';
|
||||
import type {IModalStore} from './modal';
|
||||
import {TranslateFn} from '../locale';
|
||||
import find from 'lodash/find';
|
||||
import {StoreNode} from './node';
|
||||
import type {IStoreNode} from './node';
|
||||
import {FormItemStore} from './formItem';
|
||||
import type {IFormItemStore} from './formItem';
|
||||
import {addStore, getStoreById, getStores, removeStore} from './manager';
|
||||
import {PaginationStore} from './pagination';
|
||||
import type {IPaginationStore} from './pagination';
|
||||
import {AppStore} from './app';
|
||||
import type {IAppStore} from './app';
|
||||
import {RootStore} from './root';
|
||||
|
||||
setLivelinessChecking(
|
||||
process.env.NODE_ENV === 'production' ? 'ignore' : 'error'
|
||||
);
|
||||
|
||||
const allowedStoreList = [
|
||||
ServiceStore,
|
||||
FormStore,
|
||||
ComboStore,
|
||||
CRUDStore,
|
||||
TableStore,
|
||||
TableStore2,
|
||||
ListStore,
|
||||
ModalStore,
|
||||
FormItemStore,
|
||||
PaginationStore,
|
||||
AppStore
|
||||
];
|
||||
|
||||
export const RendererStore = types
|
||||
.model('RendererStore', {
|
||||
storeType: 'RendererStore'
|
||||
})
|
||||
.views(self => ({
|
||||
get fetcher() {
|
||||
return getEnv(self).fetcher;
|
||||
},
|
||||
|
||||
get notify() {
|
||||
return getEnv(self).notify;
|
||||
},
|
||||
|
||||
get isCancel(): (value: any) => boolean {
|
||||
return getEnv(self).isCancel;
|
||||
},
|
||||
|
||||
get __(): TranslateFn {
|
||||
return getEnv(self).translate;
|
||||
},
|
||||
getStoreById(id: string) {
|
||||
return getStoreById(id);
|
||||
},
|
||||
|
||||
get stores() {
|
||||
return getStores();
|
||||
}
|
||||
}))
|
||||
.actions(self => ({
|
||||
addStore(store: {
|
||||
storeType: string;
|
||||
id: string;
|
||||
path: string;
|
||||
parentId?: string;
|
||||
[propName: string]: any;
|
||||
}): IStoreNode {
|
||||
if (store.storeType === RootStore.name) {
|
||||
return addStore(RootStore.create(store, getEnv(self)));
|
||||
}
|
||||
|
||||
const factory = find(
|
||||
allowedStoreList,
|
||||
item => item.name === store.storeType
|
||||
)!;
|
||||
|
||||
return addStore(factory.create(store as any, getEnv(self)));
|
||||
},
|
||||
|
||||
removeStore(store: IStoreNode) {
|
||||
// store.dispose();
|
||||
removeStore(store);
|
||||
}
|
||||
}));
|
||||
|
||||
export type IRendererStore = Instance<typeof RendererStore>;
|
||||
export {iRendererStore, IIRendererStore};
|
||||
export const RegisterStore = function (store: any) {
|
||||
// 外部注册的 store 优先级更高
|
||||
// 方便外部扩充系统 Store
|
||||
allowedStoreList.unshift(store as any);
|
||||
};
|
||||
export const registerStore = RegisterStore;
|
||||
|
||||
export {
|
||||
ServiceStore,
|
||||
IServiceStore,
|
||||
FormStore,
|
||||
IFormStore,
|
||||
ComboStore,
|
||||
IComboStore,
|
||||
CRUDStore,
|
||||
ICRUDStore,
|
||||
TableStore,
|
||||
IColumn,
|
||||
IRow,
|
||||
ITableStore,
|
||||
TableStore2,
|
||||
ITableStore2,
|
||||
IColumn2,
|
||||
IRow2,
|
||||
ListStore,
|
||||
IListStore,
|
||||
ModalStore,
|
||||
IModalStore,
|
||||
FormItemStore,
|
||||
IFormItemStore,
|
||||
PaginationStore,
|
||||
IPaginationStore,
|
||||
AppStore,
|
||||
IAppStore,
|
||||
StoreNode,
|
||||
IStoreNode
|
||||
};
|
||||
397
packages/amis-core/src/store/list.ts
Normal file
397
packages/amis-core/src/store/list.ts
Normal file
@@ -0,0 +1,397 @@
|
||||
import {types, getParent, SnapshotIn, Instance} from 'mobx-state-tree';
|
||||
import {iRendererStore} from './iRenderer';
|
||||
import isEqual from 'lodash/isEqual';
|
||||
import find from 'lodash/find';
|
||||
import {
|
||||
createObject,
|
||||
isObject,
|
||||
guid,
|
||||
immutableExtends,
|
||||
extendObject
|
||||
} from '../utils/helper';
|
||||
import {evalExpression} from '../utils/tpl';
|
||||
|
||||
export const Item = types
|
||||
.model('Item', {
|
||||
storeType: 'Item',
|
||||
id: types.identifier,
|
||||
pristine: types.frozen(),
|
||||
data: types.frozen(),
|
||||
index: types.number,
|
||||
newIndex: types.number
|
||||
})
|
||||
.views(self => ({
|
||||
get checked(): boolean {
|
||||
return (getParent(self, 2) as IListStore).isSelected(self as IItem);
|
||||
},
|
||||
|
||||
get modified() {
|
||||
if (!self.data) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Object.keys(self.data).some(
|
||||
key => !isEqual(self.data[key], self.pristine[key])
|
||||
);
|
||||
},
|
||||
|
||||
get moved() {
|
||||
return self.index !== self.newIndex;
|
||||
},
|
||||
|
||||
get locals(): any {
|
||||
const listStore = getParent(self, 2) as IListStore;
|
||||
return createObject(
|
||||
extendObject(listStore.data, {
|
||||
index: self.index,
|
||||
|
||||
// 只有table时,也可以获取选中行
|
||||
...listStore.eventContext
|
||||
}),
|
||||
self.data
|
||||
);
|
||||
},
|
||||
|
||||
get checkable(): boolean {
|
||||
const table = getParent(self, 2) as IListStore;
|
||||
return table && table.itemCheckableOn
|
||||
? evalExpression(table.itemCheckableOn, (self as IItem).locals)
|
||||
: true;
|
||||
},
|
||||
|
||||
get draggable(): boolean {
|
||||
const list = getParent(self, 2) as IListStore;
|
||||
|
||||
return list && list.itemDraggableOn
|
||||
? evalExpression(list.itemDraggableOn, (self as IItem).locals)
|
||||
: list.draggable;
|
||||
}
|
||||
}))
|
||||
.actions(self => ({
|
||||
toggle() {
|
||||
(getParent(self, 2) as IListStore).toggle(self as IItem);
|
||||
},
|
||||
|
||||
change(values: object, savePristine?: boolean) {
|
||||
self.data = immutableExtends(self.data, values);
|
||||
savePristine && (self.pristine = self.data);
|
||||
},
|
||||
|
||||
reset() {
|
||||
self.newIndex = self.index;
|
||||
self.data = self.pristine;
|
||||
},
|
||||
updateData({children, ...rest}: any) {
|
||||
self.data = {
|
||||
...self.data,
|
||||
...rest
|
||||
};
|
||||
|
||||
// if (Array.isArray(children)) {
|
||||
|
||||
// }
|
||||
}
|
||||
}));
|
||||
|
||||
export type IItem = Instance<typeof Item>;
|
||||
export type SItem = SnapshotIn<typeof Item>;
|
||||
|
||||
export const ListStore = iRendererStore
|
||||
.named('ListStore')
|
||||
.props({
|
||||
items: types.array(Item),
|
||||
|
||||
// 记录原始列表和原始选中的列表
|
||||
// 因为如果是前端分页,上层 crud 或者 input-table 下发到这层的
|
||||
// 是某个页区间的数据,这个时候 items 和 selectedItems 会少很多条
|
||||
fullItems: types.optional(types.array(types.frozen()), []),
|
||||
fullSelectedItems: types.optional(types.array(types.frozen()), []),
|
||||
|
||||
selectedItems: types.array(types.reference(Item)),
|
||||
primaryField: 'id',
|
||||
orderBy: '',
|
||||
orderDir: types.optional(
|
||||
types.union(types.literal('asc'), types.literal('desc')),
|
||||
'asc'
|
||||
),
|
||||
draggable: false,
|
||||
dragging: false,
|
||||
multiple: true,
|
||||
strictMode: false,
|
||||
selectable: false,
|
||||
itemCheckableOn: '',
|
||||
itemDraggableOn: '',
|
||||
hideCheckToggler: false
|
||||
})
|
||||
.views(self => {
|
||||
function isSelected(item: IItem): boolean {
|
||||
return !!~self.selectedItems.indexOf(item);
|
||||
}
|
||||
|
||||
function getModifiedItems() {
|
||||
return self.items.filter(item => item.modified);
|
||||
}
|
||||
|
||||
function getModified() {
|
||||
return getModifiedItems().length;
|
||||
}
|
||||
|
||||
function getMovedItems() {
|
||||
return self.items.filter(item => item.moved);
|
||||
}
|
||||
|
||||
function getMovied() {
|
||||
return getMovedItems().length;
|
||||
}
|
||||
|
||||
return {
|
||||
get allChecked(): boolean {
|
||||
return !!(
|
||||
self.selectedItems.length ===
|
||||
(self as IListStore).checkableItems.length &&
|
||||
(self as IListStore).checkableItems.length
|
||||
);
|
||||
},
|
||||
|
||||
get checkableItems() {
|
||||
return self.items.filter(item => item.checkable);
|
||||
},
|
||||
|
||||
get unSelectedItems() {
|
||||
return self.items.filter(item => !item.checked);
|
||||
},
|
||||
|
||||
isSelected,
|
||||
|
||||
get modified() {
|
||||
return getModified();
|
||||
},
|
||||
|
||||
get modifiedItems() {
|
||||
return getModifiedItems();
|
||||
},
|
||||
|
||||
get moved() {
|
||||
return getMovied();
|
||||
},
|
||||
|
||||
get movedItems() {
|
||||
return getMovedItems();
|
||||
},
|
||||
|
||||
/**
|
||||
* 构建事件的上下文数据
|
||||
* @param buildChain
|
||||
* @returns
|
||||
*/
|
||||
get eventContext() {
|
||||
const context = {
|
||||
selectedItems: self.selectedItems.map(item => item.data),
|
||||
selectedIndexes: self.selectedItems.map(item => item.index),
|
||||
items: self.items.map(item => item.data),
|
||||
unSelectedItems: this.unSelectedItems.map(item => item.data)
|
||||
};
|
||||
|
||||
// 如果是前端分页情况,需要根据全量数据计算
|
||||
// 如果不是前端分页,数据都没有返回,那种就没办法支持全量数据信息了
|
||||
if (self.fullItems.length > self.items.length) {
|
||||
// todo 这里的选择顺序会一直变,这个有影响吗?
|
||||
const selectedItems = self.fullSelectedItems
|
||||
.filter(
|
||||
item =>
|
||||
!self.items.find(
|
||||
row => row.pristine === (item.__pristine || item)
|
||||
)
|
||||
)
|
||||
.concat(context.selectedItems);
|
||||
|
||||
context.selectedItems = selectedItems;
|
||||
context.items = self.fullItems.concat();
|
||||
context.unSelectedItems = self.fullItems.filter(
|
||||
item => !selectedItems.includes(item)
|
||||
);
|
||||
context.selectedIndexes = selectedItems.map(item =>
|
||||
self.fullItems.indexOf(item.__pristine || item)
|
||||
);
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
};
|
||||
})
|
||||
.actions(self => {
|
||||
function update(config: Partial<SListStore>) {
|
||||
config.selectable === void 0 || (self.selectable = config.selectable);
|
||||
config.draggable === void 0 || (self.draggable = config.draggable);
|
||||
config.multiple === void 0 || (self.multiple = config.multiple);
|
||||
config.strictMode === void 0 || (self.strictMode = config.strictMode);
|
||||
config.hideCheckToggler === void 0 ||
|
||||
(self.hideCheckToggler = config.hideCheckToggler);
|
||||
|
||||
if (typeof config.orderBy !== 'undefined') {
|
||||
setOrderByInfo(
|
||||
config.orderBy,
|
||||
config.orderDir === 'desc' ? 'desc' : 'asc'
|
||||
);
|
||||
}
|
||||
|
||||
config.itemCheckableOn === void 0 ||
|
||||
(self.itemCheckableOn = config.itemCheckableOn);
|
||||
config.itemDraggableOn === void 0 ||
|
||||
(self.itemDraggableOn = config.itemDraggableOn);
|
||||
}
|
||||
|
||||
function initItems(
|
||||
items: Array<object>,
|
||||
fullItems?: Array<any>,
|
||||
fullSelectedItems?: Array<any>
|
||||
) {
|
||||
let arr = items.map((item, key) => {
|
||||
item = isObject(item)
|
||||
? item
|
||||
: {
|
||||
item: item
|
||||
};
|
||||
|
||||
return {
|
||||
// id: String((item as any)[self.primaryField] || key),
|
||||
id: guid(),
|
||||
index: key,
|
||||
newIndex: key,
|
||||
pristine: (item as any).__pristine || item,
|
||||
data: item
|
||||
};
|
||||
});
|
||||
self.selectedItems.clear();
|
||||
self.items.replace(arr as Array<IItem>);
|
||||
self.dragging = false;
|
||||
Array.isArray(fullItems) && self.fullItems.replace(fullItems);
|
||||
Array.isArray(fullSelectedItems) &&
|
||||
self.fullSelectedItems.replace(fullSelectedItems);
|
||||
}
|
||||
|
||||
function updateSelected(selected: Array<any>, valueField?: string) {
|
||||
self.selectedItems.clear();
|
||||
selected.forEach(item => {
|
||||
let resolved = self.items.find(a => a.pristine === item);
|
||||
|
||||
// 先严格比较,
|
||||
if (!resolved) {
|
||||
resolved = self.items.find(a => {
|
||||
const selectValue = item[valueField || 'value'];
|
||||
const itemValue = a.pristine[valueField || 'value'];
|
||||
return selectValue === itemValue;
|
||||
});
|
||||
}
|
||||
|
||||
// 再宽松比较
|
||||
if (!resolved) {
|
||||
resolved = self.items.find(a => {
|
||||
const selectValue = item[valueField || 'value'];
|
||||
const itemValue = a.pristine[valueField || 'value'];
|
||||
return selectValue == itemValue;
|
||||
});
|
||||
}
|
||||
|
||||
resolved && self.selectedItems.push(resolved);
|
||||
});
|
||||
}
|
||||
|
||||
function toggleAll() {
|
||||
if (self.allChecked) {
|
||||
self.selectedItems.clear();
|
||||
} else {
|
||||
self.selectedItems.replace(self.checkableItems);
|
||||
}
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
self.selectedItems.clear();
|
||||
}
|
||||
|
||||
function selectAll() {
|
||||
self.selectedItems.replace(self.checkableItems);
|
||||
}
|
||||
|
||||
function toggle(item: IItem) {
|
||||
if (!item.checkable) {
|
||||
return;
|
||||
}
|
||||
|
||||
const idx = self.selectedItems.indexOf(item);
|
||||
|
||||
if (self.multiple) {
|
||||
~idx
|
||||
? self.selectedItems.splice(idx, 1)
|
||||
: self.selectedItems.push(item);
|
||||
} else {
|
||||
~idx
|
||||
? self.selectedItems.splice(idx, 1)
|
||||
: self.selectedItems.replace([item]);
|
||||
}
|
||||
}
|
||||
|
||||
function clear() {
|
||||
self.selectedItems.clear();
|
||||
}
|
||||
|
||||
function setOrderByInfo(key: string, direction: 'asc' | 'desc') {
|
||||
self.orderBy = key;
|
||||
self.orderDir = direction;
|
||||
}
|
||||
|
||||
function reset() {
|
||||
self.items.forEach(item => item.reset());
|
||||
self.dragging = false;
|
||||
}
|
||||
|
||||
function toggleDragging() {
|
||||
self.dragging = !self.dragging;
|
||||
}
|
||||
|
||||
function startDragging() {
|
||||
self.dragging = true;
|
||||
}
|
||||
|
||||
function stopDragging() {
|
||||
self.dragging = false;
|
||||
}
|
||||
|
||||
function exchange(fromIndex: number, toIndex: number) {
|
||||
const item: IItem = self.items[fromIndex];
|
||||
item.newIndex = toIndex;
|
||||
|
||||
const newItems = self.items.slice();
|
||||
newItems.splice(fromIndex, 1);
|
||||
newItems.splice(toIndex, 0, item);
|
||||
|
||||
self.items.replace(newItems);
|
||||
}
|
||||
|
||||
function getData(superData: any): any {
|
||||
return createObject(superData, {
|
||||
...self.eventContext
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
getData,
|
||||
update,
|
||||
initItems,
|
||||
updateSelected,
|
||||
toggleAll,
|
||||
clearAll,
|
||||
selectAll,
|
||||
toggle,
|
||||
clear,
|
||||
setOrderByInfo,
|
||||
reset,
|
||||
toggleDragging,
|
||||
startDragging,
|
||||
stopDragging,
|
||||
exchange
|
||||
};
|
||||
});
|
||||
|
||||
export type IListStore = Instance<typeof ListStore>;
|
||||
export type SListStore = SnapshotIn<typeof ListStore>;
|
||||
55
packages/amis-core/src/store/manager.ts
Normal file
55
packages/amis-core/src/store/manager.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import {isAlive} from 'mobx-state-tree';
|
||||
import {IIRendererStore} from './iRenderer';
|
||||
import {IStoreNode} from './node';
|
||||
|
||||
const stores: {
|
||||
[propName: string]: IStoreNode;
|
||||
} = {};
|
||||
|
||||
export function addStore(store: IStoreNode) {
|
||||
if (stores[store.id]) {
|
||||
return stores[store.id];
|
||||
}
|
||||
|
||||
stores[store.id] = store;
|
||||
|
||||
// drawer dialog 不加进去,否则有些容器就不会自我销毁 store 了。
|
||||
if (store.parentId && !/(?:dialog|drawer)$/.test(store.path)) {
|
||||
const parent = stores[store.parentId] as IIRendererStore;
|
||||
parent.addChildId(store.id);
|
||||
}
|
||||
|
||||
cleanUp();
|
||||
return store;
|
||||
}
|
||||
|
||||
const toDelete: Array<string> = [];
|
||||
|
||||
export function removeStore(store: IStoreNode) {
|
||||
const id = store.id;
|
||||
toDelete.push(id);
|
||||
store.dispose(cleanUp);
|
||||
}
|
||||
|
||||
function cleanUp() {
|
||||
let index = toDelete.length - 1;
|
||||
while (index >= 0) {
|
||||
const id = toDelete[index];
|
||||
const store = stores[id];
|
||||
|
||||
if (store && !isAlive(store)) {
|
||||
delete stores[id];
|
||||
toDelete.splice(index, 1);
|
||||
} else {
|
||||
index--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function getStoreById(id: string) {
|
||||
return stores[id];
|
||||
}
|
||||
|
||||
export function getStores() {
|
||||
return stores;
|
||||
}
|
||||
61
packages/amis-core/src/store/modal.ts
Normal file
61
packages/amis-core/src/store/modal.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import {ServiceStore} from './service';
|
||||
import {types, SnapshotIn, Instance, isAlive} from 'mobx-state-tree';
|
||||
import {createObject} from '../utils/helper';
|
||||
|
||||
export const ModalStore = ServiceStore.named('ModalStore')
|
||||
.props({
|
||||
form: types.frozen(),
|
||||
entered: false,
|
||||
dragging: false,
|
||||
resizeCoord: 0,
|
||||
schema: types.frozen(),
|
||||
isFullscreen: false
|
||||
})
|
||||
.views(self => {
|
||||
return {
|
||||
get formData() {
|
||||
return createObject(self.data, self.form);
|
||||
},
|
||||
get inDragging() {
|
||||
return self.dragging;
|
||||
}
|
||||
};
|
||||
})
|
||||
.actions(self => {
|
||||
return {
|
||||
setEntered(value: boolean) {
|
||||
self.entered = value;
|
||||
},
|
||||
setDragging(value: boolean) {
|
||||
self.dragging = value;
|
||||
},
|
||||
setFormData(obj: any) {
|
||||
self.form = obj;
|
||||
},
|
||||
reset() {
|
||||
self.form = {};
|
||||
self.reInitData({}, true);
|
||||
},
|
||||
|
||||
setResizeCoord(value: number) {
|
||||
self.resizeCoord = value;
|
||||
},
|
||||
|
||||
setSchema(schema: any) {
|
||||
if (schema && schema.then) {
|
||||
schema.then(
|
||||
(value: any) => isAlive(self) && (self as any).setSchema(value)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
self.schema = schema;
|
||||
},
|
||||
setFullScreen(isFullscreen: boolean = false) {
|
||||
self.isFullscreen = isFullscreen;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
export type IModalStore = Instance<typeof ModalStore>;
|
||||
export type SModalStore = SnapshotIn<typeof ModalStore>;
|
||||
105
packages/amis-core/src/store/node.ts
Normal file
105
packages/amis-core/src/store/node.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import {
|
||||
types,
|
||||
destroy,
|
||||
isAlive,
|
||||
detach,
|
||||
getEnv,
|
||||
Instance,
|
||||
SnapshotIn
|
||||
} from 'mobx-state-tree';
|
||||
import {getStoreById} from './manager';
|
||||
|
||||
export const StoreNode = types
|
||||
.model('StoreNode', {
|
||||
id: types.identifier,
|
||||
path: '',
|
||||
storeType: types.string,
|
||||
disposed: false,
|
||||
parentId: '',
|
||||
childrenIds: types.optional(types.array(types.string), [])
|
||||
})
|
||||
.views(self => {
|
||||
return {
|
||||
get parentStore(): any {
|
||||
return isAlive(self) && self.parentId
|
||||
? getStoreById(self.parentId)
|
||||
: null;
|
||||
},
|
||||
|
||||
get __() {
|
||||
return getEnv(self).translate;
|
||||
},
|
||||
|
||||
get hasChildren() {
|
||||
return !!self.childrenIds.length;
|
||||
},
|
||||
|
||||
get children(): Array<any> {
|
||||
return self.childrenIds.map(item => getStoreById(item));
|
||||
}
|
||||
};
|
||||
})
|
||||
.actions(self => {
|
||||
function addChildId(id: string) {
|
||||
self.childrenIds.push(id);
|
||||
}
|
||||
|
||||
function removeChildId(id: string) {
|
||||
const childrenIds = self.childrenIds.filter(item => item !== id);
|
||||
self.childrenIds.replace(childrenIds);
|
||||
|
||||
self.disposed && dispose();
|
||||
}
|
||||
|
||||
function dispose(callback?: () => void) {
|
||||
// 先标记自己是要销毁的。
|
||||
self.disposed = true;
|
||||
|
||||
if (/(?:dialog|drawer)$/.test(self.path)) {
|
||||
destroy(self);
|
||||
callback?.();
|
||||
} else if (!self.childrenIds.length) {
|
||||
const parent = self.parentStore;
|
||||
parent && isAlive(parent) && parent.onChildStoreDispose(self);
|
||||
destroy(self);
|
||||
callback?.();
|
||||
// destroy(self);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
onChildStoreDispose(child: any) {
|
||||
removeChildId(child.id);
|
||||
},
|
||||
|
||||
syncProps(
|
||||
props: any,
|
||||
prevProps: any,
|
||||
list: Array<string> = Object.keys(props)
|
||||
) {
|
||||
const target: any = self;
|
||||
list.forEach(key => {
|
||||
if (prevProps && props[key] === prevProps[key]) {
|
||||
return;
|
||||
}
|
||||
|
||||
const setter = `set${key
|
||||
.substring(0, 1)
|
||||
.toUpperCase()}${key.substring(1)}`;
|
||||
|
||||
if (typeof target[setter] === 'function') {
|
||||
target[setter](props[key]);
|
||||
} else if (target.hasOwnProperty(key)) {
|
||||
target[key] = props[key];
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
dispose,
|
||||
addChildId,
|
||||
removeChildId
|
||||
};
|
||||
});
|
||||
|
||||
export type IStoreNode = Instance<typeof StoreNode>;
|
||||
export type SIStoreNode = SnapshotIn<typeof StoreNode>;
|
||||
54
packages/amis-core/src/store/pagination.ts
Normal file
54
packages/amis-core/src/store/pagination.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import {Instance, SnapshotIn, types} from 'mobx-state-tree';
|
||||
import {createObject} from '../utils/helper';
|
||||
import {resolveVariable} from '../utils/tpl-builtin';
|
||||
import {iRendererStore} from './iRenderer';
|
||||
|
||||
export const PaginationStore = iRendererStore
|
||||
.named('PaginationStore')
|
||||
.props({
|
||||
page: 1,
|
||||
perPage: 10,
|
||||
inputName: '',
|
||||
outputName: '',
|
||||
mode: 'normal',
|
||||
ellipsisPageGap: 5
|
||||
})
|
||||
.views(self => ({
|
||||
get inputItems() {
|
||||
const items = resolveVariable(self.inputName || 'items', self.data);
|
||||
|
||||
if (!Array.isArray(items)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return items;
|
||||
},
|
||||
|
||||
get locals() {
|
||||
const skip = (self.page - 1) * self.perPage;
|
||||
|
||||
return createObject(self.data, {
|
||||
currentPage: self.page,
|
||||
lastPage: this.lastPage,
|
||||
[self.outputName || 'items']: this.inputItems.slice(
|
||||
skip,
|
||||
skip + self.perPage
|
||||
)
|
||||
});
|
||||
},
|
||||
get lastPage() {
|
||||
return Math.ceil(this.inputItems.length / self.perPage);
|
||||
}
|
||||
}))
|
||||
.actions(self => ({
|
||||
switchTo(page: number, perPage?: number) {
|
||||
self.page = page;
|
||||
|
||||
if (typeof perPage === 'number') {
|
||||
self.perPage = perPage;
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
export type IPaginationStore = Instance<typeof PaginationStore>;
|
||||
export type SPaginationStore = SnapshotIn<typeof PaginationStore>;
|
||||
755
packages/amis-core/src/store/root.ts
Normal file
755
packages/amis-core/src/store/root.ts
Normal file
@@ -0,0 +1,755 @@
|
||||
import {addDisposer, flow, Instance, types, isAlive} from 'mobx-state-tree';
|
||||
import {parseQuery} from '../utils/helper';
|
||||
import {ServiceStore} from './service';
|
||||
import {
|
||||
createObjectFromChain,
|
||||
extractObjectChain,
|
||||
isObjectShallowModified,
|
||||
createObject,
|
||||
cloneObject
|
||||
} from '../utils';
|
||||
import {
|
||||
GlobalVariableItem,
|
||||
GlobalVariableState,
|
||||
GlobalVariableItemFull,
|
||||
buildGlobalVariable,
|
||||
createGlobalVarState,
|
||||
GlobalVarContext,
|
||||
GlobalVarGetter,
|
||||
GlobalVarBulkGetter,
|
||||
GlobalVarSetter,
|
||||
GlobalVarBulkSetter
|
||||
} from '../globalVar';
|
||||
import isPlainObject from 'lodash/isPlainObject';
|
||||
import debounce from 'lodash/debounce';
|
||||
import {reaction} from 'mobx';
|
||||
|
||||
export const RootStore = ServiceStore.named('RootStore')
|
||||
.props({
|
||||
runtimeError: types.frozen(),
|
||||
runtimeErrorStack: types.frozen(),
|
||||
query: types.frozen(),
|
||||
ready: false,
|
||||
|
||||
// 临时变更,等 react 完成一轮渲染后,将临时变更切成正式变更
|
||||
// 主要是为了让可能需要重新渲染的部分组件可以实现 this.props.data 和 prevProps.data 不一致
|
||||
// 因为很多组件内部会 diff this.props.data 和 prevProps.data 来决定是否更新的逻辑
|
||||
globalVarTempStates: types.optional(
|
||||
types.map(types.frozen<GlobalVariableState>()),
|
||||
{}
|
||||
),
|
||||
|
||||
// 正式变更
|
||||
globalVarStates: types.optional(
|
||||
types.map(types.frozen<GlobalVariableState>()),
|
||||
{}
|
||||
)
|
||||
})
|
||||
.volatile(self => {
|
||||
return {
|
||||
context: {} as any,
|
||||
legacyGlobalTempContext: {} as any,
|
||||
globalVars: [] as Array<GlobalVariableItemFull>,
|
||||
globalData: {
|
||||
global: {},
|
||||
globalState: {}
|
||||
} as any
|
||||
};
|
||||
})
|
||||
.views(self => ({
|
||||
get nextGlobalData(): any {
|
||||
let globalData = {} as any;
|
||||
let globalState = {} as any;
|
||||
const chain = extractObjectChain(self.data);
|
||||
|
||||
let touched = false;
|
||||
let saved = true;
|
||||
let errors: any = {};
|
||||
let initialized = true;
|
||||
self.globalVarTempStates.forEach((state, key) => {
|
||||
globalData[key] = state.value;
|
||||
touched = touched || state.touched;
|
||||
if (!state.saved) {
|
||||
saved = false;
|
||||
}
|
||||
|
||||
if (state.errorMessages.length) {
|
||||
errors[key] = state.errorMessages;
|
||||
}
|
||||
if (!state.initialized) {
|
||||
initialized = false;
|
||||
}
|
||||
});
|
||||
|
||||
globalState = {
|
||||
fields: self.globalVarTempStates.toJSON(),
|
||||
initialized: initialized,
|
||||
touched: touched,
|
||||
saved: saved,
|
||||
errors: errors,
|
||||
valid: !Object.keys(errors).length
|
||||
};
|
||||
chain.unshift({
|
||||
global: globalData,
|
||||
globalState: globalState
|
||||
});
|
||||
chain.unshift(self.legacyGlobalTempContext);
|
||||
chain.unshift(self.context);
|
||||
|
||||
return createObjectFromChain(chain);
|
||||
},
|
||||
|
||||
get downStream() {
|
||||
let result = self.data;
|
||||
|
||||
if (self.context || self.query) {
|
||||
const chain = extractObjectChain(result);
|
||||
|
||||
// 数据链中添加 global 和 globalState
|
||||
// 对应的是全局变量的值和全局变量的状态
|
||||
const globalData = {} as any;
|
||||
let touched = false;
|
||||
let saved = true;
|
||||
let errors: any = {};
|
||||
let initialized = true;
|
||||
self.globalVarStates.forEach((state, key) => {
|
||||
globalData[key] = state.value;
|
||||
touched = touched || state.touched;
|
||||
if (!state.saved) {
|
||||
saved = false;
|
||||
}
|
||||
|
||||
if (state.errorMessages.length) {
|
||||
errors[key] = state.errorMessages;
|
||||
}
|
||||
if (!state.initialized) {
|
||||
initialized = false;
|
||||
}
|
||||
});
|
||||
|
||||
// 保存全局变量的值和状态
|
||||
Object.assign(self.globalData.global, globalData);
|
||||
Object.assign(self.globalData.globalState, {
|
||||
fields: self.globalVarStates.toJSON(),
|
||||
initialized: initialized,
|
||||
touched: touched,
|
||||
saved: saved,
|
||||
errors: errors,
|
||||
valid: !Object.keys(errors).length
|
||||
});
|
||||
|
||||
// self.globalData 一直都是那个对象,这样组件里面始终拿到的都是最新的
|
||||
chain.unshift(self.globalData);
|
||||
|
||||
chain.unshift(self.context);
|
||||
self.query &&
|
||||
chain.splice(chain.length - 1, 0, {
|
||||
...self.query,
|
||||
__query: self.query
|
||||
});
|
||||
|
||||
result = createObjectFromChain(chain);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}))
|
||||
.actions(self => {
|
||||
function updateState(key: string, state: Partial<GlobalVariableState>) {
|
||||
return (self as any).updateGlobalVarState(key, state);
|
||||
}
|
||||
|
||||
const init: (schema: any) => Promise<any> = flow(function* init(
|
||||
fn: () => Promise<any>
|
||||
) {
|
||||
try {
|
||||
const ret: any = fn();
|
||||
if (ret?.then) {
|
||||
yield ret;
|
||||
}
|
||||
} catch (e) {
|
||||
self.runtimeError = e.message;
|
||||
self.runtimeErrorStack = e.stack;
|
||||
} finally {
|
||||
self.ready = true;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 比较新旧变量列表的差异
|
||||
* @param vars 新的变量列表
|
||||
* @param originVars 原始变量列表
|
||||
* @returns 返回新增、更新和删除的变量列表
|
||||
*/
|
||||
function diffVariables(
|
||||
vars: GlobalVariableItem[],
|
||||
originVars: GlobalVariableItem[]
|
||||
) {
|
||||
const removeVars: Array<GlobalVariableItem> = originVars.concat();
|
||||
const updateVars: Array<GlobalVariableItem> = [];
|
||||
const newVars: Array<GlobalVariableItem> = [];
|
||||
|
||||
for (let varItem of vars) {
|
||||
const idx = removeVars.findIndex(item => item.key === varItem.key);
|
||||
|
||||
if (~idx) {
|
||||
const [origin] = removeVars.splice(idx, 1);
|
||||
|
||||
if (origin.id !== varItem.id) {
|
||||
updateVars.push(varItem);
|
||||
}
|
||||
} else {
|
||||
newVars.push(varItem);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
newVars,
|
||||
updateVars,
|
||||
removeVars
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化单个全局变量
|
||||
*/
|
||||
async function initGlobalVarData(
|
||||
item: GlobalVariableItemFull,
|
||||
context: GlobalVarContext,
|
||||
getter?: GlobalVarGetter
|
||||
) {
|
||||
let value = item.defaultValue;
|
||||
|
||||
if (getter) {
|
||||
await getGlobalVarData(item, context, getter);
|
||||
const state = self.globalVarTempStates.get(item.key)!;
|
||||
updateState(item.key, {
|
||||
initialized: true,
|
||||
pristine: state.value
|
||||
});
|
||||
} else {
|
||||
updateState(item.key, {
|
||||
value,
|
||||
pristine: value,
|
||||
initialized: item.bulkGetter ? false : true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量初始化全局变量
|
||||
*/
|
||||
async function getGlobalVarData(
|
||||
item: GlobalVariableItemFull,
|
||||
context: GlobalVarContext,
|
||||
getter: GlobalVarGetter
|
||||
) {
|
||||
try {
|
||||
updateState(item.key, {
|
||||
busy: true
|
||||
});
|
||||
const value = await getter(item, context);
|
||||
updateState(item.key, {
|
||||
value
|
||||
});
|
||||
} finally {
|
||||
updateState(item.key, {
|
||||
busy: false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量初始化全局变量
|
||||
*/
|
||||
async function bulkGetGlobalVarData(
|
||||
variables: Array<GlobalVariableItem>,
|
||||
context: GlobalVarContext,
|
||||
getter: GlobalVarBulkGetter
|
||||
) {
|
||||
try {
|
||||
variables.forEach(item => {
|
||||
updateState(item.key, {
|
||||
busy: true
|
||||
});
|
||||
});
|
||||
const data = await getter.call(null, {
|
||||
...context,
|
||||
variables
|
||||
});
|
||||
|
||||
if (!isPlainObject(data)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (let key in data) {
|
||||
// 返回非定义部分的数据不处理
|
||||
if (!variables.some(item => item.key === key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const state = self.globalVarTempStates.get(key);
|
||||
if (state) {
|
||||
updateState(key, {
|
||||
value: data[key],
|
||||
pristine: data[key],
|
||||
initialized: true
|
||||
});
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
variables.forEach(item => {
|
||||
updateState(item.key, {
|
||||
busy: false
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化全局变量
|
||||
*/
|
||||
async function initializeGlobalVars(
|
||||
newVars: GlobalVariableItem[],
|
||||
updateVars: GlobalVariableItem[]
|
||||
) {
|
||||
const variables = newVars.concat(updateVars);
|
||||
const context = {
|
||||
...self.context,
|
||||
variables
|
||||
};
|
||||
const globalVars = variables.map(item =>
|
||||
buildGlobalVariable(item, context)
|
||||
);
|
||||
|
||||
const bulkGetters: Array<{
|
||||
fn: GlobalVarBulkGetter;
|
||||
variables: Array<GlobalVariableItem>;
|
||||
}> = [];
|
||||
const itemsNotInitialized: Array<GlobalVariableItemFull> = [];
|
||||
|
||||
for (let item of globalVars) {
|
||||
let state = self.globalVarTempStates.get(item.key);
|
||||
if (state?.initialized) {
|
||||
continue;
|
||||
}
|
||||
|
||||
itemsNotInitialized.push(item);
|
||||
|
||||
if (item.bulkGetter) {
|
||||
let getter = bulkGetters.find(a => a.fn === item.bulkGetter);
|
||||
if (!getter) {
|
||||
getter = {
|
||||
fn: item.bulkGetter,
|
||||
variables: []
|
||||
};
|
||||
bulkGetters.push(getter);
|
||||
}
|
||||
getter.variables.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
// 先单个初始化
|
||||
await Promise.all(
|
||||
itemsNotInitialized.map(item =>
|
||||
initGlobalVarData(item, context, item.getter)
|
||||
)
|
||||
);
|
||||
// 再批量初始化
|
||||
await Promise.all(
|
||||
bulkGetters.map(({fn, variables}) =>
|
||||
bulkGetGlobalVarData(variables, context, fn)
|
||||
)
|
||||
);
|
||||
|
||||
return globalVars;
|
||||
}
|
||||
|
||||
// 设置全局变量,返回一个Promise
|
||||
const setGlobalVars: (vars?: Array<GlobalVariableItem>) => Promise<any> =
|
||||
flow(function* setGlobalVars(vars?: Array<GlobalVariableItem>) {
|
||||
const {newVars, updateVars, removeVars} = diffVariables(
|
||||
vars || [],
|
||||
self.globalVars
|
||||
);
|
||||
|
||||
// 初始化全局变量
|
||||
const globalVars = yield initializeGlobalVars(newVars, updateVars);
|
||||
|
||||
if (!isAlive(self)) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.globalVars = globalVars;
|
||||
removeVars.forEach(item => {
|
||||
self.globalVarTempStates.delete(item.key);
|
||||
});
|
||||
|
||||
syncGlobalVarStates();
|
||||
});
|
||||
|
||||
// 更新全局变量的值
|
||||
const updateGlobalVarValue = (key: string, value: any) => {
|
||||
return modifyGlobalVarValue(key, {op: 'set', value});
|
||||
};
|
||||
|
||||
// 如果对应变量是个对象,那么可以通过这个扩充变量的值
|
||||
const modifyGlobalVarValue = (
|
||||
key: string,
|
||||
options: {
|
||||
op:
|
||||
| 'set'
|
||||
| 'merge'
|
||||
| 'push'
|
||||
| 'unshift'
|
||||
| 'remove'
|
||||
| 'toggle'
|
||||
| 'empty'
|
||||
| 'sort'
|
||||
| 'reverse'
|
||||
| 'refresh';
|
||||
value: any;
|
||||
}
|
||||
) => {
|
||||
const state = self.globalVarTempStates.get(key);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
let value = state.value;
|
||||
|
||||
switch (options.op) {
|
||||
case 'set':
|
||||
value = options.value;
|
||||
break;
|
||||
// 下面这些以后使用的地方再加
|
||||
// case 'merge':
|
||||
// value = {
|
||||
// ...isPlainObject(value) ? value : {},
|
||||
// ...options.value
|
||||
// };
|
||||
// break;
|
||||
// case 'push':
|
||||
// value = Array.isArray(value) ? value.concat() : [];
|
||||
// value = value.concat(options.value);
|
||||
// break;
|
||||
// case 'unshift':
|
||||
// value = Array.isArray(value) ? value.concat() : [];
|
||||
// value.unshift(options.value);
|
||||
// break;
|
||||
// case 'remove':
|
||||
// value = (Array.isArray(value) ? value : []).filter((item: any) => item !== options.value);
|
||||
// break;
|
||||
// case 'toggle':
|
||||
// value = value === options.value ? undefined : options.value;
|
||||
// break;
|
||||
// case 'empty':
|
||||
// value = [];
|
||||
// break;
|
||||
// case 'sort':
|
||||
// value = value.sort(options.value);
|
||||
// break;
|
||||
// case 'reverse':
|
||||
// value = value.reverse();
|
||||
// break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
updateState(key, {
|
||||
value,
|
||||
touched: true
|
||||
});
|
||||
|
||||
lazySaveGlobalVarValues();
|
||||
};
|
||||
|
||||
/**
|
||||
* 保存单个全局变量的值
|
||||
*/
|
||||
async function saveGlobalVarData(
|
||||
item: GlobalVariableItemFull,
|
||||
value: any,
|
||||
context: GlobalVarContext,
|
||||
setter: GlobalVarSetter
|
||||
) {
|
||||
try {
|
||||
updateState(item.key, {
|
||||
busy: true
|
||||
});
|
||||
|
||||
await setter(item, value, context);
|
||||
|
||||
updateState(item.key, {
|
||||
saved: true
|
||||
});
|
||||
} finally {
|
||||
updateState(item.key, {
|
||||
busy: false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量保存全局变量
|
||||
*/
|
||||
async function bulkSaveGlobalVarData(
|
||||
variables: Array<GlobalVariableItem>,
|
||||
values: any,
|
||||
context: GlobalVarContext,
|
||||
setter: GlobalVarBulkSetter
|
||||
) {
|
||||
try {
|
||||
variables.forEach(item => {
|
||||
updateState(item.key, {
|
||||
busy: true
|
||||
});
|
||||
});
|
||||
await setter(values, {
|
||||
...context,
|
||||
variables
|
||||
});
|
||||
|
||||
variables.forEach(item => {
|
||||
updateState(item.key, {
|
||||
saved: true
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
variables.forEach(item => {
|
||||
updateState(item.key, {
|
||||
busy: false
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存全局变量的值
|
||||
*/
|
||||
async function saveGlobalVarValues(key?: string) {
|
||||
const context = {
|
||||
...self.context,
|
||||
variables: self.globalVars
|
||||
};
|
||||
const setters: Array<{
|
||||
fn: GlobalVarSetter;
|
||||
value: any;
|
||||
item: GlobalVariableItem;
|
||||
}> = [];
|
||||
const bulkSetters: Array<{
|
||||
fn: GlobalVarBulkSetter;
|
||||
variables: Array<GlobalVariableItem>;
|
||||
values: any;
|
||||
}> = [];
|
||||
const values: any = {};
|
||||
for (let varItem of self.globalVars) {
|
||||
const state = self.globalVarTempStates.get(varItem.key);
|
||||
if (!state?.touched) {
|
||||
continue;
|
||||
} else if (key && key !== varItem.key) {
|
||||
continue;
|
||||
} else if (!key && varItem.autoSave === false) {
|
||||
// 没有指定 key,但是 autoSave 为 false 的不保存
|
||||
continue;
|
||||
}
|
||||
|
||||
values[varItem.key] = state.value;
|
||||
if (varItem.setter) {
|
||||
setters.push({
|
||||
fn: varItem.setter,
|
||||
item: varItem,
|
||||
value: state.value
|
||||
});
|
||||
}
|
||||
|
||||
if (varItem.bulkSetter) {
|
||||
let setter = bulkSetters.find(a => a.fn === varItem.bulkSetter);
|
||||
if (!setter) {
|
||||
setter = {
|
||||
fn: varItem.bulkSetter,
|
||||
variables: [],
|
||||
values: {}
|
||||
};
|
||||
bulkSetters.push(setter);
|
||||
}
|
||||
setter.variables.push(varItem);
|
||||
setter.values[varItem.key] = state.value;
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
setters
|
||||
.map(({fn, item, value}) =>
|
||||
saveGlobalVarData(item, value, context, fn)
|
||||
)
|
||||
.concat(
|
||||
bulkSetters.map(({variables, values, fn}) =>
|
||||
bulkSaveGlobalVarData(variables, values, context, fn)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// 延迟保存全局变量的值
|
||||
const lazySaveGlobalVarValues = debounce(saveGlobalVarValues, 250, {
|
||||
trailing: true,
|
||||
leading: false
|
||||
});
|
||||
|
||||
function syncGlobalVarStates() {
|
||||
self.globalVarStates.clear();
|
||||
self.globalVarTempStates.forEach((state, key) => {
|
||||
self.globalVarStates.set(key, {...state});
|
||||
});
|
||||
}
|
||||
|
||||
function syncLegacyGlobalVarStates() {
|
||||
if (
|
||||
self.legacyGlobalTempContext.__page !== self.context.__page ||
|
||||
self.legacyGlobalTempContext.appVariables !== self.context.appVariables
|
||||
) {
|
||||
Object.assign(self.context, self.legacyGlobalTempContext);
|
||||
self.data = cloneObject(self.data);
|
||||
}
|
||||
}
|
||||
|
||||
let pendingCount = 0;
|
||||
let callbacks: Array<() => void> = [];
|
||||
function addSyncGlobalVarStatePendingTask(
|
||||
fn: (callback: () => void) => void,
|
||||
callback?: () => void
|
||||
) {
|
||||
pendingCount++;
|
||||
callback && callbacks.push(callback);
|
||||
fn(() => {
|
||||
pendingCount--;
|
||||
|
||||
if (pendingCount === 0) {
|
||||
callbacks.forEach(callback => callback());
|
||||
callbacks = [];
|
||||
if (isAlive(self)) {
|
||||
(self as any).syncGlobalVarStates();
|
||||
(self as any).syncLegacyGlobalVarStates();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function observeSet(
|
||||
obj: Record<string, any>,
|
||||
callback: (value: any) => void
|
||||
) {
|
||||
if (!obj || obj.__observed) {
|
||||
// 如果已经被观察过了,就不需要再观察了
|
||||
return obj;
|
||||
}
|
||||
let timer: ReturnType<typeof requestAnimationFrame> = 0;
|
||||
return new Proxy(
|
||||
{...obj},
|
||||
{
|
||||
get(target, prop: string) {
|
||||
if (prop === '__observed') {
|
||||
return true;
|
||||
}
|
||||
return Reflect.get(target, prop);
|
||||
},
|
||||
set(target, prop: string, value) {
|
||||
Reflect.set(target, prop, value);
|
||||
|
||||
cancelAnimationFrame(timer);
|
||||
timer = requestAnimationFrame(() => callback(target));
|
||||
console.warn("Don't modify the context directly.");
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
updateContextBySetter(context: any) {
|
||||
this.updateContext(context);
|
||||
self.data = cloneObject(self.data);
|
||||
},
|
||||
updateContext(context: any, isInit = false) {
|
||||
// 因为 context 不是受控属性,直接共用引用好了
|
||||
// 否则还会触发孩子节点的重新渲染
|
||||
|
||||
let {__page, appVariables, ...rest} = context || {};
|
||||
|
||||
// 对历史用法做兼容
|
||||
if (__page || appVariables) {
|
||||
// 有部分用户直接在自定义动作脚本里面修改 __page 或者 appVariables 变量
|
||||
// 奇怪的是之前的实现方式这种修改是会更新变更的
|
||||
// 所以这里用 Proxy 来解决不更新的问题
|
||||
__page = __page
|
||||
? observeSet(__page, __page =>
|
||||
(self as any).updateContextBySetter({...self.context, __page})
|
||||
)
|
||||
: __page;
|
||||
appVariables = appVariables
|
||||
? observeSet(appVariables, appVariables =>
|
||||
(self as any).updateContextBySetter({
|
||||
...self.context,
|
||||
appVariables
|
||||
})
|
||||
)
|
||||
: appVariables;
|
||||
|
||||
if (isInit) {
|
||||
self.context.__page = __page;
|
||||
self.context.appVariables = appVariables;
|
||||
}
|
||||
|
||||
self.legacyGlobalTempContext.__page = __page;
|
||||
self.legacyGlobalTempContext.appVariables = appVariables;
|
||||
}
|
||||
|
||||
Object.assign(self.context, rest);
|
||||
},
|
||||
updateGlobalVarState(key: string, state: Partial<GlobalVariableState>) {
|
||||
const origin = self.globalVarTempStates.get(key);
|
||||
const newState = {
|
||||
...(origin || createGlobalVarState()),
|
||||
...state
|
||||
};
|
||||
self.globalVarTempStates.set(key, newState as any);
|
||||
},
|
||||
setGlobalVars,
|
||||
updateGlobalVarValue,
|
||||
modifyGlobalVarValue,
|
||||
saveGlobalVarValues: lazySaveGlobalVarValues,
|
||||
setRuntimeError(error: any, errorStack: any) {
|
||||
self.runtimeError = error;
|
||||
self.runtimeErrorStack = errorStack;
|
||||
},
|
||||
updateLocation(location?: any, parseFn?: Function) {
|
||||
const query = parseFn ? parseFn(location) : parseQuery(location);
|
||||
if (isObjectShallowModified(query, self.query, false)) {
|
||||
self.query = query;
|
||||
}
|
||||
},
|
||||
init: init,
|
||||
syncGlobalVarStates,
|
||||
syncLegacyGlobalVarStates,
|
||||
addSyncGlobalVarStatePendingTask,
|
||||
afterCreate() {
|
||||
addDisposer(
|
||||
self,
|
||||
reaction(
|
||||
() => self.nextGlobalData,
|
||||
() =>
|
||||
(self as any).addSyncGlobalVarStatePendingTask((callback: any) =>
|
||||
requestAnimationFrame(callback)
|
||||
)
|
||||
)
|
||||
);
|
||||
},
|
||||
afterDestroy() {
|
||||
lazySaveGlobalVarValues.flush();
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
export type IRootStore = Instance<typeof RootStore>;
|
||||
572
packages/amis-core/src/store/service.ts
Normal file
572
packages/amis-core/src/store/service.ts
Normal file
@@ -0,0 +1,572 @@
|
||||
import {types, flow, getEnv, isAlive, Instance} from 'mobx-state-tree';
|
||||
import {iRendererStore} from './iRenderer';
|
||||
import {Api, ApiObject, Payload, fetchOptions} from '../types';
|
||||
import {extendObject, isEmpty, isObject} from '../utils/helper';
|
||||
import {ServerError} from '../utils/errors';
|
||||
import {normalizeApiResponseData} from '../utils/api';
|
||||
import {replaceText} from '../utils/replaceText';
|
||||
import {concatData} from '../utils/concatData';
|
||||
import {envOverwrite} from '../envOverwrite';
|
||||
import {filter} from '../utils';
|
||||
|
||||
export const ServiceStore = iRendererStore
|
||||
.named('ServiceStore')
|
||||
.props({
|
||||
msg: '',
|
||||
error: false,
|
||||
fetching: false,
|
||||
saving: false,
|
||||
busying: false,
|
||||
checking: false,
|
||||
initializing: false,
|
||||
schema: types.optional(types.frozen(), null),
|
||||
schemaKey: ''
|
||||
})
|
||||
.views(self => ({
|
||||
get loading() {
|
||||
return self.fetching || self.saving || self.busying || self.initializing;
|
||||
}
|
||||
}))
|
||||
.actions(self => {
|
||||
let fetchCancel: Function | null;
|
||||
let fetchSchemaCancel: Function | null;
|
||||
|
||||
function markFetching(fetching = true) {
|
||||
self.fetching = fetching;
|
||||
}
|
||||
|
||||
function markSaving(saving = true) {
|
||||
self.saving = saving;
|
||||
}
|
||||
|
||||
function markBusying(busying = true) {
|
||||
self.busying = busying;
|
||||
}
|
||||
|
||||
function reInitData(
|
||||
data: object | undefined,
|
||||
replace: boolean = false,
|
||||
concatFields?: string | string[]
|
||||
) {
|
||||
if (concatFields) {
|
||||
data = concatData(data, self.data, concatFields);
|
||||
}
|
||||
const newData = extendObject(self.data, data, !replace);
|
||||
self.data = self.pristine = newData;
|
||||
}
|
||||
|
||||
function updateMessage(msg?: string, error: boolean = false) {
|
||||
self.msg = (msg && filter(msg, self.data)) || '';
|
||||
self.error = error;
|
||||
}
|
||||
|
||||
function clearMessage() {
|
||||
updateMessage('');
|
||||
}
|
||||
|
||||
const fetchInitData: (
|
||||
api: Api,
|
||||
data?: object,
|
||||
options?: fetchOptions
|
||||
) => Promise<any> = flow(function* getInitData(
|
||||
api: Api,
|
||||
data: object,
|
||||
options?: fetchOptions
|
||||
) {
|
||||
try {
|
||||
if (fetchCancel) {
|
||||
fetchCancel();
|
||||
fetchCancel = null;
|
||||
self.fetching = false;
|
||||
}
|
||||
|
||||
if (self.fetching) {
|
||||
return;
|
||||
}
|
||||
|
||||
(options && options.silent) || markFetching(true);
|
||||
const json: Payload = yield getEnv(self).fetcher(api, data, {
|
||||
...options,
|
||||
cancelExecutor: (executor: Function) => (fetchCancel = executor)
|
||||
});
|
||||
fetchCancel = null;
|
||||
|
||||
if (!json.ok) {
|
||||
updateMessage(
|
||||
(api as ApiObject)?.messages?.failed ??
|
||||
json.msg ??
|
||||
(options && options.errorMessage),
|
||||
true
|
||||
);
|
||||
!(api as ApiObject).silent &&
|
||||
getEnv(self).notify(
|
||||
'error',
|
||||
self.msg,
|
||||
json.msgTimeout !== undefined
|
||||
? {
|
||||
closeButton: true,
|
||||
timeout: json.msgTimeout
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
} else {
|
||||
self.updatedAt = Date.now();
|
||||
let replace = !!(api as ApiObject).replaceData;
|
||||
let data = {
|
||||
...(replace ? {} : self.data),
|
||||
...normalizeApiResponseData(json.data)
|
||||
};
|
||||
reInitData(data, replace, (api as ApiObject).concatDataFields);
|
||||
self.hasRemoteData = true;
|
||||
if (options && options.onSuccess) {
|
||||
const ret = options.onSuccess(json, data);
|
||||
|
||||
if (ret && ret.then) {
|
||||
yield ret;
|
||||
}
|
||||
}
|
||||
|
||||
updateMessage(
|
||||
(api as ApiObject)?.messages?.success ??
|
||||
json.msg ??
|
||||
(options && options.successMessage) ??
|
||||
json.defaultMsg
|
||||
);
|
||||
|
||||
// 配置了获取成功提示后提示,默认是空不会提示。
|
||||
options &&
|
||||
options.successMessage &&
|
||||
getEnv(self).notify('success', self.msg);
|
||||
}
|
||||
|
||||
markFetching(false);
|
||||
return json;
|
||||
} catch (e) {
|
||||
const env = getEnv(self);
|
||||
|
||||
if (!isAlive(self) || self.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (env.isCancel(e)) {
|
||||
return;
|
||||
}
|
||||
|
||||
markFetching(false);
|
||||
console.error(e);
|
||||
let message = e.message || e;
|
||||
if (e && e.message === 'Network Error') {
|
||||
message = self.__('networkError');
|
||||
}
|
||||
!(api as ApiObject).silent && env.notify('error', message);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const setHasRemoteData = () => {
|
||||
self.hasRemoteData = true;
|
||||
};
|
||||
|
||||
const fetchData: (
|
||||
api: Api,
|
||||
data?: object,
|
||||
options?: fetchOptions
|
||||
) => Promise<any> = flow(function* getInitData(
|
||||
api: Api,
|
||||
data: object,
|
||||
options?: fetchOptions
|
||||
) {
|
||||
try {
|
||||
if (fetchCancel) {
|
||||
fetchCancel();
|
||||
fetchCancel = null;
|
||||
self.fetching = false;
|
||||
}
|
||||
|
||||
if (self.fetching) {
|
||||
return;
|
||||
}
|
||||
|
||||
(options && options.silent) || markFetching(true);
|
||||
const json: Payload = yield getEnv(self).fetcher(api, data, {
|
||||
...options,
|
||||
cancelExecutor: (executor: Function) => (fetchCancel = executor)
|
||||
});
|
||||
fetchCancel = null;
|
||||
|
||||
if (!isEmpty(json.data) || json.ok) {
|
||||
self.updatedAt = Date.now();
|
||||
|
||||
json.data &&
|
||||
self.updateData(
|
||||
normalizeApiResponseData(json.data),
|
||||
undefined,
|
||||
!!(api as ApiObject).replaceData,
|
||||
(api as ApiObject).concatDataFields,
|
||||
{
|
||||
type: 'api'
|
||||
}
|
||||
);
|
||||
|
||||
self.hasRemoteData = true;
|
||||
}
|
||||
|
||||
if (!json.ok) {
|
||||
updateMessage(
|
||||
(api as ApiObject)?.messages?.failed ??
|
||||
json.msg ??
|
||||
(options && options.errorMessage),
|
||||
true
|
||||
);
|
||||
!(api as ApiObject).silent &&
|
||||
getEnv(self).notify(
|
||||
'error',
|
||||
self.msg,
|
||||
json.msgTimeout !== undefined
|
||||
? {
|
||||
closeButton: true,
|
||||
timeout: json.msgTimeout
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
} else {
|
||||
if (options && options.onSuccess) {
|
||||
const ret = options.onSuccess(json, json.data);
|
||||
|
||||
if (ret && ret.then) {
|
||||
yield ret;
|
||||
}
|
||||
}
|
||||
|
||||
updateMessage(
|
||||
(api as ApiObject)?.messages?.success ??
|
||||
json.msg ??
|
||||
(options && options.successMessage)
|
||||
);
|
||||
|
||||
// 配置了获取成功提示后提示,默认是空不会提示。
|
||||
options &&
|
||||
options.successMessage &&
|
||||
getEnv(self).notify('success', self.msg);
|
||||
}
|
||||
|
||||
markFetching(false);
|
||||
return json;
|
||||
} catch (e) {
|
||||
const env = getEnv(self);
|
||||
|
||||
if (!isAlive(self) || self.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (env.isCancel(e)) {
|
||||
return;
|
||||
}
|
||||
|
||||
markFetching(false);
|
||||
console.error(e);
|
||||
let message = e.message || e;
|
||||
if (e && e.message === 'Network Error') {
|
||||
message = self.__('networkError');
|
||||
}
|
||||
!(api as ApiObject).silent && env.notify('error', message);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const saveRemote: (
|
||||
api: Api,
|
||||
data?: object,
|
||||
options?: fetchOptions
|
||||
) => Promise<any> = flow(function* saveRemote(
|
||||
api: Api,
|
||||
data: object,
|
||||
options: fetchOptions = {}
|
||||
) {
|
||||
try {
|
||||
options = {
|
||||
method: 'post', // 默认走 post
|
||||
...options
|
||||
};
|
||||
|
||||
if (self.saving) {
|
||||
return;
|
||||
}
|
||||
markSaving(true);
|
||||
|
||||
const json: Payload = yield getEnv(self).fetcher(api, data, options);
|
||||
|
||||
if (!isEmpty(json.data) || json.ok) {
|
||||
self.updatedAt = Date.now();
|
||||
|
||||
json.data &&
|
||||
self.updateData(
|
||||
normalizeApiResponseData(json.data),
|
||||
undefined,
|
||||
!!(api as ApiObject).replaceData,
|
||||
(api as ApiObject).concatDataFields,
|
||||
{
|
||||
type: 'api'
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
if (!json.ok) {
|
||||
if (options && options.onFailed) {
|
||||
const ret = options.onFailed(json);
|
||||
|
||||
if (ret && ret.then) {
|
||||
yield ret;
|
||||
}
|
||||
}
|
||||
|
||||
updateMessage(
|
||||
(api as ApiObject)?.messages?.failed ??
|
||||
json.msg ??
|
||||
(options && options.errorMessage) ??
|
||||
self.__('saveFailed'),
|
||||
true
|
||||
);
|
||||
throw new ServerError(self.msg, json);
|
||||
} else {
|
||||
if (options && options.onSuccess) {
|
||||
const ret = options.onSuccess(json, json.data);
|
||||
|
||||
if (ret && ret.then) {
|
||||
yield ret;
|
||||
}
|
||||
}
|
||||
|
||||
updateMessage(
|
||||
(api as ApiObject)?.messages?.success ??
|
||||
json.msg ??
|
||||
(options && options.successMessage)
|
||||
);
|
||||
self.msg &&
|
||||
getEnv(self).notify(
|
||||
'success',
|
||||
self.msg,
|
||||
json.msgTimeout !== undefined
|
||||
? {
|
||||
closeButton: true,
|
||||
timeout: json.msgTimeout
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
}
|
||||
|
||||
markSaving(false);
|
||||
return json.data;
|
||||
} catch (e) {
|
||||
self.saving = false;
|
||||
|
||||
if (!isAlive(self) || self.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.error(e);
|
||||
|
||||
if (!(api as ApiObject).silent) {
|
||||
if (e.type === 'ServerError') {
|
||||
const result = (e as ServerError).response;
|
||||
getEnv(self).notify(
|
||||
'error',
|
||||
e.message,
|
||||
result.msgTimeout !== undefined
|
||||
? {
|
||||
closeButton: true,
|
||||
timeout: result.msgTimeout
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
} else {
|
||||
getEnv(self).notify('error', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
||||
const fetchSchema: (
|
||||
api: Api,
|
||||
data?: object,
|
||||
options?: fetchOptions
|
||||
) => Promise<any> = flow(function* fetchSchema(
|
||||
api: Api,
|
||||
data: object,
|
||||
options: fetchOptions = {}
|
||||
) {
|
||||
try {
|
||||
options = {
|
||||
method: 'post', // 默认走 post
|
||||
...options,
|
||||
cancelExecutor: (executor: Function) => (fetchSchemaCancel = executor)
|
||||
};
|
||||
|
||||
if (fetchSchemaCancel) {
|
||||
fetchSchemaCancel();
|
||||
fetchSchemaCancel = null;
|
||||
self.initializing = false;
|
||||
}
|
||||
|
||||
if (self.initializing) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.initializing = true;
|
||||
|
||||
if (typeof api === 'string') {
|
||||
api += (~api.indexOf('?') ? '&' : '?') + '_replace=1';
|
||||
} else {
|
||||
api = {
|
||||
...(api as any),
|
||||
url:
|
||||
(api as ApiObject).url +
|
||||
(~(api as ApiObject).url.indexOf('?') ? '&' : '?') +
|
||||
'_replace=1'
|
||||
};
|
||||
}
|
||||
|
||||
const json: Payload = yield getEnv(self).fetcher(api, data, options);
|
||||
fetchSchemaCancel = null;
|
||||
|
||||
if (!json.ok) {
|
||||
updateMessage(
|
||||
(api as ApiObject)?.messages?.failed ??
|
||||
json.msg ??
|
||||
(options && options.errorMessage) ??
|
||||
self.__('fetchFailed'),
|
||||
true
|
||||
);
|
||||
!(api as ApiObject)?.silent &&
|
||||
getEnv(self).notify(
|
||||
'error',
|
||||
self.msg,
|
||||
json.msgTimeout !== undefined
|
||||
? {
|
||||
closeButton: true,
|
||||
timeout: json.msgTimeout
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
} else {
|
||||
if (json.data) {
|
||||
const env = getEnv(self);
|
||||
json.data = envOverwrite(json.data, env.locale);
|
||||
json.data = replaceText(
|
||||
json.data,
|
||||
env.replaceText,
|
||||
env.replaceTextIgnoreKeys
|
||||
);
|
||||
|
||||
self.schema = Array.isArray(json.data)
|
||||
? json.data
|
||||
: Object.assign(
|
||||
json.data?.type
|
||||
? {}
|
||||
: {
|
||||
type: 'wrapper',
|
||||
wrap: false
|
||||
},
|
||||
normalizeApiResponseData(json.data)
|
||||
);
|
||||
self.schemaKey = '' + Date.now();
|
||||
isObject(json.data.data) &&
|
||||
self.updateData(
|
||||
json.data.data,
|
||||
undefined,
|
||||
!!(api as ApiObject).replaceData,
|
||||
(api as ApiObject).concatDataFields,
|
||||
{
|
||||
type: 'api'
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
updateMessage(
|
||||
(api as ApiObject)?.messages?.success ??
|
||||
json.msg ??
|
||||
(options && options.successMessage)
|
||||
);
|
||||
|
||||
// 配置了获取成功提示后提示,默认是空不会提示。
|
||||
options &&
|
||||
options.successMessage &&
|
||||
getEnv(self).notify('success', self.msg);
|
||||
}
|
||||
|
||||
self.initializing = false;
|
||||
return json.data;
|
||||
} catch (e) {
|
||||
const env = getEnv(self);
|
||||
|
||||
self.initializing = false;
|
||||
if (!isAlive(self) || self.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (env.isCancel(e)) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.error(e);
|
||||
let message = e.message || e;
|
||||
if (e && e.message === 'Network Error') {
|
||||
message = self.__('networkError');
|
||||
}
|
||||
!(api as ApiObject)?.silent && env.notify('error', message);
|
||||
}
|
||||
});
|
||||
|
||||
const checkRemote: (
|
||||
api: Api,
|
||||
data?: object,
|
||||
options?: fetchOptions
|
||||
) => Promise<any> = flow(function* checkRemote(
|
||||
api: Api,
|
||||
data: object,
|
||||
options?: fetchOptions
|
||||
) {
|
||||
if (self.checking) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
self.checking = true;
|
||||
const json: Payload = yield getEnv(self).fetcher(api, data, options);
|
||||
json.ok &&
|
||||
self.updateData(
|
||||
json.data,
|
||||
undefined,
|
||||
!!(api as ApiObject).replaceData,
|
||||
(api as ApiObject).concatDataFields
|
||||
);
|
||||
|
||||
if (!json.ok) {
|
||||
throw new Error(json.msg);
|
||||
}
|
||||
|
||||
return json.data;
|
||||
} finally {
|
||||
self.checking = false;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
markFetching,
|
||||
markSaving,
|
||||
markBusying,
|
||||
fetchInitData,
|
||||
fetchData,
|
||||
reInitData,
|
||||
updateMessage,
|
||||
clearMessage,
|
||||
setHasRemoteData,
|
||||
saveRemote,
|
||||
fetchSchema,
|
||||
checkRemote
|
||||
};
|
||||
});
|
||||
|
||||
export type IServiceStore = Instance<typeof ServiceStore>;
|
||||
41
packages/amis-core/src/store/status.ts
Normal file
41
packages/amis-core/src/store/status.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import {Instance, types} from 'mobx-state-tree';
|
||||
import {StoreNode} from './node';
|
||||
|
||||
export const StatusStore = types
|
||||
.model('StatusStore', {
|
||||
visibleState: types.optional(types.frozen(), {}),
|
||||
disableState: types.optional(types.frozen(), {}),
|
||||
staticState: types.optional(types.frozen(), {})
|
||||
})
|
||||
|
||||
.actions(self => ({
|
||||
setVisible(key: string, value?: boolean) {
|
||||
const state = {
|
||||
...self.visibleState,
|
||||
[key]: value
|
||||
};
|
||||
self.visibleState = state;
|
||||
},
|
||||
setDisable(key: string, value?: boolean) {
|
||||
const state = {
|
||||
...self.disableState,
|
||||
[key]: value
|
||||
};
|
||||
self.disableState = state;
|
||||
},
|
||||
setStatic(key: string, value?: boolean) {
|
||||
const state = {
|
||||
...self.staticState,
|
||||
[key]: value
|
||||
};
|
||||
self.staticState = state;
|
||||
},
|
||||
|
||||
resetAll() {
|
||||
self.visibleState = {};
|
||||
self.disableState = {};
|
||||
self.staticState = {};
|
||||
}
|
||||
}));
|
||||
|
||||
export type IStatusStore = Instance<typeof StatusStore>;
|
||||
2178
packages/amis-core/src/store/table.ts
Normal file
2178
packages/amis-core/src/store/table.ts
Normal file
File diff suppressed because it is too large
Load Diff
864
packages/amis-core/src/store/table2.ts
Normal file
864
packages/amis-core/src/store/table2.ts
Normal file
@@ -0,0 +1,864 @@
|
||||
import {
|
||||
types,
|
||||
getParent,
|
||||
Instance,
|
||||
SnapshotIn,
|
||||
isAlive,
|
||||
IAnyModelType,
|
||||
flow,
|
||||
getEnv
|
||||
} from 'mobx-state-tree';
|
||||
import find from 'lodash/find';
|
||||
import isEqual from 'lodash/isEqual';
|
||||
|
||||
import {
|
||||
isVisible,
|
||||
hasVisibleExpression,
|
||||
isObjectShallowModified,
|
||||
qsstringify,
|
||||
guid,
|
||||
eachTree,
|
||||
createObject,
|
||||
flattenTree,
|
||||
isObject,
|
||||
immutableExtends,
|
||||
isEmpty,
|
||||
extendObject,
|
||||
findTree,
|
||||
difference
|
||||
} from '../utils/helper';
|
||||
import {normalizeApiResponseData} from '../utils/api';
|
||||
import {Api, Payload, fetchOptions, ApiObject} from '../types';
|
||||
import {ServiceStore} from './service';
|
||||
import {IFormStore} from './form';
|
||||
import {getPageId} from '../utils/getPageId';
|
||||
import {filter} from '../utils/tpl';
|
||||
|
||||
class ServerError extends Error {
|
||||
type = 'ServerError';
|
||||
|
||||
constructor(msg: string) {
|
||||
super(msg);
|
||||
Object.setPrototypeOf(this, ServerError.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
export const Column = types
|
||||
.model('Column', {
|
||||
title: types.optional(types.frozen(), undefined),
|
||||
label: types.optional(types.frozen(), undefined),
|
||||
name: '',
|
||||
toggled: false,
|
||||
breakpoint: types.optional(types.frozen(), undefined),
|
||||
pristine: types.optional(types.frozen(), undefined),
|
||||
toggable: true,
|
||||
index: 0,
|
||||
type: '',
|
||||
children: types.optional(
|
||||
types.array(types.late((): IAnyModelType => Column)),
|
||||
[]
|
||||
)
|
||||
})
|
||||
.actions(self => ({
|
||||
toggleToggle() {
|
||||
self.toggled = !self.toggled;
|
||||
const table = getParent(self, 2) as ITableStore2;
|
||||
|
||||
if (!table.activeToggaleColumns.length) {
|
||||
self.toggled = true;
|
||||
}
|
||||
|
||||
table.persistSaveToggledColumns();
|
||||
},
|
||||
setToggled(value: boolean) {
|
||||
self.toggled = value;
|
||||
}
|
||||
}));
|
||||
|
||||
export type IColumn2 = Instance<typeof Column>;
|
||||
export type SColumn2 = SnapshotIn<typeof Column>;
|
||||
|
||||
export const Row = types
|
||||
.model('Row', {
|
||||
storeType: 'Row',
|
||||
id: types.identifier,
|
||||
parentId: '',
|
||||
name: types.string,
|
||||
pristine: types.frozen({} as any), // 原始数据
|
||||
data: types.frozen({} as any),
|
||||
index: types.number,
|
||||
newIndex: types.number,
|
||||
depth: types.number, // 当前children位于第几层,便于使用getParent获取最顶层TableStore
|
||||
children: types.optional(
|
||||
types.array(types.late((): IAnyModelType => Row)),
|
||||
[]
|
||||
),
|
||||
path: '' // 行数据的位置
|
||||
})
|
||||
.views(self => ({
|
||||
get checked(): boolean {
|
||||
return (getParent(self, self.depth * 2) as ITableStore2).isSelected(
|
||||
self as IRow2
|
||||
);
|
||||
},
|
||||
|
||||
get modified() {
|
||||
if (!self.data) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Object.keys(self.data).some(
|
||||
key => !isEqual(self.data[key], self.pristine[key])
|
||||
);
|
||||
},
|
||||
|
||||
get moved() {
|
||||
return self.index !== self.newIndex;
|
||||
},
|
||||
|
||||
get locals(): any {
|
||||
let children: Array<any> | null = null;
|
||||
if (self.children.length) {
|
||||
children = self.children.map(item => item.locals);
|
||||
}
|
||||
|
||||
const parent = getParent(self, 2) as ITableStore2;
|
||||
return createObject(
|
||||
extendObject((getParent(self, self.depth * 2) as ITableStore2).data, {
|
||||
index: self.index,
|
||||
// todo 以后再支持多层,目前先一层
|
||||
parent: parent.storeType === Row.name ? parent.data : undefined
|
||||
}),
|
||||
children
|
||||
? {
|
||||
...self.data,
|
||||
children
|
||||
}
|
||||
: self.data
|
||||
);
|
||||
},
|
||||
|
||||
getDataWithModifiedChilden() {
|
||||
let data = {
|
||||
...self.data
|
||||
};
|
||||
|
||||
if (data.children && self.children) {
|
||||
data.children = self.children.map(item =>
|
||||
item.getDataWithModifiedChilden()
|
||||
);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
}))
|
||||
.actions(self => ({
|
||||
replaceWith(data: any) {
|
||||
Object.keys(data).forEach(key => {
|
||||
if (key !== 'id') {
|
||||
(self as any)[key] = data[key];
|
||||
}
|
||||
});
|
||||
|
||||
if (Array.isArray(data.children)) {
|
||||
const arr = data.children;
|
||||
const pool = arr.concat();
|
||||
|
||||
// 把多的删了先
|
||||
if (self.children.length > arr.length) {
|
||||
self.children.splice(arr.length, self.children.length - arr.length);
|
||||
}
|
||||
|
||||
let index = 0;
|
||||
const len = self.children.length;
|
||||
while (pool.length) {
|
||||
// 因为父级id未更新,所以需要将子级的parentId正确指向父级id
|
||||
const item = {
|
||||
...pool.shift(),
|
||||
parentId: self.id
|
||||
}!;
|
||||
|
||||
if (index < len) {
|
||||
self.children[index].replaceWith(item);
|
||||
} else {
|
||||
const row = Row.create(item);
|
||||
self.children.push(row);
|
||||
}
|
||||
index++;
|
||||
}
|
||||
}
|
||||
},
|
||||
change(values: object, savePristine?: boolean) {
|
||||
self.data = immutableExtends(self.data, values);
|
||||
savePristine && (self.pristine = self.data);
|
||||
},
|
||||
reset() {
|
||||
self.newIndex = self.index;
|
||||
self.data = self.pristine;
|
||||
}
|
||||
}));
|
||||
|
||||
export type IRow2 = Instance<typeof Row>;
|
||||
export type SRow2 = SnapshotIn<typeof Row>;
|
||||
|
||||
export const TableStore2 = ServiceStore.named('TableStore2')
|
||||
.props({
|
||||
columns: types.array(Column),
|
||||
rows: types.array(Row),
|
||||
selectedRowKeys: types.array(types.frozen()),
|
||||
selectedRows: types.array(types.reference(Row)),
|
||||
expandedRowKeys: types.array(types.frozen()),
|
||||
columnsTogglable: types.optional(
|
||||
types.union(types.boolean, types.literal('auto'), types.frozen()),
|
||||
'auto'
|
||||
),
|
||||
orderBy: '',
|
||||
order: types.optional(
|
||||
types.union(types.literal('asc'), types.literal('desc')),
|
||||
'asc'
|
||||
),
|
||||
query: types.optional(types.frozen(), {}),
|
||||
pageNo: 1,
|
||||
pageSize: 10,
|
||||
dragging: false,
|
||||
rowSelectionKeyField: 'id',
|
||||
formsRef: types.optional(types.array(types.frozen()), []),
|
||||
canAccessSuperData: false,
|
||||
persistKey: ''
|
||||
})
|
||||
.views(self => {
|
||||
function getToggable() {
|
||||
if (self.columnsTogglable === 'auto') {
|
||||
return self.columns.filter(item => !/^__/.test(item.type)).length > 5;
|
||||
}
|
||||
|
||||
return !!self.columnsTogglable;
|
||||
}
|
||||
|
||||
function hasColumnHidden() {
|
||||
return self.columns.findIndex(column => !column.toggled) !== -1;
|
||||
}
|
||||
|
||||
function getToggableColumns() {
|
||||
return self.columns.filter(
|
||||
item => isVisible(item.pristine, self.data) && item.toggable !== false
|
||||
);
|
||||
}
|
||||
|
||||
function getActiveToggableColumns() {
|
||||
return getToggableColumns().filter(item => item.toggled);
|
||||
}
|
||||
|
||||
function getAllFilteredColumns(columns?: Array<SColumn2>): Array<any> {
|
||||
if (columns) {
|
||||
return columns
|
||||
.filter(
|
||||
item =>
|
||||
item &&
|
||||
isVisible(
|
||||
item.pristine,
|
||||
hasVisibleExpression(item.pristine) ? self.data : {}
|
||||
) &&
|
||||
(item.toggled || !item.toggable)
|
||||
)
|
||||
.map(item => ({
|
||||
...item.pristine,
|
||||
type: item.type,
|
||||
children: item.children
|
||||
? getAllFilteredColumns(item.children)
|
||||
: undefined
|
||||
}));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function getFilteredColumns() {
|
||||
return getAllFilteredColumns(self.columns);
|
||||
}
|
||||
|
||||
function getUnSelectedRows() {
|
||||
return flattenTree<IRow2>(self.rows).filter(
|
||||
(item: IRow2) => !item.checked
|
||||
);
|
||||
}
|
||||
|
||||
function getData(superData: any): any {
|
||||
return createObject(superData, {
|
||||
items: self.rows.map(item => item.data),
|
||||
selectedItems: self.selectedRows.map(item => item.data),
|
||||
unSelectedItems: getUnSelectedRows().map(item => item.data)
|
||||
});
|
||||
}
|
||||
|
||||
function getRowByIndex(
|
||||
rowIndex: number,
|
||||
levels?: Array<number>,
|
||||
rows?: Array<IRow2>
|
||||
): IRow2 {
|
||||
rows = rows || self.rows;
|
||||
if (levels && levels.length > 0) {
|
||||
const index = +(levels.shift() || 0);
|
||||
return getRowByIndex(rowIndex, levels, rows[index].children);
|
||||
}
|
||||
return rows[rowIndex];
|
||||
}
|
||||
|
||||
function isSelected(row: IRow2): boolean {
|
||||
return !!~self.selectedRows.indexOf(row);
|
||||
}
|
||||
|
||||
function getMovedRows() {
|
||||
return flattenTree(self.rows).filter((item: IRow2) => item.moved);
|
||||
}
|
||||
|
||||
function getMoved() {
|
||||
return getMovedRows().length;
|
||||
}
|
||||
|
||||
function getModifiedRows(rows: IRow2[] = [], modifiedRows: IRow2[] = []) {
|
||||
rows = rows && rows.length ? rows : self.rows;
|
||||
rows.forEach((item: IRow2) => {
|
||||
if (item.children && item.children.length) {
|
||||
getModifiedRows(item.children, modifiedRows);
|
||||
}
|
||||
let diff = difference(item.data, item.pristine);
|
||||
let hasDifference = Object.keys(diff).length;
|
||||
if (hasDifference) {
|
||||
modifiedRows.push(item);
|
||||
}
|
||||
});
|
||||
return modifiedRows;
|
||||
}
|
||||
|
||||
function getModified() {
|
||||
return getModifiedRows().length;
|
||||
}
|
||||
|
||||
return {
|
||||
get toggable() {
|
||||
return getToggable();
|
||||
},
|
||||
|
||||
get columnsData() {
|
||||
return self.columns;
|
||||
},
|
||||
|
||||
get toggableColumns() {
|
||||
return getToggableColumns();
|
||||
},
|
||||
|
||||
get filteredColumns() {
|
||||
return getFilteredColumns();
|
||||
},
|
||||
|
||||
get activeToggaleColumns() {
|
||||
return getActiveToggableColumns();
|
||||
},
|
||||
|
||||
get dataSource() {
|
||||
return self.rows.map(item =>
|
||||
self.canAccessSuperData ? item.locals : item.data
|
||||
);
|
||||
},
|
||||
|
||||
get currentSelectedRowKeys() {
|
||||
if (self.data && self.data.selectedItems) {
|
||||
return (
|
||||
self.data.selectedItems.map(
|
||||
(item: any) => item[self.rowSelectionKeyField]
|
||||
) || []
|
||||
);
|
||||
}
|
||||
return self.selectedRowKeys.map(item => item);
|
||||
},
|
||||
|
||||
get currentExpandedKeys() {
|
||||
return self.expandedRowKeys.map(item => item);
|
||||
},
|
||||
|
||||
get unSelectedRows() {
|
||||
return getUnSelectedRows();
|
||||
},
|
||||
|
||||
// 是否隐藏了某列
|
||||
hasColumnHidden() {
|
||||
return hasColumnHidden();
|
||||
},
|
||||
|
||||
getData,
|
||||
|
||||
getRowById(id: string) {
|
||||
return findTree(self.rows, item => item.id === id);
|
||||
},
|
||||
|
||||
isSelected,
|
||||
|
||||
getRowByIndex,
|
||||
|
||||
get moved() {
|
||||
return getMoved();
|
||||
},
|
||||
|
||||
get movedRows() {
|
||||
return getMovedRows();
|
||||
},
|
||||
|
||||
get keyField() {
|
||||
return self.rowSelectionKeyField;
|
||||
},
|
||||
|
||||
get modified() {
|
||||
return getModified();
|
||||
},
|
||||
|
||||
get modifiedRows() {
|
||||
return getModifiedRows();
|
||||
}
|
||||
};
|
||||
})
|
||||
.actions(self => {
|
||||
function updateColumns(
|
||||
columns: Array<SColumn2>,
|
||||
options?: {
|
||||
resolveDefinitions?: (ref: string) => any;
|
||||
}
|
||||
) {
|
||||
if (columns && Array.isArray(columns)) {
|
||||
let cols: Array<SColumn2> = columns.filter(column => column).concat();
|
||||
|
||||
cols = cols.map((item, index) => {
|
||||
if (
|
||||
options?.resolveDefinitions &&
|
||||
typeof (item as any)?.$ref == 'string' &&
|
||||
(item as any).$ref
|
||||
) {
|
||||
item = {
|
||||
...options.resolveDefinitions((item as any).$ref),
|
||||
...item
|
||||
};
|
||||
}
|
||||
return {
|
||||
...item,
|
||||
index,
|
||||
type: item.type || 'plain',
|
||||
pristine: item,
|
||||
toggled: item.toggled !== false,
|
||||
breakpoint: item.breakpoint,
|
||||
children: item.children ? updateColumns(item.children, options) : []
|
||||
};
|
||||
});
|
||||
|
||||
return cols;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
function update(
|
||||
config: Partial<STableStore2>,
|
||||
options?: {
|
||||
resolveDefinitions?: (ref: string) => any;
|
||||
}
|
||||
) {
|
||||
config.columnsTogglable !== void 0 &&
|
||||
(self.columnsTogglable = config.columnsTogglable);
|
||||
config.canAccessSuperData !== undefined &&
|
||||
(self.canAccessSuperData = !!config.canAccessSuperData);
|
||||
config.persistKey !== undefined && (self.persistKey = config.persistKey);
|
||||
|
||||
if (typeof config.orderBy === 'string') {
|
||||
setOrderByInfo(
|
||||
config.orderBy,
|
||||
config.order === 'desc' ? 'desc' : 'asc'
|
||||
);
|
||||
}
|
||||
|
||||
if (config.rowSelectionKeyField) {
|
||||
self.rowSelectionKeyField = config.rowSelectionKeyField;
|
||||
}
|
||||
|
||||
if (config.columns && Array.isArray(config.columns)) {
|
||||
self.columns.replace(updateColumns(config.columns, options) as any);
|
||||
}
|
||||
}
|
||||
|
||||
function exchange(fromIndex: number, toIndex: number, item?: IRow2) {
|
||||
item = item || self.rows[fromIndex];
|
||||
|
||||
if (item?.parentId) {
|
||||
const parent: IRow2 = self.getRowById(item.parentId) as any;
|
||||
const newRows = parent.children.concat();
|
||||
newRows.splice(fromIndex, 1);
|
||||
newRows.splice(toIndex, 0, item);
|
||||
newRows.forEach((item, index) => (item.newIndex = index));
|
||||
parent.children.replace(newRows);
|
||||
return;
|
||||
}
|
||||
|
||||
const newRows = self.rows.concat();
|
||||
newRows.splice(fromIndex, 1);
|
||||
newRows.splice(toIndex, 0, item);
|
||||
newRows.forEach((item, index) => (item.newIndex = index));
|
||||
self.rows.replace(newRows);
|
||||
}
|
||||
|
||||
function toggleAllColumns() {
|
||||
if (self.activeToggaleColumns.length) {
|
||||
if (self.activeToggaleColumns.length === self.toggableColumns.length) {
|
||||
self.toggableColumns.map(column => column.setToggled(false));
|
||||
} else {
|
||||
self.toggableColumns.map(column => column.setToggled(true));
|
||||
}
|
||||
} else {
|
||||
// 如果没有一个激活的,那就改成全选
|
||||
self.toggableColumns.map(column => column.setToggled(true));
|
||||
}
|
||||
persistSaveToggledColumns();
|
||||
}
|
||||
|
||||
function getPersistKey() {
|
||||
if (self.persistKey) {
|
||||
return filter(self.persistKey, self.data);
|
||||
}
|
||||
|
||||
const fn = getEnv(self).getPageId || getPageId;
|
||||
return fn() + self.path;
|
||||
}
|
||||
|
||||
function persistSaveToggledColumns() {
|
||||
const key =
|
||||
getPersistKey() +
|
||||
self.toggableColumns.map(item => item.name || item.index).join('-');
|
||||
|
||||
localStorage.setItem(
|
||||
key,
|
||||
JSON.stringify(self.activeToggaleColumns.map(item => item.index))
|
||||
);
|
||||
}
|
||||
|
||||
function setOrderByInfo(key: string, direction: 'asc' | 'desc') {
|
||||
self.orderBy = key;
|
||||
self.order = direction;
|
||||
}
|
||||
|
||||
function updateQuery(
|
||||
values: object,
|
||||
updater?: Function,
|
||||
pageNoField: string = 'pageNo',
|
||||
pageSizeField: string = 'pageSize',
|
||||
replace: boolean = false
|
||||
) {
|
||||
const originQuery = self.query;
|
||||
self.query = replace
|
||||
? {
|
||||
...values
|
||||
}
|
||||
: {
|
||||
...self.query,
|
||||
...values
|
||||
};
|
||||
|
||||
if (self.query[pageNoField || 'pageNo']) {
|
||||
self.pageNo = parseInt(self.query[pageNoField || 'pageNo'], 10);
|
||||
}
|
||||
|
||||
if (self.query[pageSizeField || 'pageSize']) {
|
||||
self.pageSize = parseInt(self.query[pageSizeField || 'pageSize'], 10);
|
||||
}
|
||||
|
||||
updater &&
|
||||
isObjectShallowModified(originQuery, self.query, false) &&
|
||||
setTimeout(updater.bind(null, `?${qsstringify(self.query)}`), 4);
|
||||
}
|
||||
|
||||
function updateSelectedRows(rows: Array<any>, selectedKeys: Array<any>) {
|
||||
const rowSelectionKeyField = self.rowSelectionKeyField;
|
||||
eachTree(rows, item => {
|
||||
if (~selectedKeys.indexOf(item.pristine[rowSelectionKeyField])) {
|
||||
self.selectedRows.push(item.id);
|
||||
self.selectedRowKeys.push(item.pristine[rowSelectionKeyField]);
|
||||
} else if (
|
||||
find(selectedKeys, a => a && a == item.pristine[rowSelectionKeyField])
|
||||
) {
|
||||
self.selectedRows.push(item.id);
|
||||
self.selectedRowKeys.push(item.pristine[rowSelectionKeyField]);
|
||||
} else if (item.children) {
|
||||
updateSelectedRows(item.children, selectedKeys);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function updateSelected(selectedKeys: Array<any>) {
|
||||
self.selectedRows.clear();
|
||||
self.selectedRowKeys.clear();
|
||||
|
||||
updateSelectedRows(self.rows, selectedKeys);
|
||||
}
|
||||
|
||||
function updateSelectedAll() {
|
||||
const selectedKeys: Array<any> = [];
|
||||
eachTree(self.rows, item =>
|
||||
selectedKeys.push(item.pristine[self.rowSelectionKeyField])
|
||||
);
|
||||
updateSelectedRows(self.rows, selectedKeys);
|
||||
}
|
||||
|
||||
function updateExpanded(expandedRowKeys: Array<any>, keyField: string) {
|
||||
self.expandedRowKeys.clear();
|
||||
|
||||
eachTree(self.rows, item => {
|
||||
if (~expandedRowKeys.indexOf(item.pristine[keyField])) {
|
||||
self.expandedRowKeys.push(item.pristine[keyField]);
|
||||
} else if (
|
||||
find(expandedRowKeys, a => a && a == item.pristine[keyField])
|
||||
) {
|
||||
self.expandedRowKeys.push(item.pristine[keyField]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 尽可能的复用 row
|
||||
function replaceRow(arr: Array<SRow2>, reUseRow?: boolean) {
|
||||
if (reUseRow === false) {
|
||||
self.rows.replace(arr.map(item => Row.create(item)));
|
||||
return;
|
||||
}
|
||||
|
||||
const pool = arr.concat();
|
||||
|
||||
// 把多的删了先
|
||||
if (self.rows.length > arr.length) {
|
||||
self.rows.splice(arr.length, self.rows.length - arr.length);
|
||||
}
|
||||
|
||||
let index = 0;
|
||||
const len = self.rows.length;
|
||||
while (pool.length) {
|
||||
const item = pool.shift()!;
|
||||
|
||||
if (index < len) {
|
||||
self.rows[index].replaceWith(item);
|
||||
} else {
|
||||
const row = Row.create(item);
|
||||
self.rows.push(row);
|
||||
}
|
||||
index++;
|
||||
}
|
||||
}
|
||||
|
||||
function initChildren(
|
||||
children: Array<any>,
|
||||
depth: number,
|
||||
pindex: number,
|
||||
parentId: string,
|
||||
path: string = '',
|
||||
keyField?: string
|
||||
): any {
|
||||
const key = keyField || 'children';
|
||||
|
||||
depth += 1;
|
||||
return children.map((item, index) => {
|
||||
item = isObject(item)
|
||||
? item
|
||||
: {
|
||||
item
|
||||
};
|
||||
const id = guid();
|
||||
|
||||
return {
|
||||
id: id,
|
||||
parentId,
|
||||
name: String(`${pindex}-${depth}-${index}`),
|
||||
path: `${path}${index}`,
|
||||
depth: depth,
|
||||
index: index,
|
||||
newIndex: index,
|
||||
pristine: item,
|
||||
data: item,
|
||||
rowSpans: {},
|
||||
children:
|
||||
item && Array.isArray(item[key])
|
||||
? initChildren(item[key], depth, index, id, `${path}${index}.`)
|
||||
: []
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function initRows(
|
||||
rows: Array<any>,
|
||||
getEntryId?: (entry: any, index: number) => string,
|
||||
reUseRow?: boolean,
|
||||
keyField?: string
|
||||
) {
|
||||
self.selectedRows.clear();
|
||||
|
||||
const key = keyField || 'children';
|
||||
|
||||
let arr: Array<SRow2> = rows.map((item, index) => {
|
||||
let id = getEntryId ? getEntryId(item, index) : guid();
|
||||
|
||||
return {
|
||||
id: id,
|
||||
name: String(`${index}-1-${index}`),
|
||||
index: index,
|
||||
newIndex: index,
|
||||
pristine: item,
|
||||
path: `${index}`,
|
||||
data: item,
|
||||
depth: 1, // 最大父节点默认为第一层,逐层叠加
|
||||
children:
|
||||
item && Array.isArray(item[key])
|
||||
? initChildren(item[key], 1, index, id, `${index}.`, key)
|
||||
: []
|
||||
};
|
||||
});
|
||||
replaceRow(arr, reUseRow);
|
||||
}
|
||||
|
||||
const saveRemote: (
|
||||
api: Api,
|
||||
data?: object,
|
||||
options?: fetchOptions
|
||||
) => Promise<any> = flow(function* saveRemote(
|
||||
api: Api,
|
||||
data: object,
|
||||
options: fetchOptions = {}
|
||||
) {
|
||||
try {
|
||||
options = {
|
||||
method: 'post', // 默认走 post
|
||||
...options
|
||||
};
|
||||
|
||||
self.markSaving(true);
|
||||
const json: Payload = yield getEnv(self).fetcher(api, data, options);
|
||||
self.markSaving(false);
|
||||
|
||||
if (!isEmpty(json.data) || json.ok) {
|
||||
self.updateData(
|
||||
normalizeApiResponseData(json.data),
|
||||
{
|
||||
__saved: Date.now()
|
||||
},
|
||||
!!api && (api as ApiObject).replaceData,
|
||||
(api as ApiObject)?.concatDataFields
|
||||
);
|
||||
self.updatedAt = Date.now();
|
||||
}
|
||||
|
||||
if (!json.ok) {
|
||||
self.updateMessage(
|
||||
(api as ApiObject)?.messages?.failed ??
|
||||
json.msg ??
|
||||
options.errorMessage ??
|
||||
self.__('saveFailed'),
|
||||
true
|
||||
);
|
||||
!(api as ApiObject)?.silent &&
|
||||
getEnv(self).notify(
|
||||
'error',
|
||||
self.msg,
|
||||
json.msgTimeout !== undefined
|
||||
? {
|
||||
closeButton: true,
|
||||
timeout: json.msgTimeout
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
throw new ServerError(self.msg);
|
||||
} else {
|
||||
self.updateMessage(
|
||||
(api as ApiObject)?.messages?.success ??
|
||||
json.msg ??
|
||||
options.successMessage ??
|
||||
json.defaultMsg
|
||||
);
|
||||
self.msg &&
|
||||
getEnv(self).notify(
|
||||
'success',
|
||||
self.msg,
|
||||
json.msgTimeout !== undefined
|
||||
? {
|
||||
closeButton: true,
|
||||
timeout: json.msgTimeout
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
}
|
||||
return json.data;
|
||||
} catch (e) {
|
||||
self.markSaving(false);
|
||||
|
||||
if (!isAlive(self) || self.disposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
!(api as ApiObject)?.silent &&
|
||||
e.type !== 'ServerError' &&
|
||||
getEnv(self).notify('error', e.message);
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
||||
function reset() {
|
||||
self.rows.forEach(item => item.reset());
|
||||
let rows = self.rows.concat();
|
||||
eachTree(rows, item => {
|
||||
if (item.children) {
|
||||
let rows = item.children.concat().sort((a, b) => a.index - b.index);
|
||||
rows.forEach(item => item.reset());
|
||||
item.children.replace(rows);
|
||||
}
|
||||
});
|
||||
rows.forEach(item => item.reset());
|
||||
rows = rows.sort((a, b) => a.index - b.index);
|
||||
self.rows.replace(rows);
|
||||
self.dragging = false;
|
||||
}
|
||||
|
||||
function addForm(form: IFormStore, rowIndex: number) {
|
||||
self.formsRef.push({
|
||||
id: form.id,
|
||||
rowIndex
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
update,
|
||||
persistSaveToggledColumns,
|
||||
setOrderByInfo,
|
||||
updateQuery,
|
||||
initRows,
|
||||
updateSelected,
|
||||
updateSelectedAll,
|
||||
updateExpanded,
|
||||
exchange,
|
||||
reset,
|
||||
toggleAllColumns,
|
||||
|
||||
// events
|
||||
afterCreate() {
|
||||
setTimeout(() => {
|
||||
if (!isAlive(self)) {
|
||||
return;
|
||||
}
|
||||
const key =
|
||||
getPersistKey() +
|
||||
self.toggableColumns.map(item => item.name || item.index).join('-');
|
||||
|
||||
const data = localStorage.getItem(key);
|
||||
|
||||
if (data) {
|
||||
const selectedColumns = JSON.parse(data);
|
||||
self.toggableColumns.forEach(item =>
|
||||
item.setToggled(!!~selectedColumns.indexOf(item.index))
|
||||
);
|
||||
}
|
||||
}, 200);
|
||||
},
|
||||
saveRemote,
|
||||
addForm
|
||||
};
|
||||
});
|
||||
|
||||
export type ITableStore2 = Instance<typeof TableStore2>;
|
||||
export type STableStore2 = SnapshotIn<typeof TableStore2>;
|
||||
228
packages/amis-core/src/theme.tsx
Normal file
228
packages/amis-core/src/theme.tsx
Normal file
@@ -0,0 +1,228 @@
|
||||
// 主题管理
|
||||
import cx from 'classnames';
|
||||
import React from 'react';
|
||||
import hoistNonReactStatic from 'hoist-non-react-statics';
|
||||
|
||||
export type ClassValue =
|
||||
| ClassValue[]
|
||||
| Record<string, any>
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null
|
||||
| undefined;
|
||||
|
||||
export type ClassNamesFn = (...classes: ClassValue[]) => string;
|
||||
|
||||
interface ThemeConfig {
|
||||
classPrefix?: string;
|
||||
renderers?: {
|
||||
[propName: string]: any;
|
||||
};
|
||||
components?: {
|
||||
[propName: string]: any;
|
||||
};
|
||||
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
const themes: Record<string, ThemeConfig> = {
|
||||
default: {},
|
||||
cxd: {
|
||||
classPrefix: 'cxd-'
|
||||
}
|
||||
};
|
||||
|
||||
export function theme(name: string, config: Partial<ThemeConfig>) {
|
||||
themes[name] = {
|
||||
...themes[name],
|
||||
...config
|
||||
};
|
||||
}
|
||||
|
||||
const fns: Record<string, (...classes: ClassValue[]) => string> = {};
|
||||
|
||||
export function makeClassnames(ns?: string) {
|
||||
if (ns && fns[ns]) {
|
||||
return fns[ns];
|
||||
}
|
||||
|
||||
const fn = (...classes: ClassValue[]) => {
|
||||
const str = cx(...classes);
|
||||
return str && ns
|
||||
? str
|
||||
.replace(/(^|\s)([A-Z])/g, '$1' + ns + '$2')
|
||||
.replace(/(^|\s)\:/g, '$1')
|
||||
: str || '';
|
||||
};
|
||||
|
||||
ns && (fns[ns] = fn);
|
||||
return fn;
|
||||
}
|
||||
|
||||
export interface ThemeInstance extends ThemeConfig {
|
||||
getRendererConfig: (name?: string) => any;
|
||||
getComponentConfig: (name?: string) => any;
|
||||
classnames: ClassNamesFn;
|
||||
}
|
||||
|
||||
export function hasTheme(theme: string): boolean {
|
||||
return !!themes[theme];
|
||||
}
|
||||
|
||||
export function setDefaultTheme(theme: string) {
|
||||
if (hasTheme(theme)) {
|
||||
defaultTheme = theme;
|
||||
}
|
||||
}
|
||||
|
||||
export function classnames(...classes: ClassValue[]) {
|
||||
return getTheme(defaultTheme).classnames.apply(null, classes);
|
||||
}
|
||||
|
||||
export function getClassPrefix() {
|
||||
return getTheme(defaultTheme).classPrefix;
|
||||
}
|
||||
|
||||
export function getTheme(theme: string): ThemeInstance {
|
||||
if (typeof theme !== 'string') {
|
||||
theme = 'cxd';
|
||||
}
|
||||
|
||||
const config = themes[theme || 'cxd'];
|
||||
|
||||
if (!config.getRendererConfig) {
|
||||
config.getRendererConfig = (name?: string) => {
|
||||
const config = themes[theme || 'cxd'];
|
||||
return config.renderers && name ? config.renderers[name] : null;
|
||||
};
|
||||
}
|
||||
|
||||
if (!config.classnames) {
|
||||
const ns = config.classPrefix;
|
||||
config.classnames = config.classnames || makeClassnames(ns);
|
||||
}
|
||||
|
||||
if (!config.getComponentConfig) {
|
||||
config.getComponentConfig = (name?: string) =>
|
||||
config.components && name ? config.components[name] : null;
|
||||
}
|
||||
|
||||
return config as ThemeInstance;
|
||||
}
|
||||
|
||||
export interface ThemeProps {
|
||||
classnames: ClassNamesFn;
|
||||
classPrefix: string;
|
||||
className?: string;
|
||||
theme?: string;
|
||||
mobileUI?: boolean;
|
||||
style?: {
|
||||
[propName: string]: any;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ThemeOuterProps extends Partial<ThemeProps> {}
|
||||
|
||||
export let defaultTheme: string = 'cxd';
|
||||
export const ThemeContext = React.createContext('');
|
||||
|
||||
export function themeable<
|
||||
T extends React.ComponentType<React.ComponentProps<T> & ThemeProps> & {
|
||||
themeKey?: string;
|
||||
}
|
||||
>(ComposedComponent: T, methods?: Array<string>) {
|
||||
type OuterProps = JSX.LibraryManagedAttributes<
|
||||
T,
|
||||
Omit<React.ComponentProps<T>, keyof ThemeProps>
|
||||
> &
|
||||
ThemeOuterProps;
|
||||
|
||||
const result = hoistNonReactStatic(
|
||||
class extends React.Component<OuterProps> {
|
||||
static displayName: string = `Themeable(${
|
||||
ComposedComponent.displayName || ComposedComponent.name
|
||||
})`;
|
||||
static contextType = ThemeContext;
|
||||
static ComposedComponent = ComposedComponent as React.ComponentType<T>;
|
||||
|
||||
constructor(props: OuterProps) {
|
||||
super(props);
|
||||
|
||||
this.childRef = this.childRef.bind(this);
|
||||
this.getWrappedInstance = this.getWrappedInstance.bind(this);
|
||||
}
|
||||
|
||||
ref: any;
|
||||
|
||||
childRef(ref: any) {
|
||||
while (ref && ref.getWrappedInstance) {
|
||||
ref = ref.getWrappedInstance();
|
||||
}
|
||||
|
||||
this.ref = ref;
|
||||
}
|
||||
|
||||
getWrappedInstance() {
|
||||
return this.ref;
|
||||
}
|
||||
|
||||
render() {
|
||||
const theme: string =
|
||||
this.props.theme || (this.context as string) || defaultTheme;
|
||||
const config = hasTheme(theme)
|
||||
? getTheme(theme)
|
||||
: getTheme(defaultTheme);
|
||||
const injectedProps: {
|
||||
classPrefix: string;
|
||||
classnames: ClassNamesFn;
|
||||
theme: string;
|
||||
} = {
|
||||
classPrefix: config.classPrefix as string,
|
||||
classnames: config.classnames,
|
||||
theme
|
||||
};
|
||||
const refConfig =
|
||||
ComposedComponent.prototype?.isReactComponent ||
|
||||
(ComposedComponent as any).$$typeof ===
|
||||
Symbol.for('react.forward_ref')
|
||||
? {ref: this.childRef}
|
||||
: {forwardedRef: this.childRef};
|
||||
|
||||
const body = (
|
||||
<ComposedComponent
|
||||
{...config.getComponentConfig(ComposedComponent.themeKey)}
|
||||
{...(this.props as JSX.LibraryManagedAttributes<
|
||||
T,
|
||||
React.ComponentProps<T>
|
||||
>)}
|
||||
{...injectedProps}
|
||||
{...refConfig}
|
||||
/>
|
||||
);
|
||||
|
||||
return this.context ? (
|
||||
body
|
||||
) : (
|
||||
<ThemeContext.Provider value={theme}>{body}</ThemeContext.Provider>
|
||||
);
|
||||
}
|
||||
},
|
||||
ComposedComponent
|
||||
);
|
||||
|
||||
if (Array.isArray(methods)) {
|
||||
methods.forEach(method => {
|
||||
if (ComposedComponent.prototype[method]) {
|
||||
(result as any).prototype[method] = function () {
|
||||
const fn = this.ref?.[method];
|
||||
return fn ? fn.apply(this.ref, arguments) : undefined;
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return result as typeof result & {
|
||||
ComposedComponent: T;
|
||||
};
|
||||
}
|
||||
824
packages/amis-core/src/types.ts
Normal file
824
packages/amis-core/src/types.ts
Normal file
@@ -0,0 +1,824 @@
|
||||
// https://json-schema.org/draft-07/json-schema-release-notes.html
|
||||
import type {JSONSchema7} from 'json-schema';
|
||||
import {ListenerAction} from './actions/Action';
|
||||
import {debounceConfig, trackConfig} from './utils/renderer-event';
|
||||
import type {TestIdBuilder, ValidateError} from './utils/helper';
|
||||
import {AnimationsProps} from './utils/animations';
|
||||
|
||||
export interface Option {
|
||||
/**
|
||||
* 用来显示的文字
|
||||
*/
|
||||
label?: string;
|
||||
|
||||
/**
|
||||
* 可以用来给 Option 标记个范围,让数据展示更清晰。
|
||||
*
|
||||
* 这个只有在数值展示的时候显示。
|
||||
*/
|
||||
scopeLabel?: string;
|
||||
|
||||
/**
|
||||
* 请保证数值唯一,多个选项值一致会认为是同一个选项。
|
||||
*/
|
||||
value?: any;
|
||||
|
||||
/**
|
||||
* 是否禁用
|
||||
*/
|
||||
disabled?: boolean;
|
||||
|
||||
/**
|
||||
* 禁用提示
|
||||
*/
|
||||
disabledTip?: string;
|
||||
|
||||
/**
|
||||
* 支持嵌套
|
||||
*/
|
||||
children?: Options;
|
||||
|
||||
/**
|
||||
* 是否可见
|
||||
*/
|
||||
visible?: boolean;
|
||||
|
||||
/**
|
||||
* 最好不要用!因为有 visible 就够了。
|
||||
*
|
||||
* @deprecated 用 visible
|
||||
*/
|
||||
hidden?: boolean;
|
||||
|
||||
/**
|
||||
* 描述,部分控件支持
|
||||
*/
|
||||
description?: string;
|
||||
|
||||
/**
|
||||
* 标记后数据延时加载
|
||||
*/
|
||||
defer?: boolean;
|
||||
|
||||
/**
|
||||
* 如果设置了,优先级更高,不设置走 source 接口加载。
|
||||
*/
|
||||
deferApi?: BaseApi;
|
||||
|
||||
/**
|
||||
* 标记正在加载。只有 defer 为 true 时有意义。内部字段不可以外部设置
|
||||
*/
|
||||
loading?: boolean;
|
||||
|
||||
/**
|
||||
* 只有设置了 defer 才有意义,内部字段不可以外部设置
|
||||
*/
|
||||
loaded?: boolean;
|
||||
|
||||
[propName: string]: any;
|
||||
}
|
||||
export interface Options extends Array<Option> {}
|
||||
export type OptionValue = string | number | null | undefined | Option;
|
||||
|
||||
export interface BaseApiObject {
|
||||
/**
|
||||
* API 发送类型
|
||||
*/
|
||||
method?: 'get' | 'post' | 'put' | 'delete' | 'patch' | 'jsonp' | 'js';
|
||||
|
||||
/**
|
||||
* API 发送目标地址
|
||||
*/
|
||||
url: string;
|
||||
|
||||
/**
|
||||
* 用来控制携带数据. 当key 为 `&` 值为 `$$` 时, 将所有原始数据打平设置到 data 中. 当值为 $$ 将所有原始数据赋值到对应的 key 中. 当值为 $ 打头时, 将变量值设置到 key 中.
|
||||
*/
|
||||
data?: {
|
||||
[propName: string]: any;
|
||||
};
|
||||
|
||||
/**
|
||||
* 默认数据映射中的key如果带点,或者带大括号,会转成对象比如:
|
||||
*
|
||||
* {
|
||||
* 'a.b': '123'
|
||||
* }
|
||||
*
|
||||
* 经过数据映射后变成
|
||||
* {
|
||||
* a: {
|
||||
* b: '123
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* 如果想要关闭此功能,请设置 convertKeyToPath 为 false
|
||||
*/
|
||||
convertKeyToPath?: boolean;
|
||||
|
||||
/**
|
||||
* 用来做接口返回的数据映射。
|
||||
*/
|
||||
responseData?: {
|
||||
[propName: string]: any;
|
||||
};
|
||||
|
||||
/**
|
||||
* 如果 method 为 get 的接口,设置了 data 信息。
|
||||
* 默认 data 会自动附带在 query 里面发送给后端。
|
||||
*
|
||||
* 如果想通过 body 发送给后端,那么请把这个配置成 false。
|
||||
*
|
||||
* 但是,浏览器还不支持啊,设置了只是摆设。除非服务端支持 method-override
|
||||
*/
|
||||
attachDataToQuery?: boolean;
|
||||
|
||||
/**
|
||||
* 发送体的格式
|
||||
*/
|
||||
dataType?: 'json' | 'form-data' | 'form';
|
||||
|
||||
/**
|
||||
* 如果是文件下载接口,请配置这个。
|
||||
*/
|
||||
responseType?: 'blob';
|
||||
|
||||
/**
|
||||
* 携带 headers,用法和 data 一样,可以用变量。
|
||||
*/
|
||||
headers?: {
|
||||
[propName: string]: string | number;
|
||||
};
|
||||
|
||||
/**
|
||||
* 设置发送条件
|
||||
*/
|
||||
sendOn?: string;
|
||||
|
||||
/**
|
||||
* 默认都是追加模式,如果想完全替换把这个配置成 true
|
||||
*/
|
||||
replaceData?: boolean;
|
||||
|
||||
/**
|
||||
* 是否将两次返回的数据字段,做一个合并。配置返回对象中的字段名,支持配置多个。
|
||||
*
|
||||
* 比如:同时返回 log 字段,第一次返回 {log: '1'},第二次返回 {log: '2'},合并后的结果是 {log: ['1', '2']]}
|
||||
* 再比如:同时返回 items 字段,第一次返回 {items: [1, 2]},第二次返回 {items: [3, 4]},合并后的结果是 {items: [1, 2, 3, 4]}
|
||||
*/
|
||||
concatDataFields?: string | Array<string>;
|
||||
|
||||
/**
|
||||
* 是否自动刷新,当 url 中的取值结果变化时,自动刷新数据。
|
||||
*
|
||||
* @default true
|
||||
*/
|
||||
autoRefresh?: boolean;
|
||||
|
||||
/**
|
||||
* 当开启自动刷新的时候,默认是 api 的 url 来自动跟踪变量变化的。
|
||||
* 如果你希望监控 url 外的变量,请配置 trackExpression。
|
||||
*/
|
||||
trackExpression?: string;
|
||||
|
||||
/**
|
||||
* 如果设置了值,同一个接口,相同参数,指定的时间(单位:ms)内请求将直接走缓存。
|
||||
*/
|
||||
cache?: number;
|
||||
|
||||
/**
|
||||
* 强制将数据附加在 query,默认只有 api 地址中没有用变量的时候 crud 查询接口才会
|
||||
* 自动附加数据到 query 部分,如果想强制附加请设置这个属性。
|
||||
* 对于那种临时加了个变量但是又不想全部参数写一遍的时候配置很有用。
|
||||
*/
|
||||
forceAppendDataToQuery?: boolean;
|
||||
|
||||
/**
|
||||
* qs 配置项
|
||||
*/
|
||||
qsOptions?: {
|
||||
arrayFormat?: 'indices' | 'brackets' | 'repeat' | 'comma';
|
||||
indices?: boolean;
|
||||
allowDots?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* autoFill 是否显示自动填充错误提示
|
||||
*/
|
||||
silent?: boolean;
|
||||
|
||||
/**
|
||||
* 提示信息
|
||||
*/
|
||||
messages?: {
|
||||
success?: string;
|
||||
failed?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export type BaseApi = BaseApiObject | string;
|
||||
|
||||
export type ClassName =
|
||||
| string
|
||||
| {
|
||||
[propName: string]: boolean | undefined | null | string;
|
||||
};
|
||||
|
||||
export type RequestAdaptor = (
|
||||
api: ApiObject,
|
||||
context: any
|
||||
) => ApiObject | Promise<ApiObject>;
|
||||
|
||||
export type ResponseAdaptor = (
|
||||
payload: object,
|
||||
response: fetcherResult,
|
||||
api: ApiObject,
|
||||
context: any
|
||||
) => any;
|
||||
|
||||
export interface ApiObject extends BaseApiObject {
|
||||
config?: {
|
||||
withCredentials?: boolean;
|
||||
cancelExecutor?: (cancel: Function) => void;
|
||||
};
|
||||
originUrl?: string; // 原始的 url 地址,记录将 data 拼接到 query 之前的地址
|
||||
jsonql?: any;
|
||||
graphql?: string;
|
||||
operationName?: string;
|
||||
body?: PlainObject;
|
||||
query?: PlainObject;
|
||||
mockResponse?: {
|
||||
status: number;
|
||||
data?: any;
|
||||
delay?: number;
|
||||
};
|
||||
adaptor?: ResponseAdaptor;
|
||||
requestAdaptor?: RequestAdaptor;
|
||||
/**
|
||||
* api 发送上下文,可以用来传递一些数据给 api 的 adaptor
|
||||
* @readonly
|
||||
*/
|
||||
context?: any;
|
||||
/** 是否过滤为空字符串的 query 参数 */
|
||||
filterEmptyQuery?: boolean;
|
||||
downloadFileName?: string;
|
||||
}
|
||||
export type ApiString = string;
|
||||
export type Api = ApiString | ApiObject;
|
||||
|
||||
export interface fetcherResult {
|
||||
data?: {
|
||||
data: object;
|
||||
status: number;
|
||||
msg: string;
|
||||
msgTimeout?: number;
|
||||
errors?: {
|
||||
[propName: string]: string;
|
||||
};
|
||||
type?: string;
|
||||
[propName: string]: any; // 为了兼容其他返回格式
|
||||
};
|
||||
status: number;
|
||||
headers?: object;
|
||||
}
|
||||
|
||||
export interface fetchOptions {
|
||||
method?: 'get' | 'post' | 'put' | 'patch' | 'delete' | 'jsonp' | 'js';
|
||||
successMessage?: string;
|
||||
errorMessage?: string;
|
||||
autoAppend?: boolean;
|
||||
beforeSend?: (data: any) => any;
|
||||
onSuccess?: (json: Payload, data: any) => any;
|
||||
onFailed?: (json: Payload) => any;
|
||||
silent?: boolean;
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
export interface Payload {
|
||||
ok: boolean;
|
||||
msg: string;
|
||||
defaultMsg?: string;
|
||||
msgTimeout?: number;
|
||||
data: any;
|
||||
status: number;
|
||||
errors?: {
|
||||
[propName: string]: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Schema {
|
||||
type: string;
|
||||
detectField?: string;
|
||||
visibleOn?: string;
|
||||
hiddenOn?: string;
|
||||
disabledOn?: string;
|
||||
staticOn?: string;
|
||||
visible?: boolean;
|
||||
hidden?: boolean;
|
||||
disabled?: boolean;
|
||||
static?: boolean;
|
||||
children?: JSX.Element | ((props: any, schema?: any) => JSX.Element) | null;
|
||||
definitions?: Definitions;
|
||||
animations?: AnimationsProps;
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
export interface ButtonObject {
|
||||
type: 'submit' | 'button' | 'reset';
|
||||
label?: string;
|
||||
icon?: string;
|
||||
size?: string;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export type SchemaNode = Schema | string | Array<Schema | string>;
|
||||
export interface SchemaArray extends Array<SchemaNode> {}
|
||||
export interface Definitions {
|
||||
[propName: string]: SchemaNode;
|
||||
}
|
||||
export interface ActionObject extends ButtonObject {
|
||||
actionType?:
|
||||
| 'submit'
|
||||
| 'copy'
|
||||
| 'reload'
|
||||
| 'ajax'
|
||||
| 'saveAs'
|
||||
| 'dialog'
|
||||
| 'drawer'
|
||||
| 'confirmDialog'
|
||||
| 'jump'
|
||||
| 'link'
|
||||
| 'url'
|
||||
| 'email'
|
||||
| 'close'
|
||||
| 'confirm'
|
||||
| 'add'
|
||||
| 'remove'
|
||||
| 'delete'
|
||||
| 'edit'
|
||||
| 'cancel'
|
||||
| 'next'
|
||||
| 'prev'
|
||||
| 'reset'
|
||||
| 'validate'
|
||||
| 'reset-and-submit'
|
||||
| 'clear'
|
||||
| 'clear-and-submit'
|
||||
| 'toast'
|
||||
| 'goto-step'
|
||||
| 'goto-image'
|
||||
| 'expand'
|
||||
| 'collapse'
|
||||
| 'step-submit'
|
||||
| 'select'
|
||||
| 'selectAll'
|
||||
| 'clearAll'
|
||||
| 'changeTabKey'
|
||||
| 'clearSearch'
|
||||
| 'submitQuickEdit'
|
||||
| 'initDrag'
|
||||
| 'cancelDrag'
|
||||
| 'toggleExpanded'
|
||||
| 'setExpanded'
|
||||
| 'clearError';
|
||||
|
||||
api?: BaseApi;
|
||||
asyncApi?: BaseApi;
|
||||
payload?: any;
|
||||
dialog?: SchemaNode;
|
||||
to?: string;
|
||||
target?: string;
|
||||
link?: string;
|
||||
url?: string;
|
||||
cc?: string;
|
||||
bcc?: string;
|
||||
subject?: string;
|
||||
body?: string;
|
||||
mergeData?: boolean;
|
||||
reload?: string;
|
||||
messages?: {
|
||||
success?: string;
|
||||
failed?: string;
|
||||
};
|
||||
feedback?: any;
|
||||
required?: Array<string>;
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
export interface Location {
|
||||
pathname: string;
|
||||
search: string;
|
||||
state: any;
|
||||
hash: string;
|
||||
key?: string;
|
||||
query?: any;
|
||||
}
|
||||
|
||||
export interface PlainObject {
|
||||
[propsName: string]: any;
|
||||
}
|
||||
|
||||
export interface DataChangeReason {
|
||||
type:
|
||||
| 'input' // 用户输入
|
||||
| 'api' // api 接口返回触发
|
||||
| 'formula' // 公式计算触发
|
||||
| 'hide' // 隐藏属性变化触发
|
||||
| 'init' // 表单项初始化触发
|
||||
| 'action'; // 事件动作触发
|
||||
|
||||
// 变化的字段名
|
||||
// 如果是整体变化,那么是 undefined
|
||||
name?: string;
|
||||
|
||||
// 变化的值
|
||||
value?: any;
|
||||
}
|
||||
|
||||
export interface RendererData {
|
||||
[propsName: string]: any;
|
||||
/**
|
||||
* 记录变化前的数据
|
||||
*/
|
||||
__prev?: RendererDataAlias;
|
||||
|
||||
/**
|
||||
* 记录变化的信息
|
||||
*/
|
||||
__changeReason?: DataChangeReason;
|
||||
|
||||
/**
|
||||
* 记录上层数据
|
||||
*/
|
||||
__super?: RendererData;
|
||||
}
|
||||
type RendererDataAlias = RendererData;
|
||||
|
||||
export type FunctionPropertyNames<T> = {
|
||||
[K in keyof T]: T[K] extends Function ? K : never;
|
||||
}[keyof T];
|
||||
|
||||
// 先只支持 JSONSchema draft07 好了
|
||||
|
||||
export type JSONSchema = JSONSchema7 & {
|
||||
group?: string; // 分组
|
||||
typeLabel?: string; // 类型说明
|
||||
rawType?: string; // 类型
|
||||
};
|
||||
|
||||
// export type Omit<T, K extends keyof T & any> = Pick<T, Exclude<keyof T, K>>;
|
||||
// export type Override<M, N> = Omit<M, Extract<keyof M, keyof N>> & N;
|
||||
// export type ExtractProps<
|
||||
// TComponentOrTProps
|
||||
// > = TComponentOrTProps extends React.ComponentType<infer P> ? P : never;
|
||||
|
||||
/**
|
||||
* 事件跟踪的定义
|
||||
*/
|
||||
export interface EventTrack {
|
||||
/**
|
||||
* 事件类型,目前有以下几种
|
||||
*
|
||||
* api: 所有 fetcher 前调用
|
||||
* url: 打开外部链接,组件有可能是 action 也有可能是 link
|
||||
* link: 打开内部链接
|
||||
* dialog: action 的弹框
|
||||
* drawer: action 的抽出式弹框
|
||||
* copy: action 里的复制
|
||||
* reload: action 里的 reload
|
||||
* email: action 里的 email
|
||||
* prev: action 里的 prev
|
||||
* next: action 里的 next
|
||||
* cancel: action 里的 cancel
|
||||
* close: action 里的 close
|
||||
* submit: 有可能是 action 里的 submit,也有可能是表单提交
|
||||
* confirm: action 里的 confirm
|
||||
* add: action 里的 add
|
||||
* reset: action 里的 reset
|
||||
* reset-and-submit: action 里的 reset-and-submit
|
||||
* formItemChange: 表单项内容变化
|
||||
* formError: 表单验证失败
|
||||
* formSubmit: 表单成功提交,在表单验证成功之后才会触发,这个可能会和 api 重合
|
||||
* tabChange: tab 切换
|
||||
* netError: api 报错
|
||||
*/
|
||||
eventType:
|
||||
| 'api'
|
||||
| 'url'
|
||||
| 'link'
|
||||
| 'dialog'
|
||||
| 'drawer'
|
||||
| 'copy'
|
||||
| 'reload'
|
||||
| 'email'
|
||||
| 'prev'
|
||||
| 'next'
|
||||
| 'cancel'
|
||||
| 'close'
|
||||
| 'submit'
|
||||
| 'confirm'
|
||||
| 'reset'
|
||||
| 'reset-and-submit'
|
||||
| 'formItemChange'
|
||||
| 'tabChange'
|
||||
| 'pageLoaded'
|
||||
| 'pageHidden'
|
||||
| 'pageVisible'
|
||||
| string;
|
||||
|
||||
/**
|
||||
* 事件数据
|
||||
*/
|
||||
eventData?: PlainObject | Api;
|
||||
}
|
||||
|
||||
export type ToastLevel = 'info' | 'success' | 'error' | 'warning';
|
||||
export type ToastConf = {
|
||||
position?:
|
||||
| 'top-right'
|
||||
| 'top-center'
|
||||
| 'top-left'
|
||||
| 'bottom-center'
|
||||
| 'bottom-left'
|
||||
| 'bottom-right'
|
||||
| 'center';
|
||||
closeButton: boolean;
|
||||
showIcon?: boolean;
|
||||
timeout?: number;
|
||||
errorTimeout?: number;
|
||||
className?: string;
|
||||
items?: Array<any>;
|
||||
useMobileUI?: boolean;
|
||||
validateError?: ValidateError;
|
||||
};
|
||||
|
||||
export interface OptionProps {
|
||||
className?: string;
|
||||
multi?: boolean;
|
||||
multiple?: boolean;
|
||||
valueField?: string;
|
||||
labelField?: string;
|
||||
simpleValue?: boolean; // 默认onChange 出去是整个 option 节点,如果配置了 simpleValue 就只包含值。
|
||||
options: Options;
|
||||
loading?: boolean;
|
||||
joinValues?: boolean;
|
||||
extractValue?: boolean;
|
||||
delimiter?: string;
|
||||
clearable?: boolean;
|
||||
resetValue: any;
|
||||
placeholder?: string;
|
||||
disabled?: boolean;
|
||||
creatable?: boolean;
|
||||
pathSeparator?: string;
|
||||
hasError?: boolean;
|
||||
block?: boolean;
|
||||
onAdd?: (
|
||||
idx?: number | Array<number>,
|
||||
value?: any,
|
||||
skipForm?: boolean
|
||||
) => void;
|
||||
editable?: boolean;
|
||||
onEdit?: (value: Option, origin?: Option, skipForm?: boolean) => void;
|
||||
removable?: boolean;
|
||||
onDelete?: (value: Option) => void;
|
||||
}
|
||||
|
||||
export type LinkItem = LinkItemProps;
|
||||
interface LinkItemProps {
|
||||
id?: number;
|
||||
label: string;
|
||||
hidden?: boolean;
|
||||
open?: boolean;
|
||||
active?: boolean;
|
||||
className?: string;
|
||||
children?: Array<LinkItem>;
|
||||
path?: string;
|
||||
icon?: string;
|
||||
component?: React.ElementType;
|
||||
}
|
||||
|
||||
export interface NavigationObject {
|
||||
label: string;
|
||||
children?: Array<LinkItem>;
|
||||
prefix?: JSX.Element;
|
||||
affix?: JSX.Element;
|
||||
className?: string;
|
||||
[propName: string]: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* 表达式,语法 `${xxx > 5}`。
|
||||
*/
|
||||
export type SchemaExpression = string;
|
||||
|
||||
/**
|
||||
* css类名,配置字符串,或者对象。
|
||||
*
|
||||
* className: "red"
|
||||
*
|
||||
* 用对象配置时意味着你能跟表达式一起搭配使用,如:
|
||||
*
|
||||
* className: {
|
||||
* "red": "data.progress > 80",
|
||||
* "blue": "data.progress > 60"
|
||||
* }
|
||||
*/
|
||||
export type SchemaClassName =
|
||||
| string
|
||||
| {
|
||||
[propName: string]: boolean | undefined | null | SchemaExpression;
|
||||
};
|
||||
export interface BaseSchemaWithoutType {
|
||||
/**
|
||||
* 组件唯一 id,主要用于页面设计器中定位 json 节点
|
||||
*/
|
||||
$$id?: string;
|
||||
/**
|
||||
* 容器 css 类名
|
||||
*/
|
||||
className?: SchemaClassName;
|
||||
|
||||
/**
|
||||
* 配合 definitions 一起使用,可以实现无限循环的渲染器。
|
||||
*/
|
||||
$ref?: string;
|
||||
|
||||
/**
|
||||
* 是否禁用
|
||||
*/
|
||||
disabled?: boolean;
|
||||
|
||||
/**
|
||||
* 是否禁用表达式
|
||||
*/
|
||||
disabledOn?: SchemaExpression;
|
||||
|
||||
/**
|
||||
* 是否隐藏
|
||||
* @deprecated 推荐用 visible
|
||||
*/
|
||||
hidden?: boolean;
|
||||
|
||||
/**
|
||||
* 是否隐藏表达式
|
||||
* @deprecated 推荐用 visibleOn
|
||||
*/
|
||||
hiddenOn?: SchemaExpression;
|
||||
|
||||
/**
|
||||
* 是否显示
|
||||
*/
|
||||
|
||||
visible?: boolean;
|
||||
|
||||
/**
|
||||
* 是否显示表达式
|
||||
*/
|
||||
visibleOn?: SchemaExpression;
|
||||
|
||||
/**
|
||||
* 组件唯一 id,主要用于日志采集
|
||||
*/
|
||||
id?: string;
|
||||
|
||||
/**
|
||||
* 事件动作配置
|
||||
*/
|
||||
onEvent?: {
|
||||
[propName: string]: {
|
||||
weight?: number; // 权重
|
||||
actions: ListenerAction[]; // 执行的动作集
|
||||
debounce?: debounceConfig;
|
||||
track?: trackConfig;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* 是否静态展示
|
||||
*/
|
||||
static?: boolean;
|
||||
/**
|
||||
* 是否静态展示表达式
|
||||
*/
|
||||
staticOn?: SchemaExpression;
|
||||
/**
|
||||
* 静态展示空值占位
|
||||
*/
|
||||
staticPlaceholder?: string;
|
||||
/**
|
||||
* 静态展示表单项类名
|
||||
*/
|
||||
staticClassName?: SchemaClassName;
|
||||
/**
|
||||
* 静态展示表单项Label类名
|
||||
*/
|
||||
staticLabelClassName?: SchemaClassName;
|
||||
/**
|
||||
* 静态展示表单项Value类名
|
||||
*/
|
||||
staticInputClassName?: SchemaClassName;
|
||||
staticSchema?: any;
|
||||
|
||||
/**
|
||||
* 组件样式
|
||||
*/
|
||||
style?: {
|
||||
[propName: string]: any;
|
||||
};
|
||||
|
||||
/**
|
||||
* 编辑器配置,运行时可以忽略
|
||||
*/
|
||||
editorSetting?: {
|
||||
/**
|
||||
* 组件行为、用途,如 create、update、remove
|
||||
*/
|
||||
behavior?: string;
|
||||
|
||||
/**
|
||||
* 组件名称,通常是业务名称方便定位
|
||||
*/
|
||||
displayName?: string;
|
||||
|
||||
/**
|
||||
* 编辑器假数据,方便展示
|
||||
*/
|
||||
mock?: any;
|
||||
|
||||
[propName: string]: any;
|
||||
};
|
||||
|
||||
/**
|
||||
* 可以组件级别用来关闭移动端样式
|
||||
*/
|
||||
useMobileUI?: boolean;
|
||||
}
|
||||
|
||||
export type OperatorType =
|
||||
| 'equal'
|
||||
| 'not_equal'
|
||||
| 'is_empty'
|
||||
| 'is_not_empty'
|
||||
| 'like'
|
||||
| 'not_like'
|
||||
| 'starts_with'
|
||||
| 'ends_with'
|
||||
| 'less'
|
||||
| 'less_or_equal'
|
||||
| 'greater'
|
||||
| 'greater_or_equal'
|
||||
| 'between'
|
||||
| 'not_between'
|
||||
| 'select_equals'
|
||||
| 'select_not_equals'
|
||||
| 'select_any_in'
|
||||
| 'select_not_any_in'
|
||||
| {
|
||||
label: string;
|
||||
value: string;
|
||||
};
|
||||
|
||||
export type ExpressionSimple = string | number | object | undefined;
|
||||
export type ExpressionValue =
|
||||
| ExpressionSimple
|
||||
| {
|
||||
type: 'value';
|
||||
value: ExpressionSimple;
|
||||
};
|
||||
export type ExpressionFunc = {
|
||||
type: 'func';
|
||||
func: string;
|
||||
args: Array<ExpressionComplex>;
|
||||
};
|
||||
export type ExpressionField = {
|
||||
type: 'field';
|
||||
field: string;
|
||||
};
|
||||
export type ExpressionFormula = {
|
||||
type: 'formula';
|
||||
value: string;
|
||||
};
|
||||
|
||||
export type ExpressionComplex =
|
||||
| ExpressionValue
|
||||
| ExpressionFunc
|
||||
| ExpressionField
|
||||
| ExpressionFormula;
|
||||
|
||||
export interface ConditionRule {
|
||||
id: any;
|
||||
left?: ExpressionComplex;
|
||||
op?: OperatorType;
|
||||
right?: ExpressionComplex | Array<ExpressionComplex>;
|
||||
if?: string;
|
||||
}
|
||||
|
||||
export interface ConditionGroupValue {
|
||||
id: string;
|
||||
conjunction: 'and' | 'or';
|
||||
not?: boolean;
|
||||
children?: Array<ConditionRule | ConditionGroupValue>;
|
||||
if?: string;
|
||||
}
|
||||
|
||||
export interface ConditionValue extends ConditionGroupValue {}
|
||||
383
packages/amis-core/src/utils/Animation.ts
Normal file
383
packages/amis-core/src/utils/Animation.ts
Normal file
@@ -0,0 +1,383 @@
|
||||
// 基本上都是从 sortable 那抄的,让拖拽切换有个动画,看起来更流畅。
|
||||
// 用法是移动前先 animat.capture(container) 把移动前的位置信息记住
|
||||
// 然后移动节点
|
||||
// 然后 animate.animateAll(); 计算移动后的位置,然后马上通过 css transform 到原来的位置
|
||||
// 然后开始动画到移动后的位置。
|
||||
|
||||
interface Rect {
|
||||
top: number;
|
||||
left: number;
|
||||
bottom: number;
|
||||
right: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
interface AnimationState {
|
||||
rect: Rect;
|
||||
target: HTMLElement;
|
||||
}
|
||||
|
||||
function userAgent(pattern: RegExp): any {
|
||||
if (typeof window !== 'undefined' && window.navigator) {
|
||||
return !!(/*@__PURE__*/ navigator.userAgent.match(pattern));
|
||||
}
|
||||
}
|
||||
|
||||
const IE11OrLess = userAgent(
|
||||
/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i
|
||||
);
|
||||
// const Edge = userAgent(/Edge/i);
|
||||
// const FireFox = userAgent(/firefox/i);
|
||||
// const Safari =
|
||||
// userAgent(/safari/i) && !userAgent(/chrome/i) && !userAgent(/android/i);
|
||||
// const IOS = userAgent(/iP(ad|od|hone)/i);
|
||||
// const ChromeForAndroid = userAgent(/chrome/i) && userAgent(/android/i);
|
||||
|
||||
const AnimationDurtation = 150;
|
||||
const AnimationEasing = 'cubic-bezier(1, 0, 0, 1)';
|
||||
|
||||
export class AnimationManager {
|
||||
animating: boolean = false;
|
||||
animationCallbackId: any;
|
||||
states: Array<AnimationState> = [];
|
||||
|
||||
capture(el: HTMLElement) {
|
||||
// 清空,重复调用,旧的不管了
|
||||
this.states = [];
|
||||
|
||||
let children: Array<HTMLElement> = [].slice.call(el.children);
|
||||
children.forEach(child => {
|
||||
// 如果是 ghost
|
||||
if (child.classList.contains('is-ghost')) {
|
||||
return;
|
||||
}
|
||||
|
||||
const rect = getRect(child)!;
|
||||
|
||||
// 通常是隐藏节点
|
||||
if (!rect.width) {
|
||||
return;
|
||||
}
|
||||
|
||||
let fromRect = {...rect};
|
||||
|
||||
const state: AnimationState = {
|
||||
target: child,
|
||||
rect
|
||||
};
|
||||
|
||||
// 还在动画中
|
||||
if ((child as any).thisAnimationDuration) {
|
||||
let childMatrix = matrix(child);
|
||||
|
||||
if (childMatrix) {
|
||||
fromRect.top -= childMatrix.f;
|
||||
fromRect.left -= childMatrix.e;
|
||||
}
|
||||
}
|
||||
|
||||
(child as any).fromRect = fromRect;
|
||||
this.states.push(state);
|
||||
});
|
||||
}
|
||||
|
||||
animateAll(callback?: () => void) {
|
||||
this.animating = false;
|
||||
let animationTime = 0;
|
||||
|
||||
this.states.forEach(state => {
|
||||
let time = 0,
|
||||
target = state.target,
|
||||
fromRect = (target as any).fromRect,
|
||||
toRect = {
|
||||
...getRect(target)!
|
||||
},
|
||||
prevFromRect = (target as any).prevFromRect,
|
||||
prevToRect = (target as any).prevToRect,
|
||||
animatingRect = state.rect,
|
||||
targetMatrix = matrix(target);
|
||||
|
||||
if (targetMatrix) {
|
||||
// Compensate for current animation
|
||||
toRect.top -= targetMatrix.f;
|
||||
toRect.left -= targetMatrix.e;
|
||||
}
|
||||
|
||||
(target as any).toRect = toRect;
|
||||
|
||||
if ((target as any).thisAnimationDuration) {
|
||||
// Could also check if animatingRect is between fromRect and toRect
|
||||
if (
|
||||
isRectEqual(prevFromRect, toRect) &&
|
||||
!isRectEqual(fromRect, toRect) &&
|
||||
// Make sure animatingRect is on line between toRect & fromRect
|
||||
(animatingRect.top - toRect.top) /
|
||||
(animatingRect.left - toRect.left) ===
|
||||
(fromRect.top - toRect.top) / (fromRect.left - toRect.left)
|
||||
) {
|
||||
// If returning to same place as started from animation and on same axis
|
||||
time = calculateRealTime(animatingRect, prevFromRect, prevToRect);
|
||||
}
|
||||
}
|
||||
|
||||
// if fromRect != toRect: animate
|
||||
if (!isRectEqual(toRect, fromRect)) {
|
||||
(target as any).prevFromRect = fromRect;
|
||||
(target as any).prevToRect = toRect;
|
||||
|
||||
if (!time) {
|
||||
time = AnimationDurtation;
|
||||
}
|
||||
this.animate(target, animatingRect, toRect, time);
|
||||
}
|
||||
|
||||
if (time) {
|
||||
this.animating = true;
|
||||
animationTime = Math.max(animationTime, time);
|
||||
clearTimeout((target as any).animationResetTimer);
|
||||
(target as any).animationResetTimer = setTimeout(function () {
|
||||
(target as any).animationTime = 0;
|
||||
(target as any).prevFromRect = null;
|
||||
(target as any).fromRect = null;
|
||||
(target as any).prevToRect = null;
|
||||
(target as any).thisAnimationDuration = null;
|
||||
}, time);
|
||||
(target as any).thisAnimationDuration = time;
|
||||
}
|
||||
});
|
||||
|
||||
clearTimeout(this.animationCallbackId);
|
||||
if (!this.animating) {
|
||||
if (typeof callback === 'function') callback();
|
||||
} else {
|
||||
this.animationCallbackId = setTimeout(() => {
|
||||
this.animating = false;
|
||||
if (typeof callback === 'function') callback();
|
||||
}, animationTime);
|
||||
}
|
||||
this.states = [];
|
||||
}
|
||||
|
||||
animate(
|
||||
target: HTMLElement,
|
||||
currentRect: Rect,
|
||||
toRect: Rect,
|
||||
duration: number
|
||||
) {
|
||||
if (duration) {
|
||||
let affectDisplay = false;
|
||||
css(target, 'transition', '');
|
||||
css(target, 'transform', '');
|
||||
let translateX = currentRect.left - toRect.left,
|
||||
translateY = currentRect.top - toRect.top;
|
||||
|
||||
(target as any).animatingX = !!translateX;
|
||||
(target as any).animatingY = !!translateY;
|
||||
|
||||
css(
|
||||
target,
|
||||
'transform',
|
||||
'translate3d(' + translateX + 'px,' + translateY + 'px,0)'
|
||||
);
|
||||
|
||||
if (css(target, 'display') === 'inline') {
|
||||
affectDisplay = true;
|
||||
css(target, 'display', 'inline-block');
|
||||
}
|
||||
|
||||
target.offsetWidth; // repaint
|
||||
|
||||
css(
|
||||
target,
|
||||
'transition',
|
||||
'transform ' +
|
||||
duration +
|
||||
'ms' +
|
||||
(AnimationEasing ? ' ' + AnimationEasing : '')
|
||||
);
|
||||
css(target, 'transform', 'translate3d(0,0,0)');
|
||||
typeof (target as any).animated === 'number' &&
|
||||
clearTimeout((target as any).animated);
|
||||
(target as any).animated = setTimeout(function () {
|
||||
css(target, 'transition', '');
|
||||
css(target, 'transform', '');
|
||||
affectDisplay && css(target, 'display', '');
|
||||
(target as any).animated = false;
|
||||
|
||||
(target as any).animatingX = false;
|
||||
(target as any).animatingY = false;
|
||||
}, duration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function matrix(el: HTMLElement) {
|
||||
let appliedTransforms = '';
|
||||
if (typeof el === 'string') {
|
||||
appliedTransforms = el;
|
||||
} else {
|
||||
let transform = css(el, 'transform');
|
||||
|
||||
if (transform && transform !== 'none') {
|
||||
appliedTransforms = transform + ' ' + appliedTransforms;
|
||||
}
|
||||
}
|
||||
|
||||
const matrixFn =
|
||||
window.DOMMatrix ||
|
||||
window.WebKitCSSMatrix ||
|
||||
(window as any).CSSMatrix ||
|
||||
(window as any).MSCSSMatrix;
|
||||
|
||||
/*jshint -W056 */
|
||||
return matrixFn && new matrixFn(appliedTransforms);
|
||||
}
|
||||
|
||||
function css(el: HTMLElement, prop: string, val?: any) {
|
||||
let style = el && el.style;
|
||||
|
||||
if (style) {
|
||||
if (val === void 0) {
|
||||
if (document.defaultView && document.defaultView.getComputedStyle) {
|
||||
val = document.defaultView.getComputedStyle(el, '');
|
||||
} else if ((el as any).currentStyle) {
|
||||
val = (el as any).currentStyle;
|
||||
}
|
||||
|
||||
return prop === void 0 ? val : val[prop];
|
||||
} else {
|
||||
if (!(prop in style) && prop.indexOf('webkit') === -1) {
|
||||
prop = '-webkit-' + prop;
|
||||
}
|
||||
|
||||
(style as any)[prop] = val + (typeof val === 'string' ? '' : 'px');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isRectEqual(rect1: Rect, rect2: Rect) {
|
||||
return (
|
||||
Math.round(rect1.top) === Math.round(rect2.top) &&
|
||||
Math.round(rect1.left) === Math.round(rect2.left) &&
|
||||
Math.round(rect1.height) === Math.round(rect2.height) &&
|
||||
Math.round(rect1.width) === Math.round(rect2.width)
|
||||
);
|
||||
}
|
||||
|
||||
function calculateRealTime(animatingRect: Rect, fromRect: Rect, toRect: Rect) {
|
||||
return (
|
||||
(Math.sqrt(
|
||||
Math.pow(fromRect.top - animatingRect.top, 2) +
|
||||
Math.pow(fromRect.left - animatingRect.left, 2)
|
||||
) /
|
||||
Math.sqrt(
|
||||
Math.pow(fromRect.top - toRect.top, 2) +
|
||||
Math.pow(fromRect.left - toRect.left, 2)
|
||||
)) *
|
||||
AnimationDurtation
|
||||
);
|
||||
}
|
||||
|
||||
function getWindowScrollingElement() {
|
||||
let scrollingElement = document.scrollingElement;
|
||||
|
||||
if (scrollingElement) {
|
||||
return scrollingElement;
|
||||
} else {
|
||||
return document.documentElement;
|
||||
}
|
||||
}
|
||||
|
||||
function getRect(
|
||||
el: HTMLElement,
|
||||
relativeToContainingBlock?: boolean,
|
||||
relativeToNonStaticParent?: boolean,
|
||||
undoScale?: boolean,
|
||||
container?: HTMLElement
|
||||
) {
|
||||
if (!el.getBoundingClientRect && (el as any) !== window) return;
|
||||
|
||||
let elRect, top, left, bottom, right, height, width;
|
||||
|
||||
if ((el as any) !== window && el !== getWindowScrollingElement()) {
|
||||
elRect = el.getBoundingClientRect();
|
||||
top = elRect.top;
|
||||
left = elRect.left;
|
||||
bottom = elRect.bottom;
|
||||
right = elRect.right;
|
||||
height = elRect.height;
|
||||
width = elRect.width;
|
||||
} else {
|
||||
top = 0;
|
||||
left = 0;
|
||||
bottom = window.innerHeight;
|
||||
right = window.innerWidth;
|
||||
height = window.innerHeight;
|
||||
width = window.innerWidth;
|
||||
}
|
||||
|
||||
if (
|
||||
(relativeToContainingBlock || relativeToNonStaticParent) &&
|
||||
(el as any) !== window
|
||||
) {
|
||||
// Adjust for translate()
|
||||
container = container || (el.parentNode as HTMLElement);
|
||||
|
||||
// solves #1123 (see: https://stackoverflow.com/a/37953806/6088312)
|
||||
// Not needed on <= IE11
|
||||
if (!IE11OrLess) {
|
||||
do {
|
||||
if (
|
||||
container &&
|
||||
container.getBoundingClientRect &&
|
||||
(css(container, 'transform') !== 'none' ||
|
||||
(relativeToNonStaticParent &&
|
||||
css(container, 'position') !== 'static'))
|
||||
) {
|
||||
let containerRect = container.getBoundingClientRect();
|
||||
|
||||
// Set relative to edges of padding box of container
|
||||
top -=
|
||||
containerRect.top + parseInt(css(container, 'border-top-width'));
|
||||
left -=
|
||||
containerRect.left + parseInt(css(container, 'border-left-width'));
|
||||
bottom = top + (elRect as any).height;
|
||||
right = left + (elRect as any).width;
|
||||
|
||||
break;
|
||||
}
|
||||
/* jshint boss:true */
|
||||
} while ((container = container.parentNode as HTMLElement));
|
||||
}
|
||||
}
|
||||
|
||||
if (undoScale && (el as any) !== window) {
|
||||
// Adjust for scale()
|
||||
let elMatrix = matrix(container || el),
|
||||
scaleX = elMatrix && elMatrix.a,
|
||||
scaleY = elMatrix && elMatrix.d;
|
||||
|
||||
if (elMatrix) {
|
||||
top /= scaleY;
|
||||
left /= scaleX;
|
||||
|
||||
width /= scaleX;
|
||||
height /= scaleY;
|
||||
|
||||
bottom = top + height;
|
||||
right = left + width;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
top: top,
|
||||
left: left,
|
||||
bottom: bottom,
|
||||
right: right,
|
||||
width: width,
|
||||
height: height
|
||||
};
|
||||
}
|
||||
|
||||
export default new AnimationManager();
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user