169 lines
5.9 KiB
TypeScript
169 lines
5.9 KiB
TypeScript
import React from 'react';
|
|
import { useParams, useNavigate } from 'react-router-dom';
|
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
import { useForm, Controller } from 'react-hook-form';
|
|
import { zodResolver } from '@hookform/resolvers/zod';
|
|
import { z } from 'zod';
|
|
import { toast } from 'sonner';
|
|
import { api } from '../lib/api';
|
|
import type { ApiResponse } from '../lib/api';
|
|
import type { Blog } from '../types';
|
|
import PageHeader from '../components/ui/PageHeader';
|
|
|
|
const schema = z.object({
|
|
title: z.string().min(3, 'عنوان الزامی است'),
|
|
summary: z.string().optional(),
|
|
content: z.string().min(10, 'محتوا الزامی است'),
|
|
tags: z.string().optional(),
|
|
status: z.enum(['draft', 'published']),
|
|
});
|
|
type FormData = z.infer<typeof schema>;
|
|
|
|
export default function BlogFormPage() {
|
|
const { uuid } = useParams<{ uuid: string }>();
|
|
const navigate = useNavigate();
|
|
const qc = useQueryClient();
|
|
const isEdit = !!uuid;
|
|
|
|
const { data, isLoading } = useQuery({
|
|
queryKey: ['blog', uuid],
|
|
queryFn: () => api.get<ApiResponse<Blog>>(`/api/v1/blog/${uuid}`),
|
|
enabled: isEdit,
|
|
});
|
|
|
|
const blog = data?.data;
|
|
|
|
const { register, handleSubmit, control, reset, formState: { errors, isSubmitting } } = useForm<FormData>({
|
|
resolver: zodResolver(schema),
|
|
defaultValues: { status: 'draft' },
|
|
values: blog
|
|
? {
|
|
title: blog.title,
|
|
summary: blog.summary ?? '',
|
|
content: blog.content,
|
|
tags: blog.tags?.join(', ') ?? '',
|
|
status: blog.status,
|
|
}
|
|
: undefined,
|
|
});
|
|
|
|
const createMutation = useMutation({
|
|
mutationFn: (d: FormData) =>
|
|
api.post<ApiResponse<Blog>>('/api/v1/blog', {
|
|
...d,
|
|
tags: d.tags ? d.tags.split(',').map((t) => t.trim()).filter(Boolean) : [],
|
|
}),
|
|
onSuccess: () => {
|
|
toast.success('مقاله ذخیره شد');
|
|
qc.invalidateQueries({ queryKey: ['blogs'] });
|
|
navigate('/admin/blogs');
|
|
},
|
|
onError: (err: Error) => toast.error(err.message),
|
|
});
|
|
|
|
const updateMutation = useMutation({
|
|
mutationFn: (d: FormData) =>
|
|
api.patch<ApiResponse<Blog>>(`/api/v1/blog/${uuid}`, {
|
|
...d,
|
|
tags: d.tags ? d.tags.split(',').map((t) => t.trim()).filter(Boolean) : [],
|
|
}),
|
|
onSuccess: () => {
|
|
toast.success('مقاله بروزرسانی شد');
|
|
qc.invalidateQueries({ queryKey: ['blogs'] });
|
|
qc.invalidateQueries({ queryKey: ['blog', uuid] });
|
|
navigate('/admin/blogs');
|
|
},
|
|
onError: (err: Error) => toast.error(err.message),
|
|
});
|
|
|
|
const onSubmit = (d: FormData) => {
|
|
if (isEdit) updateMutation.mutate(d);
|
|
else createMutation.mutate(d);
|
|
};
|
|
|
|
if (isEdit && isLoading) {
|
|
return (
|
|
<div className="cp-card p-6 space-y-3">
|
|
{Array.from({ length: 5 }).map((_, i) => (
|
|
<div key={i} className="h-10 rounded-lg skeleton" />
|
|
))}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div>
|
|
<PageHeader
|
|
title={isEdit ? 'ویرایش مقاله' : 'نوشتن مقاله جدید'}
|
|
breadcrumbs={[
|
|
{ label: 'داشبورد', to: '/admin/dashboard' },
|
|
{ label: 'بلاگ', to: '/admin/blogs' },
|
|
{ label: isEdit ? 'ویرایش' : 'جدید' },
|
|
]}
|
|
/>
|
|
|
|
<div className="cp-card p-6">
|
|
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
|
|
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
|
<div className="lg:col-span-2 space-y-5">
|
|
<div>
|
|
<label className="">عنوان مقاله *</label>
|
|
<input {...register('title')} placeholder="عنوان جذاب بنویسید..."
|
|
className="cp-input h-11" />
|
|
{errors.title && <p className="text-red-500 text-xs mt-1">{errors.title.message}</p>}
|
|
</div>
|
|
|
|
<div>
|
|
<label className="">خلاصه</label>
|
|
<textarea {...register('summary')} rows={2} placeholder="خلاصه کوتاه مقاله..."
|
|
className="input resize-none" />
|
|
</div>
|
|
|
|
<div>
|
|
<label className="">محتوا *</label>
|
|
<textarea {...register('content')} rows={16} placeholder="محتوای مقاله را بنویسید..."
|
|
className="input resize-none font-mono" />
|
|
{errors.content && <p className="text-red-500 text-xs mt-1">{errors.content.message}</p>}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="space-y-5">
|
|
<div>
|
|
<label className="">وضعیت انتشار</label>
|
|
<Controller
|
|
control={control}
|
|
name="status"
|
|
render={({ field }) => (
|
|
<select {...field}
|
|
className="cp-input h-11">
|
|
<option value="draft">پیشنویس</option>
|
|
<option value="published">منتشر</option>
|
|
</select>
|
|
)}
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="">تگها (با ویرگول جدا کنید)</label>
|
|
<input {...register('tags')} dir="ltr" placeholder="tag1, tag2, tag3"
|
|
className="cp-input h-11" />
|
|
</div>
|
|
|
|
<div className="pt-4 space-y-3">
|
|
<button type="submit" disabled={isSubmitting}
|
|
className="cp-btn-primary w-full justify-center py-2.5">
|
|
{isSubmitting ? 'در حال ذخیره...' : isEdit ? 'بروزرسانی' : 'ذخیره'}
|
|
</button>
|
|
<button type="button" onClick={() => navigate('/admin/blogs')}
|
|
className="cp-btn-secondary w-full justify-center py-2.5">
|
|
لغو
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|