subman-nextjs/src/app/ui/forms/story.tsx

116 lines
2.8 KiB
TypeScript

"use client"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { toast } from "@/components/ui/use-toast"
import { ComponentProps, SetStateAction } from "react"
import { Genre, Story } from "@prisma/client"
import { randomStoryTitle } from "app/lib/shortStoryTitleGenerator"
import GenrePicker from "./genrePicker"
import { useRouter } from "next/navigation"
import { Ban, Cross } from "lucide-react"
export const formSchema = z.object({
id: z.number().optional(),
title: z.string().min(2).max(50),
word_count: z.coerce.number().min(100),
genres: z.array(z.number())
})
export default function StoryForm({ genres, createStory, className, closeDialog }: ComponentProps<"div"> & { genres: Array<Genre>, createStory: (data: any) => void, className: string, closeDialog: () => void }) {
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
word_count: 500,
genres: []
},
})
const router = useRouter()
async function onSubmit(values: z.infer<typeof formSchema>) {
try {
const res = await createStory(values)
//server actions return undefined if middleware authentication fails
if (!res) throw new Error("something went wrong")
toast({ title: "Sucessfully submitted:", description: values.title })
router.refresh()
closeDialog()
} catch (error) {
toast({
title: "Oh dear... ",
description: error.message
})
}
}
function onErrors(errors) {
toast({
description: (<Ban />)
})
console.log(JSON.stringify(errors))
}
return (
<div className={className}>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit, onErrors)} className="space-y-8" id="storyform">
<FormField
control={form.control}
name="title"
render={({ field }) => (
<FormItem>
<FormLabel>Title</FormLabel>
<FormControl>
<Input placeholder={randomStoryTitle()} {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="inline-flex flex-wrap w-full gap-x-16 gap-y-8 items-baseline max-w-full">
<GenrePicker
genres={genres}
form={form}
/>
<FormField
control={form.control}
name="word_count"
render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel className="h-5">Word count</FormLabel>
<FormControl>
<Input className=" w-24" type="number" step={500} {...field}></Input>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</form>
</Form>
</div>
)
}