'use client';
// 帖子详情页
import { useEffect, useState, useCallback } from 'react';
import { API } from '@/lib/api';
import { useApp } from './AppProvider';
import ReplyList from './ReplyList';
import { Icon } from './Icons';
import ImageViewer from './ImageViewer';
import { renderMarkdown } from '@/lib/markdown';
function avatar(username) {
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
'&background=6366f1&color=fff&size=64';
}
export default function PostDetail({ postId }) {
const { currentUser, navigate, openUser, refreshKey } = useApp();
const [post, setPost] = useState(null);
const [error, setError] = useState(null);
const [viewerSrc, setViewerSrc] = useState(null);
const [editing, setEditing] = useState(false);
const [editTitle, setEditTitle] = useState('');
const [editContent, setEditContent] = useState('');
const load = useCallback(async () => {
setError(null);
try {
const data = await API.getPost(postId);
setPost(data);
} catch (err) {
setError(err.message);
}
}, [postId, refreshKey]);
useEffect(() => { load(); }, [load]);
if (error) {
return (
加载中...
;
}
const time = post.created_at ? new Date(post.created_at).toLocaleString('zh-CN') : '';
// 作者本人 或 管理员 可删除/编辑
const canDelete = currentUser && (currentUser.id === post.user_id || currentUser.role === 'admin');
const canEdit = currentUser && currentUser.id === post.user_id;
const handleDelete = async () => {
if (!confirm('确定要删除这条帖子吗?')) return;
try {
await API.deletePost(postId);
alert('删除成功');
navigate('feed');
} catch (err) {
alert('删除失败:' + err.message);
}
};
const handleTogglePin = async () => {
if (!confirm('确定要' + (post.is_pinned ? '取消' : '') + '置顶吗?')) return;
try {
await API.togglePinPost(postId);
load();
} catch (err) {
alert('操作失败:' + err.message);
}
};
const handleEdit = () => {
setEditTitle(post.title || '');
setEditContent(post.content || '');
setEditing(true);
};
const handleSaveEdit = async () => {
if (!editContent.trim()) { alert('请填写内容'); return; }
try {
await API.updatePost(postId, editTitle.trim() || '无标题', editContent.trim());
setEditing(false);
load();
} catch (err) {
alert('编辑失败:' + err.message);
}
};
return (
{post.title || '帖子详情'}
openUser(post.username)}
>
{post.username || '匿名用户'}
{time}
{post.edited_at && (
(已编辑 {new Date(post.edited_at).toLocaleString('zh-CN')})
)}
{post.is_pinned && (
📌 置顶
)}
{currentUser && currentUser.role === 'admin' && (
)}
{canDelete && (
)}
{canDelete && (
)}
{post.images && post.images.length > 0 && (
{post.images.map((img, i) => (

setViewerSrc(img)} />
))}
)}
{post.signature && (
)}
{/* 编辑帖子 modal */}
{editing && (
)}
{/* 图片查看器 */}
{viewerSrc &&
setViewerSrc(null)} />}
);
}