Files
nanocode/new-media-platform/website-new/frontend/src/pages/NewsDetail.jsx
T
Ubuntu 32b43f85bd a
2026-07-03 16:58:28 +08:00

365 lines
14 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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, '<pre class="bg-slate-900 text-slate-100 p-4 rounded-lg overflow-x-auto my-6"><code>$2</code></pre>');
// 标题
html = html.replace(/^#### (.*$)/gim, '<h4 class="text-lg font-bold mt-6 mb-3 text-gray-900">$1</h4>');
html = html.replace(/^### (.*$)/gim, '<h3 class="text-xl font-bold mt-8 mb-4 text-gray-900 border-b border-gray-200 pb-2">$1</h3>');
html = html.replace(/^## (.*$)/gim, '<h2 class="text-2xl font-bold mt-10 mb-5 text-gray-900 border-b-2 border-emerald-200 pb-3">$1</h2>');
html = html.replace(/^# (.*$)/gim, '<h1 class="text-3xl font-black mt-10 mb-6 text-gray-900">$1</h1>');
// 粗体
html = html.replace(/\*\*(.*?)\*\*/g, '<strong class="font-semibold text-gray-900">$1</strong>');
// 斜体
html = html.replace(/\*(.*?)\*/g, '<em class="italic text-gray-700">$1</em>');
// 删除线
html = html.replace(/~~(.*?)~~/g, '<del class="line-through text-gray-400">$1</del>');
// 行内代码
html = html.replace(/`([^`]+)`/g, '<code class="bg-emerald-50 text-emerald-700 px-1.5 py-0.5 rounded font-mono text-sm border border-emerald-200">$1</code>');
// 引用
html = html.replace(/^> (.*$)/gim, '<blockquote class="border-l-4 border-emerald-400 pl-4 py-3 my-6 bg-emerald-50/50 italic text-gray-700 rounded-r-lg">$1</blockquote>');
// 图片(必须在链接之前处理)
html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, src) => {
const fullSrc = src.startsWith('http') ? src : src;
return `<img src="${fullSrc}" alt="${alt}" class="max-w-full h-auto my-6 rounded-xl shadow-md" loading="lazy" onerror="this.style.display='none'" />`;
});
// 链接
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener" class="text-emerald-600 hover:text-emerald-700 hover:underline transition-colors">$1</a>');
// 无序列表
html = html.replace(/^\s*[-*] (.*$)/gim, '<li data-type="ul" class="ml-5">$1</li>');
html = html.replace(/(<li data-type="ul"[^>]*>.*?<\/li>\n?)+/g, '<ul class="list-disc my-5 space-y-2 text-gray-700">$&</ul>\n');
html = html.replace(/data-type="ul"/g, '');
// 有序列表
html = html.replace(/^\s*(\d+)\. (.*$)/gim, '<li data-type="ol" class="ml-5">$2</li>');
html = html.replace(/(<li data-type="ol"[^>]*>.*?<\/li>\n?)+/g, '<ol class="list-decimal my-5 space-y-2 text-gray-700">$&</ol>\n');
html = html.replace(/data-type="ol"/g, '');
// 分割线
html = html.replace(/^---$/gim, '<hr class="my-10 border-t border-gray-200" />');
// 段落
html = html.replace(/\n\n/g, '</p><p class="my-4 leading-relaxed text-gray-700">');
html = '<p class="my-4 leading-relaxed text-gray-700">' + html + '</p>';
// 清理空段落
html = html.replace(/<p class="my-4 leading-relaxed text-gray-700"><\/p>/g, '');
return html;
};
if (loading) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<div className="text-center">
<div className="w-12 h-12 border-4 border-emerald-200 border-t-emerald-600 rounded-full animate-spin mx-auto mb-4"></div>
<p className="text-gray-600">加载中...</p>
</div>
</div>
);
}
if (error || !post) {
return (
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
<div className="text-center">
<h2 className="text-2xl font-bold text-gray-800 mb-4">文章未找到</h2>
<p className="text-gray-600 mb-6">{error || '该文章可能已被删除或不存在'}</p>
<Link
to="/column/xin-wen-zi-xun"
className="inline-flex items-center gap-2 px-6 py-3 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors"
>
<ChevronLeft className="w-4 h-4" />
返回资讯列表
</Link>
</div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-50">
{/* 返回导航 */}
<div className="bg-white border-b border-gray-100">
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
<button
onClick={() => navigate('/column/xin-wen-zi-xun')}
className="inline-flex items-center gap-2 text-gray-600 hover:text-emerald-600 transition-colors"
>
<ChevronLeft className="w-4 h-4" />
返回资讯列表
</button>
</div>
</div>
{/* 文章内容 */}
<article className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{/* 文章头部 */}
<header className="mb-8">
{/* 分类标签 */}
{post.column && (
<Link
to={`/column/xin-wen-zi-xun?category=${post.column.slug}`}
className="inline-block px-4 py-1 bg-emerald-50 text-emerald-600 text-sm font-medium rounded-full mb-4 hover:bg-emerald-100 transition-colors"
>
{post.column.name}
</Link>
)}
{/* 标题 */}
<h1 className="text-3xl md:text-4xl font-bold text-gray-900 mb-6 leading-tight">
{post.title}
</h1>
{/* 元信息 */}
<div className="flex flex-wrap items-center gap-6 text-sm text-gray-500 border-b border-gray-100 pb-6">
<span className="flex items-center gap-2">
<Calendar className="w-4 h-4" />
{formatDate(post.updated_at)}
</span>
<span className="flex items-center gap-2">
<Eye className="w-4 h-4" />
{post.view_count || 0} 阅读
</span>
{post.author && (
<span className="flex items-center gap-2">
<User className="w-4 h-4" />
{post.author}
</span>
)}
{post.content_type === 'markdown' && (
<span className="flex items-center gap-2">
<Clock className="w-4 h-4" />
约 {Math.ceil((post.content?.length || 0) / 500)} 分钟阅读
</span>
)}
<button
onClick={handleShare}
className="ml-auto flex items-center gap-2 text-emerald-600 hover:text-emerald-700 transition-colors"
>
<Share2 className="w-4 h-4" />
分享
</button>
</div>
</header>
{/* 封面图 */}
{post.cover_image && (
<div className="mb-8 rounded-xl overflow-hidden shadow-lg">
<img
src={post.cover_image.startsWith('http') ? post.cover_image : `${post.cover_image.startsWith('/storage/') || post.cover_image.startsWith('/uploads/') ? '' : '/uploads'}${post.cover_image}`}
alt={post.title}
className="w-full h-auto"
onError={(e) => { e.target.style.display = 'none'; }}
/>
</div>
)}
{/* 文章正文 */}
<div
ref={contentRef}
className="prose prose-lg max-w-none prose-headings:text-gray-900 prose-p:text-gray-700 prose-a:text-emerald-600 hover:prose-a:text-emerald-700 prose-img:rounded-lg prose-img:shadow-md"
dangerouslySetInnerHTML={{ __html: renderMarkdown(post.content) }}
/>
{/* 文章底部 */}
<div className="mt-12 pt-8 border-t border-gray-100">
<div className="flex items-center justify-between">
<Link
to="/column/xin-wen-zi-xun"
className="inline-flex items-center gap-2 text-gray-600 hover:text-emerald-600 transition-colors"
>
<ChevronLeft className="w-4 h-4" />
返回资讯列表
</Link>
<button
onClick={handleShare}
className="inline-flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-lg text-gray-600 hover:border-emerald-500 hover:text-emerald-600 transition-colors"
>
<Share2 className="w-4 h-4" />
分享文章
</button>
</div>
</div>
</article>
{/* 相关文章 */}
{relatedPosts.length > 0 && (
<section className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-12 border-t border-gray-200">
<h3 className="text-xl font-bold text-gray-900 mb-6">相关文章</h3>
<div className="grid md:grid-cols-2 gap-4">
{relatedPosts.map((related) => (
<Link
key={related.id}
to={`/article/${related.slug}`}
className="flex gap-4 p-4 bg-white rounded-lg shadow-sm hover:shadow-md transition-shadow"
>
{related.cover_image && (
<div className="w-24 h-24 flex-shrink-0 rounded-lg overflow-hidden">
<img
src={related.cover_image.startsWith('http') ? related.cover_image : `${related.cover_image.startsWith('/storage/') || related.cover_image.startsWith('/uploads/') ? '' : '/uploads'}${related.cover_image}`}
alt={related.title}
className="w-full h-full object-cover"
onError={(e) => { e.target.style.display = 'none'; }}
/>
</div>
)}
<div className="flex-1 min-w-0">
<h4 className="font-medium text-gray-900 line-clamp-2 mb-2 hover:text-emerald-600 transition-colors">
{related.title}
</h4>
<span className="text-sm text-gray-400">
{formatDate(related.updated_at)}
</span>
</div>
</Link>
))}
</div>
</section>
)}
</div>
);
};
export default NewsDetail;