️ feat: add post fetching by ID and improve blog home page

- Implemented `getPostById` API function to fetch a post by its ID.
- Refactored the main page to use a new `BlogHome` component for better organization.
- Added loading state and sorting functionality for posts on the blog home page.
- Integrated label fetching and display on the blog home page.
- Enhanced the blog card component with improved layout and statistics display.
- Updated the navbar to use dynamic configuration values.
- Added Docker support with a comprehensive build and push workflow.
- Created a custom hook `useStoredState` for managing local storage state.
- Added a new page for displaying individual posts with metadata generation.
- Removed unused components and files to streamline the codebase.
This commit is contained in:
2025-07-25 03:58:53 +08:00
parent abe1099711
commit 5fac42439a
24 changed files with 752 additions and 338 deletions

View File

@ -41,8 +41,7 @@ const GravatarAvatar: React.FC<GravatarAvatarProps> = ({
);
}
// 使用 Gravatar
const gravatarUrl = getGravatarUrl(email, size, defaultType);
const gravatarUrl = getGravatarUrl(email, size * 10, defaultType);
return (
<Image

View File

@ -14,21 +14,8 @@ import {
} from "@/components/ui/navigation-menu"
import GravatarAvatar from "@/components/gravatar"
import { useDevice } from "@/contexts/device-context"
const components: { title: string; href: string }[] = [
{
title: "归档",
href: "/archives"
},
{
title: "标签",
href: "/labels"
},
{
title: "随机",
href: "/random"
}
]
import { metadata } from '../app/layout';
import config from "@/config"
const navbarMenuComponents = [
{
@ -59,7 +46,7 @@ export function Navbar() {
<nav className="grid grid-cols-[1fr_auto_1fr] items-center gap-4 h-12 px-4 w-full">
<div className="flex items-center justify-start">
{/* 左侧内容 */}
<span className="font-bold truncate">Snowykami's Blog</span>
<span className="font-bold truncate">{config.metadata.name}</span>
</div>
<div className="flex items-center justify-center">
{/* 中间内容 - 完全居中 */}
@ -67,7 +54,7 @@ export function Navbar() {
</div>
<div className="flex items-center justify-end">
{/* 右侧内容 */}
<GravatarAvatar email="snowykami@outlook.com" size={32} />
<GravatarAvatar email="snowykami@outlook.com"/>
</div>
</nav>
)

View File

@ -1,10 +1,9 @@
import { Post } from "@/models/post";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import Link from "next/link";
import Image from "next/image";
import { Calendar, Clock, Eye, Heart, MessageCircle, Lock } from "lucide-react";
import { Calendar, Eye, Heart, MessageCircle, Lock } from "lucide-react";
import { cn } from "@/lib/utils";
import config from "@/config";
@ -25,30 +24,30 @@ export function BlogCard({ post, className }: BlogCardProps) {
};
// 计算阅读时间(估算)
const getReadingTime = (content: string) => {
const wordsPerMinute = 200;
const wordCount = content.length;
const minutes = Math.ceil(wordCount / wordsPerMinute);
return `${minutes} 分钟阅读`;
};
// const getReadingTime = (content: string) => {
// const wordsPerMinute = 200;
// const wordCount = content.length;
// const minutes = Math.ceil(wordCount / wordsPerMinute);
// return `${minutes} 分钟阅读`;
// };
// 根据内容类型获取图标
const getContentTypeIcon = (type: Post['type']) => {
switch (type) {
case 'markdown':
return '📝';
case 'html':
return '🌐';
case 'text':
return '📄';
default:
return '📝';
}
};
// // 根据内容类型获取图标
// const getContentTypeIcon = (type: Post['type']) => {
// switch (type) {
// case 'markdown':
// return '📝';
// case 'html':
// return '🌐';
// case 'text':
// return '📄';
// default:
// return '📝';
// }
// };
return (
<Card className={cn(
"group overflow-hidden hover:shadow-xl transition-all duration-300 h-full flex flex-col cursor-pointer",
"group overflow-hidden hover:shadow-xl transition-all duration-300 h-full flex flex-col cursor-pointer pt-0 pb-4",
className
)}>
{/* 封面图片区域 */}
@ -65,44 +64,62 @@ export function BlogCard({ post, className }: BlogCardProps) {
/>
) : (
// 默认渐变背景 - 基于热度生成颜色
<div
<div
className={cn(
"w-full h-full bg-gradient-to-br",
post.heat > 80 ? "from-red-400 via-pink-500 to-orange-500" :
post.heat > 60 ? "from-orange-400 via-yellow-500 to-red-500" :
post.heat > 40 ? "from-blue-400 via-purple-500 to-pink-500" :
post.heat > 20 ? "from-green-400 via-blue-500 to-purple-500" :
"from-gray-400 via-slate-500 to-gray-600"
post.heat > 60 ? "from-orange-400 via-yellow-500 to-red-500" :
post.heat > 40 ? "from-blue-400 via-purple-500 to-pink-500" :
post.heat > 20 ? "from-green-400 via-blue-500 to-purple-500" :
"from-gray-400 via-slate-500 to-gray-600"
)}
/>
)}
{/* 覆盖层 */}
<div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent" />
{/* 私有文章标识 */}
{post.isPrivate && (
<Badge
variant="destructive"
className="absolute top-4 left-4 bg-red-500/90 text-white hover:bg-red-500"
<Badge
variant="destructive"
className="absolute top-2 left-2 bg-blue-300/90 text-white hover:bg-blue-400 text-xs"
>
<Lock className="w-3 h-3 mr-1" />
</Badge>
)}
{/* 内容类型标签 */}
<Badge
variant="secondary"
className="absolute top-4 right-4 bg-white/90 text-gray-700 hover:bg-white"
>
{getContentTypeIcon(post.type)} {post.type.toUpperCase()}
</Badge>
{/* 统计信息 */}
<div className="absolute bottom-2 left-2">
<Badge className="bg-gradient-to-r from-blue-200 to-purple-300 text-white border-0 dark:bg-gradient-to-r dark:from-blue-700 dark:to-purple-700">
{/* 统计信息 */}
<div className="grid grid-cols-1 gap-4 text-muted-foreground">
<div className="flex items-center gap-3 text-xs">
{/* 点赞数 */}
<div className="flex items-center gap-1 ">
<Heart className="w-3 h-3" />
<span>{post.likeCount}</span>
</div>
{/* 评论数 */}
<div className="flex items-center gap-1">
<MessageCircle className="w-3 h-3" />
<span>{post.commentCount}</span>
</div>
{/* 阅读量 */}
<div className="flex items-center gap-1">
<Eye className="w-3 h-3" />
<span>{post.viewCount}</span>
</div>
</div>
</div>
</Badge>
</div>
{/* 热度指示器 */}
{post.heat > 50 && (
<div className="absolute bottom-4 right-4">
<Badge className="bg-gradient-to-r from-orange-500 to-red-500 text-white border-0">
<div className="absolute bottom-2 right-2">
<Badge className="bg-gradient-to-r from-orange-500 to-red-500 text-white border-0 text-xs">
🔥 {post.heat}
</Badge>
</div>
@ -110,95 +127,32 @@ export function BlogCard({ post, className }: BlogCardProps) {
</div>
{/* Card Header - 标题区域 */}
<CardHeader className="pb-3">
<CardHeader className="">
<CardTitle className="line-clamp-2 group-hover:text-primary transition-colors text-lg leading-tight">
{post.title}
</CardTitle>
</CardHeader>
{/* Card Content - 主要内容 */}
<CardContent className="flex-1">
<CardDescription className="line-clamp-3 leading-relaxed">
{post.content.replace(/[#*`]/g, '').substring(0, 150)}
{post.content.length > 150 ? '...' : ''}
</CardDescription>
</CardHeader>
{/* Card Content - 主要内容 */}
<CardContent className="flex-1 pb-3">
{/* 标签列表 */}
{post.labels && post.labels.length > 0 && (
<div className="flex flex-wrap gap-2 mb-4">
{post.labels.slice(0, 3).map((label) => (
<Badge
key={label.id}
variant="outline"
className="text-xs hover:bg-primary/10"
style={{
borderColor: label.color || '#e5e7eb',
color: label.color || '#6b7280'
}}
>
{label.key}
</Badge>
))}
{post.labels.length > 3 && (
<Badge variant="outline" className="text-xs">
+{post.labels.length - 3}
</Badge>
)}
</div>
)}
{/* 统计信息 */}
<div className="grid grid-cols-2 gap-4 text-sm text-muted-foreground">
<div className="flex items-center gap-3">
{/* 点赞数 */}
<div className="flex items-center gap-1">
<Heart className="w-4 h-4" />
<span>{post.likeCount}</span>
</div>
{/* 评论数 */}
<div className="flex items-center gap-1">
<MessageCircle className="w-4 h-4" />
<span>{post.commentCount}</span>
</div>
</div>
<div className="flex items-center justify-end gap-3">
{/* 阅读量 */}
<div className="flex items-center gap-1">
<Eye className="w-4 h-4" />
<span>{post.viewCount}</span>
</div>
{/* 阅读时间 */}
<div className="flex items-center gap-1">
<Clock className="w-4 h-4" />
<span>{getReadingTime(post.content)}</span>
</div>
</div>
</div>
</CardContent>
{/* Card Footer - 日期和操作区域 */}
<CardFooter className="pt-3 border-t border-border/50 flex items-center justify-between">
{/* 创建日期 */}
<CardFooter className="pb-0 border-t border-border/50 flex items-center justify-between">
{/* 左侧:最新日期 */}
<div className="flex items-center gap-1 text-sm text-muted-foreground">
<Calendar className="w-4 h-4" />
<time dateTime={post.createdAt}>
{formatDate(post.createdAt)}
<time dateTime={post.updatedAt !== post.createdAt ? post.updatedAt : post.createdAt}>
{formatDate(post.updatedAt !== post.createdAt ? post.updatedAt : post.createdAt)}
</time>
</div>
{/* 更新日期(如果与创建日期不同)或阅读提示 */}
{post.updatedAt !== post.createdAt ? (
<div className="text-xs text-muted-foreground">
{formatDate(post.updatedAt)}
</div>
) : (
<div className="text-sm text-primary">
</div>
)}
</CardFooter>
</Card>
);
}
@ -209,7 +163,7 @@ export function BlogCardSkeleton() {
<Card className="overflow-hidden h-full flex flex-col">
{/* 封面图片骨架 */}
<div className="aspect-[16/9] bg-muted animate-pulse" />
{/* Header 骨架 */}
<CardHeader className="pb-3">
<div className="h-6 bg-muted rounded animate-pulse mb-2" />
@ -219,7 +173,7 @@ export function BlogCardSkeleton() {
<div className="h-4 bg-muted rounded w-1/2 animate-pulse" />
</div>
</CardHeader>
{/* Content 骨架 */}
<CardContent className="flex-1 pb-3">
<div className="flex gap-2 mb-4">
@ -232,7 +186,7 @@ export function BlogCardSkeleton() {
<div className="h-4 bg-muted rounded animate-pulse" />
</div>
</CardContent>
{/* Footer 骨架 */}
<CardFooter className="pt-3 border-t">
<div className="h-4 w-24 bg-muted rounded animate-pulse" />
@ -243,12 +197,12 @@ export function BlogCardSkeleton() {
}
// 网格布局的博客卡片列表
export function BlogCardGrid({
posts,
export function BlogCardGrid({
posts,
isLoading,
showPrivate = false
}: {
posts: Post[];
}: {
posts: Post[];
isLoading?: boolean;
showPrivate?: boolean;
}) {

View File

@ -0,0 +1,280 @@
"use client";
import { BlogCardGrid } from "@/components/blog-card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Search, TrendingUp, Clock, Heart, Eye } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import config from '@/config';
import type { Label } from "@/models/label";
import type { Post } from "@/models/post";
import { listPosts } from "@/api/post";
import { useEffect, useState } from "react";
import { useStoredState } from '@/hooks/use-storage-state';
import { listLabels } from "@/api/label";
import GravatarAvatar from "./gravatar";
import { POST_SORT_TYPE } from "@/localstore";
// 定义排序类型
type SortType = 'latest' | 'popular';
export default function BlogHome() {
const [labels, setLabels] = useState<Label[]>([]);
const [posts, setPosts] = useState<Post[]>([]);
const [loading, setLoading] = useState(false);
const [sortType, setSortType, sortTypeLoaded] = useStoredState<SortType>(POST_SORT_TYPE, 'latest');
// 根据排序类型获取文章
useEffect(() => {
if (!sortTypeLoaded) return; // 等待从 localStorage 加载完成
const fetchPosts = async () => {
try {
setLoading(true);
let orderedBy: string;
let reverse: boolean;
switch (sortType) {
case 'latest':
orderedBy = 'updated_at';
reverse = false;
break;
case 'popular':
orderedBy = 'heat';
reverse = false;
break;
default:
orderedBy = 'updated_at';
reverse = false;
}
const data = await listPosts({
page: 1,
size: 10,
orderedBy,
reverse
});
setPosts(data.data);
console.log(`${sortType} posts:`, data.data);
} catch (error) {
console.error("Failed to fetch posts:", error);
} finally {
setLoading(false);
}
};
fetchPosts();
}, [sortType, sortTypeLoaded]);
// 获取标签
useEffect(() => {
listLabels().then(data => {
setLabels(data.data);
console.log("Labels:", data.data);
}).catch(error => {
console.error("Failed to fetch labels:", error);
});
}, []);
//
// 处理排序切换
const handleSortChange = (type: SortType) => {
if (sortType !== type) {
setSortType(type);
}
};
return (
<div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 dark:bg-gradient-to-br dark:from-slate-900 dark:via-blue-900 dark:to-indigo-900">
{/* Hero Section */}
<section className="relative py-10 lg:py-16 overflow-hidden">
{/* 背景装饰 */}
<div className="absolute inset-0 bg-grid-white/[0.02] bg-grid-16 pointer-events-none" />
{/* 容器 - 关键布局 */}
<div className="container mx-auto px-4 sm:px-6 lg:px-8 max-w-7xl">
<div className="text-center max-w-4xl mx-auto">
<h1 className="text-4xl md:text-6xl lg:text-7xl font-bold mb-6 bg-gradient-to-r from-slate-900 via-blue-900 to-slate-900 bg-clip-text text-transparent dark:from-slate-100 dark:via-blue-100 dark:to-slate-100">
{config.metadata.name}
</h1>
<p className="text-xl md:text-2xl text-slate-600 mb-8 max-w-2xl mx-auto leading-relaxed">
{config.metadata.description}
</p>
{/* 搜索框 */}
<div className="relative max-w-md mx-auto mb-0">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 w-5 h-5" />
<Input
placeholder="搜索文章..."
className="pl-10 pr-4 py-0 text-lg border-slate-200 focus:border-blue-500 rounded-full"
/>
</div>
{/* 热门标签 */}
{/* <div className="flex flex-wrap justify-center gap-2 mb-8">
{labels.map(label => (
<Badge
key={label.id}
variant="outline"
className="text-xs hover:bg-blue-50 cursor-pointer"
>
{label.key}
</Badge>
))}
</div> */}
</div>
</div>
</section>
{/* 主内容区域 */}
<section className="py-16">
{/* 容器 - 关键布局 */}
<div className="container mx-auto px-4 sm:px-6 lg:px-8 max-w-7xl">
<div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
{/* 主要内容区域 */}
<div className="lg:col-span-3">
{/* 文章列表标题 */}
<div className="flex items-center justify-between mb-8">
<h2 className="text-3xl font-bold text-slate-900 dark:text-slate-100">
{sortType === 'latest' ? '最新文章' : '热门文章'}
{posts.length > 0 && (
<span className="text-sm font-normal text-slate-500 ml-2">
({posts.length} )
</span>
)}
</h2>
{/* 排序按钮组 */}
<div className="flex items-center gap-2">
<Button
variant={sortType === 'latest' ? 'default' : 'outline'}
size="sm"
onClick={() => handleSortChange('latest')}
disabled={loading}
className="transition-all duration-200"
>
<Clock className="w-4 h-4 mr-2" />
</Button>
<Button
variant={sortType === 'popular' ? 'default' : 'outline'}
size="sm"
onClick={() => handleSortChange('popular')}
disabled={loading}
className="transition-all duration-200"
>
<TrendingUp className="w-4 h-4 mr-2" />
</Button>
</div>
</div>
{/* 博客卡片网格 */}
<BlogCardGrid posts={posts} isLoading={loading} showPrivate={true} />
{/* 加载更多按钮 */}
{!loading && posts.length > 0 && (
<div className="text-center mt-12">
<Button size="lg" className="px-8">
</Button>
</div>
)}
{/* 加载状态指示器 */}
{loading && (
<div className="text-center py-8">
<div className="inline-flex items-center gap-2 text-slate-600">
<div className="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
{sortType === 'latest' ? '最新' : '热门'}...
</div>
</div>
)}
</div>
{/* 侧边栏 */}
<div className="lg:col-span-1 space-y-6">
{/* 关于我 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Heart className="w-5 h-5 text-red-500" />
</CardTitle>
</CardHeader>
<CardContent>
<div className="text-center mb-4">
<div className="w-20 h-20 mx-auto bg-gradient-to-br from-blue-400 to-purple-500 rounded-full flex items-center justify-center text-white text-2xl font-bold overflow-hidden">
<GravatarAvatar email={config.owner.gravatarEmail} className="w-full h-full object-cover" />
</div>
<h3 className="font-semibold text-lg">{config.owner.name}</h3>
<p className="text-sm text-slate-600">{config.owner.motto}</p>
</div>
<p className="text-sm text-slate-600 leading-relaxed">
{config.owner.description}
</p>
</CardContent>
</Card>
{/* 热门文章 */}
{posts.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<TrendingUp className="w-5 h-5 text-orange-500" />
{sortType === 'latest' ? '热门文章' : '最新文章'}
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{posts.slice(0, 3).map((post, index) => (
<div key={post.id} className="flex items-start gap-3">
<span className="flex-shrink-0 w-6 h-6 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center text-sm font-semibold">
{index + 1}
</span>
<div className="flex-1 min-w-0">
<h4 className="font-medium text-sm line-clamp-2 mb-1">
{post.title}
</h4>
<div className="flex items-center gap-2 text-xs text-slate-500">
<span className="flex items-center gap-1">
<Eye className="w-3 h-3" />
{post.viewCount}
</span>
<span className="flex items-center gap-1">
<Heart className="w-3 h-3" />
{post.likeCount}
</span>
</div>
</div>
</div>
))}
</CardContent>
</Card>
)}
{/* 标签云 */}
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-wrap gap-2">
{labels.map((label) => (
<Badge
key={label.id}
variant="outline"
className="text-xs hover:bg-blue-50 cursor-pointer"
>
{label.key}
</Badge>
))}
</div>
</CardContent>
</Card>
</div>
</div>
</div>
</section>
</div>
);
}

View File