feat: 更新评论和帖子模型,添加用户信息和原创标识,优化API请求和组件结构

This commit is contained in:
2025-07-28 06:22:07 +08:00
parent 5c20a310e3
commit d73ed493be
20 changed files with 260 additions and 181 deletions

View File

@ -1,9 +1,9 @@
import axios from 'axios'
import { camelToSnakeObj, snakeToCamelObj } from 'field-conv'
export const BACKEND_URL = process.env.BACKEND_URL || 'http://neo-blog-backend:8888'
export const BACKEND_URL = process.env.BACKEND_URL || (process.env.NODE_ENV == "production" ? 'http://neo-blog-backend:8888' : 'http://localhost:8888')
console.info(`Using backend URL: ${BACKEND_URL}`)
console.info(`Using ${process.env.NODE_ENV} backend URL: ${BACKEND_URL}`)
const isServer = typeof window === 'undefined'

View File

@ -11,9 +11,8 @@ interface ListPostsParams {
}
export async function getPostById(id: string): Promise<Post | null> {
console.log('Fetching post by ID:', id)
try {
const res = await axiosClient.get<BaseResponse<Post>>(`/post/p/19`)
const res = await axiosClient.get<BaseResponse<Post>>(`/post/p/${id}`)
return res.data.data
}
catch (error) {

View File

@ -1,8 +1,9 @@
'use client'
import { AnimatePresence, motion } from 'framer-motion'
import { motion } from 'framer-motion'
import { usePathname } from 'next/navigation'
import { Navbar } from '@/components/navbar'
import { BackgroundProvider } from '@/contexts/background-context'
export default function RootLayout({
children,
@ -15,22 +16,21 @@ export default function RootLayout({
<header className="fixed top-0 left-0 w-full z-50 bg-white/80 dark:bg-slate-900/80 backdrop-blur flex justify-center border-b border-slate-200 dark:border-slate-800">
<Navbar />
</header>
<AnimatePresence mode="wait">
<motion.main
key={pathname}
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 16 }}
transition={{
type: 'tween',
ease: 'easeOut',
duration: 0.18,
}}
className="pt-16"
>
{children}
</motion.main>
</AnimatePresence>
<motion.main
key={pathname}
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
transition={{
type: 'tween',
ease: 'easeOut',
duration: 0.30,
}}
className="pt-16"
>
<BackgroundProvider>
<div className='container mx-auto px-4 sm:px-6 lg:px-10 max-w-7xl'>{children}</div>
</BackgroundProvider>
</motion.main>
</>
)
}
}

View File

@ -3,6 +3,8 @@ import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { DeviceProvider } from "@/contexts/device-context";
import { NextIntlClientProvider } from 'next-intl';
import config from "@/config";
import { getUserLocales } from "@/i18n/request";
const geistSans = Geist({
variable: "--font-geist-sans",
@ -15,17 +17,17 @@ const geistMono = Geist_Mono({
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
title: config.metadata.name,
description: config.metadata.description,
};
export default function RootLayout({
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<html lang={(await getUserLocales())[0] || "en"} className="h-full">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>

View File

@ -9,10 +9,11 @@ import type { Label } from "@/models/label";
import type { Post } from "@/models/post";
import { listPosts } from "@/api/post";
import { useEffect, useState } from "react";
import { useEffect, useState } from "react";
import { useStoredState } from '@/hooks/use-storage-state';
import { listLabels } from "@/api/label";
import { POST_SORT_TYPE } from "@/localstore";
import Image from "next/image";
// 定义排序类型
type SortType = 'latest' | 'popular';
@ -84,7 +85,7 @@ export default function BlogHome() {
{/* 主内容区域 */}
<section className="py-16">
{/* 容器 - 关键布局 */}
<div className="container mx-auto px-4 sm:px-6 lg:px-10 max-w-7xl">
<div className="">
<div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
{/* 主要内容区域 */}
<div className="lg:col-span-3 self-start">

View File

@ -1,94 +1,99 @@
"use client";
import { useEffect } from "react";
import Image from "next/image";
import type { Post } from "@/models/post";
import { Calendar, Clock, FileText, Flame, Heart, MessageCircle, PenLine, SquarePen } from "lucide-react";
function WaveHeader({ title }: { title: string }) {
function PostMeta({ post }: { post: Post }) {
// 假设 post 结构包含这些字段
// post.author, post.wordCount, post.readMinutes, post.createdAt, post.isOriginal, post.viewCount, post.commentCount
return (
<div className="relative h-64 flex flex-col items-center justify-center">
{/* 波浪SVG半透明悬浮 */}
<div className="absolute inset-0 w-full h-full pointer-events-none opacity-70 z-0">
<svg className="w-full h-full" viewBox="0 0 1440 320" preserveAspectRatio="none">
<defs>
<linearGradient id="wave-gradient" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stopColor="#4f8cff" />
<stop offset="100%" stopColor="#7b61ff" />
</linearGradient>
</defs>
<path
fill="url(#wave-gradient)"
fillOpacity="1"
d="
M0,160
C360,240 1080,80 1440,160
L1440,320
L0,320
Z
"
>
<animate
attributeName="d"
dur="8s"
repeatCount="indefinite"
values="
M0,160 C360,240 1080,80 1440,160 L1440,320 L0,320 Z;
M0,120 C400,200 1040,120 1440,200 L1440,320 L0,320 Z;
M0,160 C360,240 1080,80 1440,160 L1440,320 L0,320 Z
"
/>
</path>
</svg>
</div>
{/* 标题 */}
<h1 className="relative z-10 text-white text-4xl md:text-5xl font-bold drop-shadow-lg mt-16 text-center">
{title}
</h1>
</div>
);
}
function BlogMeta({ post }: { post: Post }) {
return (
<div className="flex flex-col items-center mb-6">
<div className="flex gap-2 mb-2">
{post.labels?.map(label => (
<span
key={label.id}
className="bg-white/30 px-3 py-1 rounded-full text-sm font-medium backdrop-blur text-white"
>
{label.key}
</span>
))}
</div>
<div className="flex flex-wrap gap-4 text-base text-white/90">
<span> {new Date(post.createdAt).toLocaleDateString()}</span>
<span>👁 {post.viewCount}</span>
<span>💬 {post.commentCount}</span>
<span>🔥 {post.heat}</span>
</div>
</div>
);
}
function BlogContent({ post }: { post: Post }) {
return (
<main className="relative z-10 max-w-3xl mx-auto bg-white rounded-xl shadow-lg p-8 -mt-32">
{post.cover && (
<Image
src={post.cover}
alt="cover"
className="w-full h-64 object-cover rounded-lg mb-8"
/>
console.log(post),
<div className="flex flex-wrap items-center gap-4 mt-6">
{/* 作者 */}
<span className="flex items-center gap-1">
<PenLine className="w-4 h-4" />
{post.user.nickname || "未知作者"}
</span>
{/* 字数 */}
<span className="flex items-center gap-1">
<FileText className="w-4 h-4" />
{post.content.length || 0}
</span>
{/* 阅读时间 */}
<span className="flex items-center gap-1">
<Clock className="w-4 h-4" />
{post.content.length / 100 || 1}
</span>
{/* 发布时间 */}
<span className="flex items-center gap-1">
<Calendar className="w-4 h-4" />
{post.createdAt ? new Date(post.createdAt).toLocaleDateString("zh-CN") : ""}
</span>
{/* 最后编辑时间,如果和发布时间不一样 */}
{post.updatedAt && post.createdAt !== post.updatedAt && (
<span className="flex items-center gap-1">
<SquarePen className="w-4 h-4" />
{new Date(post.updatedAt).toLocaleDateString("zh-CN")}
</span>
)}
<article
className="prose prose-lg max-w-none"
dangerouslySetInnerHTML={{ __html: post.content }}
/>
</main>
{/* 浏览数 */}
<span className="flex items-center gap-1">
<Flame className="w-4 h-4" />
{post.viewCount || 0}
</span>
{/* 点赞数 */}
<span className="flex items-center gap-1">
<Heart className="w-4 h-4" />
{post.likeCount || 0}
</span>
{/* 评论数 */}
<span className="flex items-center gap-1">
<MessageCircle className="w-4 h-4" />
{post.commentCount || 0}
</span>
{/* 热度 */}
<span className="flex items-center gap-1">
<Flame className="w-4 h-4" />
{post.heat || 0}
</span>
</div>
);
}
function PostHeader({ post }: { post: Post }) {
// 三排 标签/标题/一些元数据
return (
<div className="py-32">
{
post.labels && post.labels.length > 0 && (
<div className="flex flex-wrap gap-2 mb-4">
{post.labels.map(label => (
<span key={label.id} className="bg-blue-100 text-blue-600 text-xs px-2 py-1 rounded">
{label.key}
</span>
))}
</div>
)
}
<h1 className="text-5xl font-bold mb-2">{post.title}</h1>
{/* 元数据区 */}
<div>
<PostMeta post={post} />
</div>
</div>
);
}
function PostContent({ post }: { post: Post }) {
return (
<div className="">
<div dangerouslySetInnerHTML={{ __html: post.content }} />
</div>
)
}
function BlogPost({ post }: { post: Post }) {
useEffect(() => {
if (typeof window !== "undefined") {
@ -96,11 +101,10 @@ function BlogPost({ post }: { post: Post }) {
}
}, []);
return (
<div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 relative">
<WaveHeader title={post.title} />
<div className="relative z-10 -mt-40">
<BlogMeta post={post} />
<BlogContent post={post} />
<div className="">
<PostHeader post={post} />
<div className="">
<PostContent post={post} />
</div>
</div>
);

View File

@ -44,8 +44,9 @@ const navbarMenuComponents = [
]
export function Navbar() {
const { navbarAdditionalClassName } = useDevice()
return (
<nav className="grid grid-cols-[1fr_auto_1fr] items-center gap-4 h-16 px-4 w-full">
<nav className={`grid grid-cols-[1fr_auto_1fr] items-center gap-4 h-16 px-4 w-full ${navbarAdditionalClassName}`}>
<div className="flex items-center justify-start">
<span className="font-bold truncate">{config.metadata.name}</span>
</div>
@ -62,7 +63,6 @@ export function Navbar() {
function NavMenuCenter() {
const { isMobile } = useDevice()
console.log("isMobile", isMobile)
if (isMobile) return null
return (
<NavigationMenu viewport={false}>
@ -121,10 +121,10 @@ function ListItem({
}
function SidebarMenuClientOnly() {
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!mounted) return null;
return <SidebarMenu />;
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
if (!mounted) return null;
return <SidebarMenu />;
}
function SidebarMenu() {

View File

@ -11,7 +11,9 @@ const config = {
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"
}
},
bodyWidth: "80vw",
bodyWidthMobile: "100vw",
}
export default config

View File

@ -0,0 +1,60 @@
import React, { createContext, useContext, useState, useCallback } from "react";
interface BackgroundContextType {
background: React.ReactNode;
setBackground: (bg: React.ReactNode) => void;
resetBackground: () => void;
}
const BackgroundContext = createContext<BackgroundContextType | undefined>(undefined);
export const BackgroundProvider: React.FC<{ children: React.ReactNode; defaultBackground?: React.ReactNode }> = ({
children,
defaultBackground = null,
}) => {
const [background, setBackgroundState] = useState<React.ReactNode>(defaultBackground);
const setBackground = useCallback((bg: React.ReactNode) => {
setBackgroundState(bg);
}, []);
const resetBackground = useCallback(() => {
setBackgroundState(defaultBackground);
}, [defaultBackground]);
return (
<BackgroundContext.Provider value={{ background, setBackground, resetBackground }}>
{/* 背景节点自动渲染在 children 之下 */}
<div style={{ position: "relative", width: "100%", height: "100%" }}>
{background && (
<div
style={{
position: "absolute",
inset: 0,
zIndex: 0,
width: "100%",
height: "100%",
pointerEvents: "none",
}}
aria-hidden="true"
>
{background}
</div>
)}
<div style={{ position: "relative", zIndex: 1 }}>{children}</div>
</div>
</BackgroundContext.Provider>
);
};
export function useBackground() {
const ctx = useContext(BackgroundContext);
if (!ctx) throw new Error("useBackground must be used within a BackgroundProvider");
return ctx;
}
// 便于直接解构使用
export const backgroundContext = {
useBackground,
BackgroundProvider,
};

View File

@ -13,6 +13,8 @@ interface DeviceContextProps {
width: number;
height: number;
};
navbarAdditionalClassName?: string; // 可选属性,允许传入额外的类名
setNavbarAdditionalClassName?: (className: string) => void; // 可选方法,允许设置额外的类名
}
const DeviceContext = createContext<DeviceContextProps>({
@ -24,6 +26,8 @@ const DeviceContext = createContext<DeviceContextProps>({
width: 0,
height: 0,
},
navbarAdditionalClassName: "",
setNavbarAdditionalClassName: () => {},
});
export const DeviceProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
@ -33,6 +37,7 @@ export const DeviceProvider: React.FC<{ children: React.ReactNode }> = ({ childr
width: typeof window !== "undefined" ? window.innerWidth : 0,
height: typeof window !== "undefined" ? window.innerHeight : 0,
});
const [navbarAdditionalClassName, setNavbarAdditionalClassName] = useState<string>("");
// 检查系统主题
const getSystemTheme = () =>
@ -109,7 +114,7 @@ export const DeviceProvider: React.FC<{ children: React.ReactNode }> = ({ childr
return (
<DeviceContext.Provider
value={{ isMobile, mode, setMode, toggleMode, viewport }}
value={{ isMobile, mode, setMode, toggleMode, viewport, navbarAdditionalClassName, setNavbarAdditionalClassName }}
>
{children}
</DeviceContext.Provider>

View File

@ -10,7 +10,8 @@ export default getRequestConfig(async () => {
try {
return (await import(`@/locales/${locale}.json`)).default;
} catch (err) {
console.error(err)
console.warn();
(err)
return {};
}
})

View File

@ -1,4 +1,5 @@
import type { Label } from "@/models/label";
import type { User } from "./user";
export interface Post {
id: number;
@ -7,7 +8,9 @@ export interface Post {
cover: string | null; // 封面可以为空
type: "markdown" | "html" | "text";
labels: Label[] | null; // 标签可以为空
user: User
isPrivate: boolean;
isOriginal: boolean;
likeCount: number;
commentCount: number;
viewCount: number;