File size: 2,663 Bytes
3318ac7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | "use client";
import { useState, useCallback } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { analyzeStep } from "@/lib/api";
import { AnalysisResponse, AnalyzeFormInputs } from "@/lib/types";
const AnalyzeFormSchema = z.object({
material: z.string().min(1, "Material is required"),
tolerance: z.string().min(1, "Tolerance is required"),
threads: z.string(),
});
type FormSchemaType = z.infer<typeof AnalyzeFormSchema>;
export function useAnalyze() {
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [result, setResult] = useState<AnalysisResponse | null>(null);
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const form = useForm<FormSchemaType>({
resolver: zodResolver(AnalyzeFormSchema),
defaultValues: {
material: "",
tolerance: "",
threads: "",
},
});
const handleFileSelect = useCallback((file: File) => {
const validExtensions = [".step", ".stp"];
const hasValidExtension = validExtensions.some((ext) =>
file.name.toLowerCase().endsWith(ext)
);
if (!hasValidExtension) {
setError("Invalid file type. Please upload a .step or .stp file.");
setSelectedFile(null);
return;
}
setSelectedFile(file);
setError(null);
}, []);
const handleFileRemove = useCallback(() => {
setSelectedFile(null);
setError(null);
}, []);
const onSubmit = async (data: FormSchemaType) => {
if (!selectedFile) {
setError("Please select a STEP file to analyze.");
return;
}
setIsLoading(true);
setError(null);
setResult(null);
try {
const formData = new FormData();
formData.append("file", selectedFile);
formData.append("material", data.material);
formData.append("tolerance", data.tolerance);
if (data.threads) {
formData.append("threads", data.threads);
}
const response = await analyzeStep(formData);
setResult(response);
} catch (err) {
const message =
err instanceof Error ? err.message : "Failed to analyze file";
setError(message);
setResult(null);
} finally {
setIsLoading(false);
}
};
const resetAnalysis = useCallback(() => {
setSelectedFile(null);
setResult(null);
setError(null);
form.reset();
}, [form]);
return {
form,
selectedFile,
handleFileSelect,
handleFileRemove,
onSubmit: form.handleSubmit(onSubmit),
result,
error,
isLoading,
resetAnalysis,
};
}
|