@formvk/schema 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/shared.ts ADDED
@@ -0,0 +1,226 @@
1
+ import { isObservable, untracked } from '@formvk/reactive'
2
+ import { each, FormPath, isArr, isFn, isPlainObj, toArr } from '@formvk/shared'
3
+
4
+ import type { ISchema } from './types'
5
+
6
+ const REVA_ACTIONS_KEY = Symbol.for('__REVA_ACTIONS')
7
+
8
+ /** 自定义扩展 key:xKey 形式(x + 大驼峰) */
9
+ export function isExtensionKey(key: string) {
10
+ return /^x[A-Z]/.test(key)
11
+ }
12
+
13
+ /**
14
+ * 值本身可以是函数的 schema key。
15
+ * 这些 key 在编译/序列化/遍历时不能被当作 Schema 内部方法丢弃。
16
+ */
17
+ export const SchemaFunctionKeys: Record<string, boolean> = {
18
+ component: true,
19
+ decorator: true,
20
+ componentProps: true,
21
+ decoratorProps: true,
22
+ validator: true,
23
+ reactions: true,
24
+ }
25
+
26
+ export function isFunctionKey(key: string) {
27
+ return isExtensionKey(key) || !!SchemaFunctionKeys[key]
28
+ }
29
+
30
+ export const SchemaNestedMap: Record<string, boolean> = {
31
+ parent: true,
32
+ root: true,
33
+ properties: true,
34
+ patternProperties: true,
35
+ additionalProperties: true,
36
+ items: true,
37
+ additionalItems: true,
38
+ reactions: true,
39
+ }
40
+
41
+ /** schema key -> 字段状态 key */
42
+ export const SchemaStateMap: Record<string, string> = {
43
+ title: 'title',
44
+ description: 'description',
45
+ default: 'initialValue',
46
+ enum: 'dataSource',
47
+ readOnly: 'readOnly',
48
+ writeOnly: 'editable',
49
+ content: 'content',
50
+ data: 'data',
51
+ value: 'value',
52
+ editable: 'editable',
53
+ disabled: 'disabled',
54
+ readPretty: 'readPretty',
55
+ visible: 'visible',
56
+ hidden: 'hidden',
57
+ display: 'display',
58
+ pattern: 'pattern',
59
+ validator: 'validator',
60
+ decorator: 'decoratorType',
61
+ component: 'componentType',
62
+ decoratorProps: 'decoratorProps',
63
+ componentProps: 'componentProps',
64
+ }
65
+
66
+ /** schema key -> 校验规则 key */
67
+ export const SchemaValidatorMap: Record<string, boolean> = {
68
+ required: true,
69
+ format: true,
70
+ maxItems: true,
71
+ minItems: true,
72
+ maxLength: true,
73
+ minLength: true,
74
+ maximum: true,
75
+ minimum: true,
76
+ exclusiveMaximum: true,
77
+ exclusiveMinimum: true,
78
+ const: true,
79
+ multipleOf: true,
80
+ maxProperties: true,
81
+ minProperties: true,
82
+ uniqueItems: true,
83
+ }
84
+
85
+ export const SchemaNormalKeys = Object.keys(SchemaStateMap)
86
+
87
+ export const SchemaValidatorKeys = Object.keys(SchemaValidatorMap)
88
+
89
+ export const hasOwnProperty = Object.prototype.hasOwnProperty
90
+
91
+ export function traverse(target: any, visitor: (value: any, path: Array<string | number>) => void) {
92
+ const seenObjects: any[] = []
93
+ const root = target
94
+ function traverse(target: any, path: Array<string | number> = []) {
95
+ if (isPlainObj(target)) {
96
+ const seenIndex = seenObjects.indexOf(target)
97
+ if (seenIndex > -1) {
98
+ return
99
+ }
100
+ const addIndex = seenObjects.length
101
+ seenObjects.push(target)
102
+ if (isNoNeedCompileObject(target) && root !== target) {
103
+ visitor(target, path)
104
+ return
105
+ }
106
+ each(target, (value, key) => {
107
+ traverse(value, path.concat(key))
108
+ })
109
+ seenObjects.splice(addIndex, 1)
110
+ } else {
111
+ visitor(target, path)
112
+ }
113
+ }
114
+ traverse(target)
115
+ }
116
+
117
+ export function traverseSchema(schema: ISchema, visitor: (value: any, path: any[], omitCompile?: boolean) => void) {
118
+ if (schema['validator'] !== undefined) {
119
+ visitor(schema['validator'], ['validator'], schema['compileOmitted']?.includes('validator'))
120
+ }
121
+ const seenObjects: any[] = []
122
+ const root = schema
123
+ function traverse(target: any, path: any[] = []) {
124
+ if (
125
+ path[0] === 'compileOmitted' ||
126
+ path[0] === 'validator' ||
127
+ path[0] === 'version' ||
128
+ path[0] === '_isJSONSchemaObject'
129
+ )
130
+ return
131
+ if (isFn(target) && !isFunctionKey(String(path[0]))) return
132
+ if (SchemaNestedMap[path[0]]) return
133
+ if ((schema['compileOmitted']?.indexOf(path[0]) ?? -1) > -1) {
134
+ visitor(target, path, true)
135
+ return
136
+ }
137
+ if (isPlainObj(target)) {
138
+ if (path[0] === 'default' || path[0] === 'value') {
139
+ visitor(target, path)
140
+ return
141
+ }
142
+ const seenIndex = seenObjects.indexOf(target)
143
+ if (seenIndex > -1) {
144
+ return
145
+ }
146
+ const addIndex = seenObjects.length
147
+ seenObjects.push(target)
148
+ if (isNoNeedCompileObject(target) && root !== target) {
149
+ visitor(target, path)
150
+ return
151
+ }
152
+ each(target, (value, key) => {
153
+ traverse(value, path.concat(key))
154
+ })
155
+ seenObjects.splice(addIndex, 1)
156
+ } else {
157
+ visitor(target, path)
158
+ }
159
+ }
160
+ traverse(schema)
161
+ }
162
+
163
+ export function isNoNeedCompileObject(source: any) {
164
+ if ('$$typeof' in source && '_owner' in source) {
165
+ return true
166
+ }
167
+ // Vue VNode / markRaw 对象:内部存在循环引用,且必须保持原始引用
168
+ if (source['__v_isVNode'] || source['__v_skip']) {
169
+ return true
170
+ }
171
+ if (source['_isAMomentObject']) {
172
+ return true
173
+ }
174
+ // 使用实例标记判定,避免与 schema.ts 形成循环依赖
175
+ if (source['_isJSONSchemaObject']) {
176
+ return true
177
+ }
178
+ if (source[REVA_ACTIONS_KEY]) {
179
+ return true
180
+ }
181
+ if (isFn(source['toJS'])) {
182
+ return true
183
+ }
184
+ if (isFn(source['toJSON'])) {
185
+ return true
186
+ }
187
+ if (isObservable(source)) {
188
+ return true
189
+ }
190
+ return false
191
+ }
192
+
193
+ export function createDataSource(source: any[]) {
194
+ return toArr(source).map(item => {
195
+ if (typeof item === 'object') {
196
+ return item
197
+ } else {
198
+ return {
199
+ label: item,
200
+ value: item,
201
+ }
202
+ }
203
+ })
204
+ }
205
+
206
+ export function patchStateFormSchema(targetState: any, pattern: any[], compiled: any) {
207
+ untracked(() => {
208
+ const path = FormPath.parse(pattern)
209
+ const segments = path.segments
210
+ const key = segments[0]
211
+ const isEnum = key === 'enum' && isArr(compiled)
212
+ const schemaMapKey = SchemaStateMap[key]
213
+ if (schemaMapKey) {
214
+ FormPath.setIn(
215
+ targetState,
216
+ ([schemaMapKey] as Array<string | number>).concat(segments.slice(1)),
217
+ isEnum ? createDataSource(compiled) : compiled
218
+ )
219
+ } else {
220
+ const isValidatorKey = SchemaValidatorMap[key]
221
+ if (isValidatorKey) {
222
+ targetState['setValidatorRule']?.(key, compiled)
223
+ }
224
+ }
225
+ })
226
+ }
@@ -0,0 +1,251 @@
1
+ import type { Field, IFieldFactoryProps } from '@formvk/core'
2
+ import {
3
+ onFieldInit,
4
+ onFieldInputValueChange,
5
+ onFieldInitialValueChange,
6
+ onFieldMount,
7
+ onFieldUnmount,
8
+ onFieldValidateEnd,
9
+ onFieldValidateFailed,
10
+ onFieldValidateStart,
11
+ onFieldValidateSuccess,
12
+ onFieldValueChange,
13
+ } from '@formvk/core'
14
+ import { autorun, observable, untracked } from '@formvk/reactive'
15
+ import { each, isArr, isFn, isPlainObj, isStr, lazyMerge, reduce, toArr } from '@formvk/shared'
16
+
17
+ import { patchCompile, patchSchemaCompile, shallowCompile } from './compiler'
18
+ import type { Schema } from './schema'
19
+ import type { IFieldStateSetterOptions, ISchema, ISchemaTransformerOptions, SchemaReaction } from './types'
20
+
21
+ const FieldEffects: Record<string, any> = {
22
+ onFieldInit,
23
+ onFieldMount,
24
+ onFieldUnmount,
25
+ onFieldValueChange,
26
+ onFieldInputValueChange,
27
+ onFieldInitialValueChange,
28
+ onFieldValidateStart,
29
+ onFieldValidateEnd,
30
+ onFieldValidateFailed,
31
+ onFieldValidateSuccess,
32
+ }
33
+
34
+ const DefaultFieldEffects = ['onFieldInit', 'onFieldValueChange']
35
+
36
+ function getDependencyValue(field: Field, pattern: string, property?: string) {
37
+ const [target, path] = String(pattern).split(/\s*#\s*/)
38
+ return field.query(target).getIn(path || property || 'value')
39
+ }
40
+
41
+ function getDependencies(
42
+ field: Field,
43
+ dependencies: Array<string | { name?: string; source?: string; property?: string }> | object
44
+ ) {
45
+ if (isArr(dependencies)) {
46
+ const results: any = []
47
+ dependencies.forEach(pattern => {
48
+ if (isStr(pattern)) {
49
+ results.push(getDependencyValue(field, pattern))
50
+ } else if (isPlainObj(pattern)) {
51
+ const item = pattern as { name?: string; source?: string; property?: string }
52
+ if (item.name && item.source) {
53
+ results[item.name] = getDependencyValue(field, item.source, item.property)
54
+ }
55
+ }
56
+ })
57
+ return results
58
+ } else if (isPlainObj(dependencies)) {
59
+ return reduce(
60
+ dependencies as Record<string, string>,
61
+ (buf, pattern, key) => {
62
+ buf[key] = getDependencyValue(field, pattern)
63
+ return buf
64
+ },
65
+ {} as Record<string, any>
66
+ )
67
+ }
68
+ return []
69
+ }
70
+
71
+ function setSchemaFieldState(options: IFieldStateSetterOptions, demand = false) {
72
+ const { request, target, runner, field, scope } = options || {}
73
+ if (!request) return
74
+ if (target) {
75
+ if (request.state) {
76
+ field.form.setFieldState(target, state =>
77
+ patchCompile(
78
+ state,
79
+ request.state,
80
+ lazyMerge(scope as any, {
81
+ $target: state,
82
+ })
83
+ )
84
+ )
85
+ }
86
+ if (request.schema) {
87
+ field.form.setFieldState(target, state =>
88
+ patchSchemaCompile(
89
+ state,
90
+ request.schema!,
91
+ lazyMerge(scope as any, {
92
+ $target: state,
93
+ }),
94
+ demand
95
+ )
96
+ )
97
+ }
98
+ if (isStr(runner) && runner) {
99
+ field.form.setFieldState(target, state => {
100
+ shallowCompile(
101
+ `{{function(){${runner}}}}`,
102
+ lazyMerge(scope as any, {
103
+ $target: state,
104
+ })
105
+ )()
106
+ })
107
+ }
108
+ } else {
109
+ if (request.state) {
110
+ field.setState(state => patchCompile(state, request.state, scope))
111
+ }
112
+ if (request.schema) {
113
+ field.setState(state => patchSchemaCompile(state, request.schema!, scope, demand))
114
+ }
115
+ if (isStr(runner) && runner) {
116
+ shallowCompile(`{{function(){${runner}}}}`, scope)()
117
+ }
118
+ }
119
+ }
120
+
121
+ function getBaseScope(field: Field, options: ISchemaTransformerOptions = {}) {
122
+ function $observable(target: any) {
123
+ return observable(target)
124
+ }
125
+ function $props(props: any) {
126
+ return field.setComponentProps(props)
127
+ }
128
+ function $effect(tracker: () => void) {
129
+ return autorun(tracker)
130
+ }
131
+ function $memo<T>(callback: () => T) {
132
+ return callback()
133
+ }
134
+ const $self = field
135
+ const $form = field.form
136
+ const $values = field.form.values
137
+ return lazyMerge(
138
+ {
139
+ get $lookup() {
140
+ return options?.scope?.$record ?? $values
141
+ },
142
+ get $records() {
143
+ return field.records
144
+ },
145
+ get $record() {
146
+ const record = field.record
147
+ if (typeof record === 'object') {
148
+ return lazyMerge(record, {
149
+ get $lookup() {
150
+ return options?.scope?.$record ?? $values
151
+ },
152
+ get $index() {
153
+ return field.index
154
+ },
155
+ })
156
+ }
157
+ return record
158
+ },
159
+ get $index() {
160
+ return field.index
161
+ },
162
+ },
163
+ options.scope as any,
164
+ {
165
+ $form,
166
+ $self,
167
+ $observable,
168
+ $effect,
169
+ $memo,
170
+ $props,
171
+ $values,
172
+ }
173
+ )
174
+ }
175
+
176
+ function getBaseReactions(schema: ISchema, options: ISchemaTransformerOptions) {
177
+ return (field: Field) => {
178
+ setSchemaFieldState(
179
+ {
180
+ field,
181
+ request: { schema },
182
+ scope: getBaseScope(field, options),
183
+ },
184
+ true
185
+ )
186
+ }
187
+ }
188
+
189
+ function getUserReactions(schema: ISchema, options: ISchemaTransformerOptions) {
190
+ const reactions: SchemaReaction[] = toArr(schema['reactions'])
191
+ return reactions.map(unCompiled => {
192
+ return (field: Field) => {
193
+ const baseScope = getBaseScope(field, options)
194
+ const reaction: any = shallowCompile(unCompiled, baseScope)
195
+ if (!reaction) return
196
+ if (isFn(reaction)) {
197
+ return reaction(field, baseScope)
198
+ }
199
+ const { when, fulfill, otherwise, target, effects } = reaction
200
+ function run() {
201
+ const $deps = getDependencies(field, reaction.dependencies)
202
+ const $dependencies = $deps
203
+ const scope = lazyMerge(baseScope, {
204
+ $target: null,
205
+ $deps,
206
+ $dependencies,
207
+ })
208
+ const compiledWhen = shallowCompile(when, scope)
209
+ const condition = when ? compiledWhen : true
210
+ const request = condition ? fulfill : otherwise
211
+ const runner = request?.run
212
+ setSchemaFieldState({
213
+ field,
214
+ target,
215
+ request,
216
+ runner,
217
+ scope,
218
+ })
219
+ }
220
+
221
+ if (target) {
222
+ reaction.effects = effects?.length ? effects : DefaultFieldEffects
223
+ }
224
+ if (reaction.effects) {
225
+ // 等价于 formily 的 autorun.memo(..., []):每个 reaction 只注册一次监听
226
+ if (!reaction.__effectRegistered) {
227
+ reaction.__effectRegistered = true
228
+ untracked(() => {
229
+ each(reaction.effects, (type: string) => {
230
+ if (FieldEffects[type]) {
231
+ FieldEffects[type](field.address, run)
232
+ }
233
+ })
234
+ })
235
+ }
236
+ } else {
237
+ run()
238
+ }
239
+ }
240
+ })
241
+ }
242
+
243
+ export function transformFieldProps(
244
+ schema: Schema,
245
+ options: ISchemaTransformerOptions = {}
246
+ ): IFieldFactoryProps<any, any> {
247
+ return {
248
+ name: schema.name as any,
249
+ reactions: [getBaseReactions(schema, options)].concat(getUserReactions(schema, options)),
250
+ }
251
+ }