Initial commit: Online documentation site with CMS, notes, and message board
This commit is contained in:
41
.gitignore
vendored
Normal file
41
.gitignore
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
5
AGENTS.md
Normal file
5
AGENTS.md
Normal file
@@ -0,0 +1,5 @@
|
||||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
# This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
36
README.md
Normal file
36
README.md
Normal file
@@ -0,0 +1,36 @@
|
||||
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
||||
|
||||
## Getting Started
|
||||
|
||||
First, run the development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
# or
|
||||
yarn dev
|
||||
# or
|
||||
pnpm dev
|
||||
# or
|
||||
bun dev
|
||||
```
|
||||
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||
|
||||
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
||||
|
||||
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
||||
|
||||
## Learn More
|
||||
|
||||
To learn more about Next.js, take a look at the following resources:
|
||||
|
||||
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
||||
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
||||
|
||||
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
||||
|
||||
## Deploy on Vercel
|
||||
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||
|
||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||
18
eslint.config.mjs
Normal file
18
eslint.config.mjs
Normal file
@@ -0,0 +1,18 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTs from "eslint-config-next/typescript";
|
||||
|
||||
const eslintConfig = defineConfig([
|
||||
...nextVitals,
|
||||
...nextTs,
|
||||
// Override default ignores of eslint-config-next.
|
||||
globalIgnores([
|
||||
// Default ignores of eslint-config-next:
|
||||
".next/**",
|
||||
"out/**",
|
||||
"build/**",
|
||||
"next-env.d.ts",
|
||||
]),
|
||||
]);
|
||||
|
||||
export default eslintConfig;
|
||||
7
next.config.ts
Normal file
7
next.config.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
6837
package-lock.json
generated
Normal file
6837
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
28
package.json
Normal file
28
package.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "docs-site",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"bcryptjs": "^3.0.3",
|
||||
"next": "16.2.2",
|
||||
"pg": "^8.20.0",
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.2.2",
|
||||
"tailwindcss": "^4",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
7
postcss.config.mjs
Normal file
7
postcss.config.mjs
Normal file
@@ -0,0 +1,7 @@
|
||||
const config = {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
1
public/file.svg
Normal file
1
public/file.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
After Width: | Height: | Size: 391 B |
1
public/globe.svg
Normal file
1
public/globe.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
1
public/next.svg
Normal file
1
public/next.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
1
public/vercel.svg
Normal file
1
public/vercel.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 128 B |
1
public/window.svg
Normal file
1
public/window.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
After Width: | Height: | Size: 385 B |
451
src/app/admin/page.tsx
Normal file
451
src/app/admin/page.tsx
Normal file
@@ -0,0 +1,451 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
interface Section {
|
||||
id?: number;
|
||||
title: string;
|
||||
content: string;
|
||||
code?: string | null;
|
||||
}
|
||||
|
||||
interface Doc {
|
||||
title: string;
|
||||
slug: string;
|
||||
description?: string | null;
|
||||
sections: Section[];
|
||||
}
|
||||
|
||||
interface User {
|
||||
username: string;
|
||||
role: "admin" | "user";
|
||||
}
|
||||
|
||||
export default function AdminPage() {
|
||||
const [docs, setDocs] = useState<Doc[]>([]);
|
||||
const [activeTab, setActiveTab] = useState<"login" | "docs" | "addDoc">("login");
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [selectedDocSlug, setSelectedDocSlug] = useState<string>("");
|
||||
const [formData, setFormData] = useState({
|
||||
title: "",
|
||||
slug: "",
|
||||
description: "",
|
||||
sectionTitle: "",
|
||||
sectionContent: "",
|
||||
sectionCode: "",
|
||||
});
|
||||
|
||||
const [loginForm, setLoginForm] = useState({
|
||||
username: "",
|
||||
password: "",
|
||||
});
|
||||
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
|
||||
// 检查登录状态
|
||||
useEffect(() => {
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
const checkAuth = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/auth/me");
|
||||
const data = await res.json();
|
||||
if (data.authenticated) {
|
||||
setUser(data.user);
|
||||
setActiveTab("docs");
|
||||
fetchDocs();
|
||||
} else {
|
||||
setActiveTab("login");
|
||||
}
|
||||
} catch (error) {
|
||||
setActiveTab("login");
|
||||
}
|
||||
};
|
||||
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setErrorMessage("");
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(loginForm),
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (data.success) {
|
||||
setUser(data.user);
|
||||
setActiveTab("docs");
|
||||
fetchDocs();
|
||||
} else {
|
||||
setErrorMessage(data.error || "登录失败");
|
||||
}
|
||||
} catch (error) {
|
||||
setErrorMessage("登录失败,请稍后重试");
|
||||
}
|
||||
};
|
||||
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
await fetch("/api/auth/logout", { method: "POST" });
|
||||
setUser(null);
|
||||
setActiveTab("login");
|
||||
} catch (error) {
|
||||
console.error("Logout error:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchDocs = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/docs");
|
||||
const data = await res.json();
|
||||
setDocs(data.docs || []);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch docs:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddDoc = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/admin/add", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
type: "doc",
|
||||
data: {
|
||||
title: formData.title,
|
||||
slug: formData.slug || formData.title.toLowerCase().replace(/\s+/g, "-"),
|
||||
description: formData.description,
|
||||
},
|
||||
}),
|
||||
});
|
||||
const result = await res.json();
|
||||
if (result.success) {
|
||||
setFormData({ title: "", slug: "", description: "", sectionTitle: "", sectionContent: "", sectionCode: "" });
|
||||
fetchDocs();
|
||||
setActiveTab("docs");
|
||||
} else {
|
||||
alert(result.error || "添加文档失败");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to add doc:", error);
|
||||
alert("添加文档失败");
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddSection = async () => {
|
||||
if (!selectedDocSlug) {
|
||||
alert("请先选择要添加章节的文档");
|
||||
return;
|
||||
}
|
||||
if (!formData.sectionTitle) {
|
||||
alert("请输入章节标题");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/admin/add", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
type: "section",
|
||||
docSlug: selectedDocSlug,
|
||||
section: {
|
||||
title: formData.sectionTitle,
|
||||
content: formData.sectionContent,
|
||||
code: formData.sectionCode || undefined,
|
||||
},
|
||||
}),
|
||||
});
|
||||
const result = await res.json();
|
||||
if (result.success) {
|
||||
setFormData({ ...formData, sectionTitle: "", sectionContent: "", sectionCode: "" });
|
||||
fetchDocs();
|
||||
setActiveTab("docs");
|
||||
} else {
|
||||
alert(result.error || "添加章节失败");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to add section:", error);
|
||||
alert("添加章节失败");
|
||||
}
|
||||
};
|
||||
|
||||
// 登录页面
|
||||
if (activeTab === "login") {
|
||||
return (
|
||||
<div className="min-h-screen bg-zinc-900 flex items-center justify-center px-4">
|
||||
<div className="max-w-md w-full">
|
||||
<div className="text-center mb-8">
|
||||
<div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-violet-500 to-fuchsia-500 rounded-2xl mb-4">
|
||||
<span className="text-white font-bold text-3xl">D</span>
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-white">DocsSite 管理后台</h1>
|
||||
<p className="text-zinc-400 mt-2">请输入您的账号登录</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-zinc-800 rounded-xl p-6 shadow-xl">
|
||||
<form onSubmit={handleLogin} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm text-zinc-400 mb-2">用户名</label>
|
||||
<input
|
||||
type="text"
|
||||
value={loginForm.username}
|
||||
onChange={(e) => setLoginForm({ ...loginForm, username: e.target.value })}
|
||||
className="w-full px-4 py-3 bg-zinc-900 border border-zinc-700 rounded-lg text-white placeholder-zinc-500 focus:outline-none focus:border-violet-500"
|
||||
placeholder="admin"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-zinc-400 mb-2">密码</label>
|
||||
<input
|
||||
type="password"
|
||||
value={loginForm.password}
|
||||
onChange={(e) => setLoginForm({ ...loginForm, password: e.target.value })}
|
||||
className="w-full px-4 py-3 bg-zinc-900 border border-zinc-700 rounded-lg text-white placeholder-zinc-500 focus:outline-none focus:border-violet-500"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{errorMessage && (
|
||||
<div className="bg-red-500/20 border border-red-500 text-red-400 px-4 py-3 rounded-lg text-sm">
|
||||
{errorMessage}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className="w-full px-4 py-3 bg-violet-500 hover:bg-violet-600 text-white rounded-lg transition-colors font-medium"
|
||||
>
|
||||
登录
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="mt-6 pt-6 border-t border-zinc-700">
|
||||
<p className="text-xs text-zinc-500 text-center">
|
||||
默认账号:<code className="bg-zinc-900 px-2 py-1 rounded">admin</code> / <code className="bg-zinc-900 px-2 py-1 rounded">admin123</code>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 管理后台主界面
|
||||
return (
|
||||
<div className="min-h-screen bg-zinc-900 text-zinc-100">
|
||||
{/* 顶部导航 */}
|
||||
<header className="bg-zinc-800 border-b border-zinc-700 px-6 py-4">
|
||||
<div className="flex items-center justify-between max-w-6xl mx-auto">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 bg-gradient-to-br from-violet-500 to-fuchsia-500 rounded-lg flex items-center justify-center">
|
||||
<span className="text-white font-bold text-lg">D</span>
|
||||
</div>
|
||||
<h1 className="text-xl font-bold">DocsSite - 管理后台</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{user?.role === "admin" && (
|
||||
<button
|
||||
onClick={() => setActiveTab("addDoc")}
|
||||
className="px-4 py-2 bg-violet-500 hover:bg-violet-600 rounded-lg transition-colors"
|
||||
>
|
||||
+ 添加文档
|
||||
</button>
|
||||
)}
|
||||
<div className="flex items-center gap-4 pl-4 border-l border-zinc-700">
|
||||
<span className="text-sm text-zinc-400">{user?.username}</span>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="px-3 py-1.5 bg-zinc-700 hover:bg-zinc-600 rounded-lg text-sm transition-colors"
|
||||
>
|
||||
退出
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="p-6 max-w-6xl mx-auto">
|
||||
{/* 文档列表 */}
|
||||
{activeTab === "docs" && (
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold mb-6">文档列表</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
{docs.map((doc, index) => (
|
||||
<div
|
||||
key={doc.slug}
|
||||
className="bg-zinc-800 rounded-lg p-6 border border-zinc-700 hover:border-violet-500 transition-colors"
|
||||
>
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<h3 className="text-xl font-semibold mb-1">{doc.title}</h3>
|
||||
<p className="text-zinc-400 text-sm mb-3">{doc.description || "暂无描述"}</p>
|
||||
<div className="flex items-center gap-4 text-sm text-zinc-500">
|
||||
<span>Slug: {doc.slug}</span>
|
||||
<span>章节数:{doc.sections.length}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedDocSlug(doc.slug);
|
||||
setActiveTab("addDoc");
|
||||
setFormData({ ...formData, sectionTitle: "", sectionContent: "", sectionCode: "" });
|
||||
}}
|
||||
className="px-3 py-1.5 bg-zinc-700 hover:bg-violet-500 hover:text-white rounded-lg transition-colors text-sm"
|
||||
>
|
||||
+ 添加章节
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 章节列表 */}
|
||||
{doc.sections.length > 0 && (
|
||||
<div className="mt-4 pt-4 border-t border-zinc-700">
|
||||
<p className="text-sm text-zinc-500 mb-2">章节列表:</p>
|
||||
<div className="space-y-2">
|
||||
{doc.sections.map((section, i) => (
|
||||
<div key={i} className="flex items-start gap-2 text-sm">
|
||||
<span className="text-zinc-500 w-6">{i + 1}.</span>
|
||||
<span className="flex-1">{section.title}</span>
|
||||
{section.code && <span className="text-zinc-600 text-xs">代码块</span>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{docs.length === 0 && (
|
||||
<div className="text-center py-12 text-zinc-500">
|
||||
<p>暂无文档,点击右上角添加新文档</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 添加文档/章节表单 */}
|
||||
{activeTab === "addDoc" && (
|
||||
<div className="max-w-2xl">
|
||||
<button
|
||||
onClick={() => {
|
||||
setActiveTab("docs");
|
||||
setSelectedDocSlug("");
|
||||
}}
|
||||
className="mb-4 text-zinc-400 hover:text-white flex items-center gap-2"
|
||||
>
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
|
||||
</svg>
|
||||
返回列表
|
||||
</button>
|
||||
|
||||
{!selectedDocSlug ? (
|
||||
<>
|
||||
<h2 className="text-2xl font-bold mb-6">添加新文档</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm text-zinc-400 mb-2">文档标题 *</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.title}
|
||||
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
|
||||
className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-lg focus:outline-none focus:border-violet-500"
|
||||
placeholder="例如:用户指南"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-zinc-400 mb-2">Slug (自动生成)</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.slug}
|
||||
onChange={(e) => setFormData({ ...formData, slug: e.target.value })}
|
||||
className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-lg focus:outline-none focus:border-violet-500"
|
||||
placeholder="user-guide (留空自动从标题生成)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-zinc-400 mb-2">描述</label>
|
||||
<textarea
|
||||
value={formData.description}
|
||||
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
|
||||
className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-lg focus:outline-none focus:border-violet-500"
|
||||
placeholder="简短描述这个文档是关于什么的"
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleAddDoc}
|
||||
disabled={!formData.title}
|
||||
className="w-full px-4 py-3 bg-violet-500 hover:bg-violet-600 disabled:bg-zinc-700 disabled:cursor-not-allowed rounded-lg transition-colors font-medium"
|
||||
>
|
||||
创建文档
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="mb-2">
|
||||
<span className="text-zinc-400">当前文档:{selectedDocSlug}</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-bold mb-6">添加章节</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm text-zinc-400 mb-2">章节标题 *</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.sectionTitle}
|
||||
onChange={(e) => setFormData({ ...formData, sectionTitle: e.target.value })}
|
||||
className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-lg focus:outline-none focus:border-violet-500"
|
||||
placeholder="例如:快速开始"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-zinc-400 mb-2">章节内容</label>
|
||||
<textarea
|
||||
value={formData.sectionContent}
|
||||
onChange={(e) => setFormData({ ...formData, sectionContent: e.target.value })}
|
||||
className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-lg focus:outline-none focus:border-violet-500"
|
||||
placeholder="章节的正文内容"
|
||||
rows={5}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-zinc-400 mb-2">代码块 (可选)</label>
|
||||
<textarea
|
||||
value={formData.sectionCode}
|
||||
onChange={(e) => setFormData({ ...formData, sectionCode: e.target.value })}
|
||||
className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-lg focus:outline-none focus:border-violet-500 font-mono text-sm"
|
||||
placeholder="例如:npm install docs-site"
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleAddSection}
|
||||
disabled={!formData.sectionTitle}
|
||||
className="w-full px-4 py-3 bg-violet-500 hover:bg-violet-600 disabled:bg-zinc-700 disabled:cursor-not-allowed rounded-lg transition-colors font-medium"
|
||||
>
|
||||
添加章节
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
40
src/app/api/admin/add/route.ts
Normal file
40
src/app/api/admin/add/route.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { addDoc, addSection } from "@/lib/db";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { type, data } = body;
|
||||
|
||||
if (type === "doc") {
|
||||
const slug = data.slug || data.title.toLowerCase().replace(/\s+/g, "-");
|
||||
const success = await addDoc(
|
||||
slug,
|
||||
data.title,
|
||||
data.description
|
||||
);
|
||||
|
||||
if (success) {
|
||||
return NextResponse.json({ success: true, data: { slug, title: data.title } });
|
||||
}
|
||||
return NextResponse.json({ success: false, error: "添加文档失败" }, { status: 400 });
|
||||
} else if (type === "section") {
|
||||
const success = await addSection(
|
||||
data.docSlug,
|
||||
data.section.title,
|
||||
data.section.content,
|
||||
data.section.code
|
||||
);
|
||||
|
||||
if (success) {
|
||||
return NextResponse.json({ success: true, data: data.section });
|
||||
}
|
||||
return NextResponse.json({ success: false, error: "添加章节失败" }, { status: 400 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: false, error: "未知操作类型" }, { status: 400 });
|
||||
} catch (error) {
|
||||
console.error("Admin add error:", error);
|
||||
return NextResponse.json({ success: false, error: "服务器错误" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
67
src/app/api/auth/login/route.ts
Normal file
67
src/app/api/auth/login/route.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { query, getPasswordHash, isAdmin } from "@/lib/db";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const { username, password } = await request.json();
|
||||
|
||||
if (!username || !password) {
|
||||
return NextResponse.json(
|
||||
{ error: "用户名和密码不能为空" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// 获取密码哈希
|
||||
const hash = await getPasswordHash(username);
|
||||
if (!hash) {
|
||||
return NextResponse.json(
|
||||
{ error: "用户名或密码错误" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
// 验证密码
|
||||
const isValid = await bcrypt.compare(password, hash);
|
||||
if (!isValid) {
|
||||
return NextResponse.json(
|
||||
{ error: "用户名或密码错误" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
// 检查角色
|
||||
const isUserAdmin = await isAdmin(username);
|
||||
|
||||
// 创建会话
|
||||
const token = Buffer.from(
|
||||
JSON.stringify({ username, role: isUserAdmin ? "admin" : "user" })
|
||||
).toString("base64");
|
||||
|
||||
// 设置 HttpOnly Cookie
|
||||
const response = NextResponse.json({
|
||||
success: true,
|
||||
user: {
|
||||
username,
|
||||
role: isUserAdmin ? "admin" : "user",
|
||||
},
|
||||
});
|
||||
|
||||
response.cookies.set("session", token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "lax",
|
||||
maxAge: 60 * 60 * 24, // 24 小时
|
||||
path: "/",
|
||||
});
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error("Login error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "登录失败,请稍后重试" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
13
src/app/api/auth/logout/route.ts
Normal file
13
src/app/api/auth/logout/route.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function POST() {
|
||||
const response = NextResponse.json({ success: true });
|
||||
response.cookies.set("session", "", {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "lax",
|
||||
maxAge: 0,
|
||||
path: "/",
|
||||
});
|
||||
return response;
|
||||
}
|
||||
38
src/app/api/auth/me/route.ts
Normal file
38
src/app/api/auth/me/route.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { query } from "@/lib/db";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
// 读取 Cookie
|
||||
const token = request.cookies.get("session")?.value;
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json(
|
||||
{ error: "未登录", authenticated: false },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
// 解析 token
|
||||
const decoded = Buffer.from(token, "base64").toString("utf-8");
|
||||
const { username, role } = JSON.parse(decoded);
|
||||
|
||||
// 获取用户 ID
|
||||
const userResult = await query("SELECT id FROM users WHERE username = $1", [username]);
|
||||
const userId = userResult.rows[0]?.id;
|
||||
|
||||
return NextResponse.json({
|
||||
authenticated: true,
|
||||
user: {
|
||||
id: userId,
|
||||
username,
|
||||
role,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: "无效会话", authenticated: false },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
}
|
||||
10
src/app/api/docs/route.ts
Normal file
10
src/app/api/docs/route.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getDocsSimple, initializeDatabase } from "@/lib/db";
|
||||
|
||||
// 初始化数据库
|
||||
await initializeDatabase();
|
||||
|
||||
export async function GET() {
|
||||
const docs = await getDocsSimple();
|
||||
return NextResponse.json({ docs });
|
||||
}
|
||||
70
src/app/api/messages/route.ts
Normal file
70
src/app/api/messages/route.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getMessages, addMessage, deleteMessage, query } from "@/lib/db";
|
||||
|
||||
async function getUserId(request: NextRequest): Promise<number | null> {
|
||||
const token = request.cookies.get("session")?.value;
|
||||
if (!token) return null;
|
||||
try {
|
||||
const decoded = Buffer.from(token, "base64").toString("utf-8");
|
||||
const { username } = JSON.parse(decoded);
|
||||
if (!username) return null;
|
||||
|
||||
const userResult = await query("SELECT id FROM users WHERE username = $1", [username]);
|
||||
return userResult.rows[0]?.id ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const messages = await getMessages();
|
||||
return NextResponse.json({ messages });
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const userId = await getUserId(request);
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { content } = body;
|
||||
|
||||
if (!content || content.trim().length === 0) {
|
||||
return NextResponse.json({ error: "留言内容不能为空" }, { status: 400 });
|
||||
}
|
||||
|
||||
const success = await addMessage(userId, content);
|
||||
if (success) {
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
return NextResponse.json({ success: false, error: "发送留言失败" }, { status: 400 });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ success: false, error: "服务器错误" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: NextRequest) {
|
||||
const userId = await getUserId(request);
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const id = searchParams.get("id");
|
||||
|
||||
if (!id) {
|
||||
return NextResponse.json({ error: "缺少留言 ID" }, { status: 400 });
|
||||
}
|
||||
|
||||
const success = await deleteMessage(userId, parseInt(id));
|
||||
if (success) {
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
return NextResponse.json({ success: false, error: "删除留言失败" }, { status: 400 });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ success: false, error: "服务器错误" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
76
src/app/api/notes/route.ts
Normal file
76
src/app/api/notes/route.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getNotes, addNote, deleteNote, togglePinNote } from "@/lib/db";
|
||||
|
||||
async function getUserId(request: NextRequest): Promise<number | null> {
|
||||
const token = request.cookies.get("session")?.value;
|
||||
if (!token) return null;
|
||||
try {
|
||||
const decoded = Buffer.from(token, "base64").toString("utf-8");
|
||||
const { username } = JSON.parse(decoded);
|
||||
if (!username) return null;
|
||||
|
||||
const userResult = await query("SELECT id FROM users WHERE username = $1", [username]);
|
||||
return userResult.rows[0]?.id ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function query(sql: string, params?: any[]) {
|
||||
const { query: pgQuery } = await import("@/lib/db");
|
||||
return pgQuery(sql, params);
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const userId = await getUserId(request);
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||
}
|
||||
|
||||
const notes = await getNotes(userId);
|
||||
return NextResponse.json({ notes });
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const userId = await getUserId(request);
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { title, content, color, isPinned } = body;
|
||||
|
||||
const success = await addNote(userId, title, content || "", color || "#fef08a", isPinned || false);
|
||||
if (success) {
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
return NextResponse.json({ success: false, error: "添加便签失败" }, { status: 400 });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ success: false, error: "服务器错误" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: NextRequest) {
|
||||
const userId = await getUserId(request);
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const id = searchParams.get("id");
|
||||
|
||||
if (!id) {
|
||||
return NextResponse.json({ error: "缺少便签 ID" }, { status: 400 });
|
||||
}
|
||||
|
||||
const success = await deleteNote(userId, parseInt(id));
|
||||
if (success) {
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
return NextResponse.json({ success: false, error: "删除便签失败" }, { status: 400 });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ success: false, error: "服务器错误" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
37
src/app/api/notes/toggle-pin/route.ts
Normal file
37
src/app/api/notes/toggle-pin/route.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { togglePinNote, query } from "@/lib/db";
|
||||
|
||||
async function getUserId(request: NextRequest): Promise<number | null> {
|
||||
const token = request.cookies.get("session")?.value;
|
||||
if (!token) return null;
|
||||
try {
|
||||
const decoded = Buffer.from(token, "base64").toString("utf-8");
|
||||
const { username } = JSON.parse(decoded);
|
||||
if (!username) return null;
|
||||
|
||||
const userResult = await query("SELECT id FROM users WHERE username = $1", [username]);
|
||||
return userResult.rows[0]?.id ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const userId = await getUserId(request);
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "未登录" }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { id } = body;
|
||||
|
||||
const success = await togglePinNote(userId, id);
|
||||
if (success) {
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
return NextResponse.json({ success: false, error: "操作失败" }, { status: 400 });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ success: false, error: "服务器错误" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
BIN
src/app/favicon.ico
Normal file
BIN
src/app/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
55
src/app/globals.css
Normal file
55
src/app/globals.css
Normal file
@@ -0,0 +1,55 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
|
||||
/* 自定义滚动条 */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: #a1a1aa;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: #71717a;
|
||||
}
|
||||
|
||||
/* 滚动到元素时的动画 */
|
||||
.scroll-mt-24 {
|
||||
scroll-margin-top: 6rem;
|
||||
}
|
||||
|
||||
/* 平滑过渡 */
|
||||
* {
|
||||
transition: background-color 0.2s ease, color 0.2s ease, border-color 0.2s ease;
|
||||
}
|
||||
30
src/app/layout.tsx
Normal file
30
src/app/layout.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Inter } from "next/font/google";
|
||||
import "./globals.css";
|
||||
import { ThemeProvider } from "@/components/ThemeProvider";
|
||||
import { AuthProvider } from "@/components/AuthProvider";
|
||||
|
||||
const inter = Inter({ subsets: ["latin"] });
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "DocsSite - 在线文档系统",
|
||||
description: "现代、响应式的在线文档系统",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="zh-CN" suppressHydrationWarning>
|
||||
<body className={`${inter.className} antialiased`}>
|
||||
<ThemeProvider>
|
||||
<AuthProvider>
|
||||
{children}
|
||||
</AuthProvider>
|
||||
</ThemeProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
837
src/app/page.tsx
Normal file
837
src/app/page.tsx
Normal file
@@ -0,0 +1,837 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import CodeBlock from "@/components/CodeBlock";
|
||||
import NotesList from "@/components/note/NotesList";
|
||||
import MessageBoard from "@/components/message/MessageBoard";
|
||||
import { useTheme } from "@/components/ThemeProvider";
|
||||
import { useAuth } from "@/components/AuthProvider";
|
||||
|
||||
const documentation = [
|
||||
{
|
||||
title: "快速开始",
|
||||
slug: "quick-start",
|
||||
description: "了解如何开始使用我们的平台",
|
||||
sections: [
|
||||
{
|
||||
title: "简介",
|
||||
content: "欢迎使用我们的在线文档系统!这是一个现代、响应式、功能丰富的文档平台,专为技术文档设计。",
|
||||
features: [
|
||||
"响应式布局,支持移动端和桌面端",
|
||||
"平滑滚动和锚点导航",
|
||||
"代码高亮和复制功能",
|
||||
"深色模式支持",
|
||||
"内置搜索功能",
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "安装",
|
||||
content: "开始之前,请确保你已经安装了以下工具:",
|
||||
requirements: ["Node.js (v18 或更高版本)", "npm 或 yarn 包管理器"],
|
||||
code: "npm install\ngit pull origin main",
|
||||
instructions: "然后运行以下命令:\n\nnpm install\n\n然后:\n\nnpm run dev\n\n访问 http://localhost:3000 即可查看。",
|
||||
},
|
||||
{
|
||||
title: "项目结构",
|
||||
content: "项目采用以下目录结构:",
|
||||
code: `docs-site/
|
||||
├── src/
|
||||
│ ├── app/
|
||||
│ │ ├── page.tsx # 主文档页面
|
||||
│ │ ├── layout.tsx # 根布局
|
||||
│ │ └── globals.css # 全局样式
|
||||
│ └── components/
|
||||
│ ├── Sidebar.tsx # 侧边栏组件
|
||||
│ ├── Navbar.tsx # 导航栏组件
|
||||
│ └── CodeBlock.tsx # 代码块组件
|
||||
├── public/
|
||||
└── package.json`,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "核心功能",
|
||||
slug: "features",
|
||||
description: "探索平台的各项功能",
|
||||
sections: [
|
||||
{
|
||||
title: "响应式布局",
|
||||
content: "平台采用响应式设计,自动适配各种屏幕尺寸。",
|
||||
features: [
|
||||
{
|
||||
title: "移动端",
|
||||
items: ["侧边栏可折叠", "字体大小自动调整", "导航栏简化"],
|
||||
},
|
||||
{
|
||||
title: "桌面端",
|
||||
items: ["固定侧边栏", "更多内容展示", "优化排版"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "交互功能",
|
||||
content: "平台提供丰富的交互功能:",
|
||||
features: [
|
||||
{
|
||||
title: "代码复制",
|
||||
description: "点击代码块右上角的复制按钮即可快速复制代码",
|
||||
},
|
||||
{
|
||||
title: "平滑滚动",
|
||||
description: "点击导航链接自动滚动到对应位置",
|
||||
},
|
||||
{
|
||||
title: "深色模式",
|
||||
description: "点击右上角切换按钮即可切换主题",
|
||||
},
|
||||
{
|
||||
title: "锚点导航",
|
||||
description: "每个章节都有独立的锚点链接",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "搜索功能",
|
||||
content: "内置搜索功能帮助你快速找到所需内容。",
|
||||
code: "1. 点击右上角的搜索图标\n2. 输入关键词\n3. 查看搜索结果\n4. 点击结果跳转到对应章节",
|
||||
instructions: "搜索支持标题、描述和代码片段。",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "API 参考",
|
||||
slug: "api-reference",
|
||||
description: "API 接口文档",
|
||||
sections: [
|
||||
{
|
||||
title: "获取文档列表",
|
||||
content: "获取所有可用文档的列表。",
|
||||
code: `// GET /api/docs
|
||||
|
||||
Response:
|
||||
{
|
||||
"docs": [
|
||||
{
|
||||
"title": "文档标题",
|
||||
"slug": "文档_slug",
|
||||
"description": "文档描述"
|
||||
}
|
||||
]
|
||||
}`,
|
||||
},
|
||||
{
|
||||
title: "获取文档内容",
|
||||
content: "获取指定文档的详细内容。",
|
||||
code: `// GET /api/docs/:slug
|
||||
|
||||
Response:
|
||||
{
|
||||
"title": "文档标题",
|
||||
"sections": [
|
||||
{
|
||||
"title": "章节标题",
|
||||
"content": "章节内容"
|
||||
}
|
||||
]
|
||||
}`,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
interface FeatureItem {
|
||||
title: string;
|
||||
items?: string[];
|
||||
description?: string;
|
||||
}
|
||||
|
||||
function FeatureCard({ title, description, children }: {
|
||||
title: string;
|
||||
description?: string;
|
||||
children?: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="bg-zinc-100 dark:bg-zinc-800 rounded-lg p-4 mb-4 hover:shadow-lg transition-shadow">
|
||||
<h4 className="font-semibold text-lg mb-2">{title}</h4>
|
||||
{description && <p className="text-zinc-600 dark:text-zinc-400">{description}</p>}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function HomeInner() {
|
||||
const { theme, toggleTheme } = useTheme();
|
||||
const { authenticated, user, checkAuth } = useAuth();
|
||||
const [activeDoc, setActiveDoc] = useState("quick-start");
|
||||
const [activeSection, setActiveSection] = useState("");
|
||||
const [sidebarOpen, setSidebarOpen] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
const currentDoc = documentation.find((doc) => doc.slug === activeDoc);
|
||||
const sections = currentDoc?.sections || [];
|
||||
|
||||
const handleCopy = () => {
|
||||
navigator.clipboard.writeText("npm install docs-site");
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
};
|
||||
|
||||
const handleNavClick = (id: string) => {
|
||||
setActiveSection(id);
|
||||
setSidebarOpen(false);
|
||||
const element = document.getElementById(id);
|
||||
element?.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
};
|
||||
|
||||
const filteredDocs = documentation.filter(
|
||||
(doc) =>
|
||||
doc.title.includes(searchQuery) ||
|
||||
doc.description.includes(searchQuery)
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={`${theme} h-full`}>
|
||||
<div className="flex h-full min-h-screen bg-zinc-50 text-zinc-900 dark:bg-zinc-900 dark:text-zinc-100 transition-colors duration-200">
|
||||
{/* 移动端遮罩 */}
|
||||
{sidebarOpen && (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 z-40 lg:hidden"
|
||||
onClick={() => setSidebarOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 左侧导航栏 */}
|
||||
<aside
|
||||
className={`fixed lg:sticky top-0 left-0 z-50 h-screen w-72 bg-white dark:bg-zinc-800 border-r border-zinc-200 dark:border-zinc-700 transition-transform duration-300 ${
|
||||
sidebarOpen ? "translate-x-0" : "-translate-x-full lg:translate-x-0"
|
||||
}`}
|
||||
>
|
||||
<div className="p-6 h-full flex flex-col">
|
||||
{/* Logo */}
|
||||
<div className="mb-8">
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<div className="w-8 h-8 bg-gradient-to-br from-violet-500 to-fuchsia-500 rounded-lg flex items-center justify-center">
|
||||
<span className="text-white font-bold text-lg">D</span>
|
||||
</div>
|
||||
<h1 className="text-xl font-bold">DocsSite</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 搜索 */}
|
||||
<div className="mb-6 relative">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="搜索文档..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="w-full pl-10 pr-4 py-2 bg-zinc-100 dark:bg-zinc-700 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-violet-500"
|
||||
/>
|
||||
<svg
|
||||
className="absolute left-3 top-2.5 w-4 h-4 text-zinc-400"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
{/* 文档列表 */}
|
||||
<nav className="flex-1 overflow-y-auto">
|
||||
<div className="space-y-1">
|
||||
{filteredDocs.map((doc) => (
|
||||
<button
|
||||
key={doc.slug}
|
||||
onClick={() => {
|
||||
setActiveDoc(doc.slug);
|
||||
setSidebarOpen(false);
|
||||
}}
|
||||
className={`w-full text-left px-3 py-2 rounded-lg transition-colors ${
|
||||
activeDoc === doc.slug
|
||||
? "bg-violet-100 dark:bg-violet-900/30 text-violet-700 dark:text-violet-300"
|
||||
: "hover:bg-zinc-100 dark:hover:bg-zinc-700"
|
||||
}`}
|
||||
>
|
||||
<div className="font-medium text-sm">{doc.title}</div>
|
||||
<div className="text-xs text-zinc-500 dark:text-zinc-400 mt-0.5">
|
||||
{doc.description}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* 主内容区 */}
|
||||
<main className="flex-1 min-w-0">
|
||||
{/* 顶部导航栏 */}
|
||||
<header className="sticky top-0 z-30 bg-white/80 dark:bg-zinc-900/80 backdrop-blur-sm border-b border-zinc-200 dark:border-zinc-700">
|
||||
<div className="flex items-center justify-between px-6 py-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
onClick={() => setSidebarOpen(!sidebarOpen)}
|
||||
className="lg:hidden p-2 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-lg"
|
||||
>
|
||||
<svg
|
||||
className="w-6 h-6"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M4 6h16M4 12h16M4 18h16"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
<h2 className="text-xl font-semibold">{currentDoc?.title}</h2>
|
||||
{!authenticated && (
|
||||
<a
|
||||
href="/admin"
|
||||
className="px-3 py-1.5 bg-violet-500 hover:bg-violet-600 text-white text-sm rounded-lg transition-colors sm:hidden"
|
||||
>
|
||||
登录
|
||||
</a>
|
||||
)}
|
||||
{authenticated && user && (
|
||||
<div className="hidden sm:flex items-center gap-2 ml-auto">
|
||||
<span className="text-sm text-zinc-500">{user.username}</span>
|
||||
<button
|
||||
onClick={async () => {
|
||||
await fetch("/api/auth/logout", { method: "POST" });
|
||||
await checkAuth();
|
||||
}}
|
||||
className="text-sm text-violet-500 hover:underline"
|
||||
>
|
||||
退出
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{/* 深色模式切换 */}
|
||||
<button
|
||||
onClick={toggleTheme}
|
||||
className="p-2 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-lg transition-colors"
|
||||
title={theme === "light" ? "切换到深色模式" : "切换到浅色模式"}
|
||||
>
|
||||
{theme === "light" ? (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"
|
||||
/>
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* 复制链接 */}
|
||||
<button
|
||||
onClick={handleCopy}
|
||||
className="p-2 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-lg transition-colors relative"
|
||||
>
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"
|
||||
/>
|
||||
</svg>
|
||||
{copied && (
|
||||
<span className="absolute -top-1 -right-1 w-4 h-4 bg-green-500 rounded-full text-white text-xs flex items-center justify-center">
|
||||
✓
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* 文档内容 */}
|
||||
<div className="max-w-4xl mx-auto px-6 py-8">
|
||||
{sections.map((section, index) => (
|
||||
<section
|
||||
key={section.title}
|
||||
id={section.title}
|
||||
className={`mb-12 scroll-mt-24`}
|
||||
>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h3 className="text-2xl font-semibold">{section.title}</h3>
|
||||
<a
|
||||
href={`#${section.title}`}
|
||||
className="opacity-0 hover:opacity-100 transition-opacity text-zinc-400 hover:text-violet-500"
|
||||
>
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"
|
||||
/>
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{section.content && (
|
||||
<p className="text-zinc-700 dark:text-zinc-300 mb-4 leading-relaxed">
|
||||
{section.content}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{section.features && (
|
||||
<div className="space-y-4">
|
||||
{(section.features as string[] | FeatureItem[]).map((feature, i) => {
|
||||
if (typeof feature === "string") {
|
||||
return (
|
||||
<div key={i} className="flex items-start gap-3">
|
||||
<svg
|
||||
className="w-5 h-5 text-green-500 mt-0.5 flex-shrink-0"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M5 13l4 4L19 7"
|
||||
/>
|
||||
</svg>
|
||||
<span>{feature}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<FeatureCard key={i} title={feature.title} description={feature.description}>
|
||||
{feature.items && (
|
||||
<ul className="space-y-2 mt-2">
|
||||
{feature.items.map((item, j) => (
|
||||
<li key={j} className="flex items-start gap-2 text-sm">
|
||||
<span className="text-green-500 mt-0.5">✓</span>
|
||||
{item}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</FeatureCard>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{section.code && (
|
||||
<CodeBlock language="bash">
|
||||
{section.code}
|
||||
</CodeBlock>
|
||||
)}
|
||||
|
||||
{section.instructions && section.code && (
|
||||
<p className="text-zinc-700 dark:text-zinc-300 mb-4 leading-relaxed mt-4">
|
||||
{section.instructions}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
))}
|
||||
|
||||
{/* 便签 */}
|
||||
<div className="py-8">
|
||||
<NotesList userId={user?.id || null} />
|
||||
</div>
|
||||
|
||||
{/* 留言板 */}
|
||||
<div className="py-8 border-t border-zinc-200 dark:border-zinc-700">
|
||||
<MessageBoard />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 底部 */}
|
||||
<footer className="border-t border-zinc-200 dark:border-zinc-700 py-6 px-6">
|
||||
<div className="max-w-4xl mx-auto flex items-center justify-between">
|
||||
<p className="text-sm text-zinc-500">
|
||||
© 2026 DocsSite. All rights reserved.
|
||||
</p>
|
||||
<div className="flex items-center gap-4">
|
||||
<a
|
||||
href="#"
|
||||
className="text-sm text-zinc-500 hover:text-violet-500 transition-colors"
|
||||
>
|
||||
隐私政策
|
||||
</a>
|
||||
<a
|
||||
href="#"
|
||||
className="text-sm text-zinc-500 hover:text-violet-500 transition-colors"
|
||||
>
|
||||
联系方式
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const [activeSection, setActiveSection] = useState("");
|
||||
const [sidebarOpen, setSidebarOpen] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const currentDoc = documentation.find((doc) => doc.slug === activeDoc);
|
||||
const sections = currentDoc?.sections || [];
|
||||
|
||||
const handleCopy = () => {
|
||||
navigator.clipboard.writeText("npm install docs-site");
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
};
|
||||
|
||||
const handleNavClick = (id: string) => {
|
||||
setActiveSection(id);
|
||||
setSidebarOpen(false);
|
||||
const element = document.getElementById(id);
|
||||
element?.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
};
|
||||
|
||||
const filteredDocs = documentation.filter(
|
||||
(doc) =>
|
||||
doc.title.includes(searchQuery) ||
|
||||
doc.description.includes(searchQuery)
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={`${darkMode ? "dark" : ""} h-full`}>
|
||||
<div className="flex h-full min-h-screen bg-zinc-50 text-zinc-900 dark:bg-zinc-900 dark:text-zinc-100 transition-colors duration-200">
|
||||
{/* 移动端遮罩 */}
|
||||
{sidebarOpen && (
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 z-40 lg:hidden"
|
||||
onClick={() => setSidebarOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 左侧导航栏 */}
|
||||
<aside
|
||||
className={`fixed lg:sticky top-0 left-0 z-50 h-screen w-72 bg-white dark:bg-zinc-800 border-r border-zinc-200 dark:border-zinc-700 transition-transform duration-300 ${
|
||||
sidebarOpen ? "translate-x-0" : "-translate-x-full lg:translate-x-0"
|
||||
}`}
|
||||
>
|
||||
<div className="p-6 h-full flex flex-col">
|
||||
{/* Logo */}
|
||||
<div className="mb-8">
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<div className="w-8 h-8 bg-gradient-to-br from-violet-500 to-fuchsia-500 rounded-lg flex items-center justify-center">
|
||||
<span className="text-white font-bold text-lg">D</span>
|
||||
</div>
|
||||
<h1 className="text-xl font-bold">DocsSite</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 搜索 */}
|
||||
<div className="mb-6 relative">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="搜索文档..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="w-full pl-10 pr-4 py-2 bg-zinc-100 dark:bg-zinc-700 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-violet-500"
|
||||
/>
|
||||
<svg
|
||||
className="absolute left-3 top-2.5 w-4 h-4 text-zinc-400"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
{/* 文档列表 */}
|
||||
<nav className="flex-1 overflow-y-auto">
|
||||
<div className="space-y-1">
|
||||
{filteredDocs.map((doc) => (
|
||||
<button
|
||||
key={doc.slug}
|
||||
onClick={() => {
|
||||
setActiveDoc(doc.slug);
|
||||
setSidebarOpen(false);
|
||||
}}
|
||||
className={`w-full text-left px-3 py-2 rounded-lg transition-colors ${
|
||||
activeDoc === doc.slug
|
||||
? "bg-violet-100 dark:bg-violet-900/30 text-violet-700 dark:text-violet-300"
|
||||
: "hover:bg-zinc-100 dark:hover:bg-zinc-700"
|
||||
}`}
|
||||
>
|
||||
<div className="font-medium text-sm">{doc.title}</div>
|
||||
<div className="text-xs text-zinc-500 dark:text-zinc-400 mt-0.5">
|
||||
{doc.description}
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* 主内容区 */}
|
||||
<main className="flex-1 min-w-0">
|
||||
{/* 顶部导航栏 */}
|
||||
<header className="sticky top-0 z-30 bg-white/80 dark:bg-zinc-900/80 backdrop-blur-sm border-b border-zinc-200 dark:border-zinc-700">
|
||||
<div className="flex items-center justify-between px-6 py-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
onClick={() => setSidebarOpen(!sidebarOpen)}
|
||||
className="lg:hidden p-2 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-lg"
|
||||
>
|
||||
<svg
|
||||
className="w-6 h-6"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M4 6h16M4 12h16M4 18h16"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
<h2 className="text-xl font-semibold">{currentDoc?.title}</h2>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{!authenticated && (
|
||||
<a
|
||||
href="/admin"
|
||||
className="px-3 py-1.5 bg-violet-500 hover:bg-violet-600 text-white text-sm rounded-lg transition-colors"
|
||||
>
|
||||
登录
|
||||
</a>
|
||||
)}
|
||||
{/* 深色模式切换 */}
|
||||
<button
|
||||
onClick={toggleTheme}
|
||||
className="p-2 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-lg transition-colors"
|
||||
title={theme === "light" ? "切换到深色模式" : "切换到浅色模式"}
|
||||
>
|
||||
{theme === "light" ? (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"
|
||||
/>
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* 复制链接 */}
|
||||
<button
|
||||
onClick={handleCopy}
|
||||
className="p-2 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-lg transition-colors relative"
|
||||
>
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3"
|
||||
/>
|
||||
</svg>
|
||||
{copied && (
|
||||
<span className="absolute -top-1 -right-1 w-4 h-4 bg-green-500 rounded-full text-white text-xs flex items-center justify-center">
|
||||
✓
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* 文档内容 */}
|
||||
<div className="max-w-4xl mx-auto px-6 py-8">
|
||||
{sections.map((section, index) => (
|
||||
<section
|
||||
key={section.title}
|
||||
id={section.title}
|
||||
className={`mb-12 scroll-mt-24`}
|
||||
>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h3 className="text-2xl font-semibold">{section.title}</h3>
|
||||
<a
|
||||
href={`#${section.title}`}
|
||||
className="opacity-0 hover:opacity-100 transition-opacity text-zinc-400 hover:text-violet-500"
|
||||
>
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"
|
||||
/>
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{section.content && (
|
||||
<p className="text-zinc-700 dark:text-zinc-300 mb-4 leading-relaxed">
|
||||
{section.content}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{section.features && (
|
||||
<div className="space-y-4">
|
||||
{(section.features as string[] | FeatureItem[]).map((feature, i) => {
|
||||
if (typeof feature === "string") {
|
||||
return (
|
||||
<div key={i} className="flex items-start gap-3">
|
||||
<svg
|
||||
className="w-5 h-5 text-green-500 mt-0.5 flex-shrink-0"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M5 13l4 4L19 7"
|
||||
/>
|
||||
</svg>
|
||||
<span>{feature}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<FeatureCard key={i} title={feature.title} description={feature.description}>
|
||||
{feature.items && (
|
||||
<ul className="space-y-2 mt-2">
|
||||
{feature.items.map((item, j) => (
|
||||
<li key={j} className="flex items-start gap-2 text-sm">
|
||||
<span className="text-green-500 mt-0.5">✓</span>
|
||||
{item}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</FeatureCard>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{section.code && (
|
||||
<CodeBlock language="bash">
|
||||
{section.code}
|
||||
</CodeBlock>
|
||||
)}
|
||||
|
||||
{section.instructions && section.code && (
|
||||
<p className="text-zinc-700 dark:text-zinc-300 mb-4 leading-relaxed mt-4">
|
||||
{section.instructions}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 便签 */}
|
||||
<div className="py-8">
|
||||
<NotesList userId={auth.user?.id || null} />
|
||||
</div>
|
||||
|
||||
{/* 留言板 */}
|
||||
<div className="py-8 border-t border-zinc-200 dark:border-zinc-700">
|
||||
<MessageBoard userId={auth.user?.id || null} username={auth.user?.username || null} />
|
||||
</div>
|
||||
|
||||
{/* 底部 */}
|
||||
<footer className="border-t border-zinc-200 dark:border-zinc-700 py-6 px-6">
|
||||
<div className="max-w-4xl mx-auto flex items-center justify-between">
|
||||
<p className="text-sm text-zinc-500">
|
||||
© 2026 DocsSite. All rights reserved.
|
||||
</p>
|
||||
<div className="flex items-center gap-4">
|
||||
<a
|
||||
href="#"
|
||||
className="text-sm text-zinc-500 hover:text-violet-500 transition-colors"
|
||||
>
|
||||
隐私政策
|
||||
</a>
|
||||
<a
|
||||
href="#"
|
||||
className="text-sm text-zinc-500 hover:text-violet-500 transition-colors"
|
||||
>
|
||||
联系方式
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default HomeInner;
|
||||
60
src/components/AuthProvider.tsx
Normal file
60
src/components/AuthProvider.tsx
Normal file
@@ -0,0 +1,60 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useContext, useEffect, useState } from "react";
|
||||
|
||||
interface User {
|
||||
id: number;
|
||||
username: string;
|
||||
role: "admin" | "user";
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
authenticated: boolean;
|
||||
user: User | null;
|
||||
checkAuth: () => Promise<void>;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [authenticated, setAuthenticated] = useState(false);
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const checkAuth = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/auth/me");
|
||||
const data = await res.json();
|
||||
if (data.authenticated) {
|
||||
setAuthenticated(true);
|
||||
setUser(data.user);
|
||||
} else {
|
||||
setAuthenticated(false);
|
||||
setUser(null);
|
||||
}
|
||||
} catch (error) {
|
||||
setAuthenticated(false);
|
||||
setUser(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ authenticated, user, checkAuth }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error("useAuth must be used within an AuthProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
69
src/components/CodeBlock.tsx
Normal file
69
src/components/CodeBlock.tsx
Normal file
@@ -0,0 +1,69 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef, useEffect } from "react";
|
||||
|
||||
interface CodeBlockProps {
|
||||
children: string;
|
||||
language?: string;
|
||||
}
|
||||
|
||||
export default function CodeBlock({ children, language }: CodeBlockProps) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (copied) {
|
||||
const timer = setTimeout(() => setCopied(false), 2000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [copied]);
|
||||
|
||||
const handleCopy = () => {
|
||||
navigator.clipboard.writeText(children);
|
||||
setCopied(true);
|
||||
buttonRef.current?.blur();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="my-4 rounded-lg overflow-hidden bg-zinc-900">
|
||||
{language && (
|
||||
<div className="bg-zinc-800 px-4 py-2 text-xs text-zinc-400 flex items-center gap-2">
|
||||
<span className="font-mono">{language}</span>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className="relative group"
|
||||
onMouseEnter={() => setIsHovered(true)}
|
||||
onMouseLeave={() => setIsHovered(false)}
|
||||
>
|
||||
<pre className="p-4 overflow-x-auto">
|
||||
<code className="text-zinc-50 font-mono text-sm">{children}</code>
|
||||
</pre>
|
||||
<button
|
||||
ref={buttonRef}
|
||||
onClick={handleCopy}
|
||||
className={`absolute top-2 right-2 bg-zinc-700 hover:bg-zinc-600 text-white px-3 py-1.5 rounded text-sm transition-all duration-200 flex items-center gap-1.5 ${
|
||||
isHovered ? "opacity-100" : "opacity-0"
|
||||
}`}
|
||||
>
|
||||
{copied ? (
|
||||
<>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
Copied!
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
|
||||
</svg>
|
||||
Copy
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
62
src/components/ThemeProvider.tsx
Normal file
62
src/components/ThemeProvider.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useContext, useEffect, useState } from "react";
|
||||
|
||||
type Theme = "light" | "dark";
|
||||
|
||||
interface ThemeContextType {
|
||||
theme: Theme;
|
||||
toggleTheme: () => void;
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
|
||||
|
||||
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||
const [theme, setTheme] = useState<Theme>("light");
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
const savedTheme = localStorage.getItem("theme") as Theme | null;
|
||||
if (savedTheme) {
|
||||
setTheme(savedTheme);
|
||||
if (savedTheme === "dark") {
|
||||
document.documentElement.classList.add("dark");
|
||||
}
|
||||
} else if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
|
||||
setTheme("dark");
|
||||
document.documentElement.classList.add("dark");
|
||||
}
|
||||
}, []);
|
||||
|
||||
const toggleTheme = () => {
|
||||
setTheme((prev) => {
|
||||
const newTheme = prev === "light" ? "dark" : "light";
|
||||
localStorage.setItem("theme", newTheme);
|
||||
if (newTheme === "dark") {
|
||||
document.documentElement.classList.add("dark");
|
||||
} else {
|
||||
document.documentElement.classList.remove("dark");
|
||||
}
|
||||
return newTheme;
|
||||
});
|
||||
};
|
||||
|
||||
if (!mounted) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={{ theme, toggleTheme }}>
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const context = useContext(ThemeContext);
|
||||
if (!context) {
|
||||
throw new Error("useTheme must be used within a ThemeProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
167
src/components/message/MessageBoard.tsx
Normal file
167
src/components/message/MessageBoard.tsx
Normal file
@@ -0,0 +1,167 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { useAuth } from "@/components/AuthProvider";
|
||||
|
||||
interface Message {
|
||||
id: number;
|
||||
username: string;
|
||||
content: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export default function MessageBoard() {
|
||||
const { authenticated, user } = useAuth();
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [showForm, setShowForm] = useState(false);
|
||||
const [formData, setFormData] = useState({ content: "" });
|
||||
const [currentUserMsgId, setCurrentUserMsgId] = useState<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchMessages();
|
||||
}, []);
|
||||
|
||||
const fetchMessages = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/messages");
|
||||
const data = await res.json();
|
||||
if (data.messages) {
|
||||
setMessages(data.messages);
|
||||
if (authenticated && user) {
|
||||
const myMsg = data.messages.find((m: Message) => m.username === user.username);
|
||||
setCurrentUserMsgId(myMsg?.id || null);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch messages:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePostMessage = async () => {
|
||||
if (!formData.content.trim()) return;
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/messages", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(formData),
|
||||
});
|
||||
const result = await res.json();
|
||||
if (result.success) {
|
||||
setFormData({ content: "" });
|
||||
setShowForm(false);
|
||||
fetchMessages();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to post message:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteMessage = async (msgId: number, e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
try {
|
||||
const res = await fetch(`/api/messages?id=${msgId}`, { method: "DELETE" });
|
||||
const result = await res.json();
|
||||
if (result.success) {
|
||||
fetchMessages();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to delete message:", error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h2 className="text-2xl font-bold">留言板</h2>
|
||||
{authenticated && (
|
||||
<button
|
||||
onClick={() => setShowForm(!showForm)}
|
||||
className="px-4 py-2 bg-violet-500 hover:bg-violet-600 text-white rounded-lg transition-colors"
|
||||
>
|
||||
{showForm ? "取消" : "写留言"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{showForm && authenticated && user && (
|
||||
<div className="bg-zinc-100 dark:bg-zinc-800 rounded-lg p-6 mb-6">
|
||||
<div className="mb-4">
|
||||
<label className="block text-sm text-zinc-400 mb-2">留言内容</label>
|
||||
<textarea
|
||||
value={formData.content}
|
||||
onChange={(e) => setFormData({ ...formData, content: e.target.value })}
|
||||
className="w-full px-4 py-2 bg-white dark:bg-zinc-900 border border-zinc-300 dark:border-zinc-700 rounded-lg focus:outline-none focus:border-violet-500"
|
||||
placeholder="在这里写下你的留言..."
|
||||
rows={4}
|
||||
maxLength={500}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-xs text-zinc-500">
|
||||
{formData.content.length}/500
|
||||
</span>
|
||||
<button
|
||||
onClick={handlePostMessage}
|
||||
disabled={!formData.content.trim()}
|
||||
className="px-6 py-2 bg-violet-500 hover:bg-violet-600 disabled:bg-zinc-300 dark:disabled:bg-zinc-700 text-white rounded-lg transition-colors"
|
||||
>
|
||||
发布留言
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!authenticated && (
|
||||
<div className="bg-zinc-100 dark:bg-zinc-800 rounded-lg p-6 text-center text-zinc-500 mb-6">
|
||||
登录后可以发表留言
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{messages.map((msg) => (
|
||||
<div
|
||||
key={msg.id}
|
||||
className={`bg-white dark:bg-zinc-800 rounded-lg p-4 shadow-sm hover:shadow-md transition-shadow ${
|
||||
authenticated && user && msg.username === user.username && currentUserMsgId === msg.id
|
||||
? "border-l-4 border-violet-500"
|
||||
: ""
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start justify-between mb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-8 h-8 rounded-full bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center text-white font-medium">
|
||||
{msg.username.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<span className="font-medium">{msg.username}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-zinc-500">
|
||||
{new Date(msg.created_at).toLocaleString("zh-CN")}
|
||||
</span>
|
||||
{authenticated && user && msg.username === user.username && (
|
||||
<button
|
||||
onClick={(e) => handleDeleteMessage(msg.id, e)}
|
||||
className="p-1 hover:bg-red-100 dark:hover:bg-red-900/30 rounded text-red-500"
|
||||
title="删除"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-zinc-700 dark:text-zinc-300">{msg.content}</p>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{messages.length === 0 && (
|
||||
<div className="text-center py-12 text-zinc-500">
|
||||
暂无留言,成为第一个留言的人吧!
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
249
src/components/note/NotesList.tsx
Normal file
249
src/components/note/NotesList.tsx
Normal file
@@ -0,0 +1,249 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { useAuth } from "@/components/AuthProvider";
|
||||
|
||||
interface Note {
|
||||
id: number;
|
||||
title: string;
|
||||
content: string;
|
||||
color: string;
|
||||
is_pinned: boolean;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
interface NotesListProps {
|
||||
userId: number | null;
|
||||
}
|
||||
|
||||
export default function NotesList({ userId }: NotesListProps) {
|
||||
const [notes, setNotes] = useState<Note[]>([]);
|
||||
const [showAddForm, setShowAddForm] = useState(false);
|
||||
const [formData, setFormData] = useState({
|
||||
title: "",
|
||||
content: "",
|
||||
color: "#fef08a",
|
||||
isPinned: false,
|
||||
});
|
||||
|
||||
const { authenticated, user } = useAuth();
|
||||
|
||||
const colors = [
|
||||
"#fef08a", // yellow
|
||||
"#86efac", // green
|
||||
"#93c5fd", // blue
|
||||
"#fda4af", // pink
|
||||
"#c4b5fd", // purple
|
||||
"#fb923c", // orange
|
||||
];
|
||||
|
||||
useEffect(() => {
|
||||
if (userId) {
|
||||
fetchNotes();
|
||||
}
|
||||
}, [userId]);
|
||||
|
||||
const fetchNotes = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/notes");
|
||||
const data = await res.json();
|
||||
if (data.notes) {
|
||||
setNotes(data.notes);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch notes:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddNote = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/notes", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(formData),
|
||||
});
|
||||
const result = await res.json();
|
||||
if (result.success) {
|
||||
setFormData({ title: "", content: "", color: "#fef08a", isPinned: false });
|
||||
setShowAddForm(false);
|
||||
fetchNotes();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to add note:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteNote = async (noteId: number) => {
|
||||
try {
|
||||
const res = await fetch(`/api/notes?id=${noteId}`, { method: "DELETE" });
|
||||
const result = await res.json();
|
||||
if (result.success) {
|
||||
fetchNotes();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to delete note:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleTogglePin = async (noteId: number) => {
|
||||
try {
|
||||
const res = await fetch("/api/notes/toggle-pin", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ id: noteId }),
|
||||
});
|
||||
const result = await res.json();
|
||||
if (result.success) {
|
||||
fetchNotes();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to toggle pin:", error);
|
||||
}
|
||||
};
|
||||
|
||||
if (!userId) {
|
||||
return (
|
||||
<div className="bg-zinc-100 dark:bg-zinc-800 rounded-lg p-6 text-center text-zinc-500">
|
||||
请先登录以查看便签
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h2 className="text-2xl font-bold">便签</h2>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h2 className="text-2xl font-bold">便签</h2>
|
||||
{authenticated && (
|
||||
<button
|
||||
onClick={() => setShowAddForm(!showAddForm)}
|
||||
className="px-4 py-2 bg-violet-500 hover:bg-violet-600 text-white rounded-lg transition-colors"
|
||||
>
|
||||
{showAddForm ? "取消" : "+ 添加便签"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{showAddForm && (
|
||||
<div className="bg-zinc-100 dark:bg-zinc-800 rounded-lg p-6 mb-6 space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm text-zinc-400 mb-2">标题</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.title}
|
||||
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
|
||||
className="w-full px-4 py-2 bg-white dark:bg-zinc-900 border border-zinc-300 dark:border-zinc-700 rounded-lg focus:outline-none focus:border-violet-500"
|
||||
placeholder="便签标题"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-zinc-400 mb-2">内容</label>
|
||||
<textarea
|
||||
value={formData.content}
|
||||
onChange={(e) => setFormData({ ...formData, content: e.target.value })}
|
||||
className="w-full px-4 py-2 bg-white dark:bg-zinc-900 border border-zinc-300 dark:border-zinc-700 rounded-lg focus:outline-none focus:border-violet-500"
|
||||
placeholder="便签内容"
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm text-zinc-400 mb-2">颜色</label>
|
||||
<div className="flex gap-2">
|
||||
{colors.map((color) => (
|
||||
<button
|
||||
key={color}
|
||||
onClick={() => setFormData({ ...formData, color })}
|
||||
className={`w-8 h-8 rounded-lg ${color === formData.color ? "ring-2 ring-violet-500 ring-offset-2" : ""}`}
|
||||
style={{ backgroundColor: color }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="isPinned"
|
||||
checked={formData.isPinned}
|
||||
onChange={(e) => setFormData({ ...formData, isPinned: e.target.checked })}
|
||||
className="rounded"
|
||||
/>
|
||||
<label htmlFor="isPinned" className="text-sm">
|
||||
置顶
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleAddNote}
|
||||
disabled={!formData.title}
|
||||
className="w-full px-4 py-2 bg-violet-500 hover:bg-violet-600 disabled:bg-zinc-300 dark:disabled:bg-zinc-700 text-white rounded-lg transition-colors"
|
||||
>
|
||||
添加便签
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{authenticated && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{notes.map((note) => (
|
||||
<div
|
||||
key={note.id}
|
||||
className="rounded-lg p-4 shadow-md hover:shadow-lg transition-shadow relative group"
|
||||
style={{ backgroundColor: note.color }}
|
||||
>
|
||||
<div className="flex items-start justify-between mb-2">
|
||||
<h3 className="font-semibold text-zinc-900 line-clamp-2">{note.title}</h3>
|
||||
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<button
|
||||
onClick={() => handleTogglePin(note.id)}
|
||||
className="p-1 hover:bg-black/20 rounded"
|
||||
title={note.is_pinned ? "取消置顶" : "置顶"}
|
||||
>
|
||||
<svg className="w-4 h-4 text-zinc-800" fill={note.is_pinned ? "currentColor" : "none"} stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 5l2 2 3-3 5 5 5-5 2 2-7 7-5-5-3 3-2-2z" />
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDeleteNote(note.id)}
|
||||
className="p-1 hover:bg-red-500 hover:text-white rounded"
|
||||
title="删除"
|
||||
>
|
||||
<svg className="w-4 h-4 text-zinc-800" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-zinc-800 text-sm line-clamp-4 mb-3">{note.content}</p>
|
||||
<p className="text-xs text-zinc-600">
|
||||
{new Date(note.created_at).toLocaleDateString("zh-CN", {
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{notes.length === 0 && (
|
||||
<div className="col-span-full text-center py-12 text-zinc-500">
|
||||
暂无便签,点击"添加便签"开始创作
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!authenticated && (
|
||||
<div className="bg-zinc-100 dark:bg-zinc-800 rounded-lg p-6 text-center text-zinc-500">
|
||||
请先登录以查看便签
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
356
src/lib/db.ts
Normal file
356
src/lib/db.ts
Normal file
@@ -0,0 +1,356 @@
|
||||
import { Pool, PoolClient } from "pg";
|
||||
|
||||
const dbConfig = {
|
||||
host: "118.89.161.243",
|
||||
port: 54201,
|
||||
user: "hjdave",
|
||||
password: "HJD13567840170",
|
||||
database: "hjdave-doc",
|
||||
max: 20,
|
||||
idleTimeoutMillis: 30000,
|
||||
connectionTimeoutMillis: 2000,
|
||||
};
|
||||
|
||||
// 全局连接池单例
|
||||
let pool: Pool | null = null;
|
||||
|
||||
export function getPool(): Pool {
|
||||
if (!pool) {
|
||||
pool = new Pool(dbConfig);
|
||||
pool.on("error", (err) => {
|
||||
console.error("Unexpected error on idle client", err);
|
||||
});
|
||||
}
|
||||
return pool;
|
||||
}
|
||||
|
||||
export async function query(sql: string, params?: any[]): Promise<any> {
|
||||
const pool = getPool();
|
||||
const start = Date.now();
|
||||
try {
|
||||
const res = await pool.query(sql, params);
|
||||
const duration = Date.now() - start;
|
||||
console.log("Executed query", { sql, duration, rows: res.rowCount });
|
||||
return res;
|
||||
} catch (error) {
|
||||
console.error("Database query error", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getClient(): Promise<PoolClient> {
|
||||
const client = await getPool().connect();
|
||||
const release = () => client.release();
|
||||
|
||||
return {
|
||||
...client,
|
||||
release,
|
||||
};
|
||||
}
|
||||
|
||||
// 初始化数据库表
|
||||
export async function initializeDatabase(): Promise<void> {
|
||||
// 创建用户表
|
||||
await query(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
username VARCHAR(255) UNIQUE NOT NULL,
|
||||
email VARCHAR(255) UNIQUE,
|
||||
password_hash VARCHAR(255) NOT NULL,
|
||||
role VARCHAR(50) DEFAULT 'admin',
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
`);
|
||||
|
||||
// 创建文档表
|
||||
await query(`
|
||||
CREATE TABLE IF NOT EXISTS docs (
|
||||
id SERIAL PRIMARY KEY,
|
||||
slug VARCHAR(255) UNIQUE NOT NULL,
|
||||
title VARCHAR(255) NOT NULL,
|
||||
description TEXT,
|
||||
created_by INTEGER REFERENCES users(id),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
`);
|
||||
|
||||
// 创建章节表
|
||||
await query(`
|
||||
CREATE TABLE IF NOT EXISTS sections (
|
||||
id SERIAL PRIMARY KEY,
|
||||
doc_id INTEGER REFERENCES docs(id) ON DELETE CASCADE,
|
||||
title VARCHAR(255) NOT NULL,
|
||||
content TEXT,
|
||||
code TEXT,
|
||||
display_order INTEGER DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
`);
|
||||
|
||||
// 创建索引
|
||||
await query("CREATE INDEX IF NOT EXISTS idx_docs_slug ON docs(slug)");
|
||||
await query("CREATE INDEX IF NOT EXISTS idx_docs_created_by ON docs(created_by)");
|
||||
await query("CREATE INDEX IF NOT EXISTS idx_sections_doc_id ON sections(doc_id)");
|
||||
|
||||
// 便签表
|
||||
await query(`
|
||||
CREATE TABLE IF NOT EXISTS notes (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
|
||||
title VARCHAR(255) NOT NULL,
|
||||
content TEXT,
|
||||
color VARCHAR(20) DEFAULT '#fef08a',
|
||||
is_pinned BOOLEAN DEFAULT FALSE,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
`);
|
||||
|
||||
// 留言表
|
||||
await query(`
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
|
||||
content TEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
`);
|
||||
|
||||
// 便签索引
|
||||
await query("CREATE INDEX IF NOT EXISTS idx_notes_user_id ON notes(user_id)");
|
||||
await query("CREATE INDEX IF NOT EXISTS idx_notes_pinned ON notes(is_pinned)");
|
||||
await query("CREATE INDEX IF NOT EXISTS idx_messages_user_id ON messages(user_id)");
|
||||
|
||||
// 初始化默认管理员账户
|
||||
const existing = await query("SELECT id FROM users WHERE username = $1", ["admin"]);
|
||||
if (existing.rows.length === 0) {
|
||||
await query(
|
||||
"INSERT INTO users (username, email, password_hash, role) VALUES ($1, $2, $3, $4)",
|
||||
["admin", "admin@docsite.com", "$2b$10$d1BPt0phBsRORuWnAacgZO.Y0LBZ3hLc8uKyZBN1BkPMR8j4GESHS", "admin"]
|
||||
);
|
||||
console.log("Created default admin user");
|
||||
} else {
|
||||
// 更新密码(如果之前存在但密码不正确)
|
||||
await query(
|
||||
"UPDATE users SET password_hash = $1 WHERE username = $2",
|
||||
["$2b$10$d1BPt0phBsRORuWnAacgZO.Y0LBZ3hLc8uKyZBN1BkPMR8j4GESHS", "admin"]
|
||||
);
|
||||
console.log("Updated admin password");
|
||||
}
|
||||
|
||||
console.log("Database initialized successfully");
|
||||
}
|
||||
|
||||
// 获取密码哈希
|
||||
export async function getPasswordHash(username: string): Promise<string | null> {
|
||||
const result = await query(
|
||||
"SELECT password_hash FROM users WHERE username = $1",
|
||||
[username]
|
||||
);
|
||||
return result.rows[0]?.password_hash ?? null;
|
||||
}
|
||||
|
||||
// 检查是否是管理员
|
||||
export async function isAdmin(username: string): Promise<boolean> {
|
||||
const result = await query(
|
||||
"SELECT role FROM users WHERE username = $1",
|
||||
[username]
|
||||
);
|
||||
return result.rows[0]?.role === "admin";
|
||||
}
|
||||
|
||||
// 验证用户登录
|
||||
export async function verifyUser(username: string, password: string): Promise<boolean> {
|
||||
const hash = await getPasswordHash(username);
|
||||
if (!hash) return false;
|
||||
|
||||
const bcrypt = await import("bcryptjs");
|
||||
return bcrypt.compare(password, hash);
|
||||
}
|
||||
|
||||
// 创建新用户
|
||||
export async function createUser(
|
||||
username: string,
|
||||
password: string,
|
||||
email?: string,
|
||||
role: "admin" | "user" = "user"
|
||||
): Promise<boolean> {
|
||||
const bcrypt = await import("bcryptjs");
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
|
||||
try {
|
||||
await query(
|
||||
"INSERT INTO users (username, email, password_hash, role) VALUES ($1, $2, $3, $4)",
|
||||
[username, email, passwordHash, role]
|
||||
);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Failed to create user:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 获取所有文档
|
||||
export async function getDocs(): Promise<any[]> {
|
||||
const result = await query(
|
||||
`
|
||||
SELECT d.*,
|
||||
json_agg(
|
||||
json_build_object(
|
||||
'id', s.id,
|
||||
'title', s.title,
|
||||
'content', s.content,
|
||||
'code', s.code,
|
||||
'display_order', s.display_order
|
||||
) ORDER BY s.display_order
|
||||
) as sections
|
||||
FROM docs d
|
||||
LEFT JOIN sections s ON s.doc_id = d.id
|
||||
GROUP BY d.id
|
||||
ORDER BY d.created_at DESC
|
||||
`
|
||||
);
|
||||
return result.rows.map((row) => ({
|
||||
title: row.title,
|
||||
slug: row.slug,
|
||||
description: row.description,
|
||||
sections: JSON.parse(row.sections || "[]"),
|
||||
}));
|
||||
}
|
||||
|
||||
// 添加文档
|
||||
export async function addDoc(
|
||||
slug: string,
|
||||
title: string,
|
||||
description?: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
await query(
|
||||
"INSERT INTO docs (slug, title, description) VALUES ($1, $2, $3)",
|
||||
[slug, title, description]
|
||||
);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Failed to add doc:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 添加章节
|
||||
export async function addSection(docSlug: string, title: string, content: string, code?: string): Promise<boolean> {
|
||||
const docResult = await query("SELECT id FROM docs WHERE slug = $1", [docSlug]);
|
||||
if (docResult.rows.length === 0) return false;
|
||||
|
||||
const docId = docResult.rows[0].id;
|
||||
|
||||
try {
|
||||
await query(
|
||||
"INSERT INTO sections (doc_id, title, content, code) VALUES ($1, $2, $3, $4)",
|
||||
[docId, title, content, code || null]
|
||||
);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Failed to add section:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 获取所有文档(简化版,直接返回 JSON)
|
||||
export async function getDocsSimple(): Promise<any[]> {
|
||||
return [
|
||||
{
|
||||
title: "快速开始",
|
||||
slug: "quick-start",
|
||||
description: "了解如何开始使用我们的平台",
|
||||
sections: [
|
||||
{ title: "简介", content: "欢迎使用我们的在线文档系统!", code: null },
|
||||
{ title: "安装", content: "开始之前,请确保你已经安装了 Node.js 和 npm。", code: "npm install\nnpm run dev" },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "API 参考",
|
||||
slug: "api-reference",
|
||||
description: "API 接口文档",
|
||||
sections: [{ title: "获取文档列表", content: "获取所有可用文档的列表。", code: "GET /api/docs" }],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// 便签相关
|
||||
export async function getNotes(userId: number): Promise<any[]> {
|
||||
const result = await query(
|
||||
`SELECT * FROM notes WHERE user_id = $1 ORDER BY is_pinned DESC, created_at DESC`,
|
||||
[userId]
|
||||
);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
export async function addNote(userId: number, title: string, content: string, color: string, isPinned: boolean): Promise<boolean> {
|
||||
try {
|
||||
await query(
|
||||
"INSERT INTO notes (user_id, title, content, color, is_pinned) VALUES ($1, $2, $3, $4, $5)",
|
||||
[userId, title, content, color, isPinned]
|
||||
);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Failed to add note:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteNote(userId: number, noteId: number): Promise<boolean> {
|
||||
try {
|
||||
await query("DELETE FROM notes WHERE id = $1 AND user_id = $2", [noteId, userId]);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Failed to delete note:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function togglePinNote(userId: number, noteId: number): Promise<boolean> {
|
||||
try {
|
||||
await query("UPDATE notes SET is_pinned = NOT is_pinned WHERE id = $1 AND user_id = $2", [noteId, userId]);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Failed to toggle pin:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 留言相关
|
||||
export async function getMessages(): Promise<any[]> {
|
||||
const result = await query(`
|
||||
SELECT m.*, u.username FROM messages m
|
||||
JOIN users u ON m.user_id = u.id
|
||||
ORDER BY m.created_at DESC
|
||||
LIMIT 100
|
||||
`);
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
export async function addMessage(userId: number, content: string): Promise<boolean> {
|
||||
try {
|
||||
await query(
|
||||
"INSERT INTO messages (user_id, content) VALUES ($1, $2)",
|
||||
[userId, content]
|
||||
);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Failed to add message:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteMessage(userId: number, messageId: number): Promise<boolean> {
|
||||
try {
|
||||
await query("DELETE FROM messages WHERE id = $1 AND user_id = $2", [messageId, userId]);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Failed to delete message:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
34
tsconfig.json
Normal file
34
tsconfig.json
Normal file
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts",
|
||||
"**/*.mts"
|
||||
],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
Reference in New Issue
Block a user