import { useEffect, useState } from "react"; import { createPortal } from "react-dom"; import { useForm } from "react-hook-form"; import { z } from "zod"; import { zodResolver } from "@hookform/resolvers/zod"; import { useAddVolumeMutation, useUpdateVolumeMutation, useVolumeQuery, } from "../../../hooks/useVolume"; import { useNotyf } from "../../../hooks/useNotyf"; const schema = z.object({ name: z.string().min(1, "Name is required"), path: z.string().min(1, "Path is required"), }); type FormValues = z.infer; export type AddVolumeModalProps = { isOpen: boolean; onClose: () => void; sandboxId: string; volumeId?: string; }; function AddVolumeModal({ isOpen, onClose, sandboxId, volumeId, }: AddVolumeModalProps) { const notyf = useNotyf(); const [isLoading, setIsLoading] = useState(false); const { mutateAsync: addVolume } = useAddVolumeMutation(); const { mutateAsync: updateVolume } = useUpdateVolumeMutation(); const { data } = useVolumeQuery(volumeId!); const { register, handleSubmit, reset, setValue, formState: { errors }, } = useForm({ resolver: zodResolver(schema), }); useEffect(() => { if (data) { setValue("name", data.volume.name); setValue("path", data.volume.path); } }, [data, setValue]); useEffect(() => { const handleEscapeKey = (event: KeyboardEvent) => { if (event.key === "Escape" && isOpen) { reset(); onClose(); } }; document.addEventListener("keydown", handleEscapeKey); return () => { document.removeEventListener("keydown", handleEscapeKey); }; }, [isOpen, onClose, reset]); const handleBackdropClick = (e: React.MouseEvent) => { e.stopPropagation(); if (e.target === e.currentTarget) { reset(); onClose(); } }; const handleContentClick = (e: React.MouseEvent) => { e.stopPropagation(); }; const handleCloseButton = (e: React.MouseEvent) => { e.stopPropagation(); reset(); onClose(); }; const onSubmit = async (data: FormValues) => { setIsLoading(true); try { if (volumeId) { await updateVolume({ id: volumeId, name: data.name, path: data.path, sandboxId, }); setIsLoading(false); reset(); onClose(); notyf.open("primary", "Volume updated successfully!"); return; } await addVolume({ sandboxId, name: data.name, path: data.path, }); setIsLoading(false); reset(); onClose(); notyf.open("primary", "Volume added successfully"); } catch { setIsLoading(false); reset(); onClose(); notyf.open("error", "Failed to add volume"); } }; if (!isOpen) return null; return createPortal( <>
{volumeId ? "Edit Volume" : "Add Volume"}
{errors.name && ( {errors.name.message} )}
{errors.path && ( {errors.path.message} )}
e.stopPropagation()} >
, document.body, ); } export default AddVolumeModal;