import React, { Fragment, useMemo } from 'react' import { FormPath, isBool, isFn, isValid } from '@formily/shared' import { GeneralField } from '@formily/core' import { Schema } from '@formily/json-schema' import { SchemaContext } from '../shared' import { IRecursionFieldProps, ReactFC } from '../types' import { useField, useExpressionScope } from '../hooks' import { ObjectField } from './ObjectField' import { ArrayField } from './ArrayField' import { Field } from './Field' import { VoidField } from './VoidField' import { ExpressionScope } from './ExpressionScope' import { observable } from '@formily/reactive' const useFieldProps = (schema: Schema) => { const scope = useExpressionScope() return schema.toFieldProps({ scope, }) as any } const useBasePath = (props: IRecursionFieldProps) => { const parent = useField() if (props.onlyRenderProperties) { return props.basePath || parent?.address.concat(props.name) } return props.basePath || parent?.address } export const RecursionField: ReactFC = (props) => { const basePath = useBasePath(props) const fieldSchema = useMemo(() => new Schema(props.schema), [props.schema]) const fieldProps = useFieldProps(fieldSchema) const renderSlots = (innerSchema, key) => { const slot = innerSchema['x-slot-node'] const { target, isRenderProp } = slot if (isRenderProp) { const args = observable({ $slotArgs: [] }) FormPath.setIn(fieldSchema.properties, target, (..._args: any) => { args.$slotArgs = _args return ( ) }) } else { FormPath.setIn( fieldSchema.properties, target, ) } } const renderProperties = (field?: GeneralField) => { if (props.onlyRenderSelf) return const properties = Schema.getOrderProperties(fieldSchema) if (!properties.length) return return ( {properties.map(({ schema: item, key: name }, index) => { const base = field?.address || basePath let schema: Schema = item if (schema['x-slot-node']) { renderSlots(schema, name) return null } if (isFn(props.mapProperties)) { const mapped = props.mapProperties(item, name) if (mapped) { schema = mapped } } if (isFn(props.filterProperties)) { if (props.filterProperties(schema, name) === false) { return null } } if (isBool(props.propsRecursion) && props.propsRecursion) { return ( ) } return ( ) })} ) } const render = () => { if (!isValid(props.name)) return renderProperties() if (fieldSchema.type === 'object') { if (props.onlyRenderProperties) return renderProperties() return ( {renderProperties} ) } else if (fieldSchema.type === 'array') { return ( ) } else if (fieldSchema.type === 'void') { if (props.onlyRenderProperties) return renderProperties() return ( {renderProperties} ) } return } if (!fieldSchema) return return ( {render()} ) }