️ 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

38
.github/workflows/build.yaml vendored Normal file
View File

@ -0,0 +1,38 @@
name: Build and Push Docker Images
on:
push:
branches:
- main
workflow_dispatch:
jobs:
build-and-push:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to DockerHub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push frontend image
uses: docker/build-push-action@v5
with:
context: ./web
push: true
tags: ${{ secrets.DOCKERHUB_USERNAME }}/neo-blog-frontend:latest
- name: Build and push backend image
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ secrets.DOCKERHUB_USERNAME }}/neo-blog-backend:latest

View File

@ -0,0 +1,31 @@
# build
FROM golang:1.24.2-alpine3.21 AS builder
ENV TZ=Asia/Chongqing
WORKDIR /app
RUN apk --no-cache add build-base git tzdata
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN go build -o server ./cmd/server
# production
FROM alpine:latest AS prod
ENV TZ=Asia/Chongqing
WORKDIR /app
COPY --from=builder /app/server /app/server
EXPOSE 8888
RUN chmod +x ./server
ENTRYPOINT ["./server"]

34
Makefile Normal file
View File

@ -0,0 +1,34 @@
FRONTEND_IMAGE = snowykami/neo-blog-frontend:latest
BACKEND_IMAGE = snowykami/neo-blog-backend:latest
# 镜像名
FRONTEND_IMAGE = snowykami/neo-blog-frontend:latest
BACKEND_IMAGE = snowykami/neo-blog-backend:latest
# 构建前端镜像
.PHONY: build-frontend
build-frontend:
docker build -t $(FRONTEND_IMAGE) ./web
# 构建后端镜像
.PHONY: build-backend
build-backend:
docker build -t $(BACKEND_IMAGE) .
# 构建全部镜像
.PHONY: build
build: build-frontend build-backend
# 推送前端镜像
.PHONY: push-frontend
push-frontend:
docker push $(FRONTEND_IMAGE)
# 推送后端镜像
.PHONY: push-backend
push-backend:
docker push $(BACKEND_IMAGE)
# 推送全部镜像
.PHONY: push
push: push-frontend push-backend

View File

@ -0,0 +1,21 @@
services:
frontend:
container_name: neo-blog-frontend
networks:
- neo-blog-network
image: snowykami/neo-blog-frontend:latest
restart: always
backend:
container_name: neo-blog-backend
networks:
- neo-blog-network
image: snowykami/neo-blog-backend:latest
restart: always
volumes:
- ./data:/app/data
- ./.env:/app/.env
networks:
neo-blog-network:
driver: bridge

View File

