'use client'; import { saveArticle } from '@/lib/feature/article/article.external'; import { Button } from '@/ui/components/shadcn/button'; import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel, } from '@/ui/components/shadcn/field'; import { Input } from '@/ui/components/shadcn/input'; import { InputGroup, InputGroupTextarea, } from '@/ui/components/shadcn/input-group'; import { zodResolver } from '@hookform/resolvers/zod'; import { useCallback, useEffect, useRef } from 'react'; import { Controller, useForm, useWatch } from 'react-hook-form'; import slugify from 'slugify'; import { toast } from 'sonner'; import { z } from 'zod'; export const CreateArticleForm = () => { const fileInputRef = useRef(null); const formSchema = z.object({ title: z.string().min(3).max(255), slug: z.string().min(3), description: z.string().min(10), coverImageUrl: z.url(), content: z.instanceof(File), }); const form = useForm>({ resolver: zodResolver(formSchema), defaultValues: { title: '', slug: '', description: '', coverImageUrl: '', content: undefined, }, }); const title = useWatch({ control: form.control, name: 'title', }); useEffect(() => { if (!title) return; form.setValue('slug', slugify(title).toLowerCase()); }, [form, title]); const handleFormSubmit = useCallback( async (data: z.infer) => { try { const result = await saveArticle({ ...data, content: await data.content.text(), }); toast.success('Article created successfully!', { description: `Article "${result.title}" has been created.`, position: 'bottom-right', }); form.reset(); if (fileInputRef.current) { fileInputRef.current.value = ''; } } catch (error) { toast.error('Failed to create article', { description: error instanceof Error ? error.message : 'An error occurred', position: 'bottom-right', }); } }, [form] ); return (
( Title {fieldState.invalid && ( )} )} /> ( Slug {fieldState.invalid && ( )} )} /> ( Description {fieldState.invalid && ( )} )} /> ( Cover Image URL {fieldState.invalid && ( )} )} /> ( Content (Markdown File) field.onChange( event.target.files && event.target.files[0] ) } /> Select your article. {fieldState.invalid && ( )} )} />
); }; export default CreateArticleForm;