import { useEffect, useMemo, useState } from 'react' import { Textarea } from '@/components/ui/textarea' import type { FieldHookComponent } from '@/lib/field-hooks' import type { ConfigSchema, FieldSchema } from '@/types/config-schema' interface JsonFieldHookOptions { emptyValue: unknown helperText: string placeholder: string } function resolveLabel(schema?: ConfigSchema | FieldSchema, fieldPath?: string): string { if (!schema) { return fieldPath?.split('.').at(-1) || 'JSON 配置' } if ('label' in schema && schema.label) { return schema.label } if ('uiLabel' in schema && schema.uiLabel) { return schema.uiLabel } if ('classDoc' in schema && schema.classDoc) { return schema.classDoc } if ('className' in schema && schema.className) { return schema.className } return fieldPath?.split('.').at(-1) || 'JSON 配置' } function resolveDescription(schema?: ConfigSchema | FieldSchema): string { if (!schema) { return '' } if ('description' in schema) { return schema.description || '' } if ('classDoc' in schema) { return schema.classDoc || '' } return '' } export function createJsonFieldHook(options: JsonFieldHookOptions): FieldHookComponent { const JsonFieldHook: FieldHookComponent = ({ fieldPath, onChange, schema, value }) => { const normalizedValue = useMemo(() => { if (value === undefined) { return options.emptyValue } return value }, [value]) const [editorValue, setEditorValue] = useState(() => JSON.stringify(normalizedValue, null, 2)) const [errorMessage, setErrorMessage] = useState('') useEffect(() => { setEditorValue(JSON.stringify(normalizedValue, null, 2)) setErrorMessage('') }, [normalizedValue]) const label = resolveLabel(schema, fieldPath) const description = resolveDescription(schema) return (

{label}

{description && (

{description}

)}

{options.helperText}