import { useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { UploadOutlined as UploadOutlinedIcon } from "@ant-design/icons"; import { Button, Form, type FormInstance, Input, InputNumber, Upload, type UploadFile, type UploadProps } from "antd"; import { createSchemaFieldRule } from "antd-zod"; import { z } from "zod"; import { type AccessConfigForSSH } from "@/domain/access"; import { readFileContent } from "@/utils/file"; import { validDomainName, validIPv4Address, validIPv6Address, validPortNumber } from "@/utils/validators"; type AccessFormSSHConfigFieldValues = Nullish; export type AccessFormSSHConfigProps = { form: FormInstance; formName: string; disabled?: boolean; initialValues?: AccessFormSSHConfigFieldValues; onValuesChange?: (values: AccessFormSSHConfigFieldValues) => void; }; const initFormModel = (): AccessFormSSHConfigFieldValues => { return { host: "127.0.0.1", port: 22, username: "root", }; }; const AccessFormSSHConfig = ({ form: formInst, formName, disabled, initialValues, onValuesChange }: AccessFormSSHConfigProps) => { const { t } = useTranslation(); const formSchema = z.object({ host: z.string().refine((v) => validDomainName(v) || validIPv4Address(v) || validIPv6Address(v), t("common.errmsg.host_invalid")), port: z.preprocess( (v) => Number(v), z .number() .int(t("access.form.ssh_port.placeholder")) .refine((v) => validPortNumber(v), t("common.errmsg.port_invalid")) ), username: z .string() .min(1, "access.form.ssh_username.placeholder") .max(64, t("common.errmsg.string_max", { max: 64 })), password: z .string() .max(64, t("common.errmsg.string_max", { max: 64 })) .nullish(), key: z .string() .max(20480, t("common.errmsg.string_max", { max: 20480 })) .nullish(), keyPassphrase: z .string() .max(20480, t("common.errmsg.string_max", { max: 20480 })) .nullish() .refine((v) => !v || formInst.getFieldValue("key"), t("access.form.ssh_key.placeholder")), }); const formRule = createSchemaFieldRule(formSchema); const fieldKey = Form.useWatch("key", formInst); const [fieldKeyFileList, setFieldKeyFileList] = useState([]); useEffect(() => { setFieldKeyFileList(initialValues?.key?.trim() ? [{ uid: "-1", name: "sshkey", status: "done" }] : []); }, [initialValues?.key]); const handleKeyFileChange: UploadProps["onChange"] = async ({ file }) => { if (file && file.status !== "removed") { formInst.setFieldValue("key", await readFileContent(file.originFileObj ?? (file as unknown as File))); setFieldKeyFileList([file]); } else { formInst.setFieldValue("key", ""); setFieldKeyFileList([]); } onValuesChange?.(formInst.getFieldsValue(true)); }; const handleFormChange = (_: unknown, values: z.infer) => { onValuesChange?.(values); }; return (
} >
}> false} fileList={fieldKeyFileList} maxCount={1} onChange={handleKeyFileChange}>
} >
); }; export default AccessFormSSHConfig;