@ -2,6 +2,7 @@ package v1
import (
"context"
"fmt"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/snowykami/neo-blog/internal/ctxutils"
@ -93,6 +94,7 @@ func (p *PostController) Update(ctx context.Context, c *app.RequestContext) {
func (p *PostController) List(ctx context.Context, c *app.RequestContext) {
pagination := ctxutils.GetPaginationParams(c)
fmt.Println(pagination)
if pagination.OrderedBy == "" {
pagination.OrderedBy = constant.OrderedByUpdatedAt
}

View File

@ -1,6 +1,7 @@
package repo
import (
"fmt"
"github.com/snowykami/neo-blog/internal/model"
"github.com/snowykami/neo-blog/pkg/constant"
"github.com/snowykami/neo-blog/pkg/errs"
@ -64,12 +65,13 @@ func (p *postRepo) ListPosts(currentUserID uint, keywords []string, page, size u
} else {
query = query.Where("is_private = ?", false)
}
fmt.Println(keywords)
if len(keywords) > 0 {
for _, keyword := range keywords {
if keyword != "" {
// 使用LIKE进行模糊匹配搜索标题、内容和标签
query = query.Where("title LIKE ? OR content LIKE ? OR tags LIKE ?",
"%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%")
query = query.Where("title LIKE ? OR content LIKE ?", // TODO: 支持标签搜索
"%"+keyword+"%", "%"+keyword+"%")
}
}
}

View File

@ -32,12 +32,13 @@ const (
OrderedByLikeCount = "like_count" // 按点赞数排序
OrderedByCommentCount = "comment_count" // 按评论数排序
OrderedByViewCount = "view_count" // 按浏览量排序
HeatFactorViewWeight = 1 // 热度因子:浏览量权重
HeatFactorLikeWeight = 5 // 热度因子:点赞权重
HeatFactorCommentWeight = 10 // 热度因子:评论权重
OrderedByHeat = "heat"
HeatFactorViewWeight = 1 // 热度因子:浏览量权重
HeatFactorLikeWeight = 5 // 热度因子:点赞权重
HeatFactorCommentWeight = 10 // 热度因子:评论权重
)
var (
OrderedByEnumPost = []string{OrderedByCreatedAt, OrderedByUpdatedAt, OrderedByLikeCount, OrderedByCommentCount, OrderedByViewCount} // 帖子可用的排序方式
OrderedByEnumPost = []string{OrderedByCreatedAt, OrderedByUpdatedAt, OrderedByLikeCount, OrderedByCommentCount, OrderedByViewCount, OrderedByHeat} // 帖子可用的排序方式
)

7
web/.dockerignore Normal file
View File

@ -0,0 +1,7 @@
Dockerfile
.dockerignore
node_modules
npm-debug.log
README.md
.next
.git

66
web/Dockerfile Normal file
View File

@ -0,0 +1,66 @@
# syntax=docker.io/docker/dockerfile:1
FROM node:20-alpine AS base
# Install dependencies only when needed
FROM base AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app
# Install dependencies based on the preferred package manager
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* .npmrc* ./
RUN \
if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
elif [ -f package-lock.json ]; then npm ci; \
elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm i --frozen-lockfile; \
else echo "Lockfile not found." && exit 1; \
fi
# Rebuild the source code only when needed
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the build.
# ENV NEXT_TELEMETRY_DISABLED=1
RUN \
if [ -f yarn.lock ]; then yarn run build; \
elif [ -f package-lock.json ]; then npm run build; \
elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm run build; \
else echo "Lockfile not found." && exit 1; \
fi
# Production image, copy all the files and run next
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
# Uncomment the following line in case you want to disable telemetry during runtime.
# ENV NEXT_TELEMETRY_DISABLED=1
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
ENV PORT=3000
# server.js is created by next build from the standalone output
# https://nextjs.org/docs/pages/api-reference/config/next-config-js/output
ENV HOSTNAME="0.0.0.0"
CMD ["node", "server.js"]

View File

@ -1,6 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone",
images: {
remotePatterns: [
{
@ -28,5 +29,4 @@ const nextConfig: NextConfig = {
]
}
};
export default nextConfig;

10
web/src/api/label.ts Normal file
View File

@ -0,0 +1,10 @@
import type { Label } from "@/models/label";
import type { BaseResponse } from "@/models/resp";
import axiosClient from "./client";
export async function listLabels(): Promise<BaseResponse<Label[]>> {
const res = await axiosClient.get<BaseResponse<Label[]>>("/label/list", {
});
return res.data;
}

View File

@ -10,6 +10,16 @@ interface ListPostsParams {
keywords?: string;
}
export async function getPostById(id: string): Promise<Post | null> {
try {
const res = await axiosClient.get<BaseResponse<Post>>(`/post/p/${id}`);
return res.data.data;
} catch (error) {
console.error("Error fetching post by ID:", error);
return null;
}
}
export async function listPosts({
page = 1,
size = 10,

View File

@ -1,189 +1,8 @@
"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 BlogHome from "@/components/blog-home";
export default function Home() {
const [labels, setLabels] = useState<Label[]>([]);
const [posts, setPosts] = useState<Post[]>([]);
useEffect(() => {
listPosts().then(data => {
setPosts(data.data);
console.log(posts);
}).catch(error => {
console.error("Failed to fetch posts:", error);
});
}, []);
return (
<div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50">
{/* 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">
Snowykami's Blog
</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-12">
<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-3 text-lg border-slate-200 focus:border-blue-500 rounded-full"
/>
</div>
{/* 热门标签 */}
<div className="flex flex-wrap justify-center gap-2 mb-8">
{['React', 'TypeScript', 'Next.js', 'Node.js', 'AI', ''].map((tag) => (
<Badge
key={tag}
variant="secondary"
className="px-4 py-2 hover:bg-blue-100 cursor-pointer transition-colors"
>
{tag}
</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">最新文章</h2>
<div className="flex items-center gap-4">
<Button variant="outline" size="sm">
<Clock className="w-4 h-4 mr-2" />
最新
</Button>
<Button variant="outline" size="sm">
<TrendingUp className="w-4 h-4 mr-2" />
热门
</Button>
</div>
</div>
{/* 博客卡片网格 */}
<BlogCardGrid posts={posts} />
{/* 加载更多按钮 */}
<div className="text-center mt-12">
<Button size="lg" className="px-8">
加载更多文章
</Button>
</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 mb-3 bg-gradient-to-br from-blue-400 to-purple-500 rounded-full flex items-center justify-center text-white text-2xl font-bold">
S
</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>
{/* 热门文章 */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<TrendingUp className="w-5 h-5 text-orange-500" />
热门文章
</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">
{['React', 'TypeScript', 'Next.js', 'Node.js', 'JavaScript', 'CSS', 'HTML', 'Vue', 'Angular', 'Webpack'].map((tag) => (
<Badge
key={tag}
variant="outline"
className="text-xs hover:bg-blue-50 cursor-pointer"
>
{tag}
</Badge>
))}
</div>
</CardContent>
</Card>
</div>
</div>
</div>
</section>
</div>
);
}
export default function Page(){
return <BlogHome />
}

View File

@ -1,10 +1,9 @@
import { GalleryVerticalEnd } from "lucide-react"
import Image from "next/image"
import { LoginForm } from "@/components/login-form"
import config from "@/config"
import { Suspense } from "react"
export default function LoginPage() {
function LoginPageContent() {
return (
<div className="bg-muted flex min-h-svh flex-col items-center justify-center gap-6 p-6 md:p-10">
<div className="flex w-full max-w-sm flex-col gap-6">
@ -25,3 +24,28 @@ export default function LoginPage() {
</div>
)
}
export default function LoginPage() {
return (
<Suspense fallback={
<div className="bg-muted flex min-h-svh flex-col items-center justify-center gap-6 p-6 md:p-10">
<div className="flex w-full max-w-sm flex-col gap-6">
<div className="animate-pulse">
<div className="flex items-center gap-3 self-center mb-6">
<div className="size-10 bg-gray-300 rounded-full"></div>
<div className="h-8 bg-gray-300 rounded w-32"></div>
</div>
<div className="bg-white rounded-lg p-6 space-y-4">
<div className="h-4 bg-gray-300 rounded w-3/4"></div>
<div className="h-4 bg-gray-300 rounded w-1/2"></div>
<div className="h-10 bg-gray-300 rounded"></div>
<div className="h-10 bg-gray-300 rounded"></div>
</div>
</div>
</div>
</div>
}>
<LoginPageContent />
</Suspense>
)
}

View File

@ -0,0 +1,82 @@
import { getPostById } from "@/api/post";
import { notFound } from "next/navigation";
interface Props {
params: Promise<{
id: string;
}>
}
export default async function PostPage({ params }: Props) {
const { id } = await params;
try {
const post = await getPostById(id);
if (!post) {
notFound();
}
return (
<article className="max-w-4xl mx-auto px-4 py-8">
<header className="mb-8">
<h1 className="text-4xl font-bold mb-4">{post.title}</h1>
<div className="text-gray-600 mb-4">
<time>{new Date(post.createdAt).toLocaleDateString()}</time>
<span className="mx-2">·</span>
<span>: {post.viewCount || 0}</span>
</div>
</header>
<div className="prose max-w-none">
<div dangerouslySetInnerHTML={{ __html: post.content }} />
</div>
{post.labels && post.labels.length > 0 && (
<footer className="mt-8 pt-8 border-t">
<div className="flex flex-wrap gap-2">
{post.labels.map((label) => (
<span key={label.id} className="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm">
#{label.key}
</span>
))}
</div>
</footer>
)}
</article>
);
} catch (error) {
console.error("Failed to fetch post:", error);
notFound();
}
}
// 生成元数据
export async function generateMetadata({ params }: Props) {
const { id } = await params;
try {
const post = await getPostById(id);
if (!post) {
return {
title: '文章未找到',
};
}
return {
title: post.title,
description: post.content?.substring(0, 160),
openGraph: {
title: post.title,
description: post.content?.substring(0, 160),
type: 'article',
publishedTime: post.createdAt,
},
};
} catch (error) {
return {
title: '文章未找到',
};
}
}

View File

@ -0,0 +1,8 @@
export default function Page() {
return (
<div>
<h1>Page Title</h1>
<p>This is the User content.</p>
</div>
)
}

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

@ -8,7 +8,9 @@ const config = {
owner: {
name: "Snowykami",
description: "全栈开发工程师,喜欢分享技术心得和生活感悟。",
motto: "And now that story unfolds into a journey that, alone, I set out to"
motto: "And now that story unfolds into a journey that, alone, I set out to",
avatar: "https://cdn.liteyuki.org/snowykami/avatar.jpg",
gravatarEmail: "snowykami@outlook.com"
}
}

View File

@ -0,0 +1,35 @@
import { useState, useEffect, useCallback } from 'react';
export function useStoredState<T>(key: string, defaultValue: T) {
const [value, setValue] = useState<T>(defaultValue);
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
try {
const stored = localStorage.getItem(key);
if (stored) {
try {
setValue(JSON.parse(stored));
} catch {
setValue(stored as T);
}
}
} catch (error) {
console.error('Error reading from localStorage:', error);
} finally {
setIsLoaded(true);
}
}, [key]);
// 使用 useCallback 确保 setter 函数引用稳定
const setStoredValue = useCallback((newValue: T) => {
setValue(newValue);
try {
localStorage.setItem(key, typeof newValue === 'string' ? newValue : JSON.stringify(newValue));
} catch (error) {
console.error('Error writing to localStorage:', error);
}
}, [key]);
return [value, setStoredValue, isLoaded] as const;
}

2
web/src/localstore.ts Normal file
View File

@ -0,0 +1,2 @@
export const POST_SORT_TYPE = "post_sort_type";
export const POST_SORT_TYPE_DEFAULT = "latest";