import { useForm } from "@tanstack/react-form"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Button } from "@/components/ui/button"; import { Progress } from "@/components/ui/progress"; import type { AxiosProgressEvent } from "axios"; import { useState } from "react"; import { toast } from "sonner"; interface UploadVersionFormProps { onSubmit: (fd: FormData, config?: { onUploadProgress: (e: AxiosProgressEvent) => void }) => Promise; closeDialog: () => void; } export function UploadVersionForm({ onSubmit, closeDialog }: UploadVersionFormProps) { const [uploadPercent, setUploadPercent] = useState(0); const [isUploading, setIsUploading] = useState(false); const [isDone, setIsDone] = useState(false); const form = useForm({ defaultValues: { files: new DataTransfer().files, newVersion: "" }, onSubmit: async ({ value }) => { if (!value.newVersion || value.files.length === 0) { toast.error("Vui lòng điền đầy đủ thông tin"); return; } try { setIsUploading(true); setUploadPercent(0); setIsDone(false); const fd = new FormData(); Array.from(value.files).forEach((f) => fd.append("FileInput", f)); fd.append("Version", value.newVersion); await onSubmit(fd, { onUploadProgress: (e: AxiosProgressEvent) => { if (e.total) { const progress = Math.round((e.loaded * 100) / e.total); setUploadPercent(progress); } }, }); setIsDone(true); } catch (error) { console.error("Upload error:", error); toast.error("Upload thất bại!"); } finally { setIsUploading(false); } }, }); return (
{ e.preventDefault(); form.handleSubmit(); }} > {(field) => (
field.handleChange(e.target.value)} placeholder="1.0.0" disabled={isUploading || isDone} />
)}
{(field) => (
e.target.files && field.handleChange(e.target.files)} disabled={isUploading || isDone} />
)}
{(uploadPercent > 0 || isUploading || isDone) && (
{isDone ? "Hoàn tất!" : "Đang tải lên..."} {uploadPercent}%
)}
{!isDone ? ( <> ) : ( )}
); }