import { Button } from '@heroui/button'; import { Input } from '@heroui/input'; import { ModalBody, ModalFooter } from '@heroui/modal'; import { Select, SelectItem } from '@heroui/select'; import { ReactElement, useEffect } from 'react'; import { Controller, useForm } from 'react-hook-form'; import type { DefaultValues, Path, PathValue, SubmitHandler, } from 'react-hook-form'; import toast from 'react-hot-toast'; import SwitchCard from '../switch_card'; export type FieldTypes = 'input' | 'select' | 'switch'; type NetworkConfigType = OneBotConfig['network']; export interface Field { name: keyof NetworkConfigType[T][0]; label: string; type: FieldTypes; options?: Array<{ key: string; value: string; }>; placeholder?: string; isRequired?: boolean; isDisabled?: boolean; description?: string; colSpan?: 1 | 2; } export interface GenericFormProps { data?: NetworkConfigType[T][0]; defaultValues: DefaultValues; onClose: () => void; onSubmit: (data: NetworkConfigType[T][0]) => Promise; fields: Array>; } const GenericForm = ({ data, defaultValues, onClose, onSubmit, fields, }: GenericFormProps): ReactElement => { const { control, handleSubmit, formState, setValue, reset } = useForm< NetworkConfigType[T][0] >({ defaultValues, }); const submitAction: SubmitHandler = async (data) => { await onSubmit(data); onClose(); }; const _onSubmit = handleSubmit(submitAction, (e) => { const errors = Object.values(e); if (errors.length > 0) { toast.error(errors[0]?.message as string); } }); useEffect(() => { if (data) { const keys = Object.keys(data) as Path[]; for (const key of keys) { const value = data[key] as PathValue< NetworkConfig[T][0], Path >; setValue(key, value); } } else { reset(); } }, [data, reset, setValue]); return ( <>
{fields.map((field) => (
} rules={ field.isRequired ? { required: `请填写${field.label}`, } : undefined } render={({ field: controllerField }) => { switch (field.type) { case 'input': return ( controllerField.onChange(value)} ref={controllerField.ref} isRequired={field.isRequired} isDisabled={field.isDisabled} label={field.label} placeholder={field.placeholder} /> ); case 'select': return ( ); case 'switch': return ( ); default: return <>; } }} />
))}
); }; export default GenericForm; export function random_token (length: number) { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$%^&*()-_=+[]{}|;:,.<>?'; let result = ''; for (let i = 0; i < length; i++) { result += chars.charAt(Math.floor(Math.random() * chars.length)); } return result; }