This commit is contained in:
爱喝水的木子
2026-03-13 16:28:51 +08:00
commit bfdf4843e1
38 changed files with 9490 additions and 0 deletions

22
.gitignore vendored Normal file
View File

@@ -0,0 +1,22 @@
# dependencies
node_modules
.pnp
.pnp.js
# production
.next
out
# debug
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
# env
.env
.env.local
.env.*.local
# misc
.DS_Store

66
README.md Normal file
View File

@@ -0,0 +1,66 @@
# OPC 信息流平台
面向 OPCOne Person Company一人公司的轻量信息流发布站。
个人即公司:记录更新、发布进展、同步给关注你的人;简单、克制、能持续。
## 你会得到什么
- 一个可公开访问的“个人公司动态墙”
- 支持 Markdown 的内容发布
- 文章详情页可长期访问(稳定 URL
- RSS 订阅与站点地图,方便搜索与关注
- 后台口令发布与统计,维护成本低
## 典型使用场景
- 个人产品更新、周报、交付日志
- 公开路线图、里程碑、版本发布
- 内容实验、灵感记录、对外同步
## 技术栈
- Next.js 14App Router
- MongoDB Atlas免费云数据库
- Tailwind CSS
- Markdown 渲染
## 快速开始
1. 安装依赖
```bash
npm install
```
2. 新建 `.env.local`
```
MONGODB_URI=你的Mongo连接串
MONGODB_DB=pushinfo
ADMIN_PASS=自定义后台口令
SESSION_SECRET=任意长随机字符串
NEXT_PUBLIC_SITE_URL=https://你的域名
```
3. 开发运行
```bash
npm run dev
```
## 功能清单
- 首页信息流:最新发布置顶
- 文章详情页Markdown 渲染
- 后台:口令登录、发布、编辑/删除、统计
- 标签聚合页与标签详情页
- 搜索与分页
- RSS`/rss`标题不务正业的木子文案less is more
- Sitemap`/sitemap.xml`
## 部署建议
- 前端Vercel
- 数据库MongoDB Atlas 免费套餐
- 图片:图床(如 `https://img.020417.xyz`
## 设计原则
- 低摩擦发布
- 少即是多
- 长期可维护
## TODO
- 草稿与置顶
- 私密分享链接
- 全文索引MongoDB Text Index

View 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
View 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>
);
}

View 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
View 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;
}

View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;");
}
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
View 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
View 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
View 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>
);
}

View File

@@ -0,0 +1,87 @@
"use client";
import Link from "next/link";
import { useState } from "react";
import { Post } from "@/types/post";
type AdminPost = Post & { createdAtText?: string };
export function AdminPostList({ initialPosts }: { initialPosts: AdminPost[] }) {
const [posts, setPosts] = useState<AdminPost[]>(initialPosts);
async function handleDelete(slug: string) {
if (!window.confirm("确定要删除这篇文章吗?此操作不可恢复。")) return;
const res = await fetch(`/api/posts/${slug}`, { method: "DELETE" });
if (!res.ok) {
const data = await res.json().catch(() => ({}));
alert(data.error || "删除失败");
return;
}
setPosts((prev) => prev.filter((post) => post.slug !== slug));
}
if (posts.length === 0) {
return (
<div className="rounded-2xl bg-white/80 p-4 text-sm text-slate-500 shadow-sm ring-1 ring-slate-100">
</div>
);
}
return (
<div className="space-y-3 rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100">
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold"></h3>
<span className="text-xs text-slate-400"> {posts.length} </span>
</div>
<div className="space-y-3">
{posts.map((post) => (
<div
key={post.slug}
className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-100 bg-white/70 p-3"
>
<div>
<Link href={`/p/${post.slug}`} className="font-medium text-slate-900 hover:text-brand-600">
{post.title}
</Link>
<p className="text-xs text-slate-500">
{post.createdAtText ||
new Date(post.createdAt).toLocaleString("zh-CN", {
hour12: false,
timeZone: "Asia/Shanghai"
})}
</p>
{post.tags && post.tags.length > 0 ? (
<div className="mt-2 flex flex-wrap gap-2">
{post.tags.map((tag) => (
<span
key={tag}
className="rounded-full bg-slate-100 px-2 py-1 text-xs text-slate-600"
>
#{tag}
</span>
))}
</div>
) : null}
</div>
<div className="flex items-center gap-2">
<Link
href={`/admin/edit/${post.slug}`}
className="rounded-full bg-brand-50 px-3 py-1 text-xs font-medium text-brand-700 ring-1 ring-brand-100 hover:bg-brand-100"
>
</Link>
<button
type="button"
onClick={() => handleDelete(post.slug)}
className="rounded-full bg-red-50 px-3 py-1 text-xs font-medium text-red-600 ring-1 ring-red-100 hover:bg-red-100"
>
</button>
</div>
</div>
))}
</div>
</div>
);
}

