import { useEffect, useState, type FormEvent } from 'react' import { Link, useNavigate, useParams } from 'react-router-dom' import { ArrowLeft } from 'lucide-react' import { createPost, fetchPost, updatePost, type PostForm, } from '@/api/posts' const EMPTY: PostForm = { slug: '', title: '', category: '', summary: '', content: '', published: false, } export default function PostEditPage() { const { id } = useParams() const navigate = useNavigate() const isEdit = Boolean(id) const [form, setForm] = useState(EMPTY) const [loading, setLoading] = useState(isEdit) const [saving, setSaving] = useState(false) const [error, setError] = useState('') useEffect(() => { if (!id) return let cancelled = false fetchPost(id) .then((post) => { if (cancelled) return setForm({ slug: post.slug, title: post.title, category: post.category, summary: post.summary, content: post.content ?? '', published: post.published_at !== null, }) setLoading(false) }) .catch((err: Error) => { if (cancelled) return setError(err.message) setLoading(false) }) return () => { cancelled = true } }, [id]) const set = (key: K, value: PostForm[K]) => setForm((f) => ({ ...f, [key]: value })) const onSubmit = async (e: FormEvent) => { e.preventDefault() setSaving(true) setError('') try { if (isEdit && id) { await updatePost(id, form) } else { await createPost(form) } navigate('/') } catch (err) { setError(err instanceof Error ? err.message : '保存失败') } finally { setSaving(false) } } const inputCls = 'w-full rounded-lg border border-hairline-strong bg-ground px-3.5 py-2 text-[14px] outline-none transition-colors focus:border-accent' return (
文章列表

{isEdit ? '编辑文章' : '新建文章'}

{loading ? (
) : (