"use client"; import * as z from "zod"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Badge } from "@/components/ui/badge"; import { X } from "lucide-react"; import { set } from "date-fns"; const formSchema = z.object({ name: z.string().min(2, { message: "Name must be at least 2 characters.", }), description: z.string().min(2, { message: "Description must be at least 2 characters.", }), stack: z.array(z.string()).min(1, { message: "Project tech stack must have at least one item.", }), }); export function CreateProject({ workspaceID }: { workspaceID: string }) { const form = useForm>({ resolver: zodResolver(formSchema), defaultValues: { name: "", description: "", stack: [], }, }); const { setValue } = form; const [stackInput, setStackInput] = useState(""); const [isLoading, setIsLoading] = useState(false); const router = useRouter(); async function onSubmit(values: z.infer) { try { setIsLoading(true); const res = await fetch(`/w/${workspaceID}/p`, { method: "POST", body: JSON.stringify(values), }); console.log("===>", res); if (!res.ok) throw new Error("Something went wrong."); router.refresh(); setIsLoading(false); return res; } catch (err) { setIsLoading(false); console.error(err); } } const keyHandler = (e: React.KeyboardEvent) => { if ((e.key === "Enter" || e.key === "Tab") && stackInput !== "") { e.preventDefault(); setValue("stack", [...form.getValues("stack"), stackInput]); setStackInput(""); } }; return ( Create a Project Give your project a name, description, and tech stack.
( Name This is your project name. )} /> ( Description This is your project description. )} /> ( Tech Stack setStackInput(e.target.value)} onKeyDown={keyHandler} /> This is your project tech stack.
{form.getValues("stack").map((stack) => ( {stack} setValue( "stack", form.getValues("stack").filter((s) => s !== stack) ) } /> ))}
)} />
); }