Refactor code structure for improved readability and maintainability
This commit is contained in:
@@ -1,30 +1,54 @@
|
||||
import React from 'react';
|
||||
import React, { useState } 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 { CKEditor } from '@ckeditor/ckeditor5-react';
|
||||
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
|
||||
import { api } from '../lib/api';
|
||||
import type { ApiResponse } from '../lib/api';
|
||||
import type { Blog } from '../types';
|
||||
import { useAuthStore } from '../stores/authStore';
|
||||
import PageHeader from '../components/ui/PageHeader';
|
||||
import SearchableSelect from '../components/ui/SearchableSelect';
|
||||
|
||||
const schema = z.object({
|
||||
title: z.string().min(3, 'عنوان الزامی است'),
|
||||
summary: z.string().optional(),
|
||||
content: z.string().min(10, 'محتوا الزامی است'),
|
||||
body: z.string().min(10, 'محتوا الزامی است'),
|
||||
tags: z.string().optional(),
|
||||
status: z.enum(['draft', 'published']),
|
||||
image_url: z.string().optional(),
|
||||
});
|
||||
type FormData = z.infer<typeof schema>;
|
||||
|
||||
async function uploadBlogImage(file: File): Promise<string> {
|
||||
const token = useAuthStore.getState().token;
|
||||
const fd = new FormData();
|
||||
fd.append('file', file);
|
||||
const res = await fetch('/file/upload/clinic_pro/blog/field_image', {
|
||||
method: 'POST',
|
||||
headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
body: fd,
|
||||
});
|
||||
const json = await res.json().catch(() => ({}));
|
||||
if (res.status === 401) {
|
||||
useAuthStore.getState().logout();
|
||||
window.location.replace('/admin/login');
|
||||
throw new Error('نشست منقضی شده است');
|
||||
}
|
||||
if (!res.ok) throw new Error(json?.errors?.[0]?.message ?? 'خطا در آپلود تصویر');
|
||||
return json.data.image_url as string;
|
||||
}
|
||||
|
||||
export default function BlogFormPage() {
|
||||
const { uuid } = useParams<{ uuid: string }>();
|
||||
const navigate = useNavigate();
|
||||
const qc = useQueryClient();
|
||||
const isEdit = !!uuid;
|
||||
const [uploading, setUploading] = useState(false);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['blog', uuid],
|
||||
@@ -34,26 +58,34 @@ export default function BlogFormPage() {
|
||||
|
||||
const blog = data?.data;
|
||||
|
||||
const { register, handleSubmit, control, reset, formState: { errors, isSubmitting } } = useForm<FormData>({
|
||||
const { register, handleSubmit, control, watch, setValue, formState: { errors, isSubmitting } } = useForm<FormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: { status: 'draft' },
|
||||
values: blog
|
||||
? {
|
||||
title: blog.title,
|
||||
summary: blog.summary ?? '',
|
||||
content: blog.content,
|
||||
body: blog.body,
|
||||
tags: blog.tags?.join(', ') ?? '',
|
||||
status: blog.status,
|
||||
image_url: blog.image_url ?? '',
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
|
||||
const imageUrl = watch('image_url');
|
||||
|
||||
const buildPayload = (d: FormData) => ({
|
||||
title: d.title,
|
||||
body: d.body,
|
||||
summary: d.summary,
|
||||
status: d.status,
|
||||
image_url: d.image_url ?? '',
|
||||
tags: d.tags ? d.tags.split(',').map((t) => t.trim()).filter(Boolean) : [],
|
||||
});
|
||||
|
||||
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) : [],
|
||||
}),
|
||||
mutationFn: (d: FormData) => api.post<ApiResponse<Blog>>('/api/v1/blog', buildPayload(d)),
|
||||
onSuccess: () => {
|
||||
toast.success('مقاله ذخیره شد');
|
||||
qc.invalidateQueries({ queryKey: ['blogs'] });
|
||||
@@ -63,11 +95,7 @@ export default function BlogFormPage() {
|
||||
});
|
||||
|
||||
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) : [],
|
||||
}),
|
||||
mutationFn: (d: FormData) => api.patch<ApiResponse<Blog>>(`/api/v1/blog/${uuid}`, buildPayload(d)),
|
||||
onSuccess: () => {
|
||||
toast.success('مقاله بروزرسانی شد');
|
||||
qc.invalidateQueries({ queryKey: ['blogs'] });
|
||||
@@ -82,6 +110,22 @@ export default function BlogFormPage() {
|
||||
else createMutation.mutate(d);
|
||||
};
|
||||
|
||||
const onImageSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
setUploading(true);
|
||||
try {
|
||||
const url = await uploadBlogImage(file);
|
||||
setValue('image_url', url, { shouldValidate: true });
|
||||
toast.success('تصویر آپلود شد');
|
||||
} catch (err) {
|
||||
toast.error((err as Error).message);
|
||||
} finally {
|
||||
setUploading(false);
|
||||
e.target.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
if (isEdit && isLoading) {
|
||||
return (
|
||||
<div className="cp-card p-6 space-y-3">
|
||||
@@ -122,13 +166,55 @@ export default function BlogFormPage() {
|
||||
|
||||
<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>}
|
||||
<Controller
|
||||
control={control}
|
||||
name="body"
|
||||
render={({ field }) => (
|
||||
<div dir="rtl" className="ck-rtl">
|
||||
<CKEditor
|
||||
editor={ClassicEditor as never}
|
||||
data={field.value ?? ''}
|
||||
onChange={(_evt: unknown, editor: { getData: () => string }) =>
|
||||
field.onChange(editor.getData())
|
||||
}
|
||||
config={{
|
||||
language: 'fa',
|
||||
toolbar: [
|
||||
'heading', '|',
|
||||
'bold', 'italic', 'link', 'bulletedList', 'numberedList', '|',
|
||||
'blockQuote', 'insertTable', '|',
|
||||
'undo', 'redo',
|
||||
],
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
{errors.body && <p className="text-red-500 text-xs mt-1">{errors.body.message}</p>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-5">
|
||||
<div>
|
||||
<label className="">تصویر شاخص</label>
|
||||
{imageUrl ? (
|
||||
<div className="relative">
|
||||
<img src={imageUrl} alt="cover"
|
||||
style={{ width: '100%', height: 160, objectFit: 'cover', borderRadius: 8 }} />
|
||||
<button type="button" onClick={() => setValue('image_url', '', { shouldValidate: true })}
|
||||
className="cp-btn-secondary w-full justify-center py-2 mt-2">
|
||||
حذف تصویر
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<label className="cp-btn-secondary w-full justify-center py-2.5 cursor-pointer"
|
||||
style={{ display: 'flex' }}>
|
||||
{uploading ? 'در حال آپلود...' : 'انتخاب تصویر'}
|
||||
<input type="file" accept="image/*" hidden disabled={uploading} onChange={onImageSelect} />
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="">وضعیت انتشار</label>
|
||||
<Controller
|
||||
|
||||
@@ -6,7 +6,7 @@ import { toast } from 'sonner';
|
||||
import { api } from '../lib/api';
|
||||
import type { ApiResponse, PaginatedResponse } from '../lib/api';
|
||||
import type { Blog } from '../types';
|
||||
import { formatDate, formatNumber } from '../lib/utils';
|
||||
import { formatDate } from '../lib/utils';
|
||||
import DataTable, { Column } from '../components/ui/DataTable';
|
||||
import Pagination from '../components/ui/Pagination';
|
||||
import ConfirmDialog from '../components/ui/ConfirmDialog';
|
||||
@@ -52,8 +52,8 @@ export default function BlogsPage() {
|
||||
header: 'عنوان',
|
||||
render: (b) => (
|
||||
<div className="cell-user">
|
||||
{b.cover_image ? (
|
||||
<img src={b.cover_image} alt="" style={{ width: 40, height: 28, borderRadius: 6, objectFit: 'cover', flexShrink: 0 }} />
|
||||
{b.image_url ? (
|
||||
<img src={b.image_url} alt="" style={{ width: 40, height: 28, borderRadius: 6, objectFit: 'cover', flexShrink: 0 }} />
|
||||
) : (
|
||||
<div style={{ width: 40, height: 28, borderRadius: 6, background: 'var(--surface-3)', flexShrink: 0 }} />
|
||||
)}
|
||||
@@ -63,7 +63,7 @@ export default function BlogsPage() {
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{ key: 'author_name', header: 'نویسنده' },
|
||||
{ key: 'author', header: 'نویسنده', render: (b) => b.author?.name ?? '—' },
|
||||
{
|
||||
key: 'status',
|
||||
header: 'وضعیت',
|
||||
@@ -85,8 +85,7 @@ export default function BlogsPage() {
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{ key: 'views_count', header: 'بازدید', render: (b) => formatNumber(b.views_count) },
|
||||
{ key: 'published_at', header: 'انتشار', render: (b) => formatDate(b.published_at) },
|
||||
{ key: 'created_at', header: 'تاریخ', render: (b) => formatDate(b.created_at) },
|
||||
];
|
||||
|
||||
const items = data?.data ?? [];
|
||||
|
||||
@@ -256,14 +256,13 @@ export interface Blog {
|
||||
title: string;
|
||||
slug: string;
|
||||
summary: string | null;
|
||||
content: string;
|
||||
cover_image: string | null;
|
||||
body: string;
|
||||
image_url: string | null;
|
||||
status: 'draft' | 'published';
|
||||
author_name: string;
|
||||
views_count: number;
|
||||
author?: { uuid: string; name: string } | null;
|
||||
tags: string[];
|
||||
published_at: string | null;
|
||||
created_at: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
export interface Secretary {
|
||||
|
||||
+7
-4
@@ -94,17 +94,19 @@ Create a new blog post.
|
||||
"body": "<p>محتوای کامل مقاله...</p>",
|
||||
"summary": "خلاصه کوتاه از مقاله",
|
||||
"tags": [1, 2],
|
||||
"status": "draft"
|
||||
"status": "draft",
|
||||
"image_url": "/uploads/blogs/blog_abc.jpg"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `title` | string | ✅ | Post title (slug auto-generated) |
|
||||
| `body` | string | ✅ | Full HTML body |
|
||||
| `body` | string | ✅ | Full HTML body (from the admin CKEditor) |
|
||||
| `summary` | string | ❌ | Short excerpt |
|
||||
| `tags` | integer[] | ❌ | Array of tag IDs |
|
||||
| `status` | string | ❌ | `"draft"` (default) or `"published"` |
|
||||
| `image_url` | string | ❌ | Cover image path returned by the upload endpoint |
|
||||
|
||||
### Response `201`
|
||||
```json
|
||||
@@ -158,11 +160,12 @@ Update a blog post.
|
||||
"body": "<p>محتوای جدید</p>",
|
||||
"summary": "خلاصه جدید",
|
||||
"tags": [1, 3],
|
||||
"status": "published"
|
||||
"status": "published",
|
||||
"image_url": "/uploads/blogs/blog_abc.jpg"
|
||||
}
|
||||
```
|
||||
|
||||
All fields optional.
|
||||
All fields optional. Send `image_url: ""` to clear the cover image.
|
||||
|
||||
### Response `200`
|
||||
Updated blog object.
|
||||
|
||||
Generated
+15354
-5
File diff suppressed because it is too large
Load Diff
@@ -22,6 +22,8 @@
|
||||
"webpack-cli": "^6.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ckeditor/ckeditor5-build-classic": "^44.3.0",
|
||||
"@ckeditor/ckeditor5-react": "^11.2.0",
|
||||
"@fontsource/vazirmatn": "^5.2.8",
|
||||
"@heroicons/react": "^2.0.0",
|
||||
"@hookform/resolvers": "^5.4.0",
|
||||
|
||||
@@ -182,9 +182,10 @@ class BlogController extends BaseController
|
||||
}
|
||||
|
||||
$blog = new Blog($user, $title, $body);
|
||||
if (!empty($data['summary'])) $blog->setSummary($data['summary']);
|
||||
if (!empty($data['tags'])) $blog->setTags((array)$data['tags']);
|
||||
if (!empty($data['status'])) $blog->setStatus($data['status']);
|
||||
if (!empty($data['summary'])) $blog->setSummary($data['summary']);
|
||||
if (!empty($data['tags'])) $blog->setTags((array)$data['tags']);
|
||||
if (!empty($data['status'])) $blog->setStatus($data['status']);
|
||||
if (!empty($data['image_url'])) $blog->setImageUrl($data['image_url']);
|
||||
|
||||
// Ensure slug uniqueness
|
||||
if ($this->blogRepo->findBySlug($blog->getSlug()) !== null) {
|
||||
@@ -255,8 +256,9 @@ class BlogController extends BaseController
|
||||
if (array_key_exists('title', $data)) $blog->setTitle($data['title']);
|
||||
if (array_key_exists('body', $data)) $blog->setBody($data['body']);
|
||||
if (array_key_exists('summary', $data)) $blog->setSummary($data['summary']);
|
||||
if (array_key_exists('tags', $data)) $blog->setTags((array)$data['tags']);
|
||||
if (array_key_exists('status', $data)) $blog->setStatus($data['status']);
|
||||
if (array_key_exists('tags', $data)) $blog->setTags((array)$data['tags']);
|
||||
if (array_key_exists('status', $data)) $blog->setStatus($data['status']);
|
||||
if (array_key_exists('image_url', $data)) $blog->setImageUrl($data['image_url'] ?: null);
|
||||
|
||||
$this->blogRepo->save($blog);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user