feat: 添加每日签到功能,新增帖子排序与社区面板优化

本次提交完成了多个核心功能迭代:
1.  新增用户每日签到系统,包含签到状态查询、连续天数统计、积分累计逻辑
2.  新增"新帖子"排序选项,替换原有的latest排序为新评论排序
3.  重构首页信息流布局,优化移动端与桌面端展示样式
4.  新增最新评论、最新注册用户模块,完善社区面板数据展示
5.  新增静态友情链接配置模块
6.  提取通用时间格式化工具函数,统一全站相对时间展示
7.  补充数据库签到模型与后端API接口,完善前后端交互链路
This commit is contained in:
2026-09-13 06:03:40 +08:00
parent 95921d24fa
commit 9bae6f2513
19 changed files with 790 additions and 280 deletions

View File

@@ -430,41 +430,34 @@ h1, h2, h3, h4 {
工作台组件(WORKSPACE EDITION)
============================================================ */
/* 分段控件:凹陷轨道 + 凸起的白色选中胶囊 */
.j13-seg {
display: inline-flex;
align-items: center;
gap: 2px;
padding: 4px;
background: var(--tint);
border: 1px solid var(--line);
border-radius: 999px;
}
.j13-seg [role="tab"] {
/* 信息流小 tab:描边小圆角按钮,选中为 accent 浅底描边(布局类走 Tailwind,此处不写 display) */
.j13-tab {
appearance: none;
border: 1px solid transparent;
background: transparent;
border: 1px solid var(--line);
background: var(--panel);
border-radius: 999px;
padding: 6.5px 15px;
padding: 4.5px 12px;
font-family: var(--font-sans);
font-size: 13.5px;
font-size: 12.5px;
font-weight: 600;
line-height: 1.35;
color: var(--ink-3);
cursor: pointer;
white-space: nowrap;
transition: background 0.18s ease, color 0.18s ease, box-shadow 0.18s ease,
transform 0.12s ease;
transition: background 0.16s ease, color 0.16s ease, border-color 0.16s ease;
}
.j13-seg [role="tab"]:hover {
.j13-tab:hover {
color: var(--ink);
border-color: var(--line-2);
background: var(--panel-2);
}
.j13-seg [role="tab"][aria-selected="true"] {
background: var(--panel);
.j13-tab[aria-selected="true"] {
background: var(--accent-soft);
border-color: color-mix(in srgb, var(--accent) 38%, var(--line));
color: var(--accent);
box-shadow: var(--shadow-sm);
font-weight: 700;
}
.j13-seg [role="tab"]:active {
.j13-tab:active {
transform: scale(0.97);
}
@@ -582,77 +575,6 @@ h1, h2, h3, h4 {
border-color: color-mix(in srgb, var(--accent) 32%, var(--line));
}
/* 首页欢迎横幅 */
.j13-hero {
position: relative;
overflow: hidden;
padding: 20px 22px;
border-radius: var(--r);
border: 1px solid var(--line);
box-shadow: var(--shadow-sm);
background:
linear-gradient(115deg, color-mix(in srgb, var(--accent-soft) 75%, var(--panel)) 0%, var(--panel) 60%);
}
.j13-hero-glow {
position: absolute;
top: -72px;
right: -52px;
width: 200px;
height: 200px;
border-radius: 9999px;
background: var(--accent-soft);
pointer-events: none;
}
.j13-hero-stats {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px 10px;
width: 100%;
}
.j13-hero-stat {
display: flex;
flex-direction: column;
gap: 3px;
min-width: 0;
}
.j13-hero-stat-num {
font-size: 21px;
font-weight: 800;
line-height: 1.15;
letter-spacing: -0.015em;
color: var(--ink);
font-variant-numeric: tabular-nums;
}
.j13-hero-stat-num.is-hot { color: var(--accent); }
.j13-hero-stat-lab {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 12px;
color: var(--ink-3);
white-space: nowrap;
}
.j13-dot-pulse {
width: 6px;
height: 6px;
border-radius: 9999px;
background: var(--accent);
animation: j13-dot-pulse 2.4s ease-in-out infinite;
}
@media (min-width: 1024px) {
.j13-hero { padding: 22px 26px; }
.j13-hero-stats {
display: flex;
width: auto;
gap: 0;
}
.j13-hero-stat + .j13-hero-stat {
margin-left: 22px;
padding-left: 22px;
border-left: 1px solid var(--line);
}
}
/* 移动端横向板块条(滚动条隐藏,保留触控惯性) */
.j13-chips {
display: flex;
@@ -810,11 +732,6 @@ h1, h2, h3, h4 {
}
.j13-fade-up { animation: j13-fade-up 0.2s ease-out both; }
@keyframes j13-dot-pulse {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.35; transform: scale(0.8); }
}
/* 跳到主内容 */
.skip-link {
position: fixed;

View File

@@ -14,7 +14,6 @@ import PostRow from "@/components/PostRow";
import FeedTabs, { type FeedSort } from "@/components/home/FeedTabs";
import { WorkspaceNav, WorkspaceNavMobile } from "@/components/home/WorkspaceNav";
import { CommunityPanels, CommunityPanelsMobile } from "@/components/home/CommunityPanels";
import HomeHero from "@/components/home/HomeHero";
export const metadata: Metadata = {
title: "姜十三论坛 · 技术讨论社区",
@@ -26,7 +25,10 @@ interface HomePageProps {
}
function normalizeSort(v?: string): FeedSort {
return v === "hot" || v === "recommended" ? v : "latest";
if (v === "new" || v === "recommended") return v;
// 兼容旧的 ?sort=hot 链接:落到最接近的推荐帖
if (v === "hot") return "recommended";
return "latest";
}
// 空结果面板(无帖 / 无搜索结果)
@@ -125,25 +127,14 @@ export default async function HomePage({ searchParams }: HomePageProps) {
);
}
// 置顶帖直接按后端 pinned DESC 顺序并入统一信息流,同样的行布局
// 置顶帖直接按后端 pinned DESC 顺序并入统一信息流;标题仅供屏幕阅读器
const heading = activeBoard
? activeBoard.name
: sort === "hot"
? "热门讨论"
: sort === "new"
? "最新发布"
: sort === "recommended"
? "精华内容"
? "推荐帖"
: "最新讨论";
const headingHint = activeBoard
? sort === "hot"
? "该板块按点赞与评论热度排序"
: sort === "recommended"
? "该板块管理员精选的优质内容"
: "该板块新发帖与新评论都会浮到顶部"
: sort === "hot"
? "按点赞与评论热度排序"
: sort === "recommended"
? "管理员精选的优质内容"
: "新发帖与新评论都会浮到顶部";
const pageQuery: Record<string, string> = {};
if (boardId > 0) pageQuery.board = String(boardId);
@@ -151,31 +142,22 @@ export default async function HomePage({ searchParams }: HomePageProps) {
return (
<div>
<HomeHero user={user} stats={overview?.stats ?? null} />
<WorkspaceNavMobile boards={boards} user={user} />
<div className="flex items-start gap-6 xl:gap-7 mt-5 lg:mt-0">
<WorkspaceNav boards={boards} user={user} />
{/* 中栏:帖子流(左栏切板块只替换这一列) */}
{/* 中栏:tab 栏与帖子流为同一个整体卡片(左栏切板块只替换这一列) */}
<div className="flex-1 min-w-0">
<div className="flex items-end justify-between gap-3 flex-wrap mb-4">
<div className="min-w-0">
<h1
className="text-[23px] sm:text-[27px] font-extrabold tracking-tight"
style={{ color: "var(--ink)" }}
>
{heading}
</h1>
<p className="meta mt-1.5">
共 {postsData.total} 篇 · {headingHint}
</p>
</div>
<FeedTabs current={sort} boardId={boardId} />
</div>
<h1 className="sr-only">{heading}</h1>
<div className="panel overflow-hidden">
<div className="flex items-center justify-between gap-2 px-3 sm:px-4 pt-3 pb-2.5">
<FeedTabs current={sort} boardId={boardId} />
<span className="meta shrink-0 text-[12px] tabular-nums">
共 {postsData.total} 篇
</span>
</div>
{postsData.posts.length > 0 ? (
postsData.posts.map((post, i) => (
<PostRow
@@ -204,14 +186,27 @@ export default async function HomePage({ searchParams }: HomePageProps) {
{/* 右栏:社区面板 */}
{overview && (
<CommunityPanels hot={overview.hot} activeUsers={overview.active_users} />
<CommunityPanels
stats={overview.stats}
hot={overview.hot}
activeUsers={overview.active_users}
latestComments={overview.latest_comments}
newUsers={overview.new_users}
checkin={overview.checkin ?? undefined}
/>
)}
</div>
{/* 窄屏:面板下沉到帖子流之后 */}
{overview && (
<div className="mt-6">
<CommunityPanelsMobile hot={overview.hot} activeUsers={overview.active_users} />
<CommunityPanelsMobile
hot={overview.hot}
activeUsers={overview.active_users}
latestComments={overview.latest_comments}
newUsers={overview.new_users}
checkin={overview.checkin ?? undefined}
/>
</div>
)}
</div>

View File

@@ -1,25 +1,11 @@
import Link from "next/link";
import { ArrowLeft } from "lucide-react";
import type { PostListItem } from "@/lib/api";
import { formatRelative } from "@/lib/format";
import LikeButton from "./LikeButton";
import Avatar from "./Avatar";
import { IconComment, IconEye } from "./Icons";
/** 发帖/回复时间统一为相对时间:刚刚 / N分钟前 / N小时前 / N天前 / N个月前 / N年前 */
function formatRelative(dateStr: string) {
const t = new Date(dateStr).getTime();
const diff = Date.now() - t;
const min = 60_000,
hour = 60 * min,
day = 24 * hour;
if (diff < min) return "刚刚";
if (diff < hour) return `${Math.floor(diff / min)}分钟前`;
if (diff < day) return `${Math.floor(diff / hour)}小时前`;
if (diff < 30 * day) return `${Math.floor(diff / day)}天前`;
if (diff < 365 * day) return `${Math.floor(diff / (30 * day))}个月前`;
return `${Math.floor(diff / (365 * day))}年前`;
}
/**
* 帖子列表行(参考社区信息流样式):
* 大头像 + 加粗标题(徽章内联)+ 第二行「板块 · 作者 · 发布时间 ← 最后回复」+
@@ -45,11 +31,13 @@ export default function PostRow({
return (
<div
className="group relative flex items-center gap-3.5 sm:gap-4 px-4 sm:px-5 border-t transition-colors hover:bg-[var(--panel-2)] j13-fade-up"
className={`group relative flex items-center px-4 sm:px-5 border-t transition-colors hover:bg-[var(--panel-2)] j13-fade-up ${
compact ? "gap-2.5 sm:gap-3" : "gap-3.5 sm:gap-4"
}`}
style={{
borderColor: "var(--line)",
paddingTop: compact ? 15 : 18,
paddingBottom: compact ? 15 : 18,
paddingTop: compact ? 11 : 18,
paddingBottom: compact ? 11 : 18,
animationDelay: `${Math.min(index, 9) * 35}ms`,
}}
>
@@ -59,7 +47,7 @@ export default function PostRow({
aria-label={post.user.nickname}
tabIndex={-1}
>
<Avatar name={post.user.nickname || post.user.username} size={compact ? 44 : 46} />
<Avatar name={post.user.nickname || post.user.username} size={compact ? 38 : 46} />
</Link>
<div className="flex-1 min-w-0">
@@ -72,14 +60,20 @@ export default function PostRow({
aria-label={post.title}
>
<h3
className="font-bold text-[16px] sm:text-[17px] leading-snug truncate transition-colors group-hover:text-[var(--accent)]"
className={`font-bold leading-snug truncate transition-colors group-hover:text-[var(--accent)] ${
compact ? "text-[15px]" : "text-[16px] sm:text-[17px]"
}`}
style={{ color: "var(--ink)" }}
>
{post.title}
</h3>
</Link>
</div>
<div className="meta relative z-[2] flex items-center gap-x-2 gap-y-1 mt-1.5 flex-wrap text-[13px]">
<div
className={`meta relative z-[2] flex items-center gap-x-2 gap-y-1 flex-wrap ${
compact ? "mt-1 text-[12.5px]" : "mt-1.5 text-[13px]"
}`}
>
{boardHref && (
<Link
href={`/board/${post.board.id}`}
@@ -109,6 +103,11 @@ export default function PostRow({
<span className="tabular-nums shrink-0">{formatRelative(lastReply!.created_at)}</span>
</span>
)}
{!replied && post.comment_count === 0 && (
<span className="hidden sm:inline" aria-hidden>
· 暂无回复
</span>
)}
</div>
</div>

View File

@@ -0,0 +1,113 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { CalendarDays, CalendarCheck, LogIn, Loader2 } from "lucide-react";
import { apiDoCheckin, type CheckinStatus } from "@/lib/api";
/**
* 每日签到卡(右栏)。
* initial 为 undefined 表示游客;否则为 SSR 注入的登录用户签到状态。
*/
export default function CheckinCard({ initial }: { initial?: CheckinStatus | null }) {
const [status, setStatus] = useState<CheckinStatus | null>(initial ?? null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
// 游客态
if (initial === undefined) {
return (
<section className="j13-module" aria-label="每日签到">
<div className="flex items-center gap-3">
<span
className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0"
style={{ background: "var(--accent-soft)", color: "var(--accent)" }}
>
<CalendarDays size={19} />
</span>
<div className="min-w-0">
<p className="text-[14px] font-bold" style={{ color: "var(--ink)" }}>
每日签到
</p>
<p className="meta text-[12px] mt-0.5">登录后每日签到领积分</p>
</div>
</div>
<Link href="/login?redirect=/" className="btn btn-line btn-sm w-full justify-center mt-3.5">
<LogIn size={14} /> 登录后签到
</Link>
</section>
);
}
const checked = status?.checked_today ?? false;
async function doCheckin() {
if (loading || checked) return;
setLoading(true);
setError("");
try {
setStatus(await apiDoCheckin());
} catch (e) {
setError(e instanceof Error ? e.message : "签到失败");
} finally {
setLoading(false);
}
}
return (
<section className="j13-module" aria-label="每日签到">
<div className="flex items-center gap-3">
<span
className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0"
style={{
background: checked ? "var(--accent-soft)" : "var(--panel-2)",
color: checked ? "var(--accent)" : "var(--ink-2)",
}}
>
{checked ? <CalendarCheck size={19} /> : <CalendarDays size={19} />}
</span>
<div className="flex-1 min-w-0">
<p className="text-[14px] font-bold" style={{ color: "var(--ink)" }}>
每日签到
</p>
<p className="meta text-[12px] mt-0.5">
{checked
? `已连续签到 ${status?.streak ?? 0} 天 · 累计 ${status?.total_points ?? 0} 积分`
: `连续 ${status?.streak ?? 0} 天 · 今日可得 ${status?.today_points ?? 5} 积分`}
</p>
</div>
{!checked && (
<span className="text-[17px] font-extrabold tabular-nums shrink-0" style={{ color: "var(--accent)" }}>
+{status?.today_points ?? 5}
</span>
)}
</div>
<button
type="button"
onClick={doCheckin}
disabled={loading || checked}
aria-disabled={loading || checked}
className={`btn w-full justify-center mt-3.5 ${checked ? "btn-line" : "btn-primary"}`}
>
{loading ? (
<>
<Loader2 size={15} className="animate-spin" /> 签到中…
</>
) : checked ? (
<>
<CalendarCheck size={15} /> 今日已签到
</>
) : (
"立即签到"
)}
</button>
{error && (
<p className="text-[12px] mt-2" style={{ color: "var(--clay)" }} role="alert">
{error}
</p>
)}
</section>
);
}

View File

@@ -1,7 +1,106 @@
import Link from "next/link";
import { Flame, Users, MessageCircle, Heart } from "lucide-react";
import type { PostListItem, ActiveUser } from "@/lib/api";
import {
Flame,
Users,
MessageCircle,
Heart,
MessageSquareText,
UserPlus,
Link2,
} from "lucide-react";
import type {
PostListItem,
ActiveUser,
OverviewStats,
LatestComment,
NewUser,
CheckinStatus,
} from "@/lib/api";
import Avatar from "@/components/Avatar";
import CheckinCard from "./CheckinCard";
import { FRIEND_LINKS } from "@/lib/friendLinks";
import { formatRelative } from "@/lib/format";
/* ---------- 品牌卡 ---------- */
function BrandCard({ stats }: { stats: OverviewStats }) {
const items: { num: number; label: string }[] = [
{ num: stats.posts, label: "帖子" },
{ num: stats.comments, label: "回复" },
{ num: stats.users, label: "用户" },
];
return (
<section className="j13-module text-center" aria-label="姜十三论坛">
<p className="text-[16.5px] font-extrabold tracking-wide" style={{ color: "var(--accent)" }}>
姜十三论坛
</p>
<p className="meta mt-1 text-[12px]">分享技术、讨论问题、交流心得</p>
<div
className="mt-3.5 pt-3.5 grid grid-cols-3"
style={{ borderTop: "1px solid var(--line)" }}
>
{items.map((it) => (
<div key={it.label}>
<p
className="text-[19px] font-extrabold tabular-nums leading-none"
style={{ color: "var(--accent)" }}
>
{it.num}
</p>
<p className="meta mt-1.5 text-[11.5px]">{it.label}</p>
</div>
))}
</div>
</section>
);
}
/* ---------- 最新评论 ---------- */
function LatestComments({ comments }: { comments: LatestComment[] }) {
if (comments.length === 0) return null;
return (
<section className="j13-module" aria-label="最新评论">
<p className="j13-module-title mb-1">
<MessageSquareText size={15} style={{ color: "var(--accent)" }} /> 最新评论
</p>
<ul>
{comments.map((c) => {
const name = c.user.nickname || c.user.username;
return (
<li key={c.id}>
<Link href={`/post/${c.post.id}`} className="j13-raillink items-start">
<Avatar name={name} src={c.user.avatar} size={28} className="mt-px" />
<span className="min-w-0 flex-1">
<span className="flex items-baseline gap-1.5">
<span
className="shrink-0 max-w-[84px] truncate text-[12.5px] font-semibold"
style={{ color: "var(--ink-2)" }}
>
{name}
</span>
<span
className="min-w-0 flex-1 truncate text-[13px]"
style={{ color: "var(--ink-2)" }}
>
{c.content}
</span>
</span>
<span className="meta mt-0.5 block truncate text-[11.5px]">
{c.post.title}
</span>
</span>
<span className="meta mt-px shrink-0 text-[11px]">
{formatRelative(c.created_at)}
</span>
</Link>
</li>
);
})}
</ul>
</section>
);
}
/* ---------- 热门榜 ---------- */
@@ -45,6 +144,41 @@ function HotRanking({ posts }: { posts: PostListItem[] }) {
);
}
/* ---------- 最新注册 ---------- */
function NewUsers({ users }: { users: NewUser[] }) {
if (users.length === 0) return null;
return (
<section className="j13-module" aria-label="最新注册">
<p className="j13-module-title mb-3">
<UserPlus size={15} style={{ color: "var(--accent)" }} /> 最新注册
</p>
<ul className="grid grid-cols-4 gap-y-3">
{users.map((u) => {
const name = u.nickname || u.username;
return (
<li key={u.id}>
<Link
href={`/u/${u.id}`}
className="flex flex-col items-center gap-1.5 rounded-lg px-1 py-1 transition-colors hover:bg-[var(--panel-2)]"
>
<Avatar name={name} src={u.avatar} size={38} />
<span
className="w-full truncate text-center text-[11px]"
style={{ color: "var(--ink-2)" }}
title={name}
>
{name}
</span>
</Link>
</li>
);
})}
</ul>
</section>
);
}
/* ---------- 活跃用户 ---------- */
function ActiveUsers({ users }: { users: ActiveUser[] }) {
@@ -73,20 +207,72 @@ function ActiveUsers({ users }: { users: ActiveUser[] }) {
);
}
/* ---------- 友情链接 ---------- */
function FriendLinks() {
return (
<section className="j13-module" aria-label="友情链接">
<p className="j13-module-title mb-3">
<Link2 size={15} style={{ color: "var(--accent)" }} /> 友情链接
<Link
href="/compose"
className="meta ml-auto text-[12px] font-normal transition-colors hover:text-[var(--accent)]"
>
申请
</Link>
</p>
<div className="flex flex-wrap gap-2">
{FRIEND_LINKS.map((l) =>
l.href.startsWith("http") ? (
<a
key={l.name}
href={l.href}
target="_blank"
rel="noopener noreferrer"
className="j13-chip"
>
{l.name}
</a>
) : (
<span key={l.name} className="j13-chip" title="友链待配置">
{l.name}
</span>
)
)}
</div>
</section>
);
}
/* ---------- 桌面 / 移动两种装配 ---------- */
export function CommunityPanels({
hot,
activeUsers,
}: {
type PanelsProps = {
stats: OverviewStats;
hot: PostListItem[];
activeUsers: ActiveUser[];
}) {
latestComments: LatestComment[];
newUsers: NewUser[];
checkin?: CheckinStatus | null;
};
export function CommunityPanels({
stats,
hot,
activeUsers,
latestComments,
newUsers,
checkin,
}: PanelsProps) {
return (
<aside className="hidden lg:block w-[280px] xl:w-[300px] shrink-0" aria-label="社区面板">
<aside className="hidden w-[280px] shrink-0 lg:block xl:w-[300px]" aria-label="社区面板">
<div className="sticky top-24 space-y-4">
<BrandCard stats={stats} />
<CheckinCard initial={checkin} />
<LatestComments comments={latestComments} />
<HotRanking posts={hot} />
<NewUsers users={newUsers} />
<ActiveUsers users={activeUsers} />
<FriendLinks />
</div>
</aside>
);
@@ -95,14 +281,18 @@ export function CommunityPanels({
export function CommunityPanelsMobile({
hot,
activeUsers,
}: {
hot: PostListItem[];
activeUsers: ActiveUser[];
}) {
latestComments,
newUsers,
checkin,
}: Omit<PanelsProps, "stats">) {
return (
<div className="lg:hidden space-y-4" aria-label="社区面板">
<div className="space-y-4 lg:hidden" aria-label="社区面板">
<CheckinCard initial={checkin} />
<LatestComments comments={latestComments} />
<HotRanking posts={hot} />
<NewUsers users={newUsers} />
<ActiveUsers users={activeUsers} />
<FriendLinks />
</div>
);
}

View File

@@ -3,15 +3,11 @@
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useRef } from "react";
import { MessageSquareText, Clock, Sparkles } from "lucide-react";
export type FeedSort = "latest" | "hot" | "recommended";
export type FeedSort = "latest" | "new" | "recommended";
const TAB_KEYS: FeedSort[] = ["latest", "hot", "recommended"];
const TAB_LABELS: Record<FeedSort, string> = {
latest: "最新",
hot: "热门",
recommended: "精华",
};
const TAB_KEYS: FeedSort[] = ["latest", "new", "recommended"];
// 在指定板块内切换排序时保留 ?board=
function tabHref(key: FeedSort, boardId: number) {
@@ -36,22 +32,27 @@ export default function FeedTabs({ current, boardId = 0 }: { current: FeedSort;
};
return (
<div className="j13-seg" role="tablist" aria-label="帖子排序">
{TAB_KEYS.map((key, i) => (
<Link
key={key}
ref={(el) => {
tabRefs.current[i] = el;
}}
href={tabHref(key, boardId)}
role="tab"
aria-selected={current === key}
tabIndex={current === key ? 0 : -1}
onKeyDown={(e) => handleKeyDown(e, i)}
>
{TAB_LABELS[key]}
</Link>
))}
<div className="flex items-center gap-1.5 sm:gap-2" role="tablist" aria-label="帖子排序">
{TAB_KEYS.map((key, i) => {
const Icon = key === "latest" ? MessageSquareText : key === "new" ? Clock : Sparkles;
return (
<Link
key={key}
ref={(el) => {
tabRefs.current[i] = el;
}}
href={tabHref(key, boardId)}
role="tab"
className="j13-tab inline-flex items-center gap-1"
aria-selected={current === key}
tabIndex={current === key ? 0 : -1}
onKeyDown={(e) => handleKeyDown(e, i)}
>
<Icon size={13} className="opacity-80" />
{key === "latest" ? "新评论" : key === "new" ? "新帖子" : "推荐帖"}
</Link>
);
})}
</div>
);
}

View File

@@ -1,76 +0,0 @@
import Link from "next/link";
import { PenSquare, LogIn, UserPlus, MessagesSquare, Users, MessageCircle, Sparkles } from "lucide-react";
import type { OverviewStats } from "@/lib/api";
type HeroUser = { username: string; nickname: string } | null;
function greetingOf(h: number): string {
if (h >= 5 && h < 11) return "早上好";
if (h >= 11 && h < 14) return "中午好";
if (h >= 14 && h < 18) return "下午好";
if (h >= 18 && h < 23) return "晚上好";
return "夜深了";
}
// 首页欢迎横幅:时段问候 + 站点主张 + 发帖引导 + 内联社区数据。纯服务端组件。
export default function HomeHero({ user, stats }: { user: HeroUser; stats: OverviewStats | null }) {
const name = user ? user.nickname || user.username : null;
const hello = greetingOf(new Date().getHours());
const today = stats?.today_posts ?? 0;
const statItems = stats
? [
{ icon: MessagesSquare, label: "讨论", value: stats.posts, hot: false },
{ icon: Users, label: "成员", value: stats.users, hot: false },
{ icon: MessageCircle, label: "评论", value: stats.comments, hot: false },
{ icon: Sparkles, label: today > 0 ? "今日新帖" : "今日", value: today, hot: today > 0 },
]
: [];
return (
<section className="j13-hero mb-5 lg:mb-6" aria-label="欢迎">
<span aria-hidden className="j13-hero-glow" />
<div className="relative flex flex-col lg:flex-row lg:items-center lg:justify-between gap-5">
<div className="min-w-0">
<p className="meta text-[13px]">{name ? `${hello},${name}` : `${hello},欢迎来到姜十三`}</p>
<h2
className="mt-1.5 text-[19px] sm:text-[22px] font-extrabold tracking-tight"
style={{ color: "var(--ink)" }}
>
分享技术、讨论问题、交流心得
</h2>
<div className="mt-4 flex flex-wrap gap-2.5">
{user ? (
<Link href="/compose" className="btn btn-primary w-full sm:w-auto justify-center">
<PenSquare size={15} /> 发起讨论
</Link>
) : (
<>
<Link href="/login?redirect=/" className="btn btn-primary w-full sm:w-auto justify-center">
<LogIn size={15} /> 登录后参与讨论
</Link>
<Link href="/register" className="btn btn-line w-full sm:w-auto justify-center">
<UserPlus size={15} /> 注册
</Link>
</>
)}
</div>
</div>
{statItems.length > 0 && (
<dl className="j13-hero-stats shrink-0" aria-label="社区数据">
{statItems.map(({ icon: Icon, label, value, hot }) => (
<div key={label} className="j13-hero-stat">
<dd className={`j13-hero-stat-num${hot ? " is-hot" : ""}`}>{value}</dd>
<dt className="j13-hero-stat-lab">
{hot && <span className="j13-dot-pulse" aria-hidden />}
<Icon size={12} /> {label}
</dt>
</div>
))}
</dl>
)}
</div>
</section>
);
}

View File

@@ -63,11 +63,37 @@ export interface BoardWithCount extends Board {
post_count: number;
}
export interface LatestComment {
id: number;
content: string;
created_at: string;
user: { id: number; username: string; nickname: string; avatar: string };
post: { id: number; title: string };
}
export interface NewUser {
id: number;
username: string;
nickname: string;
avatar: string;
created_at: string;
}
export interface CheckinStatus {
checked_today: boolean;
streak: number;
total_points: number;
today_points: number;
}
export interface OverviewResponse {
stats: OverviewStats;
hot: PostListItem[];
active_users: ActiveUser[];
boards: BoardWithCount[];
latest_comments: LatestComment[];
new_users: NewUser[];
checkin?: CheckinStatus | null;
}
export interface PostListItem {
@@ -475,3 +501,24 @@ export async function apiMarkAllRead() {
});
return res.json();
}
// ===== 每日签到 =====
export async function apiGetCheckin(): Promise<CheckinStatus> {
const res = await fetchWithRefresh("/api/checkin", {
headers: clientHeaders(),
});
if (!res.ok) throw new Error("获取签到状态失败");
return res.json();
}
// 执行签到;失败(如今日已签,409)抛出后端消息
export async function apiDoCheckin(): Promise<CheckinStatus> {
const res = await fetchWithRefresh("/api/checkin", {
method: "POST",
headers: clientHeaders(),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || "签到失败");
return data as CheckinStatus;
}

14
frontend/lib/format.ts Normal file
View File

@@ -0,0 +1,14 @@
/** 发帖/回复时间统一为相对时间:刚刚 / N分钟前 / N小时前 / N天前 / N个月前 / N年前 */
export function formatRelative(dateStr: string): string {
const t = new Date(dateStr).getTime();
const diff = Date.now() - t;
const min = 60_000,
hour = 60 * min,
day = 24 * hour;
if (diff < min) return "刚刚";
if (diff < hour) return `${Math.floor(diff / min)}分钟前`;
if (diff < day) return `${Math.floor(diff / hour)}小时前`;
if (diff < 30 * day) return `${Math.floor(diff / day)}天前`;
if (diff < 365 * day) return `${Math.floor(diff / (30 * day))}个月前`;
return `${Math.floor(diff / (365 * day))}年前`;
}

View File

@@ -0,0 +1,11 @@
// 友情链接(站点级静态配置)。
// TODO: 替换为真实友链名称与地址;后续如需后台可配,可升级为接口/设置项。
export interface FriendLink {
name: string;
href: string;
}
export const FRIEND_LINKS: FriendLink[] = [
{ name: "大佬论坛", href: "#" },
{ name: "Leo论坛", href: "#" },
];