feat(admin): صفحهٔ اختصاصی ویرایش/ساخت پروژه + گالری فقط با آپلود به MinIO

- /admin/projects/new و /admin/projects/:id — همهٔ فیلدها در یک صفحه با
  ورودی دوزبانهٔ صریح (فارسی/English)، ذخیره، حذف
- GalleryField تازه: گالری چندتصویری فقط با آپلود به MinIO (حذف/جابه‌جایی/
  افزودن چندفایلی) — فیلد «هر خط یک URL» دیگر استفاده نمی‌شود
- مدادِ کارت پروژه و دکمهٔ «افزودن پروژه» به صفحهٔ اختصاصی هدایت می‌شوند؛
  دکمهٔ ویرایش روی صفحهٔ جزئیات هم لینک همان صفحه است
This commit is contained in:
aramesh-site deploy
2026-09-28 10:33:05 +00:00
parent edcbd0dc58
commit 0c87a287a3
6 changed files with 521 additions and 10 deletions
+345
View File
@@ -0,0 +1,345 @@
import { useEffect, useState } from 'react'
import { Link, Navigate, useNavigate, useParams } from 'react-router-dom'
import { ArrowRightIcon, Trash2Icon } from 'lucide-react'
import Swal from 'sweetalert2'
import { useSiteData } from '../api'
import { useAdmin } from './AdminContext'
import { adminApi } from './adminClient'
import { ImageField } from '../components/admin/ImageField'
import { GalleryField } from '../components/admin/GalleryField'
type ProjectDraft = {
id: number
slug: string
title: string
title_en: string
location: string
location_en: string
year: string
year_en: string
status: 'done' | 'progress'
project_type: string
project_type_en: string
usage: string
usage_en: string
area: string
area_en: string
floors: string
floors_en: string
units: string
units_en: string
client: string
client_en: string
summary: string
summary_en: string
body: string[]
body_en: string[]
image: string
gallery: string[]
}
const EMPTY: ProjectDraft = {
id: 0,
slug: `project-${Date.now()}`,
title: '', title_en: '',
location: '', location_en: '',
year: '', year_en: '',
status: 'done',
project_type: '', project_type_en: '',
usage: '', usage_en: '',
area: '', area_en: '',
floors: '', floors_en: '',
units: '', units_en: '',
client: '', client_en: '',
summary: '', summary_en: '',
body: [], body_en: [],
image: '', gallery: [],
}
const INPUT =
'w-full border border-ivory/15 bg-char px-3 py-2 text-sm font-light text-ivory placeholder:text-ivory/30 focus:border-copper focus:outline-none'
/** جفت دوزبانه — فارسی و English همیشه هر دو دیده می‌شوند و با یک ذخیره ثبت می‌شوند */
function Pair({
label,
fa,
en,
textarea = false,
}: {
label: string
fa: { value: string; onChange: (v: string) => void }
en: { value: string; onChange: (v: string) => void }
textarea?: boolean
}) {
return (
<div>
<p className="text-xs font-bold text-ivory/80">{label}</p>
<div className="mt-1.5 grid gap-3 sm:grid-cols-2">
<div>
<span className="text-[10px] font-light text-ivory/40">فارسی</span>
{textarea ? (
<textarea dir="rtl" rows={4} className={`${INPUT} mt-1 leading-8`} {...fa} />
) : (
<input dir="rtl" type="text" className={`${INPUT} mt-1`} {...fa} />
)}
</div>
<div>
<span className="text-[10px] font-light text-ivory/40">English</span>
{textarea ? (
<textarea dir="ltr" rows={4} className={`${INPUT} mt-1 leading-8`} {...en} />
) : (
<input dir="ltr" type="text" className={`${INPUT} mt-1`} {...en} />
)}
</div>
</div>
</div>
)
}
/** صفحهٔ اختصاصی ویرایش/ساخت پروژه — به‌جای کشو؛ تصاویر فقط با آپلود به MinIO */
export function ProjectWritePage() {
const { id } = useParams<{ id: string }>()
const isNew = !id || id === 'new'
const numericId = Number(id)
const navigate = useNavigate()
const { data, updateSite } = useSiteData()
const { isAuthenticated, runSave } = useAdmin()
const existing = !isNew && data?.projects.find((p) => p.id === numericId)
const [fetched, setFetched] = useState<ProjectDraft | null>(null)
const [draft, setDraft] = useState<ProjectDraft>(EMPTY)
const [saving, setSaving] = useState(false)
// اگر پروژه در دادهٔ سایت نبود (پیش‌نویس تازه و… ) مستقیم از مسیر مدیریتی خوانده می‌شود
useEffect(() => {
if (isNew || existing) return
let cancelled = false
adminApi
.get<ProjectDraft>('projects', numericId)
.then((p) => {
if (!cancelled) setFetched(p)
})
.catch(() => {
/* پروژه در دادهٔ سایت نبود — از مسیر مدیریتی خوانده می‌شود */
})
return () => {
cancelled = true
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id, existing])
const project = existing ?? fetched
useEffect(() => {
if (!project) return
setDraft({ ...EMPTY, ...(project as unknown as ProjectDraft) })
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [(project as unknown as ProjectDraft | undefined)?.id])
if (!isAuthenticated) return <Navigate to="/admin/login" replace />
const set = <K extends keyof ProjectDraft>(key: K, value: ProjectDraft[K]) =>
setDraft((d) => ({ ...d, [key]: value }))
const fa = (key: keyof ProjectDraft) => ({
value: String(draft[key] ?? ''),
onChange: (v: string) => set(key, v as ProjectDraft[typeof key]),
})
const en = (key: keyof ProjectDraft) => ({
value: String(draft[`${String(key)}_en` as keyof ProjectDraft] ?? ''),
onChange: (v: string) => set(`${String(key)}_en` as keyof ProjectDraft, v as ProjectDraft[typeof key]),
})
const doSave = async () => {
if (!draft.title.trim() || !draft.slug.trim()) {
void Swal.fire({
icon: 'warning',
title: 'عنوان و نشانی (slug) لازم است',
background: '#1e1a16',
color: '#F5F3EF',
confirmButtonText: 'باشه',
buttonsStyling: false,
customClass: { popup: 'font-pinar border border-ivory/10' },
})
return
}
setSaving(true)
await runSave(async () => {
if (isNew || draft.id === 0) {
const created = await adminApi.create<ProjectDraft>('projects', { ...draft })
updateSite((d) => {
const list = d.projects as unknown as ProjectDraft[]
if (Array.isArray(list)) list.push(created)
})
navigate(`/admin/projects/${created.id}`, { replace: true })
} else {
await adminApi.patch('projects', draft.id, { ...draft })
updateSite((d) => {
const list = d.projects as unknown as ProjectDraft[]
const index = list.findIndex((x) => x.id === draft.id)
if (index >= 0) list[index] = { ...list[index], ...draft }
})
}
})
setSaving(false)
}
const doDelete = async () => {
if (isNew || draft.id === 0) return
const result = await Swal.fire({
icon: 'warning',
title: 'حذف پروژه',
text: `«${draft.title}» برای همیشه حذف شود؟`,
background: '#1e1a16',
color: '#F5F3EF',
iconColor: '#d5874c',
showCancelButton: true,
confirmButtonText: 'حذف',
cancelButtonText: 'انصراف',
buttonsStyling: false,
customClass: {
popup: 'font-pinar border border-ivory/10',
confirmButton: 'bg-red-500 text-white font-bold px-8 py-2.5 mx-2',
cancelButton: 'border border-ivory/30 text-ivory font-light px-8 py-2.5 mx-2',
},
})
if (!result.isConfirmed) return
await runSave(async () => {
await adminApi.remove('projects', draft.id)
updateSite((d) => {
const list = d.projects as unknown as ProjectDraft[]
const index = list.findIndex((x) => x.id === draft.id)
if (index >= 0) list.splice(index, 1)
})
navigate('/projects', { replace: true })
})
}
/** تصویر شاخص و گالری بلافاصله ذخیره می‌شوند (پروژهٔ موجود)؛ در پروژهٔ تازه تا اولین ذخیره در فرم می‌مانند */
const persistImage = async (url: string) => {
setDraft((d) => ({ ...d, image: url }))
if (!isNew && draft.id !== 0) {
await adminApi.patch('projects', draft.id, { image: url })
}
return true
}
const persistGallery = async (urls: string[]) => {
setDraft((d) => ({ ...d, gallery: urls }))
if (!isNew && draft.id !== 0) {
await adminApi.patch('projects', draft.id, { gallery: urls })
}
return true
}
return (
<div dir="rtl" className="min-h-screen bg-ink pb-24 pt-24">
<div className="mx-auto max-w-4xl px-6 lg:px-10">
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<Link
to="/projects"
data-admin-link
className="inline-flex items-center gap-2 text-xs font-light text-ivory/50 transition-colors hover:text-copper"
>
<ArrowRightIcon className="h-3.5 w-3.5" />
بازگشت به پروژه‌ها
</Link>
<h1 className="mt-3 text-3xl font-bold text-ivory">
{isNew ? 'پروژهٔ جدید' : `ویرایش «${draft.title}»`}
</h1>
</div>
<div className="flex items-center gap-3">
{!isNew && draft.id !== 0 && (
<button
type="button"
onClick={() => void doDelete()}
className="flex items-center gap-2 border border-red-400/40 px-5 py-2.5 text-sm font-light text-red-300 transition-colors duration-200 hover:bg-red-500/20"
>
<Trash2Icon className="h-4 w-4" />
حذف پروژه
</button>
)}
<button
type="button"
onClick={() => void doSave()}
disabled={saving}
className="flex items-center gap-2 bg-copper px-8 py-2.5 text-sm font-bold text-char transition-transform duration-200 hover:scale-105 disabled:opacity-60"
>
ذخیرهٔ پروژه
</button>
</div>
</div>
<div className="mt-10 space-y-8">
<Pair label="عنوان پروژه" fa={fa('title')} en={en('title')} />
<div className="grid gap-6 sm:grid-cols-2">
<div>
<p className="text-xs font-bold text-ivory/80">
نشانی (slug) <span className="font-light text-ivory/40">— در نشانی صفحه: /projects/…</span>
</p>
<input
dir="ltr"
type="text"
className={`${INPUT} mt-1.5`}
value={draft.slug}
onChange={(e) => set('slug', e.target.value)}
/>
</div>
<div>
<p className="text-xs font-bold text-ivory/80">وضعیت</p>
<select
className={`${INPUT} mt-1.5`}
value={draft.status}
onChange={(e) => set('status', e.target.value as ProjectDraft['status'])}
>
<option value="done">انجام‌شده (done)</option>
<option value="progress">در حال اجرا (progress)</option>
</select>
</div>
</div>
<Pair label="موقعیت" fa={fa('location')} en={en('location')} />
<Pair label="سال" fa={fa('year')} en={en('year')} />
<Pair label="نوع پروژه" fa={fa('project_type')} en={en('project_type')} />
<Pair label="کاربری" fa={fa('usage')} en={en('usage')} />
<Pair label="زیربنا" fa={fa('area')} en={en('area')} />
<Pair label="تعداد طبقات" fa={fa('floors')} en={en('floors')} />
<Pair label="واحدها" fa={fa('units')} en={en('units')} />
<Pair label="کارفرما" fa={fa('client')} en={en('client')} />
<Pair label="خلاصه" fa={fa('summary')} en={en('summary')} textarea />
<Pair
label="متن پروژه — هر پاراگراف یک خط"
fa={{
value: draft.body.join('\n'),
onChange: (v) => set('body', v.split('\n')),
}}
en={{
value: draft.body_en.join('\n'),
onChange: (v) => set('body_en', v.split('\n')),
}}
textarea
/>
<div className="border-t border-ivory/10 pt-8">
<ImageField
label="تصویر شاخص"
value={draft.image}
onSave={persistImage}
altFallback={`پروژه ${draft.title}`}
/>
</div>
<div className="border-t border-ivory/10 pt-8">
<GalleryField
label="گالری تصاویر پروژه — فقط آپلود به MinIO"
value={draft.gallery}
onSave={persistGallery}
namePrefix={draft.slug || 'project'}
/>
</div>
</div>
</div>
</div>
)
}