OPC
This commit is contained in:
28
app/admin/edit/[slug]/page.tsx
Normal file
28
app/admin/edit/[slug]/page.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
import { getDb } from "@/lib/mongo";
|
||||
import { notFound } from "next/navigation";
|
||||
import { EditPostForm } from "@/components/EditPostForm";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
async function fetchPost(slug: string) {
|
||||
const db = await getDb();
|
||||
const post = await db.collection("posts").findOne({ slug });
|
||||
if (!post) return null;
|
||||
return {
|
||||
...post,
|
||||
_id: post._id?.toString()
|
||||
};
|
||||
}
|
||||
|
||||
export default async function EditPostPage({ params }: { params: { slug: string } }) {
|
||||
const post = await fetchPost(params.slug);
|
||||
if (!post) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<EditPostForm post={post} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
73
app/admin/page.tsx
Normal file
73
app/admin/page.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
import { CreatePostForm } from "@/components/CreatePostForm";
|
||||
import { AdminPostList } from "@/components/AdminPostList";
|
||||
import { getDb } from "@/lib/mongo";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
async function fetchStats() {
|
||||
const db = await getDb();
|
||||
const collection = db.collection("posts");
|
||||
const total = await collection.countDocuments();
|
||||
const latest = await collection.find({}, { projection: { title: 1, createdAt: 1 } }).sort({ createdAt: -1 }).limit(1).toArray();
|
||||
const top = await collection.find({}, { projection: { title: 1, views: 1, slug: 1 } }).sort({ views: -1 }).limit(3).toArray();
|
||||
|
||||
return { total, latest: latest[0] || null, top };
|
||||
}
|
||||
|
||||
async function fetchRecentPosts() {
|
||||
const db = await getDb();
|
||||
const posts = await db
|
||||
.collection("posts")
|
||||
.find({}, { projection: { markdown: 0 } })
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(20)
|
||||
.toArray();
|
||||
return posts.map((p: any) => ({
|
||||
...p,
|
||||
_id: p._id?.toString(),
|
||||
createdAtText: new Date(p.createdAt).toLocaleString("zh-CN", {
|
||||
hour12: false,
|
||||
timeZone: "Asia/Shanghai"
|
||||
})
|
||||
}));
|
||||
}
|
||||
|
||||
export default async function AdminPage() {
|
||||
const stats = await fetchStats();
|
||||
const recentPosts = await fetchRecentPosts();
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<section className="grid gap-4 sm:grid-cols-3">
|
||||
<div className="rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100">
|
||||
<p className="text-sm text-slate-500">累计发布</p>
|
||||
<p className="mt-1 text-3xl font-semibold">{stats.total}</p>
|
||||
</div>
|
||||
<div className="rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100">
|
||||
<p className="text-sm text-slate-500">最新一条</p>
|
||||
<p className="mt-1 text-base font-semibold">{stats.latest?.title ?? "暂无"}</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
{stats.latest?.createdAt
|
||||
? new Date(stats.latest.createdAt).toLocaleString("zh-CN", { hour12: false })
|
||||
: ""}
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100">
|
||||
<p className="text-sm text-slate-500">Top 热度</p>
|
||||
<ul className="mt-1 space-y-1 text-sm">
|
||||
{stats.top.map((item: any) => (
|
||||
<li key={item.slug} className="flex items-center justify-between">
|
||||
<span className="truncate">{item.title}</span>
|
||||
<span className="text-slate-500">{item.views ?? 0} 次</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<CreatePostForm />
|
||||
|
||||
<AdminPostList initialPosts={recentPosts} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
16
app/api/admin/stats/route.ts
Normal file
16
app/api/admin/stats/route.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getDb } from "@/lib/mongo";
|
||||
|
||||
export async function GET() {
|
||||
const db = await getDb();
|
||||
const collection = db.collection("posts");
|
||||
const total = await collection.countDocuments();
|
||||
const latest = await collection.find({}, { projection: { title: 1, createdAt: 1 } }).sort({ createdAt: -1 }).limit(1).toArray();
|
||||
const top = await collection.find({}, { projection: { title: 1, views: 1, slug: 1 } }).sort({ views: -1 }).limit(3).toArray();
|
||||
|
||||
return NextResponse.json({
|
||||
total,
|
||||
latest: latest[0] || null,
|
||||
top
|
||||
});
|
||||
}
|
||||
27
app/api/login/route.ts
Normal file
27
app/api/login/route.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { signSession, cookieName } from "@/lib/auth";
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const password = body.password as string | undefined;
|
||||
const target = process.env.ADMIN_PASS;
|
||||
|
||||
if (!target) {
|
||||
return NextResponse.json({ error: "ADMIN_PASS is not set on server" }, { status: 500 });
|
||||
}
|
||||
|
||||
if (!password || password !== target) {
|
||||
return NextResponse.json({ error: "密码错误" }, { status: 401 });
|
||||
}
|
||||
|
||||
const token = await signSession({ role: "admin", iat: Date.now() });
|
||||
const res = NextResponse.json({ ok: true });
|
||||
res.cookies.set(cookieName, token, {
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
secure: true,
|
||||
maxAge: 60 * 60 * 24 * 30,
|
||||
path: "/"
|
||||
});
|
||||
return res;
|
||||
}
|
||||
72
app/api/posts/[slug]/route.ts
Normal file
72
app/api/posts/[slug]/route.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getDb } from "@/lib/mongo";
|
||||
import { ObjectId } from "mongodb";
|
||||
import { z } from "zod";
|
||||
|
||||
export async function GET(_: NextRequest, { params }: { params: { slug: string } }) {
|
||||
const db = await getDb();
|
||||
const post = await db.collection("posts").findOneAndUpdate(
|
||||
{ slug: params.slug },
|
||||
{ $inc: { views: 1 } },
|
||||
{ returnDocument: "after" }
|
||||
);
|
||||
|
||||
if (!post.value) {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
...post.value,
|
||||
_id: (post.value._id as ObjectId)?.toString()
|
||||
});
|
||||
}
|
||||
|
||||
export async function PATCH(req: NextRequest, { params }: { params: { slug: string } }) {
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const schema = z.object({
|
||||
title: z.string().min(2).max(80).optional(),
|
||||
markdown: z.string().min(5).optional(),
|
||||
cover: z.string().url().nullable().optional(),
|
||||
tags: z.array(z.string().trim()).optional(),
|
||||
author: z.string().optional()
|
||||
});
|
||||
const parsed = schema.safeParse(body);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
const set: Record<string, unknown> = {
|
||||
updatedAt: new Date().toISOString()
|
||||
};
|
||||
const unset: Record<string, unknown> = {};
|
||||
|
||||
if (typeof data.title === "string") set.title = data.title;
|
||||
if (typeof data.markdown === "string") set.markdown = data.markdown;
|
||||
if (data.cover === null) {
|
||||
unset.cover = "";
|
||||
} else if (typeof data.cover === "string") {
|
||||
set.cover = data.cover;
|
||||
}
|
||||
if (Array.isArray(data.tags)) set.tags = data.tags;
|
||||
if (typeof data.author === "string") set.author = data.author;
|
||||
|
||||
const update: Record<string, unknown> = { $set: set };
|
||||
if (Object.keys(unset).length > 0) update.$unset = unset;
|
||||
|
||||
const db = await getDb();
|
||||
const result = await db.collection("posts").updateOne({ slug: params.slug }, update);
|
||||
if (result.matchedCount === 0) {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
export async function DELETE(_: NextRequest, { params }: { params: { slug: string } }) {
|
||||
const db = await getDb();
|
||||
const result = await db.collection("posts").deleteOne({ slug: params.slug });
|
||||
if (result.deletedCount === 0) {
|
||||
return NextResponse.json({ error: "Not found" }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
64
app/api/posts/route.ts
Normal file
64
app/api/posts/route.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getDb } from "@/lib/mongo";
|
||||
import { z } from "zod";
|
||||
import { generateSlug } from "@/lib/slug";
|
||||
|
||||
const postSchema = z.object({
|
||||
title: z.string().min(2).max(80),
|
||||
markdown: z.string().min(5),
|
||||
cover: z.string().url().optional(),
|
||||
tags: z.array(z.string().trim()).optional(),
|
||||
author: z.string().default("admin")
|
||||
});
|
||||
|
||||
export async function GET() {
|
||||
const db = await getDb();
|
||||
const posts = await db
|
||||
.collection("posts")
|
||||
.find({}, { projection: { markdown: 0 } })
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(50)
|
||||
.toArray();
|
||||
|
||||
return NextResponse.json(
|
||||
posts.map((p) => ({
|
||||
...p,
|
||||
_id: p._id?.toString()
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const json = await req.json().catch(() => ({}));
|
||||
const parsed = postSchema.safeParse(json);
|
||||
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
|
||||
}
|
||||
|
||||
const data = parsed.data;
|
||||
const now = new Date().toISOString();
|
||||
let slug = generateSlug();
|
||||
const db = await getDb();
|
||||
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||
const exists = await db.collection("posts").findOne({ slug });
|
||||
if (!exists) break;
|
||||
slug = generateSlug();
|
||||
}
|
||||
const existsAfter = await db.collection("posts").findOne({ slug });
|
||||
if (existsAfter) {
|
||||
return NextResponse.json({ error: "Failed to allocate slug" }, { status: 500 });
|
||||
}
|
||||
|
||||
const doc = {
|
||||
...data,
|
||||
slug,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
views: 0
|
||||
};
|
||||
|
||||
await db.collection("posts").insertOne(doc);
|
||||
return NextResponse.json({ ok: true, slug });
|
||||
}
|
||||
23
app/globals.css
Normal file
23
app/globals.css
Normal file
@@ -0,0 +1,23 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
:root {
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
body {
|
||||
background: radial-gradient(circle at 10% 20%, #f5f7ff, #ffffff 35%, #f7faff);
|
||||
min-height: 100vh;
|
||||
font-family: "Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.prose img {
|
||||
border-radius: 0.75rem;
|
||||
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.07);
|
||||
}
|
||||
44
app/layout.tsx
Normal file
44
app/layout.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import "./globals.css";
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { ReactNode } from "react";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Push Info",
|
||||
description: "轻量信息流发布平台,支持 Markdown 与多端浏览。"
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<html lang="zh-CN">
|
||||
<body className="text-slate-900 antialiased">
|
||||
<div className="mx-auto flex min-h-screen w-full max-w-5xl flex-col px-5 py-8">
|
||||
<header className="mb-8 flex flex-wrap items-center justify-between gap-3 rounded-2xl bg-white/70 p-4 shadow-sm ring-1 ring-slate-100 backdrop-blur">
|
||||
<Link href="/" className="flex items-center gap-2 font-semibold text-slate-900">
|
||||
<span className="rounded-xl bg-brand-100 px-2 py-1 text-xs font-bold uppercase text-brand-700">
|
||||
Push
|
||||
</span>
|
||||
<span>信息流</span>
|
||||
</Link>
|
||||
<nav className="flex items-center gap-3 text-sm text-slate-600">
|
||||
<Link href="/" className="hover:text-brand-600">
|
||||
首页
|
||||
</Link>
|
||||
<Link href="/tags" className="hover:text-brand-600">
|
||||
标签
|
||||
</Link>
|
||||
<Link href="/admin" className="hover:text-brand-600">
|
||||
管理
|
||||
</Link>
|
||||
</nav>
|
||||
</header>
|
||||
<main className="flex-1">{children}</main>
|
||||
<footer className="mt-10 flex items-center justify-between border-t border-slate-200 pt-6 text-xs text-slate-500">
|
||||
<span>云图床:img.020417.xyz</span>
|
||||
<span>Made for friends · {new Date().getFullYear()}</span>
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
59
app/login/login-form.tsx
Normal file
59
app/login/login-form.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
|
||||
export default function LoginForm() {
|
||||
const [password, setPassword] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const router = useRouter();
|
||||
const params = useSearchParams();
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const res = await fetch("/api/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ password })
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
setError(data.error || "登录失败");
|
||||
} else {
|
||||
const next = params.get("next") || "/admin";
|
||||
router.push(next);
|
||||
router.refresh();
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<label className="block space-y-1">
|
||||
<span className="text-sm font-medium text-slate-700">后台口令</span>
|
||||
<input
|
||||
type="password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none"
|
||||
placeholder="输入 ADMIN_PASS"
|
||||
/>
|
||||
</label>
|
||||
{error ? <p className="text-sm text-red-500">{error}</p> : null}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full rounded-full bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{loading ? "登录中…" : "登录"}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
19
app/login/page.tsx
Normal file
19
app/login/page.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import LoginForm from "./login-form";
|
||||
|
||||
export const metadata = {
|
||||
title: "登录 - Push Info"
|
||||
};
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<div className="mx-auto max-w-md rounded-2xl bg-white/90 p-8 shadow-sm ring-1 ring-slate-100">
|
||||
<h1 className="text-2xl font-semibold text-slate-900">管理员登录</h1>
|
||||
<p className="mt-2 text-sm text-slate-600">
|
||||
输入后台口令即可发布/统计。口令保存在服务器的环境变量 ADMIN_PASS。
|
||||
</p>
|
||||
<div className="mt-6">
|
||||
<LoginForm />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
52
app/p/[slug]/page.tsx
Normal file
52
app/p/[slug]/page.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
import { getDb } from "@/lib/mongo";
|
||||
import { MarkdownViewer } from "@/components/MarkdownViewer";
|
||||
import { notFound } from "next/navigation";
|
||||
import { normalizeImageUrl } from "@/lib/normalize";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type Props = {
|
||||
params: { slug: string };
|
||||
};
|
||||
|
||||
async function fetchPost(slug: string) {
|
||||
const db = await getDb();
|
||||
const doc = await db.collection("posts").findOne({ slug });
|
||||
if (!doc) return null;
|
||||
// fire-and-forget view increment
|
||||
db.collection("posts").updateOne({ slug }, { $inc: { views: 1 } }).catch(() => {});
|
||||
return {
|
||||
...doc,
|
||||
_id: doc._id?.toString()
|
||||
};
|
||||
}
|
||||
|
||||
export default async function PostPage({ params }: Props) {
|
||||
const post = await fetchPost(params.slug);
|
||||
|
||||
if (!post) {
|
||||
notFound();
|
||||
}
|
||||
const coverUrl = normalizeImageUrl(post.cover);
|
||||
|
||||
return (
|
||||
<article className="rounded-2xl bg-white/80 p-6 shadow-sm ring-1 ring-slate-100">
|
||||
<div className="mb-4">
|
||||
<h1 className="text-2xl font-semibold text-slate-900">{post.title}</h1>
|
||||
<p className="mt-2 text-sm text-slate-500">
|
||||
{new Date(post.createdAt).toLocaleString("zh-CN", { hour12: false })}
|
||||
</p>
|
||||
{coverUrl ? (
|
||||
<img
|
||||
src={coverUrl}
|
||||
alt=""
|
||||
className="mt-3 w-full rounded-2xl object-cover"
|
||||
loading="lazy"
|
||||
referrerPolicy="no-referrer"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<MarkdownViewer markdown={post.markdown} />
|
||||
</article>
|
||||
);
|
||||
}
|
||||
143
app/page.tsx
Normal file
143
app/page.tsx
Normal file
@@ -0,0 +1,143 @@
|
||||
import { getDb } from "@/lib/mongo";
|
||||
import { PostCard } from "@/components/PostCard";
|
||||
import { Post } from "@/types/post";
|
||||
import { buildSearchFilter } from "@/lib/search";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const PAGE_SIZE = 10;
|
||||
|
||||
async function fetchPosts(params: {
|
||||
tag?: string;
|
||||
q?: string;
|
||||
page: number;
|
||||
}): Promise<{ posts: Post[]; total: number; page: number; totalPages: number }> {
|
||||
const db = await getDb();
|
||||
const filters: Record<string, unknown>[] = [];
|
||||
if (params.tag) {
|
||||
filters.push({ tags: params.tag });
|
||||
}
|
||||
const searchFilter = buildSearchFilter(params.q);
|
||||
if (searchFilter) {
|
||||
filters.push(searchFilter as Record<string, unknown>);
|
||||
}
|
||||
const filter = filters.length > 0 ? { $and: filters } : {};
|
||||
const total = await db.collection("posts").countDocuments(filter);
|
||||
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
|
||||
const page = Math.min(Math.max(params.page, 1), totalPages);
|
||||
const docs = await db
|
||||
.collection("posts")
|
||||
.find(filter, { projection: { markdown: 0 } })
|
||||
.sort({ createdAt: -1 })
|
||||
.skip((page - 1) * PAGE_SIZE)
|
||||
.limit(PAGE_SIZE)
|
||||
.toArray();
|
||||
return {
|
||||
posts: docs.map((d: any) => ({
|
||||
...d,
|
||||
_id: d._id?.toString()
|
||||
})),
|
||||
total,
|
||||
page,
|
||||
totalPages
|
||||
};
|
||||
}
|
||||
|
||||
export default async function HomePage({
|
||||
searchParams
|
||||
}: {
|
||||
searchParams?: { tag?: string; q?: string; page?: string };
|
||||
}) {
|
||||
const tag = searchParams?.tag?.trim();
|
||||
const q = searchParams?.q?.trim();
|
||||
const page = Number.parseInt(searchParams?.page || "1", 10) || 1;
|
||||
const { posts, total, totalPages, page: currentPage } = await fetchPosts({ tag, q, page });
|
||||
|
||||
const buildHref = (targetPage: number) => {
|
||||
const params = new URLSearchParams();
|
||||
if (tag) params.set("tag", tag);
|
||||
if (q) params.set("q", q);
|
||||
if (targetPage > 1) params.set("page", String(targetPage));
|
||||
const qs = params.toString();
|
||||
return qs ? `/?${qs}` : "/";
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="rounded-2xl bg-gradient-to-r from-brand-500 to-brand-700 p-6 text-white shadow-lg">
|
||||
<h1 className="text-2xl font-semibold">朋友圈 · 信息流</h1>
|
||||
<p className="mt-2 text-sm text-white/80">
|
||||
Markdown 排版 · 云图床 · 响应式 · 免费 MongoDB Atlas 存储。
|
||||
</p>
|
||||
{tag ? (
|
||||
<div className="mt-3 inline-flex items-center gap-2 rounded-full bg-white/15 px-3 py-1 text-xs font-medium">
|
||||
<span>筛选标签:#{tag}</span>
|
||||
<a
|
||||
href="/"
|
||||
className="rounded-full bg-white/20 px-2 py-1 text-white/90 hover:bg-white/30"
|
||||
>
|
||||
清除
|
||||
</a>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<form action="/" method="get" className="flex flex-wrap items-center gap-3 rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100">
|
||||
{tag ? <input type="hidden" name="tag" value={tag} /> : null}
|
||||
<input
|
||||
name="q"
|
||||
defaultValue={q || ""}
|
||||
placeholder="搜索标题或正文"
|
||||
className="min-w-[200px] flex-1 rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="rounded-full bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow hover:bg-brand-700"
|
||||
>
|
||||
搜索
|
||||
</button>
|
||||
{q ? (
|
||||
<a
|
||||
href={tag ? `/?tag=${encodeURIComponent(tag)}` : "/"}
|
||||
className="text-sm text-slate-500 hover:text-brand-600"
|
||||
>
|
||||
清除搜索
|
||||
</a>
|
||||
) : null}
|
||||
<span className="text-xs text-slate-400">共 {total} 条</span>
|
||||
</form>
|
||||
|
||||
{posts.length === 0 ? (
|
||||
<p className="rounded-xl bg-white/70 p-4 text-sm text-slate-500 ring-1 ring-slate-100">
|
||||
暂无匹配内容。
|
||||
</p>
|
||||
) : (
|
||||
<div className="grid gap-4">
|
||||
{posts.map((post) => (
|
||||
<PostCard key={post.slug} post={post} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between text-sm text-slate-600">
|
||||
<span>
|
||||
第 {currentPage} / {totalPages} 页
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<a
|
||||
href={buildHref(Math.max(1, currentPage - 1))}
|
||||
className={`rounded-full px-3 py-1 ${currentPage <= 1 ? "pointer-events-none text-slate-300" : "bg-white/80 ring-1 ring-slate-200 hover:text-brand-600"}`}
|
||||
>
|
||||
上一页
|
||||
</a>
|
||||
<a
|
||||
href={buildHref(Math.min(totalPages, currentPage + 1))}
|
||||
className={`rounded-full px-3 py-1 ${currentPage >= totalPages ? "pointer-events-none text-slate-300" : "bg-white/80 ring-1 ring-slate-200 hover:text-brand-600"}`}
|
||||
>
|
||||
下一页
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
71
app/rss/route.ts
Normal file
71
app/rss/route.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { getDb } from "@/lib/mongo";
|
||||
import { getSiteUrl } from "@/lib/site";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
function escapeXml(input: string): string {
|
||||
return input
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
function stripMarkdown(input: string): string {
|
||||
return input
|
||||
.replace(/```[\s\S]*?```/g, " ")
|
||||
.replace(/`[^`]*`/g, " ")
|
||||
.replace(/!\[[^\]]*]\([^)]+\)/g, " ")
|
||||
.replace(/\[[^\]]*]\([^)]+\)/g, "$1")
|
||||
.replace(/[#>*_~\-]+/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
const db = await getDb();
|
||||
const posts = await db
|
||||
.collection("posts")
|
||||
.find({}, { projection: { title: 1, slug: 1, markdown: 1, createdAt: 1, updatedAt: 1 } })
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(50)
|
||||
.toArray();
|
||||
|
||||
const siteUrl = getSiteUrl();
|
||||
const now = new Date().toUTCString();
|
||||
|
||||
const items = posts
|
||||
.map((post: any) => {
|
||||
const link = `${siteUrl}/p/${post.slug}`;
|
||||
const description = stripMarkdown(post.markdown || "").slice(0, 200);
|
||||
const pubDate = new Date(post.createdAt || post.updatedAt || Date.now()).toUTCString();
|
||||
return [
|
||||
"<item>",
|
||||
`<title>${escapeXml(post.title || "Untitled")}</title>`,
|
||||
`<link>${escapeXml(link)}</link>`,
|
||||
`<guid>${escapeXml(link)}</guid>`,
|
||||
`<pubDate>${pubDate}</pubDate>`,
|
||||
`<description>${escapeXml(description)}</description>`,
|
||||
"</item>"
|
||||
].join("");
|
||||
})
|
||||
.join("");
|
||||
|
||||
const xml = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<rss version="2.0">
|
||||
<channel>
|
||||
<title>不务正业的木子</title>
|
||||
<link>${escapeXml(siteUrl)}</link>
|
||||
<description>less is more</description>
|
||||
<lastBuildDate>${now}</lastBuildDate>
|
||||
${items}
|
||||
</channel>
|
||||
</rss>`;
|
||||
|
||||
return new Response(xml, {
|
||||
headers: {
|
||||
"Content-Type": "application/rss+xml; charset=utf-8"
|
||||
}
|
||||
});
|
||||
}
|
||||
32
app/sitemap.ts
Normal file
32
app/sitemap.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import type { MetadataRoute } from "next";
|
||||
import { getDb } from "@/lib/mongo";
|
||||
import { getSiteUrl } from "@/lib/site";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
||||
const db = await getDb();
|
||||
const posts = await db
|
||||
.collection("posts")
|
||||
.find({}, { projection: { slug: 1, updatedAt: 1, createdAt: 1 } })
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(1000)
|
||||
.toArray();
|
||||
|
||||
const siteUrl = getSiteUrl();
|
||||
const items: MetadataRoute.Sitemap = [
|
||||
{
|
||||
url: `${siteUrl}/`,
|
||||
lastModified: new Date()
|
||||
}
|
||||
];
|
||||
|
||||
for (const post of posts) {
|
||||
items.push({
|
||||
url: `${siteUrl}/p/${post.slug}`,
|
||||
lastModified: new Date(post.updatedAt || post.createdAt || Date.now())
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
130
app/tags/[tag]/page.tsx
Normal file
130
app/tags/[tag]/page.tsx
Normal file
@@ -0,0 +1,130 @@
|
||||
import { getDb } from "@/lib/mongo";
|
||||
import { PostCard } from "@/components/PostCard";
|
||||
import { Post } from "@/types/post";
|
||||
import { buildSearchFilter } from "@/lib/search";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const PAGE_SIZE = 10;
|
||||
|
||||
async function fetchTagPosts(params: {
|
||||
tag: string;
|
||||
q?: string;
|
||||
page: number;
|
||||
}): Promise<{ posts: Post[]; total: number; page: number; totalPages: number }> {
|
||||
const db = await getDb();
|
||||
const filters: Record<string, unknown>[] = [{ tags: params.tag }];
|
||||
const searchFilter = buildSearchFilter(params.q);
|
||||
if (searchFilter) {
|
||||
filters.push(searchFilter as Record<string, unknown>);
|
||||
}
|
||||
const filter = { $and: filters };
|
||||
const total = await db.collection("posts").countDocuments(filter);
|
||||
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));
|
||||
const page = Math.min(Math.max(params.page, 1), totalPages);
|
||||
const docs = await db
|
||||
.collection("posts")
|
||||
.find(filter, { projection: { markdown: 0 } })
|
||||
.sort({ createdAt: -1 })
|
||||
.skip((page - 1) * PAGE_SIZE)
|
||||
.limit(PAGE_SIZE)
|
||||
.toArray();
|
||||
return {
|
||||
posts: docs.map((d: any) => ({
|
||||
...d,
|
||||
_id: d._id?.toString()
|
||||
})),
|
||||
total,
|
||||
page,
|
||||
totalPages
|
||||
};
|
||||
}
|
||||
|
||||
export default async function TagDetailPage({
|
||||
params,
|
||||
searchParams
|
||||
}: {
|
||||
params: { tag: string };
|
||||
searchParams?: { q?: string; page?: string };
|
||||
}) {
|
||||
const tag = params.tag;
|
||||
const q = searchParams?.q?.trim();
|
||||
const page = Number.parseInt(searchParams?.page || "1", 10) || 1;
|
||||
const { posts, total, totalPages, page: currentPage } = await fetchTagPosts({ tag, q, page });
|
||||
|
||||
const buildHref = (targetPage: number) => {
|
||||
const params = new URLSearchParams();
|
||||
if (q) params.set("q", q);
|
||||
if (targetPage > 1) params.set("page", String(targetPage));
|
||||
const qs = params.toString();
|
||||
return qs ? `/tags/${encodeURIComponent(tag)}?${qs}` : `/tags/${encodeURIComponent(tag)}`;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="rounded-2xl bg-white/80 p-6 shadow-sm ring-1 ring-slate-100">
|
||||
<h1 className="text-2xl font-semibold">标签:#{tag}</h1>
|
||||
<p className="mt-2 text-sm text-slate-500">共 {total} 条内容。</p>
|
||||
</div>
|
||||
|
||||
<form
|
||||
action={`/tags/${encodeURIComponent(tag)}`}
|
||||
method="get"
|
||||
className="flex flex-wrap items-center gap-3 rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100"
|
||||
>
|
||||
<input
|
||||
name="q"
|
||||
defaultValue={q || ""}
|
||||
placeholder="在该标签下搜索"
|
||||
className="min-w-[200px] flex-1 rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm shadow-inner focus:border-brand-500 focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="rounded-full bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow hover:bg-brand-700"
|
||||
>
|
||||
搜索
|
||||
</button>
|
||||
{q ? (
|
||||
<a
|
||||
href={`/tags/${encodeURIComponent(tag)}`}
|
||||
className="text-sm text-slate-500 hover:text-brand-600"
|
||||
>
|
||||
清除搜索
|
||||
</a>
|
||||
) : null}
|
||||
</form>
|
||||
|
||||
{posts.length === 0 ? (
|
||||
<p className="rounded-xl bg-white/70 p-4 text-sm text-slate-500 ring-1 ring-slate-100">
|
||||
暂无匹配内容。
|
||||
</p>
|
||||
) : (
|
||||
<div className="grid gap-4">
|
||||
{posts.map((post) => (
|
||||
<PostCard key={post.slug} post={post} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between text-sm text-slate-600">
|
||||
<span>
|
||||
第 {currentPage} / {totalPages} 页
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<a
|
||||
href={buildHref(Math.max(1, currentPage - 1))}
|
||||
className={`rounded-full px-3 py-1 ${currentPage <= 1 ? "pointer-events-none text-slate-300" : "bg-white/80 ring-1 ring-slate-200 hover:text-brand-600"}`}
|
||||
>
|
||||
上一页
|
||||
</a>
|
||||
<a
|
||||
href={buildHref(Math.min(totalPages, currentPage + 1))}
|
||||
className={`rounded-full px-3 py-1 ${currentPage >= totalPages ? "pointer-events-none text-slate-300" : "bg-white/80 ring-1 ring-slate-200 hover:text-brand-600"}`}
|
||||
>
|
||||
下一页
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
44
app/tags/page.tsx
Normal file
44
app/tags/page.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import { getDb } from "@/lib/mongo";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type TagItem = { _id: string; count: number };
|
||||
|
||||
export default async function TagsPage() {
|
||||
const db = await getDb();
|
||||
const tags = (await db
|
||||
.collection("posts")
|
||||
.aggregate([
|
||||
{ $unwind: "$tags" },
|
||||
{ $group: { _id: "$tags", count: { $sum: 1 } } },
|
||||
{ $sort: { count: -1, _id: 1 } }
|
||||
])
|
||||
.toArray()) as TagItem[];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="rounded-2xl bg-white/80 p-6 shadow-sm ring-1 ring-slate-100">
|
||||
<h1 className="text-2xl font-semibold">标签聚合</h1>
|
||||
<p className="mt-2 text-sm text-slate-500">按标签浏览所有文章。</p>
|
||||
</div>
|
||||
|
||||
{tags.length === 0 ? (
|
||||
<p className="rounded-xl bg-white/70 p-4 text-sm text-slate-500 ring-1 ring-slate-100">
|
||||
暂无标签内容。
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{tags.map((tag) => (
|
||||
<a
|
||||
key={tag._id}
|
||||
href={`/tags/${encodeURIComponent(tag._id)}`}
|
||||
className="rounded-full bg-white/80 px-4 py-2 text-sm text-slate-700 shadow-sm ring-1 ring-slate-100 transition hover:-translate-y-0.5 hover:text-brand-600"
|
||||
>
|
||||
#{tag._id} <span className="text-xs text-slate-400">({tag.count})</span>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user