View File

@@ -0,0 +1,116 @@
"use client";
import { FormEvent, useState } from "react";
import { useRouter } from "next/navigation";
import { normalizeImageUrl } from "@/lib/normalize";
const defaultIntro = `## 新帖内容
- 这里支持 **Markdown**
- 图片请上传到 img.020417.xyz 后填入链接
`;
export function CreatePostForm() {
const [title, setTitle] = useState("");
const [cover, setCover] = useState("");
const [tags, setTags] = useState("");
const [markdown, setMarkdown] = useState(defaultIntro);
const [loading, setLoading] = useState(false);
const router = useRouter();
async function handleSubmit(e: FormEvent) {
e.preventDefault();
setLoading(true);
try {
const normalizedCover = normalizeImageUrl(cover);
const res = await fetch("/api/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
title,
markdown,
cover: normalizedCover,
tags: Array.from(
new Set(
tags
.split(",")
.map((t) => t.trim())
.filter(Boolean)
)
)
})
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
alert(data.error ? JSON.stringify(data.error) : "发布失败");
} else {
const data = await res.json();
router.push(`/p/${data.slug}`);
router.refresh();
}
} finally {
setLoading(false);
}
}
return (
<form onSubmit={handleSubmit} className="space-y-4 rounded-2xl bg-white/80 p-5 shadow-sm ring-1 ring-slate-100">
<div className="flex items-center justify-between">
<div>
<h3 className="text-lg font-semibold"></h3>
<p className="text-sm text-slate-500"></p>
</div>
<button
type="submit"
disabled={loading}
className="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>
</div>
<label className="block space-y-1">
<span className="text-sm font-medium text-slate-700"></span>
<input
required
value={title}
onChange={(e) => setTitle(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="比如:周末聚会安排"
/>
</label>
<label className="block space-y-1">
<span className="text-sm font-medium text-slate-700"></span>
<input
value={cover}
onChange={(e) => setCover(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="https://img.020417.xyz/xxxx.png"
/>
</label>
<label className="block space-y-1">
<span className="text-sm font-medium text-slate-700"></span>
<input
value={tags}
onChange={(e) => setTags(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="朋友, 聚会, 通知"
/>
</label>
<label className="block space-y-1">
<span className="text-sm font-medium text-slate-700">Markdown</span>
<textarea
required
value={markdown}
onChange={(e) => setMarkdown(e.target.value)}
rows={12}
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"
/>
</label>
</form>
);
}

129
components/EditPostForm.tsx Normal file
View File

@@ -0,0 +1,129 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { normalizeImageUrl } from "@/lib/normalize";
import { Post } from "@/types/post";
export function EditPostForm({ post }: { post: Post }) {
const router = useRouter();
const [title, setTitle] = useState(post.title);
const [cover, setCover] = useState(post.cover || "");
const [tags, setTags] = useState(post.tags ? post.tags.join(", ") : "");
const [markdown, setMarkdown] = useState(post.markdown);
const [loading, setLoading] = useState(false);
async function handleSave(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
try {
const normalizedCover = normalizeImageUrl(cover);
const res = await fetch(`/api/posts/${post.slug}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
title,
markdown,
cover: normalizedCover || null,
tags: Array.from(
new Set(
tags
.split(",")
.map((t) => t.trim())
.filter(Boolean)
)
)
})
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
alert(data.error ? JSON.stringify(data.error) : "保存失败");
return;
}
router.push("/admin");
router.refresh();
} finally {
setLoading(false);
}
}
async function handleDelete() {
if (!window.confirm("确定要删除这篇文章吗?此操作不可恢复。")) return;
const res = await fetch(`/api/posts/${post.slug}`, { method: "DELETE" });
if (!res.ok) {
const data = await res.json().catch(() => ({}));
alert(data.error || "删除失败");
return;
}
router.push("/admin");
router.refresh();
}
return (
<form onSubmit={handleSave} className="space-y-4 rounded-2xl bg-white/80 p-5 shadow-sm ring-1 ring-slate-100">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h3 className="text-lg font-semibold"></h3>
<p className="text-sm text-slate-500"></p>
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={handleDelete}
className="rounded-full bg-red-50 px-4 py-2 text-sm font-medium text-red-600 ring-1 ring-red-100 hover:bg-red-100"
>
</button>
<button
type="submit"
disabled={loading}
className="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>
</div>
</div>
<label className="block space-y-1">
<span className="text-sm font-medium text-slate-700"></span>
<input
required
value={title}
onChange={(e) => setTitle(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"
/>
</label>
<label className="block space-y-1">
<span className="text-sm font-medium text-slate-700"></span>
<input
value={cover}
onChange={(e) => setCover(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="https://img.020417.xyz/xxxx.png"
/>
</label>
<label className="block space-y-1">
<span className="text-sm font-medium text-slate-700"></span>
<input
value={tags}
onChange={(e) => setTags(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="朋友, 聚会, 通知"
/>
</label>
<label className="block space-y-1">
<span className="text-sm font-medium text-slate-700">Markdown</span>
<textarea
required
value={markdown}
onChange={(e) => setMarkdown(e.target.value)}
rows={12}
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"
/>
</label>
</form>
);
}

View File

@@ -0,0 +1,10 @@
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
export function MarkdownViewer({ markdown }: { markdown: string }) {
return (
<article className="prose prose-slate max-w-none prose-a:text-brand-600 prose-img:rounded-xl">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{markdown}</ReactMarkdown>
</article>
);
}

52
components/PostCard.tsx Normal file
View File

@@ -0,0 +1,52 @@
import Link from "next/link";
import { Post } from "@/types/post";
import { normalizeImageUrl } from "@/lib/normalize";
type Props = {
post: Post;
};
export function PostCard({ post }: Props) {
const coverUrl = normalizeImageUrl(post.cover);
return (
<article className="group rounded-2xl bg-white/80 p-4 shadow-sm ring-1 ring-slate-100 transition hover:-translate-y-1 hover:shadow-md">
<div className="flex items-start justify-between gap-3">
<div className="space-y-1">
<Link
href={`/p/${post.slug}`}
className="block text-lg font-semibold text-slate-900 transition group-hover:text-brand-600"
>
{post.title}
</Link>
<p className="text-sm text-slate-500">
{new Date(post.createdAt).toLocaleString("zh-CN", { hour12: false })}
</p>
</div>
{coverUrl ? (
<Link href={`/p/${post.slug}`} className="shrink-0">
<img
src={coverUrl}
alt={post.title}
className="h-16 w-24 rounded-xl object-cover ring-1 ring-slate-100"
loading="lazy"
referrerPolicy="no-referrer"
/>
</Link>
) : null}
</div>
{post.tags && post.tags.length > 0 ? (
<div className="mt-3 flex flex-wrap gap-2">
{post.tags.map((tag) => (
<Link
key={tag}
href={`/tags/${encodeURIComponent(tag)}`}
className="rounded-full bg-slate-100 px-2 py-1 text-xs font-medium text-slate-600 transition hover:bg-brand-50 hover:text-brand-700"
>
#{tag}
</Link>
))}
</div>
) : null}
</article>
);
}

68
lib/auth.ts Normal file
View File

@@ -0,0 +1,68 @@
import { cookies } from "next/headers";
import { NextRequest } from "next/server";
const COOKIE_NAME = "admin_session";
const encoder = new TextEncoder();
function getSecret() {
const secret = process.env.SESSION_SECRET;
if (!secret) {
throw new Error("SESSION_SECRET is required");
}
return secret;
}
export type SessionPayload = {
role: "admin";
iat: number;
};
async function hmacSha256(data: string, secret: string): Promise<string> {
const key = await crypto.subtle.importKey(
"raw",
encoder.encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"]
);
const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(data));
return Buffer.from(sig).toString("base64url");
}
export async function signSession(payload: SessionPayload): Promise<string> {
const secret = getSecret();
const base = Buffer.from(JSON.stringify(payload)).toString("base64url");
const sig = await hmacSha256(base, secret);
return `${base}.${sig}`;
}
export async function verifySession(token?: string): Promise<SessionPayload | null> {
if (!token) return null;
const secret = getSecret();
const [base, sig] = token.split(".");
if (!base || !sig) return null;
const check = await hmacSha256(base, secret);
if (check !== sig) return null;
try {
const payload = JSON.parse(Buffer.from(base, "base64url").toString());
return payload;
} catch {
return null;
}
}
export async function requireAdminFromRequest(req: NextRequest): Promise<boolean> {
const token = req.cookies.get(COOKIE_NAME)?.value;
return Boolean(await verifySession(token));
}
export function setAdminCookie(token: string) {
cookies().set(COOKIE_NAME, token, {
httpOnly: true,
sameSite: "lax",
secure: true,
maxAge: 60 * 60 * 24 * 30
});
}
export const cookieName = COOKIE_NAME;

24
lib/mongo.ts Normal file
View File

@@ -0,0 +1,24 @@
import { Db, MongoClient } from "mongodb";
const uri = process.env.MONGODB_URI;
const dbName = process.env.MONGODB_DB || "pushinfo";
if (!uri) {
throw new Error("Missing MONGODB_URI in environment variables");
}
let client: MongoClient | null = null;
let db: Db | null = null;
export async function getDb(): Promise<Db> {
if (db) return db;
if (!client) {
client = new MongoClient(uri, { serverSelectionTimeoutMS: 5000 });
}
if (!client.topology?.isConnected()) {
await client.connect();
}
db = client.db(dbName);
return db;
}

14
lib/normalize.ts Normal file
View File

@@ -0,0 +1,14 @@
export function normalizeImageUrl(input?: string): string | undefined {
if (!input) return undefined;
const trimmed = input.trim();
if (!trimmed) return undefined;
if (trimmed.startsWith("data:") || trimmed.startsWith("blob:")) {
return trimmed;
}
if (trimmed.startsWith("https://")) return trimmed;
if (trimmed.startsWith("http://")) return `https://${trimmed.slice(7)}`;
if (trimmed.startsWith("//")) return `https:${trimmed}`;
if (trimmed.startsWith("img.020417.xyz/")) return `https://${trimmed}`;
if (trimmed.startsWith("/")) return `https://img.020417.xyz${trimmed}`;
return `https://${trimmed}`;
}

14
lib/search.ts Normal file
View File

@@ -0,0 +1,14 @@
export function escapeRegExp(input: string): string {
return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
export function buildSearchFilter(query?: string) {
if (!query) return null;
const trimmed = query.trim();
if (!trimmed) return null;
const safe = escapeRegExp(trimmed);
const regex = new RegExp(safe, "i");
return {
$or: [{ title: { $regex: regex } }, { markdown: { $regex: regex } }]
};
}

6
lib/site.ts Normal file
View File

@@ -0,0 +1,6 @@
export function getSiteUrl(): string {
const raw = process.env.NEXT_PUBLIC_SITE_URL || process.env.SITE_URL;
const fallback = "http://localhost:3000";
const base = raw && raw.trim().length > 0 ? raw.trim() : fallback;
return base.replace(/\/+$/, "");
}

22
lib/slug.ts Normal file
View File

@@ -0,0 +1,22 @@
export function generateSlug(): string {
const cryptoApi = globalThis.crypto;
if (!cryptoApi?.getRandomValues) {
throw new Error("Web Crypto API is not available");
}
const timestamp = Date.now().toString().padStart(13, "0").slice(-13);
const prefixLength = 64 - 13;
const bytes = new Uint8Array(Math.ceil(prefixLength / 8));
cryptoApi.getRandomValues(bytes);
let prefix = "";
for (const byte of bytes) {
for (let bit = 0; bit < 8; bit += 1) {
prefix += (byte >> bit) & 1 ? "O" : "o";
if (prefix.length === prefixLength) break;
}
if (prefix.length === prefixLength) break;
}
return `${prefix}${timestamp}`;
}

34
middleware.ts Normal file
View File

@@ -0,0 +1,34 @@
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { verifySession, cookieName } from "./lib/auth";
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
const isProtected =
pathname.startsWith("/admin") ||
pathname.startsWith("/api/admin") ||
pathname.startsWith("/api/posts") && req.method !== "GET";
if (!isProtected) {
return NextResponse.next();
}
const token = req.cookies.get(cookieName)?.value;
const session = await verifySession(token);
if (!session) {
if (pathname.startsWith("/api/")) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const loginUrl = new URL("/login", req.url);
loginUrl.searchParams.set("next", pathname);
return NextResponse.redirect(loginUrl);
}
return NextResponse.next();
}
export const config = {
matcher: ["/admin/:path*", "/api/admin/:path*", "/api/posts/:path*"]
};

5
next-env.d.ts vendored Normal file
View File

@@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.

16
next.config.js Normal file
View File

@@ -0,0 +1,16 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
serverActions: true
},
images: {
remotePatterns: [
{
protocol: "https",
hostname: "img.020417.xyz"
}
]
}
};
module.exports = nextConfig;

7789
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

33
package.json Normal file
View File

@@ -0,0 +1,33 @@
{
"name": "push-info",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@tailwindcss/typography": "^0.5.10",
"autoprefixer": "^10.4.16",
"gray-matter": "^4.0.3",
"mongodb": "^6.5.0",
"next": "14.2.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-markdown": "^9.0.1",
"remark-gfm": "^4.0.0",
"tailwindcss": "^3.4.1",
"zod": "^3.23.8"
},
"devDependencies": {
"@types/node": "^20.11.28",
"@types/react": "^18.2.63",
"@types/react-dom": "^18.2.19",
"eslint": "^8.57.0",
"eslint-config-next": "14.2.0",
"postcss": "^8.4.35",
"typescript": "^5.4.3"
}
}

6
postcss.config.js Normal file
View File

@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {}
}
};

26
tailwind.config.js Normal file
View File

@@ -0,0 +1,26 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./app/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}"
],
theme: {
extend: {
colors: {
brand: {
50: "#f1f5ff",
100: "#dfe8ff",
200: "#c4d3ff",
300: "#9eb5ff",
400: "#6c88ff",
500: "#3f5bff",
600: "#2d3fd6",
700: "#2433aa",
800: "#212f89",
900: "#1e2b72"
}
}
}
},
plugins: [require("@tailwindcss/typography")]
};

42
tsconfig.json Normal file
View File

@@ -0,0 +1,42 @@
{
"compilerOptions": {
"target": "ES2020",
"lib": [
"dom",
"dom.iterable",
"es2020"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"paths": {
"@/*": [
"./*"
]
},
"baseUrl": ".",
"plugins": [
{
"name": "next"
}
]
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}

12
types/post.ts Normal file
View File

@@ -0,0 +1,12 @@
export type Post = {
_id?: string;
title: string;
slug: string;
markdown: string;
cover?: string;
tags?: string[];
author: string;
createdAt: string;
updatedAt: string;
views?: number;
};