import { useState, useEffect, useRef } from 'react'; import { Link, useParams, useNavigate } from 'react-router-dom'; import { Calendar, Eye, ChevronLeft, Share2, User, Clock } from 'lucide-react'; import api from '../api'; import { updateSEO, extractSummary } from '../utils/seo'; const NewsDetail = () => { const { slug } = useParams(); const navigate = useNavigate(); const [post, setPost] = useState(null); const [relatedPosts, setRelatedPosts] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(''); const contentRef = useRef(null); useEffect(() => { if (slug) { loadPost(); } }, [slug]); useEffect(() => { if (post) { updateSEO({ title: post.title, description: post.summary || extractSummary(post.content, 150), keywords: `${post.title},${post.column?.name || ''},飞点健康,吾大夫`, ogTitle: post.title, ogDescription: post.summary || extractSummary(post.content, 150), ogImage: post.cover_image || '', canonical: `http://team.niaodaifu.cn/news/${post.slug}` }); } }, [post]); // 渲染数学公式(KaTeX) useEffect(() => { if (!post || !contentRef.current) return; const renderMath = () => { if (window.renderMathInElement) { window.renderMathInElement(contentRef.current, { delimiters: [ { left: '$$', right: '$$', display: true }, { left: '\\[', right: '\\]', display: true }, { left: '\\(', right: '\\)', display: false }, { left: '$', right: '$', display: false } ], throwOnError: false, trust: true, strict: false }); } }; const timer = setTimeout(renderMath, 100); const retryTimer = setTimeout(renderMath, 500); return () => { clearTimeout(timer); clearTimeout(retryTimer); }; }, [post]); const loadPost = async () => { setLoading(true); setError(''); try { const res = await api.get(`/api/public/articles/${slug}`); setPost(res); // 加载相关文章 if (res.column?.slug) { loadRelatedPosts(res.column.slug, res.id); } } catch (err) { setError('文章加载失败,请稍后重试'); console.error('加载文章失败:', err); } finally { setLoading(false); } }; const loadRelatedPosts = async (columnSlug, excludeId) => { try { const res = await api.get('/api/public/articles', { params: { column_slug: columnSlug, page: 1, size: 5 } }); // 排除当前文章 const filtered = (res.items || []).filter(p => p.id !== excludeId).slice(0, 4); setRelatedPosts(filtered); } catch (err) { console.error('加载相关文章失败:', err); } }; const formatDate = (dateStr) => { const date = new Date(dateStr); return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' }); }; const handleShare = async () => { if (navigator.share) { try { await navigator.share({ title: post?.title, text: post?.summary, url: window.location.href }); } catch { // 用户取消分享 } } else { // 复制链接 navigator.clipboard.writeText(window.location.href); alert('链接已复制到剪贴板'); } }; // Markdown 渲染(从 personal-blog 移植,样式适配 emerald 主题) const renderMarkdown = (markdown) => { if (!markdown) return ''; if (post?.content_type !== 'markdown') return markdown; let html = markdown; // 代码块(必须在行内代码之前处理) html = html.replace(/```(\w+)?\n([\s\S]*?)```/g, '
$2
'); // 标题 html = html.replace(/^#### (.*$)/gim, '

$1

'); html = html.replace(/^### (.*$)/gim, '

$1

'); html = html.replace(/^## (.*$)/gim, '

$1

'); html = html.replace(/^# (.*$)/gim, '

$1

'); // 粗体 html = html.replace(/\*\*(.*?)\*\*/g, '$1'); // 斜体 html = html.replace(/\*(.*?)\*/g, '$1'); // 删除线 html = html.replace(/~~(.*?)~~/g, '$1'); // 行内代码 html = html.replace(/`([^`]+)`/g, '$1'); // 引用 html = html.replace(/^> (.*$)/gim, '
$1
'); // 图片(必须在链接之前处理) html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, src) => { const fullSrc = src.startsWith('http') ? src : src; return `${alt}`; }); // 链接 html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1'); // 无序列表 html = html.replace(/^\s*[-*] (.*$)/gim, '
  • $1
  • '); html = html.replace(/(
  • ]*>.*?<\/li>\n?)+/g, '\n'); html = html.replace(/data-type="ul"/g, ''); // 有序列表 html = html.replace(/^\s*(\d+)\. (.*$)/gim, '
  • $2
  • '); html = html.replace(/(
  • ]*>.*?<\/li>\n?)+/g, '
      $&
    \n'); html = html.replace(/data-type="ol"/g, ''); // 分割线 html = html.replace(/^---$/gim, '
    '); // 段落 html = html.replace(/\n\n/g, '

    '); html = '

    ' + html + '

    '; // 清理空段落 html = html.replace(/

    <\/p>/g, ''); return html; }; if (loading) { return (

    加载中...

    ); } if (error || !post) { return (

    文章未找到

    {error || '该文章可能已被删除或不存在'}

    返回资讯列表
    ); } return (
    {/* 返回导航 */}
    {/* 文章内容 */}
    {/* 文章头部 */}
    {/* 分类标签 */} {post.column && ( {post.column.name} )} {/* 标题 */}

    {post.title}

    {/* 元信息 */}
    {formatDate(post.updated_at)} {post.view_count || 0} 阅读 {post.author && ( {post.author} )} {post.content_type === 'markdown' && ( 约 {Math.ceil((post.content?.length || 0) / 500)} 分钟阅读 )}
    {/* 封面图 */} {post.cover_image && (
    {post.title} { e.target.style.display = 'none'; }} />
    )} {/* 文章正文 */}
    {/* 文章底部 */}
    返回资讯列表
    {/* 相关文章 */} {relatedPosts.length > 0 && (

    相关文章

    {relatedPosts.map((related) => ( {related.cover_image && (
    {related.title} { e.target.style.display = 'none'; }} />
    )}

    {related.title}

    {formatDate(related.updated_at)}
    ))}
    )}
    ); }; export default NewsDetail;