-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
ReactiveField.ts
259 lines (235 loc) 路 7.69 KB
/
ReactiveField.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import { inject, provide, Ref, ref, shallowRef, watch, isVue2 } from 'vue-demi'
import { GeneralField, isVoidField } from '@formily/core'
import { each, FormPath } from '@formily/shared'
import { observer } from '@formily/reactive-vue'
import { toJS, reaction } from '@formily/reactive'
import { SchemaOptionsSymbol, FieldSymbol, h, Fragment } from '../shared'
import { useAttach } from '../hooks/useAttach'
import { useField, useForm } from '../hooks'
import type {
IReactiveFieldProps,
VueComponentProps,
DefineComponent,
} from '../types'
import type { VNode } from 'vue'
function isVueOptions(options: Record<string, unknown>) {
return (
typeof options.template === 'string' ||
typeof options.render === 'function' ||
typeof options.setup === 'function'
)
}
const wrapFragment = (childNodes: VNode[] | VNode): VNode => {
if (!Array.isArray(childNodes)) {
return childNodes
}
if (childNodes.length > 1) {
return h(Fragment, {}, { default: () => childNodes })
}
return childNodes[0]
}
const resolveComponent = (render: () => unknown[], extra?: any) => {
if (extra === undefined || extra === null) {
return render
}
if (typeof extra === 'string') {
return () => [...render(), extra]
}
// not component
if (!isVueOptions(extra) && typeof extra !== 'function') {
return render
}
// for scoped slot
if (extra.length > 1 || extra?.render?.length > 1) {
return (scopedProps: VueComponentProps<any>) => [
...render(),
h(extra, { props: scopedProps }, {}),
]
}
return () => [...render(), h(extra, {}, {})]
}
const mergeSlots = (
field: GeneralField,
slots: Record<string, any>,
content: any
): Record<string, (...args: any) => any[]> => {
const slotNames = Object.keys(slots)
if (!slotNames.length) {
if (!content) {
return {}
}
if (typeof content === 'string') {
return {
default: resolveComponent(() => [], content),
}
}
}
const patchSlot =
(slotName: string) =>
(...originArgs) =>
slots[slotName]?.({ field, form: field.form, ...originArgs[0] }) ?? []
const patchedSlots: Record<string, (...args: any) => unknown[]> = {}
slotNames.forEach((name) => {
patchedSlots[name] = patchSlot(name)
})
// for named slots
if (content && typeof content === 'object' && !isVueOptions(content)) {
Object.keys(content).forEach((key) => {
const child = content[key]
const slot = patchedSlots[key] ?? (() => [])
patchedSlots[key] = resolveComponent(slot, child)
})
return patchedSlots
}
// maybe default slot is empty
patchedSlots['default'] = resolveComponent(
patchedSlots['default'] ?? (() => []),
content
)
return patchedSlots
}
const createFieldInVue2 = (innerCreateField) => {
return () => {
let res: GeneralField
const disposer = reaction(() => {
res = innerCreateField()
})
disposer()
return res
}
}
export default observer({
name: 'ReactiveField',
props: {
fieldType: {
type: String,
default: 'Field',
},
fieldProps: {
type: Object,
default: () => ({}),
},
},
setup(props: IReactiveFieldProps, { slots }) {
const formRef = useForm()
const parentRef = useField()
const optionsRef = inject(SchemaOptionsSymbol, ref(null))
let createField = () =>
formRef?.value?.[`create${props.fieldType}`]?.({
...props.fieldProps,
basePath: props.fieldProps?.basePath ?? parentRef.value?.address,
})
if (isVue2) {
createField = createFieldInVue2(createField)
}
const fieldRef = shallowRef(createField()) as Ref<GeneralField>
watch(
() => props.fieldProps,
() => (fieldRef.value = createField())
)
useAttach(fieldRef)
provide(FieldSymbol, fieldRef)
return () => {
const field = fieldRef.value
const options = optionsRef.value
if (!field) {
return slots.default?.()
}
if (field.display !== 'visible') {
return h('template', {}, {})
}
const mergedSlots = mergeSlots(field, slots, field.content)
const renderDecorator = (childNodes: any[]) => {
if (!field.decoratorType) {
return wrapFragment(childNodes)
}
const finalComponent =
FormPath.getIn(options?.components, field.decoratorType as string) ??
field.decoratorType
const componentAttrs = toJS(field.decorator[1]) || {}
const events: Record<string, any> = {}
each(componentAttrs, (value, eventKey) => {
const onEvent = eventKey.startsWith('on')
const atEvent = eventKey.startsWith('@')
if (!onEvent && !atEvent) return
if (onEvent) {
const eventName = `${eventKey[2].toLowerCase()}${eventKey.slice(3)}`
// '@xxx' has higher priority
events[eventName] = events[eventName] || value
} else if (atEvent) {
const eventName = eventKey.slice(1)
events[eventName] = value
delete componentAttrs[eventKey]
}
})
const componentData = {
attrs: componentAttrs,
style: componentAttrs?.style,
class: componentAttrs?.class,
on: events,
}
delete componentData.attrs.style
delete componentData.attrs.class
return h(finalComponent, componentData, {
default: () => childNodes,
})
}
const renderComponent = () => {
if (!field.componentType) return wrapFragment(mergedSlots?.default?.())
const component =
FormPath.getIn(options?.components, field.componentType as string) ??
field.componentType
const originData = toJS(field.component[1]) || {}
const events = {} as Record<string, any>
const originChange = originData['@change'] || originData['onChange']
const originFocus = originData['@focus'] || originData['onFocus']
const originBlur = originData['@blur'] || originData['onBlur']
each(originData, (value, eventKey) => {
const onEvent = eventKey.startsWith('on')
const atEvent = eventKey.startsWith('@')
if (!onEvent && !atEvent) return
if (onEvent) {
const eventName = `${eventKey[2].toLowerCase()}${eventKey.slice(3)}`
// '@xxx' has higher priority
events[eventName] = events[eventName] || value
} else if (atEvent) {
const eventName = eventKey.slice(1)
events[eventName] = value
delete originData[eventKey]
}
})
events.change = (...args: any[]) => {
if (!isVoidField(field)) field.onInput(...args)
originChange?.(...args)
}
events.focus = (...args: any[]) => {
if (!isVoidField(field)) field.onFocus(...args)
originFocus?.(...args)
}
events.blur = (...args: any[]) => {
if (!isVoidField(field)) field.onBlur(...args)
originBlur?.(...args)
}
const componentData = {
attrs: {
disabled: !isVoidField(field)
? field.pattern === 'disabled' || field.pattern === 'readPretty'
: undefined,
readOnly: !isVoidField(field)
? field.pattern === 'readOnly'
: undefined,
...originData,
value: !isVoidField(field) ? field.value : undefined,
},
style: originData?.style,
class: originData?.class,
on: events,
}
delete componentData.attrs.style
delete componentData.attrs.class
return h(component, componentData, mergedSlots)
}
return renderDecorator([renderComponent()])
}
},
} as unknown as DefineComponent<IReactiveFieldProps>)