Compare commits
228
Commits
| Author | SHA1 | Date | ||
|---|---|---|---|---|
| ||||
|
|
1ff6eb13e6 | |||
|
|
0d77dc3572 | |||
| ||||
|
|
7c66cb931a | |||
|
|
5995efc7a0 | |||
|
|
c26e834982 | |||
|
|
fdf90f4b1d | |||
|
|
9844988cf2 | |||
|
|
d16ed6c1e8 | |||
|
|
edc68744d5 | |||
|
|
7176bea12c | |||
|
|
0ea921186a | |||
|
|
3558247aac | |||
|
|
82c878ce33 | |||
|
|
381b98bf1f | |||
|
|
7361ad157d | |||
|
|
17b6ee35ef | |||
|
|
74204f7bb2 | |||
|
|
645c990778 | |||
| ||||
|
|
1e05b18f0c | |||
|
|
68ef257759 | |||
|
|
c4acf06253 | |||
|
|
38ccc16d7a | |||
|
|
ab49b93c4d | |||
|
|
627d284b02 | |||
|
|
f147f4b248 | |||
|
|
75cc78d5f8 | |||
|
|
51032c44d0 | |||
|
|
2f9528939a | |||
|
|
f982b2e0a6 | |||
|
|
b0bf66e1aa | |||
|
|
b1f4363433 | |||
|
|
57a99ccd23 | |||
|
|
c6bf968178 | |||
|
|
f1c9aca4c7 | |||
|
|
86a934ac87 | |||
|
|
a085b385b1 | |||
|
|
ec235d37bd | |||
| ||||
|
|
3808fd2e94 | |||
| ||||
|
|
5b1b16c222 | |||
|
|
593e766596 | |||
|
|
5314d60f53 | |||
|
|
8a2036035a | |||
|
|
1fce581c52 | |||
|
|
547742cb6d | |||
|
|
01250c0e3f | |||
|
|
b7db82ec0b | |||
|
|
17dc1c4f41 | |||
|
|
28bdea9572 | |||
|
|
c3e87d5a92 | |||
|
|
d2f87b13ae | |||
|
|
50d916bb28 | |||
|
|
1104b6e2e4 | |||
|
|
bce8d1fdc7 | |||
|
|
6e6e8ca8f4 | |||
|
|
3f7b9dbb9c | |||
|
|
b036a51eef | |||
|
|
52fed4212b | |||
| ||||
|
|
07596ea83c | |||
|
|
8ad3ca578f | |||
|
|
3adbe4fab4 | |||
|
|
f074ab890c | |||
|
|
cb0377220c | |||
|
|
0864aa2b92 | |||
|
|
14b63f4e1c | |||
|
|
c3b197d488 | |||
|
|
29f7795f00 | |||
| ||||
|
|
ab66d9a6fc | |||
|
|
16f39fc7c6 | |||
|
|
5721a84c54 | |||
|
|
1cd6b5c4dd | |||
|
|
39f219d2ac | |||
|
|
aa9bcd8d12 | |||
|
|
9f5944020b | |||
|
|
9e407d0a2d | |||
|
|
8f88f803f5 | |||
|
|
5d71e66354 | |||
|
|
320000c8b9 | |||
|
|
46dd281c7b | |||
|
|
503a34f5fb | |||
| ||||
|
|
a5a880dfb2 | |||
|
|
3fc74ae189 | |||
|
|
feefadae11 | |||
|
|
924f9ffcc6 | |||
|
|
2e12468293 | |||
|
|
5605ded575 | |||
|
|
145f13fee5 | |||
|
|
3ed09fbcdf | |||
|
|
5aa16b0f05 | |||
|
|
3ffb92dc23 | |||
|
|
3fbf2743d0 | |||
|
|
b4330666a4 | |||
|
|
51a6b49459 | |||
|
|
8d1b59479e | |||
|
|
3cee3ae530 | |||
|
|
2e745b547d | |||
|
|
7cf69ad476 | |||
|
|
c57863fc47 | |||
|
|
b449e05f3f | |||
|
|
5d0a148804 | |||
|
|
f30a3dcacb | |||
|
|
9e99d6909a | |||
|
|
2e74b1505b | |||
|
|
db34b09b2e | |||
|
|
63b804d2a0 | |||
|
|
1f51e66d8c | |||
|
|
383ad94d41 | |||
|
|
b72732a774 | |||
|
|
b2539ea911 | |||
|
|
dbb72b8afe | |||
|
|
2746f50685 | |||
|
|
0169db134c | |||
|
|
a6dcf461ec | |||
|
|
a660d605c9 | |||
|
|
4e1e24699d | |||
|
|
955c9d38d1 | |||
|
|
bc4d0d9471 | |||
|
|
756ccf34a1 | |||
|
|
e8bc9ab302 | |||
|
|
10e8db0b2d | |||
|
|
d40c8bd866 | |||
|
|
496234b519 | |||
|
|
bb849fc67a | |||
|
|
c563e2ed55 | |||
|
|
cbb15df923 | |||
|
|
287c8c2a12 | |||
|
|
8c09df2978 | |||
|
|
f4998524c6 | |||
|
|
27638e6d34 | |||
|
|
8d651cba38 | |||
|
|
3eaa276a1f | |||
|
|
27364074ea | |||
|
|
2010652895 | |||
|
|
2a01e8ca3d | |||
|
|
222c9b8f3c | |||
|
|
1526fce759 | |||
|
|
12b3513f29 | |||
|
|
6eb60df5ee | |||
|
|
7c2b303b02 | |||
|
|
f0e83d2484 | |||
|
|
d4f25bf098 | |||
|
|
205c97ed6b | |||
|
|
851a445beb | |||
|
|
1503864f37 | |||
|
|
c0ad458b3e | |||
|
|
429f8fff64 | |||
|
|
4252f54a7e | |||
|
|
291ad9c06c | |||
|
|
c7f6496161 | |||
|
|
5b89506040 | |||
| ||||
|
|
b421cb297a | |||
|
|
4ced755deb | |||
|
|
ce932784bc | |||
|
|
942c71cacb | |||
|
|
f8916b580d | |||
|
|
cd770a082e | |||
|
|
6f58aa4fdc | |||
|
|
706286eb1c | |||
|
|
6ab52bd7ac | |||
|
|
4e172f193a | |||
|
|
d167ab3132 | |||
|
|
03d46f95d7 | |||
|
|
197350d7a9 | |||
|
|
155e3a465e | |||
|
|
7498f07b98 | |||
|
|
8e417048ee | |||
|
|
427d1cb624 | |||
|
|
3108dfc4cd | |||
|
|
5a03c56ff4 | |||
|
|
3f3e44a737 | |||
|
|
963791b0bb | |||
|
|
c25564588d | |||
|
|
737ba6c587 | |||
|
|
223a003f5f | |||
|
|
34a24920a8 | |||
|
|
17b195c10e | |||
|
|
115dd7131d | |||
|
|
fd15e7b427 | |||
|
|
04759a0716 | |||
|
|
da88709d6f | |||
|
|
44ba238ef6 | |||
|
|
e40be0ceb4 | |||
|
|
23b236c9d7 | |||
|
|
d9b3417469 | |||
|
|
4abe6d75d7 | |||
|
|
a6b3a587eb | |||
|
|
1d960fca3e | |||
|
|
aa38a31aa3 | |||
|
|
d188c3eded | |||
|
|
b109e59fc4 | |||
|
|
77e5c8c3ba | |||
|
|
5f274c2d86 | |||
|
|
7a32d23976 | |||
|
|
454578e8d6 | |||
|
|
b0d2f94207 | |||
|
|
59ef72fbc3 | |||
|
|
6dccedc781 | |||
|
|
84a11df8b2 | |||
|
|
8e86473429 | |||
|
|
71afe65f63 | |||
|
|
e2fd713539 | |||
|
|
b2d85e9e1d | |||
|
|
0953234bc9 | |||
|
|
d87f1b2ab9 | |||
|
|
58d6ee7018 | |||
|
|
f677eae6f5 | |||
|
|
2bec523999 | |||
|
|
68d0d158c9 | |||
|
|
b6a7450ef8 | |||
|
|
19ec83d3a6 | |||
|
|
12006d39e3 | |||
|
|
5c7f02d586 | |||
|
|
d31cb1523f | |||
|
|
31ef7e6fd0 | |||
|
|
7664d172ae | |||
|
|
e693627e5b | |||
|
|
146b7dd1f3 | |||
|
|
5cf8fed892 | |||
|
|
39af657905 | |||
|
|
00a36b570f | |||
|
|
90678440eb | |||
|
|
a74181a97d | |||
|
|
d97645fdc8 | |||
|
|
0581aa0027 | |||
|
|
3aa6f0130d | |||
|
|
233c919738 | |||
|
|
73f8ed581f | |||
|
|
bdfbdb7375 | |||
|
|
283724fc14 | |||
No files matched your search
@@ -1,13 +0,0 @@
|
||||
# Cloudflare Workers 环境变量示例
|
||||
# 复制为 .dev.vars 用于本地 preview;远程部署请在 CF 面板配置为 Secrets
|
||||
|
||||
DATABASE_URL=postgresql://user:pass@host:5432/forumlify
|
||||
JWT_SECRET=change-me-in-production
|
||||
|
||||
# 图片上传(S3 兼容,R2)
|
||||
S3_ENDPOINT=https://<account_id>.r2.cloudflarestorage.com
|
||||
S3_BUCKET=forum
|
||||
S3_REGION=auto
|
||||
S3_ACCESS_KEY_ID=your-r2-access-key
|
||||
S3_SECRET_ACCESS_KEY=your-r2-secret-key
|
||||
S3_PUBLIC_URL=https://your-public-domain.example
|
||||
+9
-8
@@ -1,9 +1,10 @@
|
||||
node_modules
|
||||
.next
|
||||
uploads
|
||||
.git
|
||||
*.log
|
||||
.DS_Store
|
||||
.vercel
|
||||
.wrangler
|
||||
.open-next
|
||||
.github
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
node_modules
|
||||
npm-debug.log*
|
||||
uploads
|
||||
coverage
|
||||
*.md
|
||||
+4
-20
@@ -1,20 +1,4 @@
|
||||
# Forumlify 环境变量示例
|
||||
# 复制为 .env 并按需修改
|
||||
|
||||
# PostgreSQL 连接串(默认与 docker-compose.yml 一致)
|
||||
DATABASE_URL=postgresql://forumlify:123456@localhost:5432/forumlify
|
||||
|
||||
# JWT 签名密钥(生产环境务必修改为随机长字符串)
|
||||
JWT_SECRET=forumlify-secret-key-change-me-in-production
|
||||
|
||||
# 可选:监听端口/地址(也可在 config.js 中设置 SERVER_PORT / SERVER_HOST)
|
||||
# PORT=3000
|
||||
# HOST=0.0.0.0
|
||||
|
||||
# ===== Serverless / 对象存储(可选,仅 serverless 部署需要)=====
|
||||
# S3_ENDPOINT=https://xxx.r2.cloudflarestorage.com
|
||||
# S3_BUCKET=forumlify
|
||||
# S3_REGION=auto
|
||||
# S3_ACCESS_KEY_ID=
|
||||
# S3_SECRET_ACCESS_KEY=
|
||||
# S3_PUBLIC_URL=https://cdn.example.com
|
||||
# Copy to .env, then set both required secrets before running Docker Compose.
|
||||
POSTGRES_PASSWORD=
|
||||
JWT_SECRET=
|
||||
PORT=3000
|
||||
@@ -0,0 +1,90 @@
|
||||
name: 🐛 Bug 报告 / Bug Report
|
||||
description: 报告一个 Bug / Report a bug
|
||||
title: "[Bug] "
|
||||
labels: [bug]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## 感谢你报告问题!/ Thanks for reporting an issue!
|
||||
请填写以下信息,帮助我们快速定位问题。/ Please fill in the following information to help us locate the issue quickly.
|
||||
|
||||
- type: dropdown
|
||||
id: branch
|
||||
attributes:
|
||||
label: 你使用的是哪个分支?/ Which branch are you using?
|
||||
description: 请选择你所使用的分支。/ Please select the branch you are using.
|
||||
options:
|
||||
- Lite(原生单文件版 / Original single-file version)
|
||||
- next(Next.js 16 版 / Next.js 16 version)
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: 后台版本号 / Backend version (管理员填写 / admins only)
|
||||
description: |
|
||||
如果你使用的是 next 分支且是管理员,请粘贴后台显示的版本号。其他情况请留空。
|
||||
/ If you are using the next branch and are an administrator, please paste the version shown in the admin panel. Leave blank otherwise.
|
||||
placeholder: "例如 / e.g. 2.0.0"
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: 问题描述 / Description
|
||||
description: 请清晰描述你遇到的问题。/ Please clearly describe the issue you encountered.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: 复现步骤 / Steps to reproduce
|
||||
description: 如何复现这个问题?/ How can this issue be reproduced?
|
||||
placeholder: |
|
||||
1. 打开... / Open ...
|
||||
2. 点击... / Click ...
|
||||
3. 看到错误... / See the error...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: 期望行为 / Expected behavior
|
||||
description: 你期望发生什么?/ What did you expect to happen?
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: actual
|
||||
attributes:
|
||||
label: 实际行为 / Actual behavior
|
||||
description: 实际发生了什么?/ What actually happened?
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: environment
|
||||
attributes:
|
||||
label: 环境信息 / Environment
|
||||
description: 你的运行环境。/ Your running environment.
|
||||
placeholder: |
|
||||
- 操作系统 / OS:
|
||||
- 浏览器 / Browser:
|
||||
- Node.js 版本 / Node.js version:
|
||||
- 部署方式 / Deployment method (Docker / 源码 / Source):
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: 日志 / Logs
|
||||
description: 如有报错日志,请粘贴于此。/ Paste any error logs here if available.
|
||||
render: shell
|
||||
validations:
|
||||
required: false
|
||||
@@ -0,0 +1 @@
|
||||
blank_issues_enabled: false
|
||||
@@ -0,0 +1,65 @@
|
||||
name: ✨ 功能建议 / Feature Request
|
||||
description: 提出一个新功能或改进建议 / Suggest an idea for this project
|
||||
title: "[Feature] "
|
||||
labels: [enhancement]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## 感谢你的建议!/ Thanks for your suggestion!
|
||||
请填写以下信息,让我们了解你的想法。/ Please fill in the information below to help us understand your idea.
|
||||
|
||||
- type: dropdown
|
||||
id: branch
|
||||
attributes:
|
||||
label: 这个功能针对哪个分支?/ Which branch is this feature for?
|
||||
description: 请选择你所使用的分支。/ Please select the branch you are using.
|
||||
options:
|
||||
- Lite(原生单文件版 / Original single-file version)
|
||||
- next(Next.js 16 版 / Next.js 16 version)
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: 后台版本号 / Backend version (管理员填写 / admins only)
|
||||
description: |
|
||||
如果你使用的是 next 分支且是管理员,请粘贴后台显示的版本号。其他情况请留空。
|
||||
/ If you are using the next branch and are an administrator, please paste the version shown in the admin panel. Leave blank otherwise.
|
||||
placeholder: "例如 / e.g. 2.0.0"
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: 要解决的问题 / Problem to solve
|
||||
description: 这个功能解决什么问题?/ What problem does this feature solve?
|
||||
placeholder: "当我...时,我希望... / When I ..., I wish ..."
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: solution
|
||||
attributes:
|
||||
label: 期望的解决方案 / Proposed solution
|
||||
description: 你希望如何实现?/ How would you like it to work?
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: 替代方案 / Alternatives considered
|
||||
description: 你考虑过其他方案吗?/ Have you considered any alternative approaches?
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
id: additional
|
||||
attributes:
|
||||
label: 补充说明 / Additional context
|
||||
description: 其他任何信息、截图或示例。/ Any other information, screenshots, or examples.
|
||||
validations:
|
||||
required: false
|
||||
@@ -0,0 +1,52 @@
|
||||
# 感谢你为 Forumlify 提交贡献!/ Thank you for contributing to Forumlify!
|
||||
|
||||
<!-- 请填写以下信息,帮助我们快速处理你的 PR。/ Please fill in the information below to help us process your PR quickly. -->
|
||||
|
||||
## 目标分支 / Target branch
|
||||
|
||||
**你提交的代码是基于哪个分支?/ Which branch is your code based on?**
|
||||
|
||||
- [ ] **Lite**(原生单文件版 / Original single-file version)
|
||||
- [ ] **next**(Next.js 16 版 / Next.js 16 version)
|
||||
|
||||
> ⚠️ 请确保 PR 的 base 分支与你的代码来源分支一致。/ Please make sure the PR's base branch matches the branch your code comes from.
|
||||
|
||||
## 版本信息 / Version info
|
||||
|
||||
<!-- 仅当你选择 next 分支且为管理员时填写。/ Only fill in if you chose the next branch AND you are an administrator. -->
|
||||
**后台版本号 / Backend version (admin only):**
|
||||
|
||||
```
|
||||
(在此粘贴后台显示的版本号 / Paste the version shown in the admin panel here)
|
||||
```
|
||||
|
||||
## 变更内容 / What does this PR do?
|
||||
|
||||
<!-- 简要描述你的改动。/ Briefly describe your changes. -->
|
||||
|
||||
-
|
||||
|
||||
## 动机 / Motivation
|
||||
|
||||
<!-- 为什么需要这个改动?/ Why is this change needed? -->
|
||||
|
||||
-
|
||||
|
||||
## 测试 / Testing
|
||||
|
||||
<!-- 你如何验证这些改动?/ How did you verify these changes? -->
|
||||
|
||||
- [ ] 本地构建通过 / Local build passes (`npm run build`,仅 next 分支 / next branch only)
|
||||
- [ ] 相关功能已手动测试 / Related features manually tested
|
||||
- [ ] 测试用例已更新 / Tests updated
|
||||
|
||||
## 截图 / Screenshots
|
||||
|
||||
<!-- 如有 UI 改动,请附截图。/ Attach screenshots if this changes the UI. -->
|
||||
|
||||
## 检查清单 / Checklist
|
||||
|
||||
- [ ] 我已阅读并遵循了贡献指南 / I have read and followed the contributing guidelines
|
||||
- [ ] 我的代码遵循现有代码风格 / My code follows the existing code style
|
||||
- [ ] 我已同步最新的上游分支 / I have synced with the latest upstream branch
|
||||
- [ ] 本 PR 只包含必要的改动 / This PR contains only the necessary changes
|
||||
@@ -1,131 +0,0 @@
|
||||
name: Coverage
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [next]
|
||||
pull_request:
|
||||
branches: [next]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
test-and-upload:
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:15
|
||||
env:
|
||||
POSTGRES_USER: forumlify
|
||||
POSTGRES_PASSWORD: 123456
|
||||
POSTGRES_DB: forumlify
|
||||
ports:
|
||||
- 5433:5432
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U forumlify -d forumlify"
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 5
|
||||
|
||||
env:
|
||||
DATABASE_URL: postgresql://forumlify:123456@localhost:5433/forumlify
|
||||
JWT_SECRET: ci-test-secret
|
||||
ENABLE_CAPTCHA: 'false'
|
||||
PORT: 3100
|
||||
BASE_URL: http://127.0.0.1:3100
|
||||
NEXT_TELEMETRY_DISABLED: '1'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Initialize test database
|
||||
env:
|
||||
PGPASSWORD: '123456'
|
||||
run: psql -h localhost -p 5433 -U forumlify -d forumlify -f schema.sql
|
||||
|
||||
- name: Build application
|
||||
run: npm run build
|
||||
|
||||
- name: Upload bundle analysis to Codecov
|
||||
env:
|
||||
CODECOV_BUNDLE_ANALYSIS: 'true'
|
||||
run: npx next build --webpack
|
||||
|
||||
- name: Run integration tests with coverage
|
||||
run: |
|
||||
node node_modules/next/dist/bin/next start -H 127.0.0.1 -p "$PORT" > server.log 2>&1 &
|
||||
server_pid=$!
|
||||
cleanup() {
|
||||
kill "$server_pid" 2>/dev/null || true
|
||||
wait "$server_pid" 2>/dev/null || true
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
for attempt in {1..30}; do
|
||||
if curl --fail --silent --show-error "$BASE_URL/api/stats" >/dev/null; then
|
||||
break
|
||||
fi
|
||||
if [ "$attempt" -eq 30 ]; then
|
||||
cat server.log
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
node --test \
|
||||
--test-concurrency=1 \
|
||||
--test-reporter=spec \
|
||||
--test-reporter=junit \
|
||||
--test-reporter-destination=stdout \
|
||||
--test-reporter-destination=test-results.xml \
|
||||
test/*.test.js
|
||||
cleanup
|
||||
trap - EXIT
|
||||
|
||||
mkdir -p coverage
|
||||
node --test \
|
||||
--experimental-test-coverage \
|
||||
--test-reporter=lcov \
|
||||
--test-reporter-destination=coverage/lcov.info \
|
||||
test/http-cache.test.js \
|
||||
test/i18n-ui.test.js
|
||||
test -s coverage/lcov.info
|
||||
covered_lines=$(awk -F: '/^DA:/{split($2, data, ","); hits += data[2]} END {print hits + 0}' coverage/lcov.info)
|
||||
test "$covered_lines" -gt 0
|
||||
test -s test-results.xml
|
||||
|
||||
- name: Publish coverage report
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: coverage-report
|
||||
path: coverage/
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Upload coverage to Codecov
|
||||
uses: codecov/codecov-action@v5
|
||||
with:
|
||||
use_oidc: true
|
||||
files: coverage/lcov.info
|
||||
disable_search: true
|
||||
fail_ci_if_error: true
|
||||
verbose: true
|
||||
|
||||
- name: Upload test results to Codecov
|
||||
uses: codecov/codecov-action@v5
|
||||
with:
|
||||
use_oidc: true
|
||||
files: test-results.xml
|
||||
report_type: test_results
|
||||
disable_search: true
|
||||
fail_ci_if_error: true
|
||||
@@ -1,13 +1,15 @@
|
||||
name: Build & Push Docker to GHCR
|
||||
name: Build & Push Docker to GHCR (Lite)
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [next, main]
|
||||
branches: [Lite]
|
||||
tags: ['v*']
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
# 推仓库自己的 GHCR 包(github.repository = Furrium/forumlify)——
|
||||
# 仓库 GITHUB_TOKEN 无权推跨仓库包(如 lezi-fun/forumlify-deploy)
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
|
||||
jobs:
|
||||
@@ -36,9 +38,9 @@ jobs:
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
# Lite 分支 → lite 标签(与 next 镜像隔离,避免覆盖)
|
||||
type=raw,value=lite,enable=${{ github.ref == 'refs/heads/Lite' }}
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=sha,prefix=git-
|
||||
|
||||
- name: Build and push (linux/amd64 + linux/arm64)
|
||||
@@ -47,8 +49,6 @@ jobs:
|
||||
context: .
|
||||
push: true
|
||||
platforms: linux/amd64, linux/arm64
|
||||
build-args: |
|
||||
FORUMLIFY_COMMIT=${{ github.sha }}
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
@@ -0,0 +1,83 @@
|
||||
name: ghbot
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types:
|
||||
- opened
|
||||
- synchronize
|
||||
- reopened
|
||||
- ready_for_review
|
||||
- edited
|
||||
issues:
|
||||
types:
|
||||
- opened
|
||||
- edited
|
||||
- reopened
|
||||
issue_comment:
|
||||
types:
|
||||
- created
|
||||
pull_request_review:
|
||||
types:
|
||||
- submitted
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
checks: write
|
||||
statuses: read
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
review:
|
||||
if: |
|
||||
github.event_name == 'pull_request_target' ||
|
||||
github.event_name == 'issues' ||
|
||||
(github.event_name == 'issue_comment' && github.event.issue.pull_request != null) ||
|
||||
github.event_name == 'pull_request_review'
|
||||
uses: lezi-fun/ghbot/.github/workflows/review-reusable.yml@main
|
||||
secrets:
|
||||
GOOSE_API_KEY: ${{ secrets.GOOSE_API_KEY || secrets.OPENCODE_API_KEY }}
|
||||
GH_APP_ID: ${{ secrets.GH_APP_ID }}
|
||||
GH_APP_PRIVATE_KEY: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||
GH_APP_INSTALLATION_ID: ${{ secrets.GH_APP_INSTALLATION_ID }}
|
||||
R2_ACCESS_KEY_ID: ${{ secrets.R2_ACCESS_KEY_ID }}
|
||||
R2_SECRET_ACCESS_KEY: ${{ secrets.R2_SECRET_ACCESS_KEY }}
|
||||
with:
|
||||
event_name: ${{ github.event_name }}
|
||||
event_action: ${{ github.event.action }}
|
||||
repository_owner: ${{ github.repository_owner }}
|
||||
repository_name: ${{ github.event.repository.name }}
|
||||
repository_id: ${{ github.repository_id }}
|
||||
pull_number: ${{ github.event.pull_request.number || github.event.issue.number }}
|
||||
pull_head_repository: ${{ github.event.pull_request.head.repo.full_name || '' }}
|
||||
comment_id: ${{ github.event.comment.id || '' }}
|
||||
commenter_login: ${{ github.event.comment.user.login || '' }}
|
||||
comment_body: ${{ github.event.comment.body || '' }}
|
||||
reviewer_login: ${{ github.event.review.user.login || '' }}
|
||||
review_state: ${{ github.event.review.state || '' }}
|
||||
review_commit_id: ${{ github.event.review.commit_id || '' }}
|
||||
bot_name: ${{ vars.BOT_NAME || 'github-actions[bot]' }}
|
||||
goose_base_url: ${{ vars.GOOSE_BASE_URL || vars.OPENCODE_BASE_URL || 'https://api.openai.com/v1' }}
|
||||
goose_model: ${{ vars.GOOSE_MODEL || vars.OPENCODE_MODEL || 'gpt-5.4' }}
|
||||
goose_thinking_effort: ${{ vars.GOOSE_THINKING_EFFORT || vars.OPENCODE_REASONING_EFFORT || 'high' }}
|
||||
review_policy: ${{ vars.REVIEW_POLICY || 'allow' }}
|
||||
review_strictness: ${{ vars.REVIEW_STRICTNESS || 'normal' }}
|
||||
review_instructions: ${{ vars.REVIEW_INSTRUCTIONS || '' }}
|
||||
review_branches: ${{ vars.REVIEW_BRANCHES || '' }}
|
||||
repository_knowledge_enabled: ${{ vars.REPOSITORY_KNOWLEDGE_ENABLED || 'true' }}
|
||||
repository_knowledge_write: ${{ vars.REPOSITORY_KNOWLEDGE_WRITE || 'false' }}
|
||||
r2_endpoint: ${{ vars.R2_ENDPOINT || '' }}
|
||||
r2_bucket_name: ${{ vars.R2_BUCKET_NAME || '' }}
|
||||
r2_prefix: ${{ vars.R2_PREFIX || '' }}
|
||||
triage_enabled: ${{ vars.TRIAGE_ENABLED || 'true' }}
|
||||
triage_labels: ${{ vars.TRIAGE_LABELS || 'bug,enhancement,documentation,question' }}
|
||||
triage_duplicate_label: ${{ vars.TRIAGE_DUPLICATE_LABEL || 'duplicate' }}
|
||||
triage_candidate_limit: ${{ vars.TRIAGE_CANDIDATE_LIMIT || '50' }}
|
||||
triage_instructions: ${{ vars.TRIAGE_INSTRUCTIONS || '' }}
|
||||
auto_merge: ${{ vars.AUTO_MERGE || 'false' }}
|
||||
auto_resolve_conflicts: ${{ vars.AUTO_RESOLVE_CONFLICTS || 'false' }}
|
||||
conflict_test_command: ${{ vars.CONFLICT_TEST_COMMAND || '' }}
|
||||
merge_method: ${{ vars.MERGE_METHOD || 'squash' }}
|
||||
require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }}
|
||||
max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }}
|
||||
log_level: info
|
||||
+8
-17
@@ -1,24 +1,15 @@
|
||||
node_modules/
|
||||
.next/
|
||||
out/
|
||||
/uploads/
|
||||
uploads/
|
||||
*.log
|
||||
coverage/
|
||||
.coverage-tmp/
|
||||
test-results.xml
|
||||
.DS_Store
|
||||
|
||||
# 环境变量:.env 是用户本地环境变量(不提交),模板 .env.example 进仓库
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
.vercel
|
||||
# Wrangler 本地状态
|
||||
.wrangler/
|
||||
|
||||
# OpenNext
|
||||
.open-next
|
||||
|
||||
# wrangler files
|
||||
.wrangler
|
||||
.dev.vars*
|
||||
!.dev.vars.example
|
||||
# 构建产物
|
||||
.open-next/
|
||||
.vercel/
|
||||
.next/
|
||||
.wrangler/
|
||||
@@ -1,74 +0,0 @@
|
||||
<!-- 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/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
|
||||
|
||||
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
|
||||
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
|
||||
# Forumlify repository guide
|
||||
|
||||
## Project scope
|
||||
|
||||
- This repository is the Forumlify NEXT edition: Next.js 16 App Router, React 19, PostgreSQL, and JavaScript.
|
||||
- Normal development happens on the `next` branch and is pushed to `origin/next`. The `main` branch is the separate Lite/Express implementation; do not copy behavior from it blindly.
|
||||
- Before changing code, run `git status --short --branch`. Preserve unrelated user changes and untracked files.
|
||||
- Do not commit generated or local artifacts such as `.next/`, `.playwright-cli/`, uploaded files, logs, database data, or secrets.
|
||||
|
||||
## Commands and runtime
|
||||
|
||||
- Requires Node.js 20.9 or newer.
|
||||
- Install dependencies with `npm install`.
|
||||
- Start local development with `npm run dev`; it listens on `0.0.0.0` and normally uses port 3000.
|
||||
- Create a production build with `npm run build`.
|
||||
- Start a built server with `npm start`.
|
||||
- Run tests with `npm test`. The test suite expects a running Forumlify instance and PostgreSQL; see `test/README.md`. Override the service URL with `BASE_URL` when needed.
|
||||
- Always provide `DATABASE_URL` explicitly when the active PostgreSQL instance is not the default `localhost:5432/forumlify`. Inspect existing Docker containers before creating another database or changing ports.
|
||||
- Never delete or recreate a database, volume, or upload directory merely to make a test pass.
|
||||
|
||||
## Architecture
|
||||
|
||||
- `app/page.js` and `app/HomeClient.js` render the application shell. Most navigation is SPA-style state managed by `components/AppProvider.js` and synchronized to `/post/:number`, `/user/:username`, built-in page paths, and direct custom-page paths. Legacy `?post=`, `?user=`, and `?page=` links are normalized on load.
|
||||
- `app/api/**/route.js` contains the Next.js Route Handlers. Keep authentication and authorization checks on the server even when the UI already hides an action.
|
||||
- `components/` contains client UI. Reuse `AppProvider`, `Toast`, `Icons`, and existing component patterns instead of introducing parallel state or notification systems.
|
||||
- `app/globals.css` owns the theme, responsive layout, glass/card styling, page transitions, and View Transition pseudo-elements. Check nearby selectors before adding another override.
|
||||
- `locales/zh.json` and `locales/en.json` are the translation sources. User-facing text added or changed in an i18n-enabled area must be updated in both files.
|
||||
- `lib/api.js` is the browser API wrapper, `lib/db.js` owns the PostgreSQL pool, and `lib/http-cache.js` provides ETag/304 helpers for cacheable JSON responses.
|
||||
- `schema.sql` is shared with the Lite branch. Keep schema changes backward-compatible unless a migration and compatibility plan is explicitly requested.
|
||||
|
||||
## UI and interaction conventions
|
||||
|
||||
- Support both light and dark themes. Verify page backgrounds, cards, modals, settings/admin pages, borders, and text contrast in both modes.
|
||||
- Do not use browser `alert`, `confirm`, or `prompt`. Use `useToast()` for timed success/warning/error notices and `confirmAction()` for decisions requiring user input.
|
||||
- Use SVG icons through `components/Icons.js`; do not add emoji as interface icons. The existing empty-message greeting ending in `👋` is an intentional exception and must remain.
|
||||
- Avoid hard-coded Chinese or English in newly touched UI when a translation key is appropriate. Date formatting must follow the selected language.
|
||||
- Keep settings and administration layouts responsive: content should use the available right-side width, wrap long text, and must not become wider solely because English is selected.
|
||||
- Preserve the current navigation bar during page transitions unless a task explicitly requires otherwise.
|
||||
|
||||
## View Transition rules
|
||||
|
||||
- `components/AppProvider.js` is the single coordination point for cross-page View Transitions. Do not start competing transitions from individual page components.
|
||||
- Shared elements must exist in both the old and new DOM snapshots and must have exactly one matching `view-transition-name` per snapshot. Apply names only to the clicked card or target element to avoid duplicates.
|
||||
- When the destination data is asynchronous, pass a preview object so the destination avatar, title, author, content, or other shared element renders in the first transition frame. Replace it with fetched data without remounting the shared element.
|
||||
- Elements that exist only on the destination should reveal after shared geometry settles. Elements that exist only on the source should disappear before the destination content is revealed.
|
||||
- Opening and returning animations should be visible inverses. On return, prefer the original `data-post-id` or stored source identity; if the target is unavailable, fall back to a simple fade instead of animating to the wrong element.
|
||||
- Disable the default `.page-slide` animation on pages using a custom shared transition, otherwise the page will slide a second time after the transition completes.
|
||||
- Respect `prefers-reduced-motion` and provide an immediate navigation fallback when `document.startViewTransition` is unavailable.
|
||||
- For animation bugs, inspect intermediate frames and the trajectories of the outer card, lower edge, text, timestamps, badges, and background separately. Do not judge only the first and final screenshots.
|
||||
|
||||
## API, caching, and security
|
||||
|
||||
- Preserve conditional GET behavior for cacheable endpoints. Use `jsonWithEtag()` from `lib/http-cache.js` where appropriate so matching `If-None-Match` requests return 304 without a response body.
|
||||
- Do not cache personalized, authenticated, rapidly changing, or mutation responses as public data.
|
||||
- Never commit real JWT secrets, database credentials, cloud credentials, tokens, private keys, or local `.env` files. Example values belong only in example configuration.
|
||||
- Validate and sanitize all user-controlled Markdown, uploads, identifiers, and custom content using the existing helpers and route patterns.
|
||||
|
||||
## Validation and Git
|
||||
|
||||
- For ordinary code changes, run `git diff --check` and `npm run build` at minimum.
|
||||
- For API changes, run the focused `node:test` coverage and then `npm test` when the required database/service is available.
|
||||
- For visual or animation changes, use Playwright against the local development server and check both themes and relevant viewport sizes. Keep Playwright artifacts untracked.
|
||||
- Stage only files belonging to the task. Use concise commit messages that describe the outcome.
|
||||
- When asked to push, fetch first if the remote has moved, rebase the scoped commit onto the latest `origin/next`, resolve conflicts without discarding remote work, and never force-push unless the user explicitly authorizes it.
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
FROM node:22.23.2-bookworm-slim
|
||||
|
||||
ENV NODE_ENV=production
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev && npm cache clean --force
|
||||
|
||||
COPY --chown=node:node . .
|
||||
RUN mkdir -p /app/uploads && chown node:node /app/uploads
|
||||
RUN chmod +x /app/scripts/docker-entrypoint.sh
|
||||
|
||||
USER node
|
||||
EXPOSE 3000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
||||
CMD ["node", "scripts/healthcheck.js"]
|
||||
|
||||
ENTRYPOINT ["/app/scripts/docker-entrypoint.sh"]
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Furrium Network & lezi-fun
|
||||
Copyright (c) 2026 Furrium Network
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,33 +1,34 @@
|
||||
# Forumlify NEXT Edition🌊
|
||||
|
||||
[](https://app.codecov.io/gh/forumlify/public/tree/next)
|
||||
|
||||
# Forumlify LITE Edition 🌊
|
||||
|
||||
> 一个简洁、优雅的现代社区系统。5 分钟 Docker 一键部署。
|
||||
|
||||
官方演示地址:[Forumlify NEXT](https://next.forumlify.org)
|
||||
**在线演示:** https://lite.forumlify.org
|
||||
|
||||
## ✨ 特性
|
||||
|
||||
- 🎨 精致简约的界面设计,支持亮色/暗色模式
|
||||
- ⚡️ 基于 Next.js 16 (App Router) + React 19,前后端一体化
|
||||
- 🔐 自带用户认证(JWT)
|
||||
- 📝 发帖、回复、举报、管理后台
|
||||
- ⚡️ 轻量快速,无需复杂配置
|
||||
- 🔐 自带用户认证(JWT),改密码后旧令牌立即失效
|
||||
- 📝 发帖、回复、举报、私信、管理后台
|
||||
- 📧 邮件支持:后台配置 SMTP,可用于注册邮箱验证与密码找回
|
||||
- 🌍 界面中英文双语,管理后台可配置自定义页面与样式
|
||||
- 🐳 Docker 一键部署
|
||||
- 🌓 暗色/亮色模式切换
|
||||
|
||||
## 🤔 如何选择版本
|
||||
|
||||
Forumlify 提供了两个不同架构的分支版本,以满足不同部署环境与开发需求的场景:
|
||||
|
||||
* **Lite 版 (`main` 分支)**:轻量单体架构,零构建步骤,资源占用极低,主要由Furrium维护。
|
||||
* **Lite 版 (`lite` 分支)**:轻量单体架构,零构建步骤,资源占用极低,主要由Furrium维护。
|
||||
* **Next.js 版 (`next` 分支)**:现代全栈架构,组件化开发,支持云原生与 Serverless / 边缘部署,主要由lezi-fun维护。
|
||||
|
||||
你可以根据以下维度选择最适合你当前需求的版本:
|
||||
|
||||
| 对比维度 | Forumlify (Lite 版 / `main`) | Forumlify-Next (Next.js 版 / `next`) | 选择建议 |
|
||||
| 对比维度 | Forumlify (Lite 版 / `lite`) | Forumlify-Next (Next.js 版 / `next`) | 选择建议 |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **上手速度与部署** | **极快**(零编译步骤,直接 `node server.js` 或 Docker 启动) | **中等**(需要经过 `next build` 编译打包,或配置 OpenNext) | 希望 1 分钟快速跑起来选 `main` |
|
||||
| **VPS 最低配置要求** | **1 核 512MB RAM**(资源占用极低,适合低配小鸡) | **1 核 1GB RAM+**(主要在打包构建时需要较多内存) | 内存有限或低配 VPS 推荐 `main` |
|
||||
| **上手速度与部署** | **极快**(零编译步骤,直接 `node server.js` 或 Docker 启动) | **中等**(需要经过 `next build` 编译打包,或配置 OpenNext) | 希望 1 分钟快速跑起来选 `lite` |
|
||||
| **VPS 最低配置要求** | **1 核 512MB RAM**(资源占用极低,适合低配小鸡) | **1 核 1GB RAM+**(主要在打包构建时需要较多内存) | 内存有限或低配 VPS 推荐 `lite` |
|
||||
| **存储扩展性** | 本地磁盘存储(`uploads/` 目录) | 支持 **Cloudflare R2 / S3 兼容对象存储** + 本地回退 | 需要接云存储或海量图片存储选 `next` |
|
||||
| **部署环境支持** | 传统 VPS / Docker 容器 | VPS / Docker / **Cloudflare Workers / Vercel** | 需要 Serverless / 边缘部署选 `next` |
|
||||
| **技术栈与二次开发** | 原生 Vanilla JS + Express,无框架门槛 | React 19 + Next.js 16 + Tailwind,组件化程度高 | 熟悉 React 框架或需要团队协同选 `next` |
|
||||
@@ -38,26 +39,55 @@ Forumlify 提供了两个不同架构的分支版本,以满足不同部署环
|
||||
|
||||
### Docker 部署(推荐)
|
||||
|
||||
```bash
|
||||
# 本分支(NEXT 版);如要部署 LITE 版请 clone main 分支
|
||||
git clone -b next https://github.com/forumlify/public.git
|
||||
```
|
||||
git clone https://github.com/forumlify/public.git
|
||||
cd public
|
||||
docker-compose up -d
|
||||
|
||||
cp .env.example .env
|
||||
# 编辑 .env,为 POSTGRES_PASSWORD 和 JWT_SECRET 设置强随机值
|
||||
docker compose up --build -d
|
||||
|
||||
```
|
||||
|
||||
应用默认运行在 `http://localhost:3000`(监听 `0.0.0.0`,局域网可访问)。
|
||||
旧版 Compose 也可以使用 `docker-compose up -d`。请妥善备份 `.env`;更换
|
||||
`JWT_SECRET` 会使现有登录令牌失效。
|
||||
|
||||
## Docker 更新
|
||||
> `git clone` 生成的目录名是 `public`(取自仓库名),不是 `forumlify`。
|
||||
> 若想使用其他目录名,可在 clone 时指定,例如
|
||||
> `git clone https://github.com/forumlify/public.git forumlify`。
|
||||
|
||||
应用默认运行在 `http://localhost:3000`。
|
||||
|
||||
容器启动时会自动执行 `migrations/` 中尚未应用的 SQL 文件。可使用以下命令检查状态:
|
||||
|
||||
```bash
|
||||
./scripts/update-docker.sh
|
||||
docker compose ps
|
||||
docker compose logs -f app
|
||||
curl http://localhost:3000/health/live
|
||||
curl http://localhost:3000/health/ready
|
||||
```
|
||||
|
||||
更新脚本兼容 Docker Compose v2(`docker compose`)和 v1(`docker-compose`)。它会先拉取最新的 `app` 镜像,再让 Compose 在镜像发生变化时重新创建应用容器;数据库容器和数据卷不会重建。
|
||||
- `/health/live` 表示 Node.js 服务正在运行。
|
||||
- `/health/ready` 仅在 PostgreSQL 可用时返回成功。
|
||||
- PostgreSQL 不再暴露到宿主机网络;应用通过 Compose 内部网络访问数据库。
|
||||
- 应用收到 `SIGTERM`/`SIGINT` 后会停止接收新连接并关闭数据库连接池。
|
||||
|
||||
升级代码后执行 `docker compose up --build -d`,应用会在启动前自动应用新增迁移。
|
||||
|
||||
#### Docker 数据备份
|
||||
|
||||
数据库保存在 `db_data` 卷中,上传文件继续保存在宿主机的 `./uploads` 目录,以兼容旧版部署。升级或删除容器前请备份:
|
||||
|
||||
```bash
|
||||
docker compose exec -T db pg_dump -U forumlify forumlify > forumlify.sql
|
||||
tar czf forumlify-uploads.tar.gz uploads/
|
||||
```
|
||||
|
||||
`docker compose down` 会保留数据卷;只有明确执行 `docker compose down -v` 才会删除数据。
|
||||
|
||||
---
|
||||
|
||||
> 以下内容需要一定的Nextjs开发技术!
|
||||
> 如需部署 Next.js 版本,请前往 [forumlify/tree/next](https://github.com/forumlify/public/tree/next)。
|
||||
|
||||
---
|
||||
|
||||
@@ -67,202 +97,354 @@ docker-compose up -d
|
||||
|
||||
#### 环境要求
|
||||
|
||||
- Node.js 20.9+(Next.js 16 要求)
|
||||
- PostgreSQL 13+(`schema.sql` 使用了内置的 `gen_random_uuid()`)
|
||||
- Node.js 20+
|
||||
- PostgreSQL 13+
|
||||
|
||||
#### 步骤
|
||||
|
||||
1. **克隆并安装依赖**
|
||||
|
||||
```bash
|
||||
# 克隆 next 分支(Next.js 版);main 分支是 Express 版
|
||||
git clone -b next https://github.com/forumlify/public.git
|
||||
git clone https://github.com/forumlify/public.git
|
||||
cd public
|
||||
npm install
|
||||
```
|
||||
|
||||
2. **准备数据库**(以本机 PostgreSQL 为例)
|
||||
2. **准备数据库**
|
||||
|
||||
创建数据库用户与空库即可,表结构交给迁移脚本处理:
|
||||
|
||||
```bash
|
||||
# 创建数据库和用户(与 docker-compose.yml 默认一致)
|
||||
psql -U postgres -c "CREATE USER forumlify WITH PASSWORD '123456';"
|
||||
psql -U postgres -c "CREATE USER forumlify WITH PASSWORD '请替换为强密码';"
|
||||
psql -U postgres -c "CREATE DATABASE forumlify OWNER forumlify;"
|
||||
# 导入表结构
|
||||
psql -U forumlify -d forumlify -f schema.sql
|
||||
```
|
||||
|
||||
3. **配置环境变量**(可选,均有默认值)
|
||||
> `schema.sql` 仅作为表结构的参考快照保留,**不要**再用它手工建表。
|
||||
> 请统一使用第 4 步的 `npm run migrate`,它会按顺序执行 `migrations/`
|
||||
> 下的文件并记录版本。手工建表后再跑迁移会导致版本记录与实际结构
|
||||
> 不一致,后续升级容易出错。
|
||||
|
||||
3. **配置环境变量**
|
||||
|
||||
复制示例文件并按需修改:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
`migrations/` 与 `server.js` 直接读取进程环境变量,`.env` 不会自动加载。
|
||||
使用 `npm start` 手动启动时,请先导出这些变量:
|
||||
|
||||
```bash
|
||||
set -a && . ./.env && set +a
|
||||
```
|
||||
|
||||
| 变量 | 默认值 | 说明 |
|
||||
|------|--------|------|
|
||||
| `DATABASE_URL` | `postgresql://forumlify:123456@localhost:5432/forumlify` | PostgreSQL 连接串 |
|
||||
| `JWT_SECRET` | `forumlify-secret-key-change-me-in-production` | JWT 签名密钥,**生产环境务必修改** |
|
||||
| `DATABASE_URL` | `postgresql://forumlify:***@localhost:5432/forumlify` | PostgreSQL 连接串 |
|
||||
| `PORT` | `3000` | HTTP 监听端口 |
|
||||
| `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;生产环境必须显式设置,建议至少 32 个字符。较短的旧密钥会产生警告但仍可启动,便于安排会话失效窗口后再轮换 |
|
||||
| `ALLOWED_ORIGINS` | 空 | 允许跨域访问的来源,多个值用逗号分隔;为空时仅支持同源访问 |
|
||||
| `TRUST_PROXY` | `false` | 位于可信反向代理后时设为 `true`,用于正确识别限流 IP |
|
||||
| `PGHOST` / `PGPORT` / `PGUSER` / `PGPASSWORD` / `PGDATABASE` | PostgreSQL 客户端默认值 | 可替代 `DATABASE_URL`,Compose 使用这些变量避免密码 URL 编码问题 |
|
||||
| `ADMIN_BOOTSTRAP_TOKEN` | 空 | 首次部署时设置强随机值;注册时填写相同值可创建唯一初始管理员,初始化后应删除该变量 |
|
||||
|
||||
|
||||
4. **执行迁移并启动**
|
||||
|
||||
```bash
|
||||
# 例如:
|
||||
export DATABASE_URL=postgresql://forumlify:123456@localhost:5432/forumlify
|
||||
export JWT_SECRET=your-own-secret-key
|
||||
```
|
||||
|
||||
4. **构建并启动**
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
npm run migrate
|
||||
npm start
|
||||
```
|
||||
|
||||
应用运行在 `http://localhost:3000`,API 在 `http://localhost:3000/api`。
|
||||
|
||||
开发模式(热更新):`npm run dev`。
|
||||
#### 创建第一个管理员
|
||||
|
||||
#### 服务端配置
|
||||
站点默认没有任何管理员。首次部署时在 `.env` 中设置一个强随机
|
||||
`ADMIN_BOOTSTRAP_TOKEN`,然后在注册页面的「管理员初始化令牌」一栏填入
|
||||
相同的值完成注册,该账号即成为管理员。
|
||||
|
||||
监听端口与地址可在 `config.js` 中调整(服务端读取,浏览器端忽略):
|
||||
管理员只能这样创建:普通注册一律是普通用户,且系统存在管理员后,
|
||||
引导令牌不再生效。初始化完成后请从 `.env` 中删除该变量并重启服务。
|
||||
|
||||
#### 前端配置
|
||||
|
||||
前端页面为 `index.html`,相关行为可在 `config.js` 中调整:
|
||||
|
||||
| 配置项 | 默认值 | 说明 |
|
||||
|--------|--------|------|
|
||||
| `SERVER_PORT` | `null` | 可选:监听端口。优先级:环境变量 `PORT` > `SERVER_PORT` > 默认 `3000` |
|
||||
| `SERVER_HOST` | `null` | 可选:监听地址。优先级:环境变量 `HOST` > `SERVER_HOST` > 默认 `0.0.0.0`(所有网卡)。设为 `127.0.0.1` 仅本机访问 |
|
||||
| `FORUM_NAME` | `Forumlify` | 论坛名称(左上角显示) |
|
||||
| `ENABLE_CAPTCHA` | `true` | 发帖/注册的人机验证(10 以内加减法) |
|
||||
| `SERVER_PORT` | `null` | 可选:服务端监听端口。优先级:环境变量 `PORT` > `SERVER_PORT` > 默认 `3000` |
|
||||
|
||||
#### 上传目录
|
||||
|
||||
帖子图片默认保存在 `uploads/` 目录(Docker 部署时通过 volume 挂载到 `/app/uploads`),源码部署时请确保该目录有写入权限:
|
||||
帖子图片默认保存在 `uploads/` 目录,请确保该目录有写入权限:
|
||||
|
||||
```bash
|
||||
mkdir -p uploads && chmod 755 uploads
|
||||
```
|
||||
|
||||
## ☁️ Serverless 部署(Vercel / Cloudflare Workers)
|
||||
#### 反向代理与 HTTPS
|
||||
|
||||
Forumlify 的 Next.js 版本天然支持 serverless 部署。与传统部署相比需要处理三件事:
|
||||
生产环境建议让 Nginx 终止 TLS 并反代到本机的 3000 端口。要点如下:
|
||||
|
||||
1. **数据库**:使用外部 PostgreSQL(Neon / Supabase / RDS 等),设置 `DATABASE_URL` 环境变量。连接池会自动适配 serverless(单连接 + 定期轮换)。
|
||||
2. **文件上传**:serverless 无持久磁盘,需要 S3 兼容对象存储(Cloudflare R2 / AWS S3 / MinIO)。设置 `S3_*` 环境变量后,上传自动切换到对象存储。
|
||||
3. **密码哈希**:已使用 `bcryptjs`(纯 JS),无原生编译依赖,各平台均可直接构建。
|
||||
```nginx
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name lite.example.org;
|
||||
|
||||
### 环境变量说明
|
||||
ssl_certificate /etc/nginx/ssl/lite.example.org.fullchain.pem;
|
||||
ssl_certificate_key /etc/nginx/ssl/lite.example.org.key;
|
||||
|
||||
| 变量 | 必填 | 说明 |
|
||||
|------|------|------|
|
||||
| `DATABASE_URL` | ✅ 必须 | PostgreSQL 连接串,如 `postgresql://user:pass@host:5432/dbname`(可用 [Neon](https://neon.tech) / [Supabase](https://supabase.com) 免费实例) |
|
||||
| `JWT_SECRET` | ✅ 必须 | JWT 签名密钥,任意长随机字符串(生产环境务必修改) |
|
||||
| `S3_ENDPOINT` | 上传图片时 | S3 兼容端点,如 R2 的 `https://<account_id>.r2.cloudflarestorage.com` |
|
||||
| `S3_BUCKET` | 上传图片时 | 存储桶名 |
|
||||
| `S3_REGION` | 上传图片时 | 区域(R2 用 `auto`,AWS 用 `us-east-1` 等) |
|
||||
| `S3_ACCESS_KEY_ID` | 上传图片时 | 对象存储 Access Key |
|
||||
| `S3_SECRET_ACCESS_KEY` | 上传图片时 | 对象存储 Secret Key |
|
||||
| `S3_PUBLIC_URL` | 上传图片时 | 公开访问前缀,如 `https://cdn.example.com`(图片 URL 将指向这里) |
|
||||
# 保留 ACME 挑战路径,否则证书续期会失败
|
||||
location /.well-known/acme-challenge/ {
|
||||
root /var/www/acme;
|
||||
}
|
||||
|
||||
> 只搭一个纯文字论坛、不上传图片的话,只需配置 `DATABASE_URL` 和 `JWT_SECRET` 两个变量。
|
||||
|
||||
### Vercel 部署(一键)
|
||||
|
||||
[](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Flezi-fun%2Fforumlify-deploy&env=DATABASE_URL,JWT_SECRET,S3_ENDPOINT,S3_BUCKET,S3_REGION,S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY,S3_PUBLIC_URL)
|
||||
|
||||
点击上方按钮,Vercel 会自动:
|
||||
1. Fork 部署模板仓库([lezi-fun/forumlify-deploy](https://github.com/lezi-fun/forumlify-deploy),默认分支 `next`,即 Next.js 版,无需手动选分支)
|
||||
2. 提示你填写环境变量(见上方表格,前两个必填,其余可跳过)
|
||||
3. 自动完成构建并部署,完成后会给你一个 `https://xxx.vercel.app` 地址
|
||||
|
||||
也可以用 CLI 手动部署:
|
||||
|
||||
```bash
|
||||
npm i -g vercel
|
||||
vercel # 首次会要求登录并配置环境变量
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> 注意:不传图片的话 S3 变量可以留空;后续要传图时再到 Vercel 项目设置 → Environment Variables 补上即可,无需重新部署。
|
||||
配套设置 `.env` 中的 `TRUST_PROXY=true`,否则限流会把所有用户识别为
|
||||
同一个来源 IP。应用记录审计日志时也依赖该设置取到真实客户端地址。
|
||||
|
||||
### Cloudflare Workers 部署(一键)
|
||||
两个容易踩的坑:
|
||||
|
||||
[](https://deploy.workers.cloudflare.com/?url=https%3A%2F%2Fgithub.com%2Flezi-fun%2Fforumlify-deploy)
|
||||
- **80 端口若已存在其他站点的 `default_server`**,它会接管所有未显式
|
||||
匹配的 Host,导致本域名的 ACME 挑战请求被 301 跳走、证书签发失败。
|
||||
必须为本域名单独写一个 `server_name` 的 80 端口块。
|
||||
- **ACME 挑战路径要放在 `return 301` 之前**,否则同样会被重定向。
|
||||
|
||||
点击上方按钮,Cloudflare 会自动导入部署模板仓库([lezi-fun/forumlify-deploy](https://github.com/lezi-fun/forumlify-deploy),默认分支 `next`),在 Workers 面板确认后即完成部署。
|
||||
### 邮件(SMTP)
|
||||
|
||||
#### 面板手动部署(Git 集成)
|
||||
邮件功能**默认关闭**,全部在管理后台配置,无需改环境变量或重启服务。
|
||||
入口:登录管理员账号 → 右上角头像 → **管理后台** → **邮件设置**。
|
||||
|
||||
1. 打开 Cloudflare 控制台 → **Workers & Pages** → **Create** → **Connect to Git**
|
||||
2. 选择 `lezi-fun/forumlify-deploy` 仓库(或你 fork 的副本),分支选 `next`
|
||||
3. **构建设置**:
|
||||
- Build command: `npx opennextjs-cloudflare build --dangerouslyUseUnsupportedNextVersion`
|
||||
- 部署命令由 OpenNext 自动处理(`wrangler deploy`)
|
||||
4. **环境变量**(Settings → Variables and Secrets,设为 **Secrets**):按上方表格配置 `DATABASE_URL`、`JWT_SECRET`、`S3_*`
|
||||
5. 保存并部署。完成后会得到 `https://<name>.<subdomain>.workers.dev` 地址
|
||||
> 配置保存在数据库的 `settings` 表中,因此在 Docker 部署下也会随
|
||||
> `db_data` 卷一起持久化,容器重建不会丢失,也不需要给 Compose 增加
|
||||
> 任何环境变量。
|
||||
|
||||
#### 命令行部署
|
||||
配置项:
|
||||
|
||||
```bash
|
||||
# 需要 Node.js 20+,安装依赖后:
|
||||
npx opennextjs-cloudflare build --dangerouslyUseUnsupportedNextVersion
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| 启用邮件发送 | 总开关,关闭时所有邮件功能不可用 |
|
||||
| SMTP 服务器 | 如 `smtp.qq.com`、`smtp.gmail.com` |
|
||||
| 端口 | 587(STARTTLS)或 465(SSL/TLS) |
|
||||
| 加密方式 | 需与端口匹配:**587 选 STARTTLS,465 选 SSL/TLS** |
|
||||
| 用户名 | 通常为完整邮箱地址 |
|
||||
| 密码 / 授权码 | 见下方说明 |
|
||||
| 发件人名称 | 显示在收件人邮箱里的发件人名字 |
|
||||
| 发件人邮箱 | 必填,建议与用户名一致,否则易被判定为伪造发件人 |
|
||||
|
||||
# 部署前先配置 wrangler 认证(三选一):
|
||||
# wrangler login # 浏览器登录
|
||||
# CLOUDFLARE_API_TOKEN=<token> # API Token
|
||||
# CLOUDFLARE_API_KEY + CLOUDFLARE_API_EMAIL # Global API Key
|
||||
export CLOUDFLARE_ACCOUNT_ID=<account_id>
|
||||
填写后点击**发送测试邮件**验证连通性,默认发到当前管理员的邮箱。
|
||||
测试通过即表示配置可用。
|
||||
|
||||
# 设置环境变量(Secret)
|
||||
echo 'postgresql://...' | npx wrangler secret put DATABASE_URL
|
||||
echo 'your-jwt-secret' | npx wrangler secret put JWT_SECRET
|
||||
# ... 其余 S3_* 同理
|
||||
#### 关于「授权码」
|
||||
|
||||
npx opennextjs-cloudflare deploy
|
||||
```
|
||||
**QQ 邮箱、163、Gmail 等服务商不能用登录密码发信**,必须先生成专用
|
||||
授权码:
|
||||
|
||||
> 注意:OpenNext 使用 R2 增量缓存,首次部署前需创建缓存桶:
|
||||
> `npx wrangler r2 bucket create forumlify-opennext-cache`
|
||||
>
|
||||
> `--dangerouslyUseUnsupportedNextVersion` 用于跳过 Next.js 主版本支持期检查(如仍在使用旧主版本时)。
|
||||
- **QQ 邮箱**:设置 → 账户 → 开启 SMTP 服务 → 生成授权码
|
||||
- **163 邮箱**:设置 → POP3/SMTP/IMAP → 开启服务 → 获取授权码
|
||||
- **Gmail**:需开启两步验证后创建「应用专用密码」
|
||||
|
||||
> 提示:`next.config.js` 中的 `output: 'standalone'` 仅在设置了 `DOCKER=1` 环境变量时启用,serverless 平台会自动跳过。
|
||||
把授权码填进「密码 / 授权码」一栏即可。
|
||||
|
||||
## 🔄 与 main 分支(Express 版)的对比
|
||||
#### 使用 Resend
|
||||
|
||||
本分支(`next`)基于上游 `main` 的 Express 单文件架构全面重构为 Next.js 16(App Router)。两者功能一致,实现方式不同:
|
||||
[Resend](https://resend.com) 提供 SMTP 接口,按其官方参数填写即可:
|
||||
|
||||
| 维度 | main 分支(Express) | next 分支(Next.js 16) |
|
||||
|------|---------------------|------------------------|
|
||||
| **前端** | 单个 1488 行 `index.html` + `js/` 原生 JS 模块(手写 DOM 操作) | React 19 组件(`components/`),状态由 `AppProvider` 管理 |
|
||||
| **后端** | 单个 1000+ 行 `server.js`(Express 路由) | 36 个 Route Handlers(`app/api/**/route.js`),每个接口独立文件 |
|
||||
| **模板渲染** | `innerHTML` 字符串拼接 + `onclick` 事件绑定 | JSX 声明式渲染 + React 事件 |
|
||||
| **图片上传** | multer + `uploads/` 本地目录 | 存储抽象层(`lib/storage.js`):本地磁盘 或 S3 兼容对象存储(serverless) |
|
||||
| **密码哈希** | `bcrypt`(原生编译) | `bcryptjs`(纯 JS,serverless 友好) |
|
||||
| **数据库** | 共享同一套 PostgreSQL schema | **同一 `schema.sql`,与 main 完全兼容**(已实测互操作) |
|
||||
| **部署** | Docker 或裸机 `node server.js` | Docker / 裸机 / **Vercel / Cloudflare Pages(serverless)** |
|
||||
| **性能** | Express 同步渲染 | Next.js 增量静态生成 + 流式渲染 |
|
||||
| **API 路径** | `/api/*` | `/api/*`(路径一致,前端兼容) |
|
||||
| 字段 | 值 |
|
||||
|------|-----|
|
||||
| SMTP 服务器 | `smtp.resend.com` |
|
||||
| 端口 | `465`(推荐)或 `587` |
|
||||
| 加密方式 | 465 选 **SSL/TLS**;587 选 STARTTLS |
|
||||
| 用户名 | `resend` ← **固定值,不是邮箱地址** |
|
||||
| 密码 / 授权码 | 你的 **API Key**(`re_` 开头) |
|
||||
| 发件人邮箱 | 已验证域名下的地址,如 `noreply@你的域名` |
|
||||
|
||||
### 数据库兼容性
|
||||
使用前需在 Resend 控制台完成两件事:**创建 API Key**,以及
|
||||
**添加并验证发信域名**(配置 SPF / DKIM 记录)。未验证域名时
|
||||
只能发往自己的注册邮箱,无法发给其他收件人。
|
||||
|
||||
两个分支使用**完全相同的 `schema.sql`**,共用同一个数据库实例(已验证:main 的 Express 代码与 next 的 Next.js 代码可同时连接同一 PostgreSQL 库,表结构、数据互不冲突)。
|
||||
> 用户名填成自己的邮箱地址是常见错误——Resend 要求固定填 `resend`。
|
||||
|
||||
## 🏗️ 项目结构
|
||||
##### Resend 的收件人限制
|
||||
|
||||
Resend **禁止向 `example.com`、`test.com` 等保留/测试域名发信**,
|
||||
会直接返回 `550 Invalid to field`。这是服务商的反滥用策略,不是本站
|
||||
的限制。
|
||||
|
||||
因此**不要用测试域名验证邮件功能**——测试时请使用真实可收信的邮箱。
|
||||
本站会把该错误翻译成中文提示。
|
||||
|
||||
若已启用注册邮箱验证,而用户恰好使用了这类邮箱注册,会看到
|
||||
「收件人邮箱被邮件服务商拒绝」的提示,属预期行为。
|
||||
|
||||
#### 使用其他服务商
|
||||
|
||||
常见服务商的 SMTP 参数:
|
||||
|
||||
| 服务商 | 服务器 | 端口 | 用户名 | 密码 |
|
||||
|--------|--------|------|--------|------|
|
||||
| QQ 邮箱 | `smtp.qq.com` | 465 / 587 | 完整邮箱 | 授权码 |
|
||||
| 163 邮箱 | `smtp.163.com` | 465 / 587 | 完整邮箱 | 授权码 |
|
||||
| Gmail | `smtp.gmail.com` | 465 / 587 | 完整邮箱 | 应用专用密码 |
|
||||
| Resend | `smtp.resend.com` | 465 / 587 | `resend` | API Key |
|
||||
| 阿里云邮件推送 | `smtpdm.aliyun.com` | 465 / 80 | 发信地址 | 设置的密码 |
|
||||
|
||||
#### 关于「允许自签证书」
|
||||
|
||||
默认开启证书校验。如果你使用的是**自建邮件服务器且用自签证书**,
|
||||
连接会因证书不受信任而失败,此时才需要打开这个开关。
|
||||
|
||||
对 Resend、QQ、Gmail 等使用可信证书的服务商,**保持关闭**。关闭校验
|
||||
会让连接暴露在中间人攻击下。
|
||||
|
||||
#### 密码的存储与显示
|
||||
|
||||
SMTP 密码**只写不读**:保存后任何接口都不会返回明文,界面只显示
|
||||
「已保存密码,留空则不修改」。因此:
|
||||
|
||||
- 想改其他字段时,**密码栏留空即可**,原密码保持不变
|
||||
- 需要更换密码时才填写新值
|
||||
- 「清除密码」按钮用于彻底移除已保存的密码
|
||||
|
||||
#### 邮件用在哪里
|
||||
|
||||
配置完成并发送测试邮件成功后,可以开启 **要求注册时验证邮箱**:
|
||||
|
||||
- **注册邮箱验证**:新用户注册时必须填写邮箱收到的 6 位验证码。
|
||||
验证码 10 分钟有效,连续输错 5 次即作废,且只能使用一次。
|
||||
该字段仅在开启此选项时才出现在注册框里。
|
||||
- **密码找回**:登录页的「忘记密码」支持通过邮箱验证码重置密码,
|
||||
与原有的恢复码机制并行,两种方式都可用。
|
||||
|
||||
> 未完成 SMTP 配置时**无法开启**注册邮箱验证——这是有意为之,
|
||||
> 避免开启后所有人都注册不了。
|
||||
|
||||
#### 常见配置问题
|
||||
|
||||
| 现象 | 原因 |
|
||||
|------|------|
|
||||
| 认证失败 | 用了登录密码而非授权码;或用 Resend 时用户名没填 `resend` |
|
||||
| 连接超时 | 端口被防火墙拦截,**或加密方式与端口不匹配**(465 必须配 SSL/TLS) |
|
||||
| 套接字错误 | 同上,端口与加密方式不匹配;也可能是证书校验未通过 |
|
||||
| 发件人被拒 | 发件人邮箱不属于已验证的域名,或与服务商要求不符 |
|
||||
| 域名解析失败 | SMTP 服务器地址拼写错误 |
|
||||
| 证书校验失败 | 自建服务器用了自签证书,需打开「允许自签证书」 |
|
||||
|
||||
多数云服务商默认封禁 25 端口,建议使用 465 或 587。
|
||||
|
||||
> 排错时最有效的两步:先在后台点**发送测试邮件**看具体报错,
|
||||
> 再对照上表定位。中间的错误提示会直接给出去改哪个字段。
|
||||
|
||||
## 📁 项目结构
|
||||
|
||||
```
|
||||
app/
|
||||
page.js # 主页(SPA 视图调度)
|
||||
layout.js # 全局布局
|
||||
globals.css # 全局样式(含亮/暗主题)
|
||||
api/ # Route Handlers(API 后端)
|
||||
auth/ posts/ replies/ users/ reports/ links/
|
||||
stats/ event-logs/ settings/ upload/ uploads/
|
||||
components/
|
||||
AppProvider.js # 全局状态(用户/主题/路由)
|
||||
Navbar.js Feed.js PostDetail.js ReplyList.js
|
||||
NewPost.js AdminPage.js SettingsPage.js Modals.js
|
||||
lib/
|
||||
db.js # PostgreSQL 连接池
|
||||
auth.js # JWT 认证工具
|
||||
api.js # 前端 API 封装
|
||||
scripts/
|
||||
start.js # 启动入口(读取 config.js 监听配置)
|
||||
schema.sql # 数据库表结构
|
||||
config.js # 服务端配置(端口/地址)
|
||||
public/
|
||||
├── index.html # 前端页面
|
||||
├── style.css # 全局样式
|
||||
├── config.js # 前端配置(同时也是服务端配置入口)
|
||||
├── server.js # 后端服务(Express)
|
||||
├── lib/
|
||||
│ └── mailer.js # SMTP 发信封装(配置读取、发送、错误翻译)
|
||||
├── Dockerfile # Docker 镜像构建文件
|
||||
├── docker-compose.yml # Docker 编排
|
||||
├── package-lock.json # 依赖锁定文件
|
||||
├── migrations/ # 数据库迁移(按文件名顺序执行,请勿手工修改已应用的版本)
|
||||
│ ├── 001_initial.sql
|
||||
│ ├── 002_restore_auth_and_audit_columns.sql
|
||||
│ └── 003_email_verification.sql
|
||||
├── schema.sql # 表结构参考快照(仅供阅读,请勿用于建表)
|
||||
├── scripts/
|
||||
│ ├── migrate.js # 迁移执行器
|
||||
│ ├── docker-entrypoint.sh
|
||||
│ └── healthcheck.js
|
||||
├── test/ # 测试(node --test)
|
||||
│ ├── app.test.js # 接口与安全头
|
||||
│ ├── bootstrap-ui.test.js # 管理员引导令牌的显示条件
|
||||
│ ├── i18n-coverage.test.js # 界面文案翻译覆盖率
|
||||
│ ├── migration-schema.test.js # 迁移必须覆盖服务端依赖的列
|
||||
│ └── schema-parity.test.js # schema.sql 与 migrations 的结构一致性
|
||||
└── js/ # 前端 JS 模块
|
||||
├── app.js # 主入口、路由、Toast、确认框
|
||||
├── admin.js # 管理后台各标签页
|
||||
├── api.js # 接口封装
|
||||
├── auth.js # 登录、注册、退出
|
||||
├── captcha.js # 人机验证
|
||||
├── feed.js # 帖子列表
|
||||
├── i18n.js # 中英文词典与外挂翻译
|
||||
├── icons.js # SVG 图标
|
||||
├── post.js # 帖子详情与回复
|
||||
├── security.js # 转义与安全渲染
|
||||
├── theme.js # 亮色/暗色切换
|
||||
└── user.js # 用户主页
|
||||
```
|
||||
|
||||
## 📚 技术栈
|
||||
## ❓ 常见问题
|
||||
|
||||
**升级代码后,登录之后的接口全部返回 500?**
|
||||
|
||||
说明数据库缺少 `users.token_version` 或 `event_logs` 的审计字段。执行
|
||||
`npm run migrate` 应用 `migrations/` 中的修复迁移即可,无需重建数据库。
|
||||
若该库曾经手工执行过 `schema.sql`,迁移记录可能与实际结构不一致,可先
|
||||
检查 `SELECT * FROM schema_migrations;`。
|
||||
|
||||
**忘记了管理员密码?**
|
||||
|
||||
两种方式:若已配置邮件,在登录页的「忘记密码」用邮箱验证码重置;
|
||||
否则使用注册后在设置页生成的恢复码重置。恢复码建议生成后立即离线保存。
|
||||
|
||||
**修改密码或邮箱后被登出?**
|
||||
|
||||
这两个操作会递增 `users.token_version` 使所有已签发的令牌失效,属于预期
|
||||
行为;服务端会随响应补发一个新令牌,前端会自动保存并保持在登录状态。
|
||||
若仍被登出,请强制刷新页面(Ctrl+F5)以载入最新的前端脚本。
|
||||
|
||||
**注册框里看不到邮箱验证码输入框?**
|
||||
|
||||
这是正常的。该字段仅在管理后台开启了「要求注册时验证邮箱」、
|
||||
且 SMTP 配置完整时才显示。未配置邮件时注册流程与以往一致。
|
||||
|
||||
**开启了邮箱验证,但收不到验证码?**
|
||||
|
||||
先在后台点「发送测试邮件」确认 SMTP 可用。若测试邮件能收到而验证码
|
||||
收不到,检查是否被投进了垃圾箱;若用的是自建发信域名,还需配置 SPF
|
||||
与 DKIM 记录,否则容易进垃圾箱或被直接拒收。
|
||||
|
||||
**用 Resend 发送失败?**
|
||||
|
||||
按顺序检查三项:用户名必须是 `resend`(不是你的邮箱)、密码必须是
|
||||
`re_` 开头的 API Key、发件人邮箱必须属于已在 Resend 验证过的域名。
|
||||
若尚未验证域名,Resend 只允许发往账号注册邮箱,发给其他地址会被拒。
|
||||
|
||||
**怎么确认 SMTP 是通的?**
|
||||
|
||||
后台「发送测试邮件」默认发到当前管理员的邮箱。收到即表示配置可用,
|
||||
不必开启注册验证去试探。
|
||||
|
||||
**邮件相关接口返回 429?**
|
||||
|
||||
发送验证码与找回密码的接口有独立限流(15 分钟 5 次),用于防止被当作
|
||||
垃圾邮件发射器。稍后再试即可。
|
||||
|
||||
**改动 SMTP 配置后没有生效?**
|
||||
|
||||
配置保存在数据库中,保存即时生效,无需重启。若填了新的密码但仍是旧
|
||||
行为,确认密码栏确实填入了新值——留空表示保持原密码不变。
|
||||
|
||||
## 📝 License
|
||||
|
||||
MIT
|
||||
|
||||
- Next.js 16 (App Router) + React 19
|
||||
- Express 风格 Route Handlers (Node.js Runtime)
|
||||
- PostgreSQL + pg
|
||||
- JWT 认证 + bcrypt 密码哈希
|
||||
@@ -1,13 +0,0 @@
|
||||
import { cookies } from 'next/headers';
|
||||
import HomeClient from './HomeClient';
|
||||
|
||||
export default async function ForumPage() {
|
||||
let cachedName = '';
|
||||
try {
|
||||
const cookieStore = await cookies();
|
||||
cachedName = decodeURIComponent(cookieStore.get('forumlify-name')?.value || '');
|
||||
} catch {
|
||||
cachedName = '';
|
||||
}
|
||||
return <HomeClient cachedName={cachedName} />;
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 主页客户端组件:SPA 视图调度 (feed/post/new/admin/settings/messages)
|
||||
import { useState } from 'react';
|
||||
import AppProvider, { useApp } from '@/components/AppProvider';
|
||||
import Navbar from '@/components/Navbar';
|
||||
import Sidebar from '@/components/Sidebar';
|
||||
import Feed from '@/components/Feed';
|
||||
import PostDetail from '@/components/PostDetail';
|
||||
import NewPost from '@/components/NewPost';
|
||||
import AdminPage from '@/components/AdminPage';
|
||||
import SettingsPage from '@/components/SettingsPage';
|
||||
import UserProfile from '@/components/UserProfile';
|
||||
import CustomPage from '@/components/CustomPage';
|
||||
import MessagesPage from '@/components/MessagesPage';
|
||||
import ChatManager from '@/components/chat/ChatManager';
|
||||
import Modals from '@/components/Modals';
|
||||
import LoadingScreen from '@/components/LoadingScreen';
|
||||
|
||||
function HomeInner() {
|
||||
const { view, currentPostId, currentPostPreview, currentUsername, currentUserPreview, currentUserPostsPreview, currentPageName, ready, forumName, forumNameLoaded } = useApp();
|
||||
const [modal, setModal] = useState(null); // null | login | register | report
|
||||
const [reportPostId, setReportPostId] = useState(null);
|
||||
|
||||
const openModal = (m) => setModal(m);
|
||||
const openReport = (postId) => { setReportPostId(postId); setModal('report'); };
|
||||
|
||||
// 初始化未完成:显示全屏加载页,避免未加载完的界面闪烁
|
||||
if (!ready) {
|
||||
return <LoadingScreen forumName={forumName} forumNameLoaded={forumNameLoaded} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="app-fade-in">
|
||||
<Navbar onOpenModal={openModal} />
|
||||
<ChatManager />
|
||||
<div id="app" style={{ display: view === 'feed' ? undefined : 'none' }}>
|
||||
<Sidebar />
|
||||
<Feed onOpenModal={openModal} onReport={openReport} />
|
||||
</div>
|
||||
|
||||
{/* 独立页面 */}
|
||||
<div style={{ display: view !== 'feed' ? 'block' : 'none' }}>
|
||||
{view === 'post' && currentPostId && <PostDetail postId={currentPostId} initialPost={currentPostPreview} />}
|
||||
{view === 'user' && currentUsername && <UserProfile username={currentUsername} initialUser={currentUserPreview} initialPosts={currentUserPostsPreview} />}
|
||||
{view === 'custom' && currentPageName && <CustomPage pageName={currentPageName} />}
|
||||
{view === 'new' && <NewPost />}
|
||||
{view === 'admin' && <AdminPage />}
|
||||
{view === 'settings' && <SettingsPage />}
|
||||
{view === 'messages' && <MessagesPage />}
|
||||
</div>
|
||||
|
||||
<Modals modal={modal} onClose={() => setModal(null)} reportPostId={reportPostId} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function HomeClient({ cachedName = '' }) {
|
||||
return (
|
||||
<AppProvider cachedName={cachedName}>
|
||||
<HomeInner />
|
||||
</AppProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import ForumPage from '../ForumPage';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default function NamedPage() {
|
||||
return <ForumPage />;
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
// POST /api/admin/custom-css, DELETE /api/admin/custom-css — 管理自定义 CSS
|
||||
import { writeFile, mkdir, unlink } from 'fs/promises';
|
||||
import path from 'path';
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
// 上传 style.css(管理员)
|
||||
export async function POST(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
|
||||
const form = await req.formData();
|
||||
const file = form.get('file');
|
||||
if (!file || typeof file === 'string') {
|
||||
return Response.json({ error: '请选择文件' }, { status: 400 });
|
||||
}
|
||||
if (file.name !== 'style.css') {
|
||||
return Response.json({ error: '文件名必须是 style.css' }, { status: 400 });
|
||||
}
|
||||
if (file.size > 1024 * 1024) {
|
||||
return Response.json({ error: 'CSS 文件不能超过 1MB' }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const dir = path.join(process.cwd(), 'uploads', 'custom');
|
||||
await mkdir(dir, { recursive: true });
|
||||
const buffer = Buffer.from(await file.arrayBuffer());
|
||||
await writeFile(path.join(dir, 'style.css'), buffer);
|
||||
await pool.query(
|
||||
`INSERT INTO settings (key, value) VALUES ($1, $2)
|
||||
ON CONFLICT (key) DO UPDATE SET value = $2, updated_at = NOW()`,
|
||||
['custom_css_enabled', 'true']
|
||||
);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '上传失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// 删除自定义 CSS(管理员)
|
||||
export async function DELETE(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
|
||||
try {
|
||||
const cssPath = path.join(process.cwd(), 'uploads', 'custom', 'style.css');
|
||||
try { await unlink(cssPath); } catch { /* 不存在则忽略 */ }
|
||||
await pool.query(
|
||||
`INSERT INTO settings (key, value) VALUES ($1, $2)
|
||||
ON CONFLICT (key) DO UPDATE SET value = $2, updated_at = NOW()`,
|
||||
['custom_css_enabled', 'false']
|
||||
);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
// PUT /api/admin/custom-pages/[id], DELETE /api/admin/custom-pages/[id]
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
if (!UUID_RE.test((await params).id)) {
|
||||
return Response.json({ error: '页面不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
const { title, content, enabled } = await req.json();
|
||||
try {
|
||||
const r = await pool.query(
|
||||
`UPDATE custom_pages
|
||||
SET title = $1, content = $2, enabled = $3, updated_at = NOW()
|
||||
WHERE id = $4
|
||||
RETURNING *`,
|
||||
[title, content, enabled, (await params).id]
|
||||
);
|
||||
if (r.rows.length === 0) {
|
||||
return Response.json({ error: '页面不存在' }, { status: 404 });
|
||||
}
|
||||
return Response.json(r.rows[0]);
|
||||
} catch {
|
||||
return Response.json({ error: '更新失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
if (!UUID_RE.test((await params).id)) {
|
||||
return Response.json({ error: '页面不存在' }, { status: 404 });
|
||||
}
|
||||
try {
|
||||
await pool.query('DELETE FROM custom_pages WHERE id = $1', [(await params).id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
// GET /api/admin/custom-pages, POST /api/admin/custom-pages — 管理 CRUD
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
|
||||
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
const RESERVED_PAGE_NAMES = new Set([
|
||||
'api', 'post', 'user', 'settings', 'messages', 'admin', 'new', 'uploads',
|
||||
]);
|
||||
|
||||
export async function GET(req) {
|
||||
const user = getUser(req);
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
try {
|
||||
const r = await pool.query(
|
||||
'SELECT id, name, title, content, enabled, created_at, updated_at FROM custom_pages ORDER BY created_at'
|
||||
);
|
||||
return Response.json(r.rows);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
|
||||
const { name, title, content } = await req.json();
|
||||
if (!name || !title || !content) {
|
||||
return Response.json({ error: '请填写完整信息' }, { status: 400 });
|
||||
}
|
||||
if (!/^[a-zA-Z0-9\-_]+$/.test(name)) {
|
||||
return Response.json({ error: '页面名称只允许字母、数字、短横线和下划线' }, { status: 400 });
|
||||
}
|
||||
if (RESERVED_PAGE_NAMES.has(name.toLowerCase())) {
|
||||
return Response.json({ error: '该页面名称为系统保留路径' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const r = await pool.query(
|
||||
`INSERT INTO custom_pages (name, title, content)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING *`,
|
||||
[name, title, content]
|
||||
);
|
||||
return Response.json(r.rows[0]);
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
return Response.json({ error: '页面名称已存在' }, { status: 400 });
|
||||
}
|
||||
return Response.json({ error: '创建失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
import pool from '@/lib/db';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
import { sniffImage } from '@/lib/image-type';
|
||||
import { deleteObject, saveObject } from '@/lib/storage';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
const MAX_SIZE = 5 * 1024 * 1024;
|
||||
|
||||
export async function POST(req) {
|
||||
const user = getUser(req);
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
|
||||
const form = await req.formData();
|
||||
const file = form.get('file');
|
||||
if (!file || typeof file === 'string') {
|
||||
return Response.json({ error: '请选择图标文件' }, { status: 400 });
|
||||
}
|
||||
if (file.size > MAX_SIZE) {
|
||||
return Response.json({ error: '图标大小不能超过 5MB' }, { status: 400 });
|
||||
}
|
||||
|
||||
const buffer = Buffer.from(await file.arrayBuffer());
|
||||
const image = sniffImage(buffer, { allowIcon: true });
|
||||
if (!image) {
|
||||
return Response.json({ error: '仅支持 PNG、JPEG、GIF、WebP 或 ICO 图标' }, { status: 400 });
|
||||
}
|
||||
|
||||
const objectName = `forumlify-favicon-${randomUUID()}${image.ext}`;
|
||||
let oldObject = '';
|
||||
try {
|
||||
const { url } = await saveObject(objectName, buffer, image.mime);
|
||||
let client = null;
|
||||
let committed = false;
|
||||
let version = '';
|
||||
|
||||
try {
|
||||
client = await pool.connect();
|
||||
await client.query('BEGIN');
|
||||
await client.query(
|
||||
`INSERT INTO settings (key, value) VALUES ('favicon_object', '')
|
||||
ON CONFLICT (key) DO NOTHING`
|
||||
);
|
||||
const current = await client.query(
|
||||
"SELECT value FROM settings WHERE key = 'favicon_object' FOR UPDATE"
|
||||
);
|
||||
oldObject = current.rows[0]?.value || '';
|
||||
version = Date.now().toString();
|
||||
await client.query(
|
||||
`INSERT INTO settings (key, value) VALUES ($1, $2), ($3, $4), ($5, $6)
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()`,
|
||||
['favicon_url', url, 'favicon_version', version, 'favicon_object', objectName]
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
committed = true;
|
||||
} catch (error) {
|
||||
if (client) await client.query('ROLLBACK').catch(() => {});
|
||||
if (!committed) await deleteObject(objectName).catch(() => {});
|
||||
throw error;
|
||||
} finally {
|
||||
client?.release();
|
||||
}
|
||||
|
||||
if (oldObject && /^forumlify-favicon-[\w-]+\.(?:png|jpg|gif|webp|ico)$/.test(oldObject)) {
|
||||
await deleteObject(oldObject).catch(() => {});
|
||||
}
|
||||
|
||||
return Response.json({ favicon_url: url, favicon_version: version });
|
||||
} catch {
|
||||
return Response.json({ error: '上传失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
// POST /api/auth/login
|
||||
import bcrypt from 'bcryptjs';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import pool from '@/lib/db';
|
||||
import { JWT_SECRET } from '@/lib/auth';
|
||||
import { logAudit } from '@/lib/audit';
|
||||
|
||||
export async function POST(req) {
|
||||
const { email, password } = await req.json();
|
||||
if (!email || !password) {
|
||||
return Response.json({ error: '请填写邮箱和密码' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const r = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
|
||||
const user = r.rows[0];
|
||||
if (!user) {
|
||||
return Response.json({ error: '邮箱或密码错误' }, { status: 401 });
|
||||
}
|
||||
const valid = await bcrypt.compare(password, user.password_hash);
|
||||
if (!valid) {
|
||||
return Response.json({ error: '邮箱或密码错误' }, { status: 401 });
|
||||
}
|
||||
const token = jwt.sign(
|
||||
{ id: user.id, email: user.email, role: user.role },
|
||||
JWT_SECRET,
|
||||
{ expiresIn: '7d' }
|
||||
);
|
||||
// 服务端审计:登录成功
|
||||
await logAudit(req, 'login', user.id);
|
||||
return Response.json({
|
||||
token,
|
||||
user: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
avatar_url: user.avatar_url,
|
||||
bio: user.bio,
|
||||
role: user.role,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
return Response.json({ error: '登录失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
// GET /api/auth/me
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
export async function GET(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
try {
|
||||
const r = await pool.query(
|
||||
'SELECT id, username, avatar_url, bio, signature, role, created_at FROM users WHERE id = $1',
|
||||
[user.id]
|
||||
);
|
||||
if (!r.rows[0]) {
|
||||
return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||
}
|
||||
return Response.json(r.rows[0]);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
// GET /api/auth/recovery-codes/count — 剩余恢复码数量
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
export async function GET(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
try {
|
||||
const r = await pool.query(
|
||||
'SELECT COUNT(*) FROM recovery_codes WHERE user_id = $1 AND is_used = false',
|
||||
[user.id]
|
||||
);
|
||||
return Response.json({ count: parseInt(r.rows[0].count) || 0 });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
// POST /api/auth/recovery-codes/generate — 生成 10 个恢复码
|
||||
import bcrypt from 'bcryptjs';
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
function generateRecoveryCode() {
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
||||
let code = '';
|
||||
for (let i = 0; i < 20; i++) {
|
||||
code += chars[Math.floor(Math.random() * chars.length)];
|
||||
if (i === 4 || i === 9 || i === 14) code += '-';
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
export async function POST(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
try {
|
||||
await pool.query('DELETE FROM recovery_codes WHERE user_id = $1', [user.id]);
|
||||
const codes = [];
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const code = generateRecoveryCode();
|
||||
codes.push(code);
|
||||
const hash = await bcrypt.hash(code, 10);
|
||||
await pool.query(
|
||||
'INSERT INTO recovery_codes (user_id, code_hash) VALUES ($1, $2)',
|
||||
[user.id, hash]
|
||||
);
|
||||
}
|
||||
return Response.json({ success: true, codes });
|
||||
} catch {
|
||||
return Response.json({ error: '生成失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
// POST /api/auth/register
|
||||
import bcrypt from 'bcryptjs';
|
||||
import pool from '@/lib/db';
|
||||
import { verifyCaptcha } from '@/lib/captcha';
|
||||
import { logAudit } from '@/lib/audit';
|
||||
|
||||
export async function POST(req) {
|
||||
const { email, password, username, captcha_id, captcha_answer, captcha_sig } = await req.json();
|
||||
if (!email || !password || !username) {
|
||||
return Response.json({ error: '请填写完整信息' }, { status: 400 });
|
||||
}
|
||||
if (password.length < 6) {
|
||||
return Response.json({ error: '密码至少6位' }, { status: 400 });
|
||||
}
|
||||
// 服务端验证码校验(ENABLE_CAPTCHA 关闭时跳过)
|
||||
if (process.env.ENABLE_CAPTCHA !== 'false' && !verifyCaptcha(captcha_id, captcha_answer, captcha_sig)) {
|
||||
return Response.json({ error: '验证码错误,请重新计算' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const countResult = await pool.query('SELECT COUNT(*) FROM users');
|
||||
const isFirstUser = parseInt(countResult.rows[0].count) === 0;
|
||||
|
||||
const hash = await bcrypt.hash(password, 10);
|
||||
const avatar = 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) + '&background=6366f1&color=fff&size=64';
|
||||
const role = isFirstUser ? 'admin' : 'user';
|
||||
|
||||
const r = await pool.query(
|
||||
`INSERT INTO users (email, password_hash, username, avatar_url, role)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING id, username, avatar_url, role, created_at`,
|
||||
[email, hash, username, avatar, role]
|
||||
);
|
||||
|
||||
// 服务端审计:注册成功
|
||||
await logAudit(req, 'register', r.rows[0].id);
|
||||
return Response.json({
|
||||
user: r.rows[0],
|
||||
message: isFirstUser ? '你是第一个用户,已自动设为管理员!' : '注册成功',
|
||||
});
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
return Response.json({ error: '邮箱或用户名已被注册' }, { status: 400 });
|
||||
}
|
||||
return Response.json({ error: '注册失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
// POST /api/auth/reset-password — 用恢复码重置密码(公开)
|
||||
import bcrypt from 'bcryptjs';
|
||||
import pool from '@/lib/db';
|
||||
|
||||
export async function POST(req) {
|
||||
const { email, recoveryCode, newPassword } = await req.json();
|
||||
if (!email || !recoveryCode || !newPassword) {
|
||||
return Response.json({ error: '请填写完整信息' }, { status: 400 });
|
||||
}
|
||||
if (newPassword.length < 6) {
|
||||
return Response.json({ error: '密码至少6位' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const user = await pool.query('SELECT id FROM users WHERE email = $1', [email]);
|
||||
if (user.rows.length === 0) {
|
||||
return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||
}
|
||||
const codes = await pool.query(
|
||||
'SELECT id, code_hash FROM recovery_codes WHERE user_id = $1 AND is_used = false',
|
||||
[user.rows[0].id]
|
||||
);
|
||||
let matched = false;
|
||||
let matchedId = null;
|
||||
for (const row of codes.rows) {
|
||||
const valid = await bcrypt.compare(recoveryCode, row.code_hash);
|
||||
if (valid) { matched = true; matchedId = row.id; break; }
|
||||
}
|
||||
if (!matched) {
|
||||
return Response.json({ error: '恢复码无效或已使用' }, { status: 400 });
|
||||
}
|
||||
await pool.query('UPDATE recovery_codes SET is_used = true WHERE id = $1', [matchedId]);
|
||||
const hash = await bcrypt.hash(newPassword, 10);
|
||||
await pool.query('UPDATE users SET password_hash = $1 WHERE id = $2', [hash, user.rows[0].id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '重置失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// GET /api/captcha — 服务端验证码挑战(HMAC 签名答案,防前端绕过)
|
||||
import { generateCaptchaChallenge } from '@/lib/captcha';
|
||||
|
||||
export async function GET() {
|
||||
const ch = generateCaptchaChallenge();
|
||||
return Response.json({ id: ch.id, text: ch.text, sig: ch.sig });
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
// GET /api/conversations/[id]/messages, POST /api/conversations/[id]/messages
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export async function GET(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
if (!UUID_RE.test((await params).id)) {
|
||||
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||
}
|
||||
try {
|
||||
const check = await pool.query(`
|
||||
SELECT id FROM conversations
|
||||
WHERE id = $1 AND (user1_id = $2 OR user2_id = $2)
|
||||
`, [(await params).id, user.id]);
|
||||
if (check.rows.length === 0) {
|
||||
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||
}
|
||||
const r = await pool.query(`
|
||||
SELECT
|
||||
m.*,
|
||||
u.username as sender_username,
|
||||
u.avatar_url as sender_avatar_url
|
||||
FROM messages m
|
||||
JOIN users u ON m.sender_id = u.id
|
||||
WHERE m.conversation_id = $1
|
||||
ORDER BY m.created_at ASC
|
||||
`, [(await params).id]);
|
||||
await pool.query(`
|
||||
UPDATE messages SET is_read = true
|
||||
WHERE conversation_id = $1 AND sender_id != $2 AND is_read = false
|
||||
`, [(await params).id, user.id]);
|
||||
return Response.json(r.rows);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
if (!UUID_RE.test((await params).id)) {
|
||||
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||
}
|
||||
const { content } = await req.json();
|
||||
if (!content || content.trim().length === 0) {
|
||||
return Response.json({ error: '请填写消息内容' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const check = await pool.query(`
|
||||
SELECT id FROM conversations
|
||||
WHERE id = $1 AND (user1_id = $2 OR user2_id = $2)
|
||||
`, [(await params).id, user.id]);
|
||||
if (check.rows.length === 0) {
|
||||
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
|
||||
}
|
||||
const r = await pool.query(`
|
||||
INSERT INTO messages (conversation_id, sender_id, content)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING *
|
||||
`, [(await params).id, user.id, content]);
|
||||
await pool.query('UPDATE conversations SET last_message_at = NOW() WHERE id = $1', [(await params).id]);
|
||||
const userInfo = await pool.query('SELECT username, avatar_url FROM users WHERE id = $1', [user.id]);
|
||||
return Response.json({
|
||||
...r.rows[0],
|
||||
sender_username: userInfo.rows[0].username,
|
||||
sender_avatar_url: userInfo.rows[0].avatar_url,
|
||||
});
|
||||
} catch {
|
||||
return Response.json({ error: '发送失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
// GET /api/conversations, POST /api/conversations
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
|
||||
export async function GET(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
try {
|
||||
const r = await pool.query(`
|
||||
SELECT
|
||||
c.id,
|
||||
c.user1_id,
|
||||
c.user2_id,
|
||||
c.last_message_at,
|
||||
c.created_at,
|
||||
u.id as other_user_id,
|
||||
u.username as other_username,
|
||||
u.avatar_url as other_avatar_url,
|
||||
(SELECT COUNT(*) FROM messages WHERE conversation_id = c.id AND sender_id != $1 AND is_read = false) as unread_count,
|
||||
(SELECT content FROM messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) as last_message,
|
||||
(SELECT created_at FROM messages WHERE conversation_id = c.id ORDER BY created_at DESC LIMIT 1) as last_message_time
|
||||
FROM conversations c
|
||||
JOIN users u ON (u.id = c.user1_id OR u.id = c.user2_id) AND u.id != $1
|
||||
WHERE c.user1_id = $1 OR c.user2_id = $1
|
||||
ORDER BY c.last_message_at DESC
|
||||
`, [user.id]);
|
||||
return Response.json(r.rows);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
const { other_user_id } = await req.json();
|
||||
if (!other_user_id) {
|
||||
return Response.json({ error: '缺少对方用户ID' }, { status: 400 });
|
||||
}
|
||||
if (other_user_id === user.id) {
|
||||
return Response.json({ error: '不能与自己私信' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const userCheck = await pool.query('SELECT id FROM users WHERE id = $1', [other_user_id]);
|
||||
if (userCheck.rows.length === 0) {
|
||||
return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||
}
|
||||
const existing = await pool.query(`
|
||||
SELECT id FROM conversations
|
||||
WHERE (user1_id = $1 AND user2_id = $2) OR (user1_id = $2 AND user2_id = $1)
|
||||
`, [user.id, other_user_id]);
|
||||
if (existing.rows.length > 0) {
|
||||
return Response.json({ id: existing.rows[0].id });
|
||||
}
|
||||
const r = await pool.query(`
|
||||
INSERT INTO conversations (user1_id, user2_id)
|
||||
VALUES ($1, $2)
|
||||
RETURNING id
|
||||
`, [user.id, other_user_id]);
|
||||
return Response.json({ id: r.rows[0].id });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
// GET /api/custom-css — 公开获取自定义 CSS
|
||||
import { readFile } from 'fs/promises';
|
||||
import path from 'path';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const cssPath = path.join(process.cwd(), 'uploads', 'custom', 'style.css');
|
||||
const css = await readFile(cssPath, 'utf-8');
|
||||
return new Response(css, { headers: { 'Content-Type': 'text/css' } });
|
||||
} catch {
|
||||
return new Response('', { status: 404 });
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
// GET /api/custom-pages/[name] — 公开单个页面
|
||||
import pool from '@/lib/db';
|
||||
import { jsonWithEtag } from '@/lib/http-cache';
|
||||
|
||||
export async function GET(req, { params }) {
|
||||
try {
|
||||
const r = await pool.query(
|
||||
'SELECT id, name, title, content FROM custom_pages WHERE name = $1 AND enabled = true',
|
||||
[(await params).name]
|
||||
);
|
||||
if (r.rows.length === 0) {
|
||||
return Response.json({ error: '页面不存在' }, { status: 404 });
|
||||
}
|
||||
return jsonWithEtag(req, r.rows[0]);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
// GET /api/custom-pages — 公开页面列表
|
||||
import pool from '@/lib/db';
|
||||
import { jsonWithEtag } from '@/lib/http-cache';
|
||||
|
||||
export async function GET(req) {
|
||||
try {
|
||||
const r = await pool.query(
|
||||
'SELECT id, name, title FROM custom_pages WHERE enabled = true ORDER BY created_at'
|
||||
);
|
||||
return jsonWithEtag(req, r.rows);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
// GET /api/event-logs, POST /api/event-logs
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
|
||||
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
|
||||
export async function GET(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
try {
|
||||
const r = await pool.query(
|
||||
`SELECT el.*, u.username
|
||||
FROM event_logs el
|
||||
LEFT JOIN users u ON el.user_id = u.id
|
||||
ORDER BY el.created_at DESC
|
||||
LIMIT 100`
|
||||
);
|
||||
return Response.json(r.rows);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// 审计日志由服务端在关键操作后记录(对齐上游 PR #22)——
|
||||
// 客户端上报端点已移除,防止伪造审计记录
|
||||
@@ -1,18 +0,0 @@
|
||||
// DELETE /api/links/[id]
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
|
||||
export async function DELETE(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
try {
|
||||
await pool.query('DELETE FROM friendly_links WHERE id = $1', [(await params).id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
// GET /api/links, POST /api/links
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
import { jsonWithEtag } from '@/lib/http-cache';
|
||||
|
||||
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
|
||||
export async function GET(req) {
|
||||
try {
|
||||
const r = await pool.query('SELECT * FROM friendly_links ORDER BY sort_order');
|
||||
return jsonWithEtag(req, r.rows);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
|
||||
const { title, url } = await req.json();
|
||||
if (!title || !url) {
|
||||
return Response.json({ error: '请填写完整信息' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const r = await pool.query(
|
||||
`INSERT INTO friendly_links (title, url)
|
||||
VALUES ($1, $2)
|
||||
RETURNING *`,
|
||||
[title, url]
|
||||
);
|
||||
return Response.json(r.rows[0]);
|
||||
} catch {
|
||||
return Response.json({ error: '添加失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
// PUT /api/messages/[id]/read — 标记消息已读
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
if (!UUID_RE.test((await params).id)) {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
try {
|
||||
await pool.query(`
|
||||
UPDATE messages SET is_read = true
|
||||
WHERE id = $1 AND sender_id != $2
|
||||
`, [(await params).id, user.id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
// PUT /api/notifications/[id]/read — 标记单条已读
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
if (!UUID_RE.test((await params).id)) {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
try {
|
||||
await pool.query(
|
||||
'UPDATE notifications SET is_read = true WHERE id = $1 AND user_id = $2',
|
||||
[(await params).id, user.id]
|
||||
);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
// PUT /api/notifications/read-all — 全部标记已读
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
export async function PUT(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
try {
|
||||
await pool.query('UPDATE notifications SET is_read = true WHERE user_id = $1', [user.id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
// GET /api/notifications — 我的通知列表
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
export async function GET(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
try {
|
||||
const r = await pool.query(
|
||||
'SELECT id, type, title, content, link, is_read, created_at FROM notifications WHERE user_id = $1 ORDER BY created_at DESC LIMIT 50',
|
||||
[user.id]
|
||||
);
|
||||
return Response.json(r.rows);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
// PUT /api/posts/[id]/pin — 置顶/取消置顶(管理员)
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
import { createNotification } from '@/lib/notify';
|
||||
import { resolvePostReference } from '@/lib/post-reference';
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
try {
|
||||
const reference = await resolvePostReference((await params).id);
|
||||
if (!reference) {
|
||||
return Response.json({ error: '帖子不存在' }, { status: 404 });
|
||||
}
|
||||
const post = await pool.query(
|
||||
'SELECT id, user_id, post_number, is_pinned FROM posts WHERE id = $1',
|
||||
[reference.id]
|
||||
);
|
||||
const isPinned = post.rows[0].is_pinned;
|
||||
|
||||
const r = await pool.query(
|
||||
`UPDATE posts SET is_pinned = $1, pinned_at = $2 WHERE id = $3 RETURNING *`,
|
||||
[!isPinned, !isPinned ? new Date().toISOString() : null, reference.id]
|
||||
);
|
||||
|
||||
await createNotification(
|
||||
post.rows[0].user_id,
|
||||
'system',
|
||||
isPinned ? '你的帖子已被取消置顶' : '你的帖子已被置顶',
|
||||
isPinned ? '管理员取消了你的帖子置顶' : '管理员把你的帖子置顶了',
|
||||
'/post/' + post.rows[0].post_number
|
||||
);
|
||||
|
||||
return Response.json(r.rows[0]);
|
||||
} catch {
|
||||
return Response.json({ error: '操作失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
// GET /api/posts/[id]/replies, POST /api/posts/[id]/replies
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
import { jsonWithEtag } from '@/lib/http-cache';
|
||||
import { verifyCaptcha } from '@/lib/captcha';
|
||||
import { logAudit } from '@/lib/audit';
|
||||
import { getReplySchemaCapabilities } from '@/lib/reply-schema';
|
||||
import { resolvePostReference } from '@/lib/post-reference';
|
||||
|
||||
function repliesSelectSql(capabilities) {
|
||||
if (capabilities.replyToId) {
|
||||
return `SELECT r.id, r.post_id, r.user_id, r.content, r.created_at,
|
||||
r.reply_to_id, u.username, u.avatar_url,
|
||||
ru.username AS reply_to_username
|
||||
FROM replies r
|
||||
JOIN users u ON r.user_id = u.id
|
||||
LEFT JOIN replies rt ON r.reply_to_id = rt.id
|
||||
LEFT JOIN users ru ON rt.user_id = ru.id
|
||||
WHERE r.post_id = $1
|
||||
ORDER BY r.created_at ASC`;
|
||||
}
|
||||
|
||||
if (capabilities.replyToUsername) {
|
||||
return `SELECT r.id, r.post_id, r.user_id, r.content, r.created_at,
|
||||
NULL::uuid AS reply_to_id,
|
||||
u.username, u.avatar_url,
|
||||
r.reply_to_username
|
||||
FROM replies r
|
||||
JOIN users u ON r.user_id = u.id
|
||||
WHERE r.post_id = $1
|
||||
ORDER BY r.created_at ASC`;
|
||||
}
|
||||
|
||||
return `SELECT r.id, r.post_id, r.user_id, r.content, r.created_at,
|
||||
NULL::uuid AS reply_to_id,
|
||||
NULL::varchar AS reply_to_username,
|
||||
u.username, u.avatar_url
|
||||
FROM replies r
|
||||
JOIN users u ON r.user_id = u.id
|
||||
WHERE r.post_id = $1
|
||||
ORDER BY r.created_at ASC`;
|
||||
}
|
||||
|
||||
export async function GET(req, { params }) {
|
||||
try {
|
||||
const reference = await resolvePostReference((await params).id);
|
||||
if (!reference) return Response.json({ error: '帖子不存在' }, { status: 404 });
|
||||
const capabilities = await getReplySchemaCapabilities();
|
||||
const r = await pool.query(repliesSelectSql(capabilities), [reference.id]);
|
||||
return jsonWithEtag(req, r.rows);
|
||||
} catch (error) {
|
||||
console.error('[replies] list failed:', error?.code || error?.message);
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
const { content, captcha_id, captcha_answer, captcha_sig, reply_to_id, reply_to_username } = await req.json();
|
||||
if (!content || content.trim().length === 0) {
|
||||
return Response.json({ error: '请填写回复内容' }, { status: 400 });
|
||||
}
|
||||
// 服务端验证码校验(ENABLE_CAPTCHA 关闭时跳过)
|
||||
if (process.env.ENABLE_CAPTCHA !== 'false' && !verifyCaptcha(captcha_id, captcha_answer, captcha_sig)) {
|
||||
return Response.json({ error: '验证码错误,请重新计算' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const reference = await resolvePostReference((await params).id);
|
||||
if (!reference) return Response.json({ error: '帖子不存在' }, { status: 404 });
|
||||
const postId = reference.id;
|
||||
const capabilities = await getReplySchemaCapabilities();
|
||||
let replyTargetUsername = null;
|
||||
|
||||
if (reply_to_id) {
|
||||
const target = await pool.query(
|
||||
`SELECT u.username
|
||||
FROM replies r
|
||||
JOIN users u ON u.id = r.user_id
|
||||
WHERE r.id = $1 AND r.post_id = $2`,
|
||||
[reply_to_id, postId]
|
||||
);
|
||||
if (!target.rows[0]) {
|
||||
return Response.json({ error: '回复目标不存在' }, { status: 400 });
|
||||
}
|
||||
replyTargetUsername = target.rows[0].username;
|
||||
} else if (reply_to_username && capabilities.replyToUsername) {
|
||||
const target = await pool.query(
|
||||
`SELECT u.username
|
||||
FROM replies r
|
||||
JOIN users u ON u.id = r.user_id
|
||||
WHERE r.post_id = $1 AND u.username = $2
|
||||
LIMIT 1`,
|
||||
[postId, reply_to_username]
|
||||
);
|
||||
if (!target.rows[0]) {
|
||||
return Response.json({ error: '回复目标不存在' }, { status: 400 });
|
||||
}
|
||||
replyTargetUsername = target.rows[0].username;
|
||||
}
|
||||
|
||||
let r;
|
||||
if (capabilities.replyToId) {
|
||||
r = await pool.query(
|
||||
`INSERT INTO replies (post_id, user_id, content, reply_to_id)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING *`,
|
||||
[postId, user.id, content.trim(), reply_to_id || null]
|
||||
);
|
||||
} else if (capabilities.replyToUsername) {
|
||||
r = await pool.query(
|
||||
`INSERT INTO replies (post_id, user_id, content, reply_to_username)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING *, NULL::uuid AS reply_to_id`,
|
||||
[postId, user.id, content.trim(), replyTargetUsername]
|
||||
);
|
||||
} else {
|
||||
r = await pool.query(
|
||||
`INSERT INTO replies (post_id, user_id, content)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING *, NULL::uuid AS reply_to_id, NULL::varchar AS reply_to_username`,
|
||||
[postId, user.id, content.trim()]
|
||||
);
|
||||
}
|
||||
await logAudit(req, 'create_reply', user.id);
|
||||
await pool.query('UPDATE posts SET updated_at = NOW() WHERE id = $1', [postId]);
|
||||
return Response.json(r.rows[0]);
|
||||
} catch (error) {
|
||||
console.error('[replies] create failed:', error?.code || error?.message);
|
||||
return Response.json({ error: '回复失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
// GET /api/posts/[id], DELETE /api/posts/[id]
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
import { jsonWithEtag } from '@/lib/http-cache';
|
||||
import { resolvePostReference } from '@/lib/post-reference';
|
||||
|
||||
function invalidId() {
|
||||
return Response.json({ error: '帖子不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
export async function GET(req, { params }) {
|
||||
try {
|
||||
const reference = await resolvePostReference((await params).id);
|
||||
if (!reference) return invalidId();
|
||||
const r = await pool.query(
|
||||
`SELECT p.*, u.username, u.avatar_url, u.signature
|
||||
FROM posts p
|
||||
JOIN users u ON p.user_id = u.id
|
||||
WHERE p.id = $1`,
|
||||
[reference.id]
|
||||
);
|
||||
if (r.rows.length === 0) {
|
||||
return invalidId();
|
||||
}
|
||||
return jsonWithEtag(req, r.rows[0]);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
const { title, content, images } = await req.json();
|
||||
if (!content || content.trim().length === 0) {
|
||||
return Response.json({ error: '请填写内容' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const reference = await resolvePostReference((await params).id);
|
||||
if (!reference) return invalidId();
|
||||
const post = await pool.query('SELECT user_id, images FROM posts WHERE id = $1', [reference.id]);
|
||||
if (post.rows.length === 0) return invalidId();
|
||||
if (post.rows[0].user_id !== user.id) {
|
||||
return Response.json({ error: '无权限编辑此帖子' }, { status: 403 });
|
||||
}
|
||||
// images: 可选,传入完整图片 URL 数组(编辑时替换全部图片);不传则保留原图
|
||||
const r = await pool.query(
|
||||
`UPDATE posts SET title = $1, content = $2, images = $3, edited_at = NOW() WHERE id = $4 RETURNING *`,
|
||||
[title || '无标题', content, Array.isArray(images) ? images : post.rows[0].images || [], reference.id]
|
||||
);
|
||||
return Response.json(r.rows[0]);
|
||||
} catch {
|
||||
return Response.json({ error: '编辑失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
try {
|
||||
const reference = await resolvePostReference((await params).id);
|
||||
if (!reference) return invalidId();
|
||||
const post = await pool.query('SELECT user_id FROM posts WHERE id = $1', [reference.id]);
|
||||
if (post.rows.length === 0) {
|
||||
return invalidId();
|
||||
}
|
||||
const u = await pool.query('SELECT role FROM users WHERE id = $1', [user.id]);
|
||||
if (post.rows[0].user_id !== user.id && u.rows[0]?.role !== 'admin') {
|
||||
return Response.json({ error: '无权限删除此帖子' }, { status: 403 });
|
||||
}
|
||||
await pool.query('DELETE FROM posts WHERE id = $1', [reference.id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
// GET /api/posts, POST /api/posts — 支持 ?sort= & ?user_id= & 分页
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
import { jsonWithEtag } from '@/lib/http-cache';
|
||||
import { verifyCaptcha } from '@/lib/captcha';
|
||||
import { logAudit } from '@/lib/audit';
|
||||
import { ensurePostNumberSchema } from '@/lib/post-reference';
|
||||
|
||||
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
|
||||
export async function GET(req) {
|
||||
const url = new URL(req.url);
|
||||
const sort = url.searchParams.get('sort') === 'hot' ? 'updated_at' : 'created_at';
|
||||
const userId = url.searchParams.get('user_id');
|
||||
const page = Math.max(1, parseInt(url.searchParams.get('page')) || 1);
|
||||
// 分页边界:limit 封顶 50,page 封顶 10000(防深分页 DoS)
|
||||
const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get('limit')) || 20));
|
||||
const maxPage = Math.max(1, Math.ceil(200000 / limit));
|
||||
const safePage = Math.min(page, maxPage);
|
||||
const offset = (safePage - 1) * limit;
|
||||
|
||||
try {
|
||||
await ensurePostNumberSchema();
|
||||
const params = [];
|
||||
let where = '';
|
||||
if (userId) {
|
||||
where = ' WHERE p.user_id = $1';
|
||||
(await params).push(userId);
|
||||
}
|
||||
|
||||
const countResult = await pool.query(`SELECT COUNT(*) as total FROM posts p${where}`, params);
|
||||
const total = parseInt(countResult.rows[0]?.total || 0);
|
||||
|
||||
const r = await pool.query(`
|
||||
SELECT
|
||||
p.*,
|
||||
u.username,
|
||||
u.avatar_url,
|
||||
u.signature,
|
||||
(SELECT COUNT(*) FROM replies WHERE post_id = p.id) as reply_count
|
||||
FROM posts p
|
||||
JOIN users u ON p.user_id = u.id
|
||||
${where}
|
||||
ORDER BY is_pinned DESC, pinned_at DESC NULLS LAST, ${sort} DESC
|
||||
LIMIT $${(await params).length + 1} OFFSET $${(await params).length + 2}
|
||||
`, [...params, limit, offset]);
|
||||
|
||||
return jsonWithEtag(req, {
|
||||
data: r.rows,
|
||||
pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
|
||||
});
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
const { title, content, images, captcha_id, captcha_answer, captcha_sig } = await req.json();
|
||||
if (!content || content.trim().length === 0) {
|
||||
return Response.json({ error: '请填写内容' }, { status: 400 });
|
||||
}
|
||||
// 服务端验证码校验(ENABLE_CAPTCHA 关闭时跳过)
|
||||
if (process.env.ENABLE_CAPTCHA !== 'false' && !verifyCaptcha(captcha_id, captcha_answer, captcha_sig)) {
|
||||
return Response.json({ error: '验证码错误,请重新计算' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
await ensurePostNumberSchema();
|
||||
const r = await pool.query(
|
||||
`INSERT INTO posts (user_id, title, content, images)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING *`,
|
||||
[user.id, title || '无标题', content, images || []]
|
||||
);
|
||||
await logAudit(req, 'create_post', user.id);
|
||||
return Response.json(r.rows[0]);
|
||||
} catch {
|
||||
return Response.json({ error: '发布失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
// DELETE /api/replies/[id]
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export async function DELETE(req, { params }) {
|
||||
if (!UUID_RE.test((await params).id)) {
|
||||
return Response.json({ error: '回复不存在' }, { status: 404 });
|
||||
}
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
try {
|
||||
const reply = await pool.query('SELECT user_id FROM replies WHERE id = $1', [(await params).id]);
|
||||
if (reply.rows.length === 0) {
|
||||
return Response.json({ error: '回复不存在' }, { status: 404 });
|
||||
}
|
||||
const u = await pool.query('SELECT role FROM users WHERE id = $1', [user.id]);
|
||||
if (reply.rows[0].user_id !== user.id && u.rows[0]?.role !== 'admin') {
|
||||
return Response.json({ error: '无权限删除此回复' }, { status: 403 });
|
||||
}
|
||||
await pool.query('DELETE FROM replies WHERE id = $1', [(await params).id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '删除失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
// PUT /api/reports/[id]
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
if (!UUID_RE.test((await params).id)) {
|
||||
return Response.json({ error: '操作失败,请稍后重试' }, { status: 404 });
|
||||
}
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
|
||||
const { status, note } = await req.json();
|
||||
if (!['pending', 'approved', 'rejected'].includes(status)) {
|
||||
return Response.json({ error: '无效的状态' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
await pool.query(
|
||||
`UPDATE reports
|
||||
SET status = $1, handled_at = NOW(), handler_id = $2, handler_note = $3
|
||||
WHERE id = $4`,
|
||||
[status, user.id, note || '', (await params).id]
|
||||
);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '操作失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
// GET /api/reports, POST /api/reports
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
import { resolvePostReference } from '@/lib/post-reference';
|
||||
|
||||
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
|
||||
export async function GET(req) {
|
||||
const user = getUser(req);
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
try {
|
||||
const r = await pool.query(`
|
||||
SELECT
|
||||
r.*,
|
||||
reporter.username as reporter_name,
|
||||
handler.username as handler_name,
|
||||
p.title as post_title,
|
||||
p.content as post_content
|
||||
FROM reports r
|
||||
JOIN users reporter ON r.reporter_id = reporter.id
|
||||
LEFT JOIN users handler ON r.handler_id = handler.id
|
||||
LEFT JOIN posts p ON r.post_id = p.id
|
||||
ORDER BY r.created_at DESC
|
||||
`);
|
||||
return Response.json(r.rows);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
const { post_id, reason } = await req.json();
|
||||
if (!post_id || !reason) {
|
||||
return Response.json({ error: '请填写完整信息' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const post = await resolvePostReference(post_id);
|
||||
if (!post) return Response.json({ error: '帖子不存在' }, { status: 404 });
|
||||
const existing = await pool.query(
|
||||
'SELECT id FROM reports WHERE post_id = $1 AND reporter_id = $2 AND status = $3',
|
||||
[post.id, user.id, 'pending']
|
||||
);
|
||||
if (existing.rows.length > 0) {
|
||||
return Response.json({ error: '你已经举报过此帖子,请等待处理' }, { status: 400 });
|
||||
}
|
||||
await pool.query(
|
||||
`INSERT INTO reports (post_id, reporter_id, reason)
|
||||
VALUES ($1, $2, $3)`,
|
||||
[post.id, user.id, reason]
|
||||
);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '举报失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
// GET /api/settings, PUT /api/settings
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, requireAdmin } from '@/lib/auth';
|
||||
import { jsonWithEtag } from '@/lib/http-cache';
|
||||
|
||||
const VERSION_COMMIT = (process.env.FORUMLIFY_COMMIT || 'unknown').slice(0, 7);
|
||||
|
||||
// 避免 GET 被静态优化导致 PUT 405(动态接口,不能缓存)
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function GET(req) {
|
||||
try {
|
||||
// 确保 forum_name 始终存在(未设置过则初始化默认值),前端拿到后显示
|
||||
await pool.query(
|
||||
`INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
|
||||
ON CONFLICT (key) DO NOTHING`
|
||||
);
|
||||
const r = await pool.query('SELECT key, value FROM settings ORDER BY key');
|
||||
const settings = {};
|
||||
r.rows.forEach((row) => { settings[row.key] = row.value; });
|
||||
delete settings.favicon_object;
|
||||
// 兜底:即使插入失败也保证返回 forum_name
|
||||
if (!settings.forum_name) settings.forum_name = 'Forumlify';
|
||||
settings.version_commit = VERSION_COMMIT;
|
||||
return jsonWithEtag(req, settings);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(req) {
|
||||
const user = getUser(req);
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
|
||||
const { forum_name } = await req.json();
|
||||
if (!forum_name || forum_name.trim().length === 0) {
|
||||
return Response.json({ error: '论坛名称不能为空' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
await pool.query(
|
||||
`INSERT INTO settings (key, value) VALUES ($1, $2)
|
||||
ON CONFLICT (key) DO UPDATE SET value = $2, updated_at = NOW()`,
|
||||
['forum_name', forum_name.trim()]
|
||||
);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '更新失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
// GET /api/stats
|
||||
import pool from '@/lib/db';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const [postsRes, usersRes] = await Promise.all([
|
||||
pool.query('SELECT COUNT(*) FROM posts'),
|
||||
pool.query('SELECT COUNT(*) FROM users'),
|
||||
]);
|
||||
return Response.json({
|
||||
posts: parseInt(postsRes.rows[0].count) || 0,
|
||||
users: parseInt(usersRes.rows[0].count) || 0,
|
||||
topics: parseInt(postsRes.rows[0].count) || 0,
|
||||
online: Math.floor(Math.random() * 20) + 5,
|
||||
});
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
// POST /api/upload — 图片上传 (multipart/form-data)
|
||||
// 安全:校验文件 magic bytes(不信任客户端 MIME/文件名),服务器生成 UUID 文件名
|
||||
import path from 'path';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { getUser } from '@/lib/auth';
|
||||
import { sniffImage } from '@/lib/image-type';
|
||||
import { saveObject } from '@/lib/storage';
|
||||
|
||||
const MAX_SIZE = 5 * 1024 * 1024;
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
export async function POST(req) {
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
|
||||
const form = await req.formData();
|
||||
const file = form.get('file');
|
||||
if (!file || typeof file === 'string') {
|
||||
return Response.json({ error: '请选择图片' }, { status: 400 });
|
||||
}
|
||||
if (file.size > MAX_SIZE) {
|
||||
return Response.json({ error: '图片大小不能超过 5MB' }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const buffer = Buffer.from(await file.arrayBuffer());
|
||||
const sniff = sniffImage(buffer);
|
||||
if (!sniff) {
|
||||
return Response.json({ error: '不支持的图片格式' }, { status: 400 });
|
||||
}
|
||||
// 服务器生成 UUID 文件名 + 嗅探出的扩展名(不信任客户端文件名)
|
||||
const name = randomUUID() + sniff.ext;
|
||||
const { url } = await saveObject(name, buffer, sniff.mime);
|
||||
return Response.json({ url });
|
||||
} catch {
|
||||
return Response.json({ error: '上传失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
// GET /api/uploads/[name] — 提供上传的图片文件(本地存储模式)
|
||||
// (next.config.js 中 rewrites 把 /uploads/* 指向这里,URL 保持 /uploads/... 不变)
|
||||
// S3 模式下走 S3_PUBLIC_URL 直接访问,此路由不生效(rewrite 仍指向但返回 404 前可跳过)
|
||||
import path from 'path';
|
||||
import { getObject, STORAGE_TYPE } from '@/lib/storage';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
const MIME = {
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.ico': 'image/x-icon',
|
||||
};
|
||||
|
||||
export async function GET(req, { params }) {
|
||||
const name = (await params).name;
|
||||
// 防止路径穿越
|
||||
if (!/^[\w-]+\.\w+$/.test(name)) {
|
||||
return new Response('Not Found', { status: 404 });
|
||||
}
|
||||
// S3 模式下文件不在本地,由 S3_PUBLIC_URL 提供
|
||||
if (STORAGE_TYPE === 's3') {
|
||||
return new Response('Not Found', { status: 404 });
|
||||
}
|
||||
try {
|
||||
const data = await getObject(name);
|
||||
if (!data) return new Response('Not Found', { status: 404 });
|
||||
const ext = path.extname(name).toLowerCase();
|
||||
return new Response(new Uint8Array(data), {
|
||||
headers: { 'Content-Type': MIME[ext] || 'application/octet-stream' },
|
||||
});
|
||||
} catch {
|
||||
return new Response('Not Found', { status: 404 });
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
// PUT /api/users/[id]/avatar — 修改头像
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
if ((await params).id !== user.id) {
|
||||
return Response.json({ error: '无权限修改他人头像' }, { status: 403 });
|
||||
}
|
||||
const { avatar_url } = await req.json();
|
||||
if (!avatar_url) {
|
||||
return Response.json({ error: '请提供头像地址' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
await pool.query('UPDATE users SET avatar_url = $1 WHERE id = $2', [avatar_url, (await params).id]);
|
||||
return Response.json({ success: true, avatar_url });
|
||||
} catch {
|
||||
return Response.json({ error: '更新失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
// PUT /api/users/[id]/email — 修改邮箱(需密码验证)
|
||||
import bcrypt from 'bcryptjs';
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
if ((await params).id !== user.id) {
|
||||
return Response.json({ error: '无权限' }, { status: 403 });
|
||||
}
|
||||
const { password, newEmail } = await req.json();
|
||||
if (!password || !newEmail) {
|
||||
return Response.json({ error: '请填写完整信息' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const u = await pool.query('SELECT password_hash FROM users WHERE id = $1', [(await params).id]);
|
||||
if (u.rows.length === 0) {
|
||||
return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||
}
|
||||
const valid = await bcrypt.compare(password, u.rows[0].password_hash);
|
||||
if (!valid) {
|
||||
return Response.json({ error: '密码错误' }, { status: 400 });
|
||||
}
|
||||
const existing = await pool.query('SELECT id FROM users WHERE email = $1 AND id != $2', [newEmail, (await params).id]);
|
||||
if (existing.rows.length > 0) {
|
||||
return Response.json({ error: '邮箱已被占用' }, { status: 400 });
|
||||
}
|
||||
await pool.query('UPDATE users SET email = $1 WHERE id = $2', [newEmail, (await params).id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '修改失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
// PUT /api/users/[id]/password — 修改密码
|
||||
import bcrypt from 'bcryptjs';
|
||||
import pool from '@/lib/db';
|
||||
import { getUser } from '@/lib/auth';
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
const user = getUser(req);
|
||||
if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
if ((await params).id !== user.id) {
|
||||
return Response.json({ error: '无权限' }, { status: 403 });
|
||||
}
|
||||
const { oldPassword, newPassword } = await req.json();
|
||||
if (!oldPassword || !newPassword) {
|
||||
return Response.json({ error: '请填写完整信息' }, { status: 400 });
|
||||
}
|
||||
if (newPassword.length < 6) {
|
||||
return Response.json({ error: '新密码至少6位' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const u = await pool.query('SELECT password_hash FROM users WHERE id = $1', [(await params).id]);
|
||||
if (u.rows.length === 0) {
|
||||
return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||
}
|
||||
const valid = await bcrypt.compare(oldPassword, u.rows[0].password_hash);
|
||||
if (!valid) {
|
||||
return Response.json({ error: '当前密码错误' }, { status: 400 });
|
||||
}
|
||||
const hash = await bcrypt.hash(newPassword, 10);
|
||||
await pool.query('UPDATE users SET password_hash = $1 WHERE id = $2', [hash, (await params).id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '修改失败,请稍后重试' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
// PUT /api/users/[id]/role (admin 改角色)
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, isSuperAdmin, requireAdmin } from '@/lib/auth';
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
const { id } = await params;
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
|
||||
const { role } = await req.json();
|
||||
if (!['user', 'admin'].includes(role)) {
|
||||
return Response.json({ error: '无效的角色' }, { status: 400 });
|
||||
}
|
||||
if (id === user.id) {
|
||||
return Response.json({ error: '不能修改自己的角色' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
if (role !== 'admin' && await isSuperAdmin(id)) {
|
||||
return Response.json({ error: '不能降级超级管理员' }, { status: 403 });
|
||||
}
|
||||
await pool.query('UPDATE users SET role = $1 WHERE id = $2', [role, id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
// PUT /api/users/[id] (更新资料), PUT /api/users/[id]/role (改角色)
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, isSuperAdmin, requireAdmin } from '@/lib/auth';
|
||||
|
||||
export async function PUT(req, { params }) {
|
||||
const { id } = await params;
|
||||
const user = getUser(req);
|
||||
if (!user) {
|
||||
return Response.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = await req.json();
|
||||
const { username, bio, signature, role } = body;
|
||||
|
||||
// 改角色:仅管理员
|
||||
if (role !== undefined) {
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
if (!['user', 'admin'].includes(role)) {
|
||||
return Response.json({ error: '无效的角色' }, { status: 400 });
|
||||
}
|
||||
if (id === user.id) {
|
||||
return Response.json({ error: '不能修改自己的角色' }, { status: 400 });
|
||||
}
|
||||
// 超级管理员不能被降级(兼容旧的角色更新入口)
|
||||
if (role !== 'admin' && await isSuperAdmin(id)) {
|
||||
return Response.json({ error: '不能降级超级管理员' }, { status: 403 });
|
||||
}
|
||||
try {
|
||||
await pool.query('UPDATE users SET role = $1 WHERE id = $2', [role, id]);
|
||||
return Response.json({ success: true });
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// 更新资料:仅本人
|
||||
if (id !== user.id) {
|
||||
return Response.json({ error: '无权限修改他人资料' }, { status: 403 });
|
||||
}
|
||||
try {
|
||||
await pool.query('UPDATE users SET username = $1, bio = $2, signature = $3 WHERE id = $4', [username, bio || '', signature || '', id]);
|
||||
return Response.json({ success: true });
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
return Response.json({ error: '用户名已被占用' }, { status: 400 });
|
||||
}
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
// GET /api/users/profile/:username — 用户公开信息(无需登录,用于用户主页)
|
||||
import pool from '@/lib/db';
|
||||
import { jsonWithEtag } from '@/lib/http-cache';
|
||||
|
||||
export async function GET(req, { params }) {
|
||||
const { username } = await params;
|
||||
if (!username) {
|
||||
return Response.json({ error: '缺少用户名' }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
const r = await pool.query(
|
||||
'SELECT id, username, avatar_url, bio, role, signature, created_at FROM users WHERE username = $1',
|
||||
[username]
|
||||
);
|
||||
if (r.rows.length === 0) {
|
||||
return Response.json({ error: '用户不存在' }, { status: 404 });
|
||||
}
|
||||
return jsonWithEtag(req, r.rows[0]);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
// GET /api/users (admin) — 支持 ?username= 按用户名查询
|
||||
import pool from '@/lib/db';
|
||||
import { getUser, getSuperAdminId, requireAdmin } from '@/lib/auth';
|
||||
|
||||
export async function GET(req) {
|
||||
const user = getUser(req);
|
||||
const forbidden = await requireAdmin(user);
|
||||
if (forbidden) return forbidden;
|
||||
|
||||
const url = new URL(req.url);
|
||||
const username = url.searchParams.get('username');
|
||||
|
||||
try {
|
||||
// 超级管理员 = 最早注册的 admin(对齐迁移:无 admin 时自动提升最早注册用户)
|
||||
const superAdminId = await getSuperAdminId();
|
||||
|
||||
let query = 'SELECT id, username, avatar_url, bio, role, created_at FROM users';
|
||||
const params = [];
|
||||
if (username) {
|
||||
query += ' WHERE username = $1';
|
||||
(await params).push(username);
|
||||
}
|
||||
query += ' ORDER BY created_at DESC';
|
||||
const r = await pool.query(query, params);
|
||||
// 标记超级管理员(前端显示"超级管理员")
|
||||
const rows = r.rows.map((u) => ({ ...u, is_super: u.id === superAdminId }));
|
||||
return Response.json(rows);
|
||||
} catch {
|
||||
return Response.json({ error: '服务器错误' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
// 全局布局
|
||||
import './globals.css';
|
||||
import { cookies, headers } from 'next/headers';
|
||||
import CustomCssLoader from '@/components/CustomCssLoader';
|
||||
import { ToastProvider } from '@/components/Toast';
|
||||
import I18nInit from '@/components/I18nInit';
|
||||
|
||||
export const metadata = {
|
||||
// 初始标题用默认论坛名(AppProvider 加载期轮换 Loading.,完成后覆盖为真实名)。
|
||||
// 注意:不能设 'Loading...' —— Next.js 客户端重渲染会重置 <title> 为 metadata 值,
|
||||
// 导致加载完成后标题又变回 "Loading..."。
|
||||
title: 'Forumlify',
|
||||
description: 'Forumlify - 简洁优雅的现代社区系统',
|
||||
};
|
||||
|
||||
// cookies()/headers() 是动态 API:禁止静态优化
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default async function RootLayout({ children }) {
|
||||
// 语言检测:用户配置 cookie 优先,否则按浏览器 Accept-Language
|
||||
let lng = 'zh';
|
||||
try {
|
||||
const cookieStore = await cookies();
|
||||
const saved = cookieStore.get('forumlify-lang')?.value;
|
||||
if (saved === 'en' || saved === 'zh') {
|
||||
lng = saved;
|
||||
} else {
|
||||
const hdrs = await headers();
|
||||
const accept = (hdrs.get('accept-language') || '').toLowerCase();
|
||||
if (accept.startsWith('en')) lng = 'en';
|
||||
}
|
||||
} catch (e) { /* 默认 zh */ }
|
||||
|
||||
return (
|
||||
<html lang={lng === 'en' ? 'en' : 'zh-CN'} suppressHydrationWarning>
|
||||
<head>
|
||||
</head>
|
||||
<body>
|
||||
{/* 首帧初始化(主题防 FOUC + 论坛名首帧显示):
|
||||
script 放 body 首个子元素(children 前),React 官方防 FOUC 模式 */}
|
||||
<script dangerouslySetInnerHTML={{ __html: `(function(){
|
||||
try {
|
||||
var t = localStorage.getItem('forumlify-theme');
|
||||
if (!t) { t = (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light'; }
|
||||
document.documentElement.setAttribute('data-theme', t);
|
||||
} catch (e) {}
|
||||
try { var n = localStorage.getItem('forumlify-forum-name'); if (n) document.title = n; } catch (e) {}
|
||||
// 加载页论坛名不再由脚本注入 DOM——由 Server Component 读 cookie 首帧输出,
|
||||
// React 状态渲染,SSR/客户端一致,无 hydration mismatch
|
||||
})();` }} />
|
||||
<ToastProvider>
|
||||
<I18nInit lng={lng} />
|
||||
<CustomCssLoader />
|
||||
{children}
|
||||
</ToastProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
// 主页:Server Component,路径页面共用同一个客户端应用外壳。
|
||||
import ForumPage from './ForumPage';
|
||||
|
||||
// cookies() 是动态 API:禁止静态优化,每次请求 SSR
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default function Home() {
|
||||
return <ForumPage />;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import ForumPage from '../../ForumPage';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default function PostPage() {
|
||||
return <ForumPage />;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import ForumPage from '../../ForumPage';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default function UserPage() {
|
||||
return <ForumPage />;
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
coverage:
|
||||
status:
|
||||
project:
|
||||
default:
|
||||
target: auto
|
||||
threshold: 1%
|
||||
patch:
|
||||
default:
|
||||
target: auto
|
||||
threshold: 1%
|
||||
|
||||
ignore:
|
||||
- "test/**"
|
||||
- "scripts/**"
|
||||
@@ -1,76 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 账户安全:修改密码 + 修改邮箱
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
import { useToast } from './Toast';
|
||||
|
||||
export default function AccountSecurity() {
|
||||
const { currentUser } = useApp();
|
||||
const { t } = useTranslation();
|
||||
const { toast } = useToast();
|
||||
const [oldPassword, setOldPassword] = useState('');
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
const [pwStatus, setPwStatus] = useState(null);
|
||||
const [emailPassword, setEmailPassword] = useState('');
|
||||
const [newEmail, setNewEmail] = useState('');
|
||||
const [emailStatus, setEmailStatus] = useState(null);
|
||||
|
||||
const changePassword = async () => {
|
||||
if (!oldPassword || !newPassword) { toast(t('security.fillAll'), 'warning'); return; }
|
||||
if (newPassword.length < 6) { toast(t('security.pwMin'), 'warning'); return; }
|
||||
try {
|
||||
await API.updatePassword(currentUser.id, oldPassword, newPassword);
|
||||
setPwStatus({ ok: true, msg: t('security.pwChanged') });
|
||||
setOldPassword('');
|
||||
setNewPassword('');
|
||||
} catch (err) {
|
||||
setPwStatus({ ok: false, msg: err.message });
|
||||
}
|
||||
};
|
||||
|
||||
const changeEmail = async () => {
|
||||
if (!emailPassword || !newEmail) { toast(t('security.fillAll'), 'warning'); return; }
|
||||
try {
|
||||
await API.updateEmail(currentUser.id, emailPassword, newEmail);
|
||||
setEmailStatus({ ok: true, msg: t('security.emailChanged') });
|
||||
setEmailPassword('');
|
||||
setNewEmail('');
|
||||
} catch (err) {
|
||||
setEmailStatus({ ok: false, msg: err.message });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ marginTop: 16, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
|
||||
<h3 style={{ fontSize: 16, marginBottom: 12 }}><Icon name="lock" size={16} /> {t('security.title')}</h3>
|
||||
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>{t('security.currentPw')}</label>
|
||||
<input type="password" value={oldPassword} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setOldPassword(e.target.value)} />
|
||||
</div>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>{t('security.newPw')}</label>
|
||||
<input type="password" value={newPassword} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setNewPassword(e.target.value)} />
|
||||
</div>
|
||||
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={changePassword}>{t('security.changePw')}</button>
|
||||
{pwStatus && <div style={{ fontSize: 13, marginTop: 6, color: pwStatus.ok ? '#22c55e' : '#ef4444', display: 'flex', alignItems: 'center', gap: 5 }}><Icon name={pwStatus.ok ? 'success' : 'error'} size={14} /> {pwStatus.msg}</div>}
|
||||
|
||||
<div style={{ borderTop: '1px solid var(--border)', margin: '16px 0' }}></div>
|
||||
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>{t('security.currentPwVerify')}</label>
|
||||
<input type="password" value={emailPassword} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setEmailPassword(e.target.value)} />
|
||||
</div>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 13, display: 'block', marginBottom: 4 }}>{t('security.newEmail')}</label>
|
||||
<input type="email" value={newEmail} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setNewEmail(e.target.value)} />
|
||||
</div>
|
||||
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={changeEmail}>{t('security.changeEmail')}</button>
|
||||
{emailStatus && <div style={{ fontSize: 13, marginTop: 6, color: emailStatus.ok ? '#22c55e' : '#ef4444', display: 'flex', alignItems: 'center', gap: 5 }}><Icon name={emailStatus.ok ? 'success' : 'error'} size={14} /> {emailStatus.msg}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台:侧边栏布局(对齐上游 main 分支)
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Icon } from './Icons';
|
||||
import AdminReports from './admin/AdminReports';
|
||||
import AdminUsers from './admin/AdminUsers';
|
||||
import AdminLogs from './admin/AdminLogs';
|
||||
import AdminLinks from './admin/AdminLinks';
|
||||
import AdminForumSettings from './admin/AdminForumSettings';
|
||||
import AdminCustomPages from './admin/AdminCustomPages';
|
||||
import AdminCustomCss from './admin/AdminCustomCss';
|
||||
|
||||
const NAV = [
|
||||
{ key: 'reports', labelKey: 'admin.reports', icon: 'shieldAlert' },
|
||||
{ key: 'users', labelKey: 'admin.users', icon: 'users' },
|
||||
{ key: 'logs', labelKey: 'admin.logs', icon: 'file' },
|
||||
{ key: 'links', labelKey: 'admin.links', icon: 'link' },
|
||||
{ key: 'settings', labelKey: 'admin.forumSettings', icon: 'settings' },
|
||||
{ key: 'custom', labelKey: 'admin.customPages', icon: 'file' },
|
||||
{ key: 'css', labelKey: 'admin.customCss', icon: 'file' },
|
||||
];
|
||||
|
||||
export default function AdminPage() {
|
||||
const { t } = useTranslation();
|
||||
const [tab, setTab] = useState('reports');
|
||||
const [panelPhase, setPanelPhase] = useState('idle');
|
||||
const [panelHeight, setPanelHeight] = useState(null);
|
||||
const contentRef = useRef(null);
|
||||
const panelRef = useRef(null);
|
||||
const transitionTimer = useRef(null);
|
||||
const transitionFrame = useRef(null);
|
||||
const pendingTab = useRef('reports');
|
||||
const switching = useRef(false);
|
||||
const panelPhaseRef = useRef(panelPhase);
|
||||
|
||||
panelPhaseRef.current = panelPhase;
|
||||
|
||||
const measurePanelHeight = () => {
|
||||
if (!contentRef.current || !panelRef.current) return null;
|
||||
|
||||
const style = getComputedStyle(panelRef.current);
|
||||
return contentRef.current.scrollHeight
|
||||
+ parseFloat(style.paddingTop)
|
||||
+ parseFloat(style.paddingBottom)
|
||||
+ parseFloat(style.borderTopWidth)
|
||||
+ parseFloat(style.borderBottomWidth);
|
||||
};
|
||||
|
||||
useEffect(() => () => {
|
||||
clearTimeout(transitionTimer.current);
|
||||
cancelAnimationFrame(transitionFrame.current);
|
||||
}, []);
|
||||
|
||||
// Keep the outer frame at a concrete height. Data-heavy tabs such as reports
|
||||
// first render a loader, then receive their rows asynchronously. Without
|
||||
// this lock, the frame switches from auto height to the loaded height in one
|
||||
// frame after the drawer has already opened.
|
||||
useLayoutEffect(() => {
|
||||
if (panelHeight != null) return;
|
||||
const height = measurePanelHeight();
|
||||
if (height != null) setPanelHeight(height);
|
||||
}, [panelHeight, tab]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!contentRef.current || typeof ResizeObserver === 'undefined') return undefined;
|
||||
|
||||
const observer = new ResizeObserver(() => {
|
||||
if (panelPhaseRef.current !== 'idle') return;
|
||||
const height = measurePanelHeight();
|
||||
if (height == null) return;
|
||||
setPanelHeight((currentHeight) => (
|
||||
currentHeight != null && Math.abs(currentHeight - height) < 1 ? currentHeight : height
|
||||
));
|
||||
});
|
||||
|
||||
observer.observe(contentRef.current);
|
||||
return () => observer.disconnect();
|
||||
}, [tab]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!switching.current || panelPhase !== 'hidden' || !contentRef.current || !panelRef.current) return;
|
||||
|
||||
const targetHeight = measurePanelHeight();
|
||||
if (targetHeight == null) return;
|
||||
|
||||
transitionFrame.current = requestAnimationFrame(() => {
|
||||
setPanelHeight(targetHeight);
|
||||
setPanelPhase('opening');
|
||||
transitionTimer.current = setTimeout(() => {
|
||||
switching.current = false;
|
||||
setPanelPhase('idle');
|
||||
const settledHeight = measurePanelHeight();
|
||||
if (settledHeight != null) setPanelHeight(settledHeight);
|
||||
if (pendingTab.current !== tab) {
|
||||
const queuedTab = pendingTab.current;
|
||||
transitionFrame.current = requestAnimationFrame(() => changeTab(queuedTab));
|
||||
}
|
||||
}, 360);
|
||||
});
|
||||
}, [panelPhase, tab]);
|
||||
|
||||
const changeTab = (nextTab) => {
|
||||
if (nextTab === tab && panelPhase === 'idle') return;
|
||||
pendingTab.current = nextTab;
|
||||
if (switching.current) return;
|
||||
|
||||
switching.current = true;
|
||||
clearTimeout(transitionTimer.current);
|
||||
setPanelHeight(panelRef.current?.getBoundingClientRect().height || null);
|
||||
setPanelPhase('closing');
|
||||
transitionTimer.current = setTimeout(() => {
|
||||
setTab(pendingTab.current);
|
||||
setPanelPhase('hidden');
|
||||
}, 220);
|
||||
};
|
||||
|
||||
const renderPanel = () => {
|
||||
if (tab === 'reports') return <AdminReports />;
|
||||
if (tab === 'users') return <AdminUsers />;
|
||||
if (tab === 'logs') return <AdminLogs />;
|
||||
if (tab === 'links') return <AdminLinks />;
|
||||
if (tab === 'custom') return <AdminCustomPages />;
|
||||
if (tab === 'css') return <AdminCustomCss />;
|
||||
return <AdminForumSettings />;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="page-slide active">
|
||||
<div className="page-header" style={{ maxWidth: 1200, margin: '0 auto', width: '100%' }}>
|
||||
<h2><Icon name="shieldAlert" size={20} /> {t('admin.title')}</h2>
|
||||
</div>
|
||||
<div className="admin-layout" style={{ maxWidth: 1200, margin: '0 auto', width: '100%' }}>
|
||||
<aside className="admin-sidebar">
|
||||
<nav className="admin-nav">
|
||||
{NAV.map((n) => (
|
||||
<a
|
||||
key={n.key}
|
||||
href="#"
|
||||
className={'admin-nav-item' + (tab === n.key ? ' active' : '')}
|
||||
data-tab={n.key}
|
||||
onClick={(e) => { e.preventDefault(); changeTab(n.key); }}
|
||||
>
|
||||
<span className="nav-icon"><Icon name={n.icon} size={18} /></span>
|
||||
{t(n.labelKey)}
|
||||
</a>
|
||||
))}
|
||||
</nav>
|
||||
</aside>
|
||||
<main
|
||||
ref={panelRef}
|
||||
className="admin-content"
|
||||
id="adminContent"
|
||||
style={panelHeight == null ? undefined : { height: panelHeight }}
|
||||
>
|
||||
<div className={'admin-content-drawer ' + panelPhase}>
|
||||
<div ref={contentRef} className="admin-content-drawer-inner">
|
||||
{renderPanel()}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,976 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 全局状态 Provider:用户、主题、论坛名、当前视图(feed/post/new/admin/...)
|
||||
import { createContext, useContext, useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { flushSync } from 'react-dom';
|
||||
import { API, getTheme, setToken, getToken } from '@/lib/api';
|
||||
import { applyFavicon } from '@/lib/favicon';
|
||||
|
||||
const AppContext = createContext(null);
|
||||
|
||||
const POST_TRANSITION_PARTS = [
|
||||
['.post-avatar', 'post-avatar'],
|
||||
['.post-username', 'post-author'],
|
||||
['.post-title', 'post-heading'],
|
||||
['.post-time', 'post-time'],
|
||||
['.post-content', 'post-body'],
|
||||
['.post-images', 'post-media'],
|
||||
['.post-pin-state', 'post-pin-state'],
|
||||
['.post-edited-label', 'post-edited-label'],
|
||||
['.post-actions', 'post-feed-actions'],
|
||||
];
|
||||
|
||||
function namePostTransitionParts(card) {
|
||||
if (!card) return [];
|
||||
return POST_TRANSITION_PARTS.flatMap(([selector, name]) => {
|
||||
const element = card.querySelector(selector);
|
||||
if (!element) return [];
|
||||
element.style.viewTransitionName = name;
|
||||
return [element];
|
||||
});
|
||||
}
|
||||
|
||||
function clearPostTransitionParts(elements) {
|
||||
elements.forEach((element) => {
|
||||
element.style.viewTransitionName = '';
|
||||
});
|
||||
}
|
||||
|
||||
const SETTINGS_AVATAR_SELECTOR = [
|
||||
'.post-avatar',
|
||||
'.reply-avatar',
|
||||
'.user-profile-avatar',
|
||||
'.admin-user-avatar',
|
||||
].join(', ');
|
||||
|
||||
const SETTINGS_NAME_SELECTOR = [
|
||||
'.post-username',
|
||||
'.reply-username',
|
||||
'.user-profile-name',
|
||||
'.admin-user-name',
|
||||
].join(', ');
|
||||
|
||||
function visibleAreaRatio(element) {
|
||||
if (!element?.isConnected) return 0;
|
||||
const style = window.getComputedStyle(element);
|
||||
if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) return 0;
|
||||
|
||||
const bounds = element.getBoundingClientRect();
|
||||
const totalArea = bounds.width * bounds.height;
|
||||
if (totalArea <= 0) return 0;
|
||||
|
||||
let left = Math.max(0, bounds.left);
|
||||
let top = Math.max(0, bounds.top);
|
||||
let right = Math.min(window.innerWidth, bounds.right);
|
||||
let bottom = Math.min(window.innerHeight, bounds.bottom);
|
||||
|
||||
// Account for scroll/clip containers, but deliberately do not treat the
|
||||
// translucent navbar as an occluder: content underneath it is still visible.
|
||||
for (let parent = element.parentElement; parent && parent !== document.body; parent = parent.parentElement) {
|
||||
const parentStyle = window.getComputedStyle(parent);
|
||||
const clipsX = ['auto', 'scroll', 'hidden', 'clip'].includes(parentStyle.overflowX);
|
||||
const clipsY = ['auto', 'scroll', 'hidden', 'clip'].includes(parentStyle.overflowY);
|
||||
if (!clipsX && !clipsY) continue;
|
||||
const parentBounds = parent.getBoundingClientRect();
|
||||
if (clipsX) {
|
||||
left = Math.max(left, parentBounds.left);
|
||||
right = Math.min(right, parentBounds.right);
|
||||
}
|
||||
if (clipsY) {
|
||||
top = Math.max(top, parentBounds.top);
|
||||
bottom = Math.min(bottom, parentBounds.bottom);
|
||||
}
|
||||
}
|
||||
|
||||
return Math.max(0, right - left) * Math.max(0, bottom - top) / totalArea;
|
||||
}
|
||||
|
||||
function randomElement(elements) {
|
||||
return elements[Math.floor(Math.random() * elements.length)] || null;
|
||||
}
|
||||
|
||||
function findSettingsTransitionSource(username) {
|
||||
const groups = Array.from(document.querySelectorAll('[data-username]')).filter(
|
||||
(element) => !element.closest('#navbar') && element.dataset.username === String(username || '')
|
||||
);
|
||||
const candidates = groups.map((group) => {
|
||||
const avatarElement = group.querySelector(SETTINGS_AVATAR_SELECTOR);
|
||||
const nameElement = group.querySelector(SETTINGS_NAME_SELECTOR);
|
||||
return {
|
||||
avatarElement: visibleAreaRatio(avatarElement) >= 0.5 ? avatarElement : null,
|
||||
nameElement: visibleAreaRatio(nameElement) >= 0.5 ? nameElement : null,
|
||||
};
|
||||
});
|
||||
const completeCandidates = candidates.filter(({ avatarElement, nameElement }) => avatarElement && nameElement);
|
||||
if (completeCandidates.length > 0) return randomElement(completeCandidates);
|
||||
|
||||
return randomElement(candidates.filter(({ avatarElement, nameElement }) => avatarElement || nameElement)) || {
|
||||
avatarElement: null,
|
||||
nameElement: null,
|
||||
};
|
||||
}
|
||||
|
||||
const BUILT_IN_PAGES = new Set(['messages', 'settings', 'admin', 'new']);
|
||||
|
||||
function cleanPathSegment(value) {
|
||||
return encodeURIComponent(String(value || '').trim());
|
||||
}
|
||||
|
||||
function pathForPage(page) {
|
||||
return page === 'feed' ? '/' : `/${cleanPathSegment(page)}`;
|
||||
}
|
||||
|
||||
function pathForUser(username) {
|
||||
return `/user/${cleanPathSegment(username)}`;
|
||||
}
|
||||
|
||||
function pathForPost(postRef) {
|
||||
return `/post/${cleanPathSegment(postRef)}`;
|
||||
}
|
||||
|
||||
function pathForCustomPage(pageName) {
|
||||
return `/${cleanPathSegment(pageName)}`;
|
||||
}
|
||||
|
||||
function routeFromLocation(location) {
|
||||
const parts = location.pathname.split('/').filter(Boolean).map((part) => {
|
||||
try { return decodeURIComponent(part); } catch { return part; }
|
||||
});
|
||||
const legacy = new URLSearchParams(location.search);
|
||||
const legacyPost = legacy.get('post');
|
||||
const legacyUser = legacy.get('user');
|
||||
const legacyPage = legacy.get('page');
|
||||
|
||||
if (parts[0] === 'post' && parts.length === 2) return { page: 'post', postId: parts[1] };
|
||||
if (parts[0] === 'user' && parts.length === 2) return { page: 'user', username: parts[1] };
|
||||
if (parts.length === 1 && BUILT_IN_PAGES.has(parts[0])) return { page: parts[0] };
|
||||
if (parts.length === 1) return { page: 'custom', pageName: parts[0] };
|
||||
|
||||
// Compatibility for links created before path-based navigation.
|
||||
if (legacyPost) return { page: 'post', postId: legacyPost, legacy: true };
|
||||
if (legacyUser) return { page: 'user', username: legacyUser, legacy: true };
|
||||
if (legacyPage && BUILT_IN_PAGES.has(legacyPage)) return { page: legacyPage, legacy: true };
|
||||
if (legacyPage) return { page: 'custom', pageName: legacyPage, legacy: true };
|
||||
return { page: 'feed' };
|
||||
}
|
||||
|
||||
function pathForRoute(route) {
|
||||
if (route.page === 'post') return pathForPost(route.postId);
|
||||
if (route.page === 'user') return pathForUser(route.username);
|
||||
if (route.page === 'custom') return pathForCustomPage(route.pageName);
|
||||
return pathForPage(route.page);
|
||||
}
|
||||
|
||||
function clearLegacyPageParams(url) {
|
||||
url.searchParams.delete('page');
|
||||
url.searchParams.delete('post');
|
||||
url.searchParams.delete('user');
|
||||
return url;
|
||||
}
|
||||
|
||||
function postCardMatches(element, postRef) {
|
||||
const ref = String(postRef || '');
|
||||
return element?.dataset.postRef === ref || element?.dataset.postId === ref;
|
||||
}
|
||||
|
||||
function waitForPostImages(container) {
|
||||
const images = Array.from(container?.querySelectorAll('img') || []);
|
||||
if (images.length === 0) return Promise.resolve();
|
||||
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const finish = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
resolve();
|
||||
};
|
||||
const timeout = setTimeout(finish, 1200);
|
||||
Promise.all(images.map((image) => image.decode?.().catch(() => {}) || Promise.resolve())).then(finish);
|
||||
});
|
||||
}
|
||||
|
||||
function stageSharedGeometry(transition, {
|
||||
name,
|
||||
duration,
|
||||
moveOffset,
|
||||
moveEasing = 'cubic-bezier(0.16, 1, 0.3, 1)',
|
||||
resizeEasing = 'cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
reverse = false,
|
||||
}) {
|
||||
transition.ready.then(() => {
|
||||
const groupAnimation = document.getAnimations().find(
|
||||
(animation) => animation.effect?.pseudoElement === `::view-transition-group(${name})`
|
||||
);
|
||||
const frames = groupAnimation?.effect?.getKeyframes();
|
||||
if (!groupAnimation || !frames || frames.length < 2) return;
|
||||
|
||||
const start = frames[0];
|
||||
const end = frames[frames.length - 1];
|
||||
groupAnimation.effect.setKeyframes(reverse ? [
|
||||
{
|
||||
offset: 0,
|
||||
width: start.width,
|
||||
height: start.height,
|
||||
transform: start.transform,
|
||||
easing: resizeEasing,
|
||||
},
|
||||
{
|
||||
offset: 1 - moveOffset,
|
||||
width: start.width,
|
||||
height: end.height,
|
||||
transform: start.transform,
|
||||
easing: moveEasing,
|
||||
},
|
||||
{
|
||||
offset: 1,
|
||||
width: end.width,
|
||||
height: end.height,
|
||||
transform: end.transform,
|
||||
},
|
||||
] : [
|
||||
{
|
||||
offset: 0,
|
||||
width: start.width,
|
||||
height: start.height,
|
||||
transform: start.transform,
|
||||
easing: moveEasing,
|
||||
},
|
||||
{
|
||||
offset: moveOffset,
|
||||
width: end.width,
|
||||
height: start.height,
|
||||
transform: end.transform,
|
||||
easing: resizeEasing,
|
||||
},
|
||||
{
|
||||
offset: 1,
|
||||
width: end.width,
|
||||
height: end.height,
|
||||
transform: end.transform,
|
||||
},
|
||||
]);
|
||||
groupAnimation.effect.updateTiming({ duration, easing: 'linear', fill: 'both' });
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
function stagePostBodyGeometry(transition, {
|
||||
duration,
|
||||
moveOffset,
|
||||
moveEasing = 'cubic-bezier(0.42, 0, 0.58, 1)',
|
||||
resizeEasing = 'cubic-bezier(0.42, 0, 0.58, 1)',
|
||||
}) {
|
||||
transition.ready.then(() => {
|
||||
const animations = document.getAnimations();
|
||||
const cardAnimation = animations.find(
|
||||
(animation) => animation.effect?.pseudoElement === '::view-transition-group(post-expand)'
|
||||
);
|
||||
const bodyAnimation = animations.find(
|
||||
(animation) => animation.effect?.pseudoElement === '::view-transition-group(post-body)'
|
||||
);
|
||||
const cardFrames = cardAnimation?.effect?.getKeyframes();
|
||||
const bodyFrames = bodyAnimation?.effect?.getKeyframes();
|
||||
if (!bodyAnimation || !cardFrames || cardFrames.length < 2 || !bodyFrames || bodyFrames.length < 2) return;
|
||||
|
||||
const cardStart = cardFrames[0];
|
||||
const cardEnd = cardFrames[cardFrames.length - 1];
|
||||
const bodyStart = bodyFrames[0];
|
||||
const bodyEnd = bodyFrames[bodyFrames.length - 1];
|
||||
const cardStartMatrix = new DOMMatrixReadOnly(cardStart.transform);
|
||||
const cardEndMatrix = new DOMMatrixReadOnly(cardEnd.transform);
|
||||
const bodyStartMatrix = new DOMMatrixReadOnly(bodyStart.transform);
|
||||
const bodyEndMatrix = new DOMMatrixReadOnly(bodyEnd.transform);
|
||||
const startCardWidth = Number.parseFloat(cardStart.width);
|
||||
const endCardWidth = Number.parseFloat(cardEnd.width);
|
||||
const startBodyWidth = Number.parseFloat(bodyStart.width);
|
||||
if (![startCardWidth, endCardWidth, startBodyWidth].every(Number.isFinite)) return;
|
||||
|
||||
// 第一阶段让正文锁定在卡片内的原始位置;卡片停稳后,正文才调整到详情布局。
|
||||
const leftInset = bodyStartMatrix.e - cardStartMatrix.e;
|
||||
const topInset = bodyStartMatrix.f - cardStartMatrix.f;
|
||||
const rightInset = startCardWidth - leftInset - startBodyWidth;
|
||||
const midpointWidth = Math.max(0, endCardWidth - leftInset - rightInset);
|
||||
const midpointTransform = new DOMMatrix([
|
||||
bodyEndMatrix.a,
|
||||
bodyEndMatrix.b,
|
||||
bodyEndMatrix.c,
|
||||
bodyEndMatrix.d,
|
||||
cardEndMatrix.e + leftInset,
|
||||
cardEndMatrix.f + topInset,
|
||||
]).toString();
|
||||
|
||||
bodyAnimation.effect.setKeyframes([
|
||||
{
|
||||
offset: 0,
|
||||
width: bodyStart.width,
|
||||
height: bodyStart.height,
|
||||
transform: bodyStart.transform,
|
||||
easing: moveEasing,
|
||||
},
|
||||
{
|
||||
offset: moveOffset,
|
||||
width: `${midpointWidth}px`,
|
||||
height: bodyStart.height,
|
||||
transform: midpointTransform,
|
||||
easing: resizeEasing,
|
||||
},
|
||||
{
|
||||
offset: 1,
|
||||
width: bodyEnd.width,
|
||||
height: bodyEnd.height,
|
||||
transform: bodyEnd.transform,
|
||||
},
|
||||
]);
|
||||
bodyAnimation.effect.updateTiming({ duration, easing: 'linear', fill: 'both' });
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
export function useApp() {
|
||||
return useContext(AppContext);
|
||||
}
|
||||
|
||||
export default function AppProvider({ children, cachedName = '' }) {
|
||||
const [currentUser, setCurrentUser] = useState(null);
|
||||
// 论坛名初始值来自 cookie(SSR 首帧即输出,SSR/客户端一致 → 无 hydration mismatch)
|
||||
const [forumName, setForumName] = useState(cachedName || 'Forumlify');
|
||||
const [theme, setThemeState] = useState('light');
|
||||
const [view, setView] = useState('feed'); // feed | post | new | admin | settings | messages | user | custom
|
||||
const [currentPostId, setCurrentPostId] = useState(null);
|
||||
const [currentPostPreview, setCurrentPostPreview] = useState(null);
|
||||
const [currentPostOrigin, setCurrentPostOrigin] = useState(null);
|
||||
const [currentUsername, setCurrentUsername] = useState(null);
|
||||
const [currentUserPreview, setCurrentUserPreview] = useState(null);
|
||||
const [currentUserPostsPreview, setCurrentUserPostsPreview] = useState(null);
|
||||
const [currentPageName, setCurrentPageName] = useState(null);
|
||||
const [sort, setSort] = useState('latest');
|
||||
const [refreshKey, setRefreshKey] = useState(0);
|
||||
const [ready, setReady] = useState(false); // 初始加载完成标记(控制加载页/淡入)
|
||||
// 有 cookie 缓存名即视为已加载(SSR/客户端一致)
|
||||
const [forumNameLoaded, setForumNameLoaded] = useState(!!cachedName);
|
||||
const loadedRef = useRef(false);
|
||||
|
||||
const refresh = useCallback(() => setRefreshKey((k) => k + 1), []);
|
||||
|
||||
// 论坛名写 cookie(SSR 可读 → 首帧输出,无需内联脚本注入 DOM)
|
||||
const syncForumNameCookie = useCallback((name) => {
|
||||
try {
|
||||
document.cookie = 'forumlify-name=' + encodeURIComponent(name) + '; path=/; max-age=31536000';
|
||||
} catch (e) {}
|
||||
}, []);
|
||||
|
||||
// 主题
|
||||
useEffect(() => {
|
||||
const t = getTheme();
|
||||
setThemeState(t);
|
||||
document.documentElement.setAttribute('data-theme', t);
|
||||
// 系统主题变化时跟随(仅当用户未手动设置过)
|
||||
const mq = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)');
|
||||
if (mq && mq.addEventListener) {
|
||||
const onSysChange = () => {
|
||||
if (!localStorage.getItem('forumlify-theme')) {
|
||||
const next = mq.matches ? 'dark' : 'light';
|
||||
setThemeState(next);
|
||||
document.documentElement.setAttribute('data-theme', next);
|
||||
}
|
||||
};
|
||||
mq.addEventListener('change', onSysChange);
|
||||
return () => mq.removeEventListener('change', onSysChange);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 论坛名变化时同步浏览器标题(覆盖初始化/数据库加载/改名三条路径)
|
||||
useEffect(() => {
|
||||
document.title = forumName;
|
||||
const titleEl = document.querySelector('title');
|
||||
if (titleEl) titleEl.textContent = forumName;
|
||||
}, [forumName]);
|
||||
|
||||
const toggleTheme = useCallback(() => {
|
||||
setThemeState((prev) => {
|
||||
const next = prev === 'light' ? 'dark' : 'light';
|
||||
document.documentElement.setAttribute('data-theme', next);
|
||||
localStorage.setItem('forumlify-theme', next);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// 初始化:读取缓存论坛名(立即显示),恢复登录、加载服务器论坛名
|
||||
useEffect(() => {
|
||||
// 缓存论坛名(hydrate 后立即生效;SSR 首帧已由 cookie 输出)
|
||||
try {
|
||||
const cached = localStorage.getItem('forumlify-forum-name');
|
||||
if (cached) {
|
||||
setForumName(cached);
|
||||
setForumNameLoaded(true);
|
||||
syncForumNameCookie(cached);
|
||||
}
|
||||
} catch (e) {}
|
||||
|
||||
if (loadedRef.current) return;
|
||||
loadedRef.current = true;
|
||||
|
||||
async function init() {
|
||||
const token = getToken();
|
||||
if (token) {
|
||||
try {
|
||||
const user = await API.getMe();
|
||||
setCurrentUser(user);
|
||||
} catch {
|
||||
setToken(null);
|
||||
}
|
||||
}
|
||||
try {
|
||||
const s = await API.getSettings();
|
||||
if (s.forum_name) {
|
||||
setForumName(s.forum_name);
|
||||
localStorage.setItem('forumlify-forum-name', s.forum_name);
|
||||
syncForumNameCookie(s.forum_name);
|
||||
}
|
||||
if (s.favicon_url) applyFavicon(s.favicon_url, s.favicon_version);
|
||||
// 先标记论坛名已收到(加载页原地淡入名字),稍后切换主页
|
||||
setForumNameLoaded(true);
|
||||
setTimeout(() => setReady(true), 650);
|
||||
} catch {
|
||||
setForumNameLoaded(true);
|
||||
setReady(true);
|
||||
}
|
||||
}
|
||||
init();
|
||||
}, []);
|
||||
|
||||
// 页面标题:初始化中轮换 Loading. → Loading.. → Loading...,收到论坛名/完成后显示论坛名
|
||||
useEffect(() => {
|
||||
// 尚未收到论坛名且未完成初始化:轮换 Loading.
|
||||
if (!ready && !forumNameLoaded) {
|
||||
const seq = ['Loading.', 'Loading..', 'Loading...'];
|
||||
let i = 0;
|
||||
document.title = seq[0];
|
||||
const t = setInterval(() => {
|
||||
i = (i + 1) % seq.length;
|
||||
document.title = seq[i];
|
||||
}, 1000);
|
||||
return () => {
|
||||
clearInterval(t);
|
||||
};
|
||||
}
|
||||
// 已收到论坛名或初始化完成:标题显示论坛名(Next 重置 metadata 时也能恢复)
|
||||
document.title = forumName;
|
||||
const titleEl = document.querySelector('title');
|
||||
if (titleEl) titleEl.textContent = forumName;
|
||||
}, [ready, forumNameLoaded, forumName]);
|
||||
|
||||
const applyRoute = useCallback((route, state = {}) => {
|
||||
setView(route.page);
|
||||
setCurrentPostId(route.page === 'post' ? route.postId : null);
|
||||
setCurrentPostPreview(null);
|
||||
setCurrentPostOrigin(route.page === 'post' ? state.origin || null : null);
|
||||
setCurrentUsername(route.page === 'user' ? route.username : null);
|
||||
setCurrentUserPreview(null);
|
||||
setCurrentUserPostsPreview(null);
|
||||
setCurrentPageName(route.page === 'custom' ? route.pageName : null);
|
||||
}, []);
|
||||
|
||||
// Initialize from path routes and normalize legacy query-based links.
|
||||
useEffect(() => {
|
||||
const route = routeFromLocation(window.location);
|
||||
applyRoute(route, window.history.state || {});
|
||||
if (route.legacy) {
|
||||
const normalized = clearLegacyPageParams(new URL(window.location));
|
||||
normalized.pathname = pathForRoute(route);
|
||||
window.history.replaceState({ ...window.history.state, ...route }, '', normalized);
|
||||
}
|
||||
}, [applyRoute]);
|
||||
|
||||
// 视图切换:同步 URL (pushState,模拟原 SPA 行为)
|
||||
const navigate = useCallback((page) => {
|
||||
const url = clearLegacyPageParams(new URL(window.location));
|
||||
url.pathname = pathForPage(page);
|
||||
const commitNavigation = (refreshFeed = true) => {
|
||||
window.history.pushState({ page }, '', url);
|
||||
setView(page);
|
||||
setCurrentPostId(null);
|
||||
setCurrentPostPreview(null);
|
||||
setCurrentPostOrigin(null);
|
||||
setCurrentUsername(null);
|
||||
setCurrentUserPreview(null);
|
||||
setCurrentUserPostsPreview(null);
|
||||
if (refreshFeed) refresh();
|
||||
};
|
||||
|
||||
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
||||
if (page === 'new' && view === 'feed' && document.startViewTransition && !reduceMotion) {
|
||||
const root = document.documentElement;
|
||||
const sourceIcon = document.querySelector('#feed .fab-btn .new-post-launch-icon');
|
||||
const sourceLabel = document.querySelector('#feed .fab-btn .new-post-launch-label');
|
||||
|
||||
if (!sourceIcon || !sourceLabel) {
|
||||
commitNavigation();
|
||||
return;
|
||||
}
|
||||
|
||||
root.classList.add('new-post-view-transition');
|
||||
sourceIcon.style.viewTransitionName = 'new-post-plus';
|
||||
sourceLabel.style.viewTransitionName = 'new-post-title';
|
||||
|
||||
const transition = document.startViewTransition(() => {
|
||||
sourceIcon.style.viewTransitionName = '';
|
||||
sourceLabel.style.viewTransitionName = '';
|
||||
flushSync(() => commitNavigation(false));
|
||||
});
|
||||
transition.finished.finally(() => {
|
||||
root.classList.remove('new-post-view-transition');
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (page === 'feed' && view === 'new' && document.startViewTransition && !reduceMotion) {
|
||||
const root = document.documentElement;
|
||||
const sourceIcon = document.querySelector('#pageNew .new-post-title-icon');
|
||||
const sourceLabel = document.querySelector('#pageNew .new-post-title-label');
|
||||
|
||||
if (!sourceIcon || !sourceLabel) {
|
||||
commitNavigation();
|
||||
return;
|
||||
}
|
||||
|
||||
let targetIcon = null;
|
||||
let targetLabel = null;
|
||||
root.classList.add('new-post-view-transition', 'returning-new-post-home');
|
||||
sourceIcon.style.viewTransitionName = 'new-post-plus';
|
||||
sourceLabel.style.viewTransitionName = 'new-post-title';
|
||||
|
||||
const transition = document.startViewTransition(() => {
|
||||
sourceIcon.style.viewTransitionName = '';
|
||||
sourceLabel.style.viewTransitionName = '';
|
||||
flushSync(() => commitNavigation(false));
|
||||
targetIcon = document.querySelector('#feed .fab-btn .new-post-launch-icon');
|
||||
targetLabel = document.querySelector('#feed .fab-btn .new-post-launch-label');
|
||||
if (targetIcon) targetIcon.style.viewTransitionName = 'new-post-plus';
|
||||
if (targetLabel) targetLabel.style.viewTransitionName = 'new-post-title';
|
||||
});
|
||||
const clearTargetNames = () => {
|
||||
if (targetIcon) targetIcon.style.viewTransitionName = '';
|
||||
if (targetLabel) targetLabel.style.viewTransitionName = '';
|
||||
};
|
||||
transition.ready.then(clearTargetNames, clearTargetNames);
|
||||
transition.finished.finally(() => {
|
||||
root.classList.remove('new-post-view-transition', 'returning-new-post-home');
|
||||
refresh();
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (page === 'settings' && view !== 'settings' && document.startViewTransition && !reduceMotion) {
|
||||
const root = document.documentElement;
|
||||
const visibleSource = findSettingsTransitionSource(currentUser?.username);
|
||||
const navbarAvatar = document.querySelector('#navbar #userDropdown .avatar');
|
||||
const sourceAvatar = visibleSource.avatarElement || navbarAvatar;
|
||||
const sourceName = visibleSource.nameElement;
|
||||
const avatarFromNavbar = sourceAvatar === navbarAvatar;
|
||||
|
||||
if (!sourceAvatar) {
|
||||
commitNavigation();
|
||||
return;
|
||||
}
|
||||
|
||||
root.classList.add('settings-view-transition');
|
||||
if (avatarFromNavbar) root.classList.add('settings-avatar-from-navbar');
|
||||
if (!sourceName) root.classList.add('settings-name-fade-only');
|
||||
sourceAvatar.style.viewTransitionName = 'settings-avatar';
|
||||
if (sourceName) sourceName.style.viewTransitionName = 'settings-user-name';
|
||||
|
||||
const transition = document.startViewTransition(() => {
|
||||
sourceAvatar.style.viewTransitionName = '';
|
||||
if (sourceName) sourceName.style.viewTransitionName = '';
|
||||
if (avatarFromNavbar) root.classList.add('settings-navbar-avatar-hidden');
|
||||
flushSync(() => commitNavigation(false));
|
||||
});
|
||||
transition.finished.finally(() => {
|
||||
root.classList.remove(
|
||||
'settings-view-transition',
|
||||
'settings-avatar-from-navbar',
|
||||
'settings-name-fade-only',
|
||||
'settings-navbar-avatar-hidden'
|
||||
);
|
||||
if (avatarFromNavbar) {
|
||||
root.classList.add('settings-navbar-avatar-reveal');
|
||||
window.setTimeout(() => root.classList.remove('settings-navbar-avatar-reveal'), 360);
|
||||
}
|
||||
refresh();
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (page === 'feed' && view === 'settings' && document.startViewTransition && !reduceMotion) {
|
||||
const root = document.documentElement;
|
||||
const sourceAvatar = document.querySelector('#pageSettings .settings-profile-avatar');
|
||||
const sourceName = document.querySelector('#pageSettings .settings-profile-name');
|
||||
|
||||
if (!sourceAvatar) {
|
||||
commitNavigation();
|
||||
return;
|
||||
}
|
||||
|
||||
let targetAvatar = null;
|
||||
let targetName = null;
|
||||
root.classList.add(
|
||||
'settings-view-transition',
|
||||
'returning-settings-home',
|
||||
'settings-navbar-avatar-hidden'
|
||||
);
|
||||
|
||||
const transition = document.startViewTransition(() => {
|
||||
flushSync(() => commitNavigation(false));
|
||||
const visibleTarget = findSettingsTransitionSource(currentUser?.username);
|
||||
const navbarAvatar = document.querySelector('#navbar #userDropdown .avatar');
|
||||
targetAvatar = visibleTarget.avatarElement || navbarAvatar;
|
||||
targetName = visibleTarget.nameElement;
|
||||
|
||||
// Hide the navbar avatar only in the old snapshot. The new snapshot
|
||||
// must expose it as the shared target when no visible feed avatar exists.
|
||||
root.classList.remove('settings-navbar-avatar-hidden');
|
||||
|
||||
if (targetAvatar) targetAvatar.style.viewTransitionName = 'settings-avatar';
|
||||
if (targetName) {
|
||||
targetName.style.viewTransitionName = 'settings-user-name';
|
||||
} else {
|
||||
root.classList.add('settings-name-return-fade-only');
|
||||
}
|
||||
});
|
||||
const clearTargetNames = () => {
|
||||
if (targetAvatar) targetAvatar.style.viewTransitionName = '';
|
||||
if (targetName) targetName.style.viewTransitionName = '';
|
||||
};
|
||||
transition.ready.then(clearTargetNames, clearTargetNames);
|
||||
transition.finished.finally(() => {
|
||||
root.classList.remove(
|
||||
'settings-view-transition',
|
||||
'returning-settings-home',
|
||||
'settings-name-return-fade-only',
|
||||
'settings-navbar-avatar-hidden'
|
||||
);
|
||||
refresh();
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (page !== 'feed' || view === 'feed' || !document.startViewTransition || reduceMotion) {
|
||||
commitNavigation();
|
||||
return;
|
||||
}
|
||||
|
||||
if (view === 'user') {
|
||||
const root = document.documentElement;
|
||||
const sourceAvatar = document.querySelector('#pageUser .user-profile-avatar');
|
||||
const sourceName = document.querySelector('#pageUser .user-profile-name');
|
||||
const findTargetCard = () => {
|
||||
if (currentUserPreview?.sourcePostId) {
|
||||
const exact = Array.from(document.querySelectorAll('[data-post-ref], [data-post-id]')).find(
|
||||
(element) => postCardMatches(element, currentUserPreview.sourcePostId)
|
||||
);
|
||||
if (exact) return exact;
|
||||
}
|
||||
return Array.from(document.querySelectorAll('[data-username]')).find(
|
||||
(element) => element.dataset.username === String(currentUsername || '')
|
||||
) || null;
|
||||
};
|
||||
let targetCard = findTargetCard();
|
||||
|
||||
if (sourceAvatar && sourceName && targetCard) {
|
||||
let targetAvatar = null;
|
||||
let targetName = null;
|
||||
root.classList.add('user-view-transition', 'returning-user-home');
|
||||
const transition = document.startViewTransition(() => {
|
||||
flushSync(() => commitNavigation(false));
|
||||
targetCard = findTargetCard();
|
||||
targetAvatar = targetCard?.querySelector('.post-avatar') || null;
|
||||
targetName = targetCard?.querySelector('.post-username') || null;
|
||||
if (targetAvatar) targetAvatar.style.viewTransitionName = 'user-avatar';
|
||||
if (targetName) targetName.style.viewTransitionName = 'user-name';
|
||||
});
|
||||
const clearTargetNames = () => {
|
||||
if (targetAvatar) targetAvatar.style.viewTransitionName = '';
|
||||
if (targetName) targetName.style.viewTransitionName = '';
|
||||
};
|
||||
transition.ready.then(clearTargetNames, clearTargetNames);
|
||||
transition.finished.finally(() => {
|
||||
root.classList.remove('user-view-transition', 'returning-user-home');
|
||||
refresh();
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let targetCard = currentPostId
|
||||
? Array.from(document.querySelectorAll('[data-post-ref], [data-post-id]')).find((element) => postCardMatches(element, currentPostId))
|
||||
: null;
|
||||
let targetParts = [];
|
||||
document.documentElement.classList.add('home-view-transition');
|
||||
if (targetCard) document.documentElement.classList.add('returning-home');
|
||||
|
||||
const transition = document.startViewTransition(() => {
|
||||
flushSync(() => commitNavigation(false));
|
||||
targetCard = currentPostId
|
||||
? Array.from(document.querySelectorAll('[data-post-ref], [data-post-id]')).find((element) => postCardMatches(element, currentPostId))
|
||||
: null;
|
||||
if (targetCard) targetCard.style.viewTransitionName = 'post-expand';
|
||||
targetParts = namePostTransitionParts(targetCard);
|
||||
});
|
||||
stageSharedGeometry(transition, {
|
||||
name: 'post-expand',
|
||||
duration: 1100,
|
||||
moveOffset: 0.73,
|
||||
moveEasing: 'cubic-bezier(0.42, 0, 0.58, 1)',
|
||||
resizeEasing: 'cubic-bezier(0.16, 1, 0.3, 1)',
|
||||
reverse: true,
|
||||
});
|
||||
stageSharedGeometry(transition, {
|
||||
name: 'post-body',
|
||||
duration: 1100,
|
||||
moveOffset: 0.73,
|
||||
moveEasing: 'cubic-bezier(0.42, 0, 0.58, 1)',
|
||||
resizeEasing: 'cubic-bezier(0.16, 1, 0.3, 1)',
|
||||
reverse: true,
|
||||
});
|
||||
const clearTargetNames = () => {
|
||||
if (targetCard) targetCard.style.viewTransitionName = '';
|
||||
clearPostTransitionParts(targetParts);
|
||||
};
|
||||
transition.ready.then(clearTargetNames, clearTargetNames);
|
||||
transition.finished.finally(() => {
|
||||
document.documentElement.classList.remove('home-view-transition', 'returning-home');
|
||||
refresh();
|
||||
});
|
||||
}, [currentPostId, currentUser, currentUsername, currentUserPreview, refresh, view]);
|
||||
|
||||
const openPost = useCallback((postId, sourceElement = null, preview = null, origin = null) => {
|
||||
const postRef = preview?.post_number || postId;
|
||||
const url = clearLegacyPageParams(new URL(window.location));
|
||||
url.pathname = pathForPost(postRef);
|
||||
const resolvedOrigin = origin || { view };
|
||||
const historyOrigin = resolvedOrigin?.view === 'user'
|
||||
? { view: 'user', username: resolvedOrigin.username }
|
||||
: { view: resolvedOrigin?.view || 'feed' };
|
||||
const commitNavigation = () => {
|
||||
window.history.pushState({ page: 'post', postId: postRef, origin: historyOrigin }, '', url);
|
||||
setView('post');
|
||||
setCurrentPostId(postRef);
|
||||
setCurrentPostPreview(preview);
|
||||
setCurrentPostOrigin(resolvedOrigin);
|
||||
setCurrentUserPreview(null);
|
||||
setCurrentUserPostsPreview(null);
|
||||
};
|
||||
|
||||
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
||||
if (!sourceElement || !document.startViewTransition || reduceMotion) {
|
||||
commitNavigation();
|
||||
return;
|
||||
}
|
||||
|
||||
document.documentElement.classList.remove('post-transition-settled');
|
||||
sourceElement.style.viewTransitionName = 'post-expand';
|
||||
const sourceParts = namePostTransitionParts(sourceElement);
|
||||
document.documentElement.classList.add('post-view-transition');
|
||||
const transition = document.startViewTransition(async () => {
|
||||
flushSync(commitNavigation);
|
||||
await waitForPostImages(document.querySelector('#pagePost .post-detail-card'));
|
||||
});
|
||||
stageSharedGeometry(transition, {
|
||||
name: 'post-expand',
|
||||
duration: 960,
|
||||
moveOffset: 0.62,
|
||||
moveEasing: 'cubic-bezier(0.42, 0, 0.58, 1)',
|
||||
resizeEasing: 'cubic-bezier(0.42, 0, 0.58, 1)',
|
||||
});
|
||||
stagePostBodyGeometry(transition, {
|
||||
duration: 960,
|
||||
moveOffset: 0.62,
|
||||
moveEasing: 'cubic-bezier(0.42, 0, 0.58, 1)',
|
||||
resizeEasing: 'cubic-bezier(0.42, 0, 0.58, 1)',
|
||||
});
|
||||
const clearSourceNames = () => {
|
||||
sourceElement.style.viewTransitionName = '';
|
||||
clearPostTransitionParts(sourceParts);
|
||||
};
|
||||
transition.ready.then(clearSourceNames, clearSourceNames);
|
||||
transition.finished.finally(() => {
|
||||
const root = document.documentElement;
|
||||
root.classList.remove('post-view-transition');
|
||||
root.classList.add('post-transition-settled');
|
||||
window.setTimeout(() => root.classList.remove('post-transition-settled'), 220);
|
||||
});
|
||||
}, [view]);
|
||||
|
||||
const returnFromPost = useCallback(() => {
|
||||
if (currentPostOrigin?.view !== 'user' || !currentPostOrigin.username) {
|
||||
navigate('feed');
|
||||
return;
|
||||
}
|
||||
|
||||
const url = clearLegacyPageParams(new URL(window.location));
|
||||
url.pathname = pathForUser(currentPostOrigin.username);
|
||||
const commitNavigation = () => {
|
||||
window.history.pushState({ page: 'user', username: currentPostOrigin.username }, '', url);
|
||||
setView('user');
|
||||
setCurrentUsername(currentPostOrigin.username);
|
||||
setCurrentUserPreview(currentPostOrigin.user || { username: currentPostOrigin.username });
|
||||
setCurrentUserPostsPreview(currentPostOrigin.posts || []);
|
||||
setCurrentPostId(null);
|
||||
setCurrentPostPreview(null);
|
||||
};
|
||||
|
||||
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
||||
const sourceCard = document.querySelector('#pagePost .post-detail-card');
|
||||
if (!sourceCard || !document.startViewTransition || reduceMotion) {
|
||||
commitNavigation();
|
||||
return;
|
||||
}
|
||||
|
||||
const root = document.documentElement;
|
||||
let targetCard = null;
|
||||
let targetParts = [];
|
||||
root.classList.add('home-view-transition', 'returning-home', 'returning-user-post');
|
||||
const transition = document.startViewTransition(() => {
|
||||
flushSync(commitNavigation);
|
||||
const userPage = document.getElementById('pageUser');
|
||||
if (userPage) userPage.scrollTop = currentPostOrigin.scrollTop || 0;
|
||||
targetCard = Array.from(document.querySelectorAll('#userProfileContent [data-post-ref], #userProfileContent [data-post-id]')).find(
|
||||
(element) => postCardMatches(element, currentPostId)
|
||||
) || null;
|
||||
if (targetCard) targetCard.style.viewTransitionName = 'post-expand';
|
||||
targetParts = namePostTransitionParts(targetCard);
|
||||
});
|
||||
stageSharedGeometry(transition, {
|
||||
name: 'post-expand',
|
||||
duration: 1100,
|
||||
moveOffset: 0.73,
|
||||
moveEasing: 'cubic-bezier(0.42, 0, 0.58, 1)',
|
||||
resizeEasing: 'cubic-bezier(0.16, 1, 0.3, 1)',
|
||||
reverse: true,
|
||||
});
|
||||
stageSharedGeometry(transition, {
|
||||
name: 'post-body',
|
||||
duration: 1100,
|
||||
moveOffset: 0.73,
|
||||
moveEasing: 'cubic-bezier(0.42, 0, 0.58, 1)',
|
||||
resizeEasing: 'cubic-bezier(0.16, 1, 0.3, 1)',
|
||||
reverse: true,
|
||||
});
|
||||
const clearTargetNames = () => {
|
||||
if (targetCard) targetCard.style.viewTransitionName = '';
|
||||
clearPostTransitionParts(targetParts);
|
||||
};
|
||||
transition.ready.then(clearTargetNames, clearTargetNames);
|
||||
transition.finished.finally(() => {
|
||||
root.classList.remove('home-view-transition', 'returning-home', 'returning-user-post');
|
||||
setCurrentPostOrigin(null);
|
||||
});
|
||||
}, [currentPostId, currentPostOrigin, navigate]);
|
||||
|
||||
const openUser = useCallback((username, source = null, preview = null) => {
|
||||
const url = clearLegacyPageParams(new URL(window.location));
|
||||
url.pathname = pathForUser(username);
|
||||
const commitNavigation = () => {
|
||||
window.history.pushState({ page: 'user', username }, '', url);
|
||||
setView('user');
|
||||
setCurrentUsername(username);
|
||||
setCurrentUserPreview(preview || { username });
|
||||
setCurrentPostId(null);
|
||||
setCurrentPostPreview(null);
|
||||
setCurrentPostOrigin(null);
|
||||
setCurrentUserPostsPreview(null);
|
||||
};
|
||||
|
||||
const avatarElement = source?.avatarElement;
|
||||
const nameElement = source?.nameElement;
|
||||
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
||||
if (!avatarElement || !nameElement || !document.startViewTransition || reduceMotion) {
|
||||
commitNavigation();
|
||||
return;
|
||||
}
|
||||
|
||||
const root = document.documentElement;
|
||||
root.classList.remove('user-transition-settled');
|
||||
root.classList.add('user-view-transition');
|
||||
avatarElement.style.viewTransitionName = 'user-avatar';
|
||||
nameElement.style.viewTransitionName = 'user-name';
|
||||
|
||||
const transition = document.startViewTransition(() => {
|
||||
flushSync(commitNavigation);
|
||||
});
|
||||
const clearSourceNames = () => {
|
||||
avatarElement.style.viewTransitionName = '';
|
||||
nameElement.style.viewTransitionName = '';
|
||||
};
|
||||
transition.ready.then(clearSourceNames, clearSourceNames);
|
||||
transition.finished.finally(() => {
|
||||
root.classList.remove('user-view-transition');
|
||||
root.classList.add('user-transition-settled');
|
||||
window.setTimeout(() => root.classList.remove('user-transition-settled'), 320);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const openCustomPage = useCallback((pageName) => {
|
||||
const url = clearLegacyPageParams(new URL(window.location));
|
||||
url.pathname = pathForCustomPage(pageName);
|
||||
window.history.pushState({ page: 'custom', pageName }, '', url);
|
||||
setView('custom');
|
||||
setCurrentPageName(pageName);
|
||||
setCurrentUserPreview(null);
|
||||
}, []);
|
||||
|
||||
// 浏览器前进后退
|
||||
useEffect(() => {
|
||||
const onPop = (e) => {
|
||||
const state = e.state || {};
|
||||
applyRoute(routeFromLocation(window.location), state);
|
||||
};
|
||||
window.addEventListener('popstate', onPop);
|
||||
return () => window.removeEventListener('popstate', onPop);
|
||||
}, [applyRoute]);
|
||||
|
||||
const login = useCallback(async (email, password) => {
|
||||
const result = await API.login(email, password);
|
||||
if (result.user) {
|
||||
setCurrentUser(result.user);
|
||||
}
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
const register = useCallback(async (email, password, username, captcha) => {
|
||||
const result = await API.register(email, password, username, captcha);
|
||||
const loginResult = await API.login(email, password);
|
||||
if (loginResult.user) {
|
||||
setCurrentUser(loginResult.user);
|
||||
}
|
||||
return result;
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
API.logout();
|
||||
setCurrentUser(null);
|
||||
navigate('feed');
|
||||
}, [navigate]);
|
||||
|
||||
const updateForumName = useCallback((name) => {
|
||||
setForumName(name);
|
||||
localStorage.setItem('forumlify-forum-name', name);
|
||||
syncForumNameCookie(name);
|
||||
}, [syncForumNameCookie]);
|
||||
|
||||
const value = {
|
||||
currentUser, setCurrentUser,
|
||||
forumName, forumNameLoaded, updateForumName,
|
||||
theme, toggleTheme,
|
||||
view, navigate,
|
||||
currentPostId, currentPostPreview, currentPostOrigin, openPost, returnFromPost,
|
||||
currentUsername, currentUserPreview, currentUserPostsPreview, openUser,
|
||||
currentPageName, openCustomPage,
|
||||
sort, setSort,
|
||||
refreshKey, refresh,
|
||||
ready,
|
||||
login, register, logout,
|
||||
};
|
||||
|
||||
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 图片验证码:用 canvas 绘制算式(带噪点/干扰线,挡一部分人机)
|
||||
// 点击图片可刷新验证码
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
export default function CaptchaImage({ captcha, onRefresh }) {
|
||||
const canvasRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas || !captcha) return;
|
||||
const ctx = canvas.getContext('2d');
|
||||
const W = canvas.width;
|
||||
const H = canvas.height;
|
||||
|
||||
// 背景(半透明玻璃感)
|
||||
ctx.clearRect(0, 0, W, H);
|
||||
ctx.fillStyle = 'rgba(91, 155, 213, 0.10)';
|
||||
ctx.fillRect(0, 0, W, H);
|
||||
|
||||
// 干扰线
|
||||
for (let i = 0; i < 4; i++) {
|
||||
ctx.strokeStyle = `rgba(${80 + Math.random() * 120}, ${80 + Math.random() * 120}, 200, ${0.2 + Math.random() * 0.3})`;
|
||||
ctx.lineWidth = 1 + Math.random();
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(Math.random() * W, Math.random() * H);
|
||||
ctx.lineTo(Math.random() * W, Math.random() * H);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
// 噪点
|
||||
for (let i = 0; i < 30; i++) {
|
||||
ctx.fillStyle = `rgba(${Math.random() * 200}, ${Math.random() * 200}, 220, ${0.3 + Math.random() * 0.5})`;
|
||||
ctx.beginPath();
|
||||
ctx.arc(Math.random() * W, Math.random() * H, 1 + Math.random() * 1.5, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
// 算式文字(每个字符轻微旋转/位移,增加识别难度)
|
||||
const text = (captcha.text || captcha.question || '').replace(' = ?', '');
|
||||
const chars = text.split('');
|
||||
const fontSize = Math.floor(H * 0.52);
|
||||
const step = W / (chars.length + 1);
|
||||
chars.forEach((ch, i) => {
|
||||
ctx.save();
|
||||
ctx.translate(step * (i + 1) + (Math.random() - 0.5) * 6, H / 2 + (Math.random() - 0.5) * 6);
|
||||
ctx.rotate((Math.random() - 0.5) * 0.25);
|
||||
ctx.font = `bold ${fontSize}px -apple-system, "SF Pro Display", "Segoe UI", Roboto, sans-serif`;
|
||||
ctx.fillStyle = `rgba(${40 + Math.random() * 60}, ${50 + Math.random() * 50}, 90, 0.9)`;
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(ch, 0, 0);
|
||||
ctx.restore();
|
||||
});
|
||||
}, [captcha]);
|
||||
|
||||
return (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
width={120}
|
||||
height={40}
|
||||
onClick={onRefresh}
|
||||
title="看不清?点击刷新"
|
||||
style={{ cursor: 'pointer', borderRadius: 6, border: '1px solid var(--glass-border)', verticalAlign: 'middle' }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 加载自定义 CSS(管理员上传的 style.css,覆盖默认样式)
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export default function CustomCssLoader() {
|
||||
useEffect(() => {
|
||||
// 尝试加载 /api/custom-css;404 表示未设置,静默跳过
|
||||
const link = document.createElement('link');
|
||||
link.rel = 'stylesheet';
|
||||
link.href = '/api/custom-css';
|
||||
link.id = 'custom-css-link';
|
||||
document.head.appendChild(link);
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 自定义页面:以 iframe srcdoc 渲染 HTML 内容(与原版一致)
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
|
||||
export default function CustomPage({ pageName }) {
|
||||
const [html, setHtml] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
setHtml(null);
|
||||
setError(null);
|
||||
API.getCustomPage(pageName)
|
||||
.then((page) => setHtml(page.content))
|
||||
.catch((err) => setError(err.message));
|
||||
}, [pageName]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div style={{ padding: '84px 32px', textAlign: 'center', color: '#ef4444' }}>
|
||||
页面加载失败:{error}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (html === null) {
|
||||
return <div style={{ padding: '84px 32px', textAlign: 'center', color: '#94a3b8' }}><span className="spinner-sm" />加载中...</div>;
|
||||
}
|
||||
|
||||
const srcdoc = `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
padding: 24px;
|
||||
background: var(--bg, #f6f8fc);
|
||||
color: var(--text, #0a0e1a);
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body { background: #0f1117; color: #e8edf5; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>${html}</body>
|
||||
</html>`;
|
||||
|
||||
return (
|
||||
<div className="custom-page-container" style={{ padding: '84px 32px 40px', background: 'var(--bg)', minHeight: '100vh' }}>
|
||||
<iframe
|
||||
style={{ width: '100%', minHeight: '70vh', border: 'none', borderRadius: 8, background: 'var(--surface)' }}
|
||||
sandbox="allow-scripts allow-modals allow-same-origin"
|
||||
srcDoc={srcdoc}
|
||||
title={pageName}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,278 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 信息流:帖子列表 + 排序 tab + 发布新帖按钮
|
||||
import { useEffect, useState, useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
import ImageViewer from './ImageViewer';
|
||||
import { renderMarkdown } from '@/lib/markdown';
|
||||
import { useToast } from './Toast';
|
||||
|
||||
function avatar(username) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
}
|
||||
|
||||
export default function Feed({ onOpenModal, onReport }) {
|
||||
const { currentUser, sort, setSort, openPost, openUser, navigate, refreshKey } = useApp();
|
||||
const { t } = useTranslation();
|
||||
const { toast, confirmAction } = useToast();
|
||||
const [posts, setPosts] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [page, setPage] = useState(1);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [viewerSrc, setViewerSrc] = useState(null);
|
||||
const [selectedSort, setSelectedSort] = useState(sort);
|
||||
const [drawerPhase, setDrawerPhase] = useState('closed');
|
||||
const postListRef = useRef(null);
|
||||
const sortTimerRef = useRef(null);
|
||||
const pendingSortRef = useRef(null);
|
||||
const initialDrawerOpenedRef = useRef(false);
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
const load = useCallback(async (targetPage) => {
|
||||
setError(null);
|
||||
try {
|
||||
const result = await API.getPosts(sort, null, targetPage, PAGE_SIZE);
|
||||
setPosts(result.data || []);
|
||||
setTotalPages(result.pagination?.totalPages || 1);
|
||||
setPage(result.pagination?.page || 1);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
setPosts([]);
|
||||
} finally {
|
||||
if (pendingSortRef.current === sort) {
|
||||
requestAnimationFrame(() => {
|
||||
setDrawerPhase('opening');
|
||||
sortTimerRef.current = setTimeout(() => {
|
||||
pendingSortRef.current = null;
|
||||
setDrawerPhase('idle');
|
||||
}, 360);
|
||||
});
|
||||
} else if (!initialDrawerOpenedRef.current) {
|
||||
// 首次加载:先在收起状态完成列表渲染,再像排序切换一样抽屉式展开。
|
||||
// Feed 在 SPA 视图间保持挂载,因此从帖子/用户页返回时不会重复播放。
|
||||
initialDrawerOpenedRef.current = true;
|
||||
requestAnimationFrame(() => {
|
||||
setDrawerPhase('opening');
|
||||
sortTimerRef.current = setTimeout(() => setDrawerPhase('idle'), 360);
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [sort, refreshKey]);
|
||||
|
||||
useEffect(() => { load(page); }, [load]);
|
||||
|
||||
// 长帖内容:超过 3 行时加 .has-fade(底部渐变遮罩提示还有更多内容)
|
||||
useEffect(() => {
|
||||
if (!posts || posts.length === 0 || !postListRef.current) return;
|
||||
const els = postListRef.current.querySelectorAll('.post-content');
|
||||
els.forEach((el) => {
|
||||
if (el.scrollHeight > el.clientHeight + 4) {
|
||||
el.classList.add('has-fade');
|
||||
} else {
|
||||
el.classList.remove('has-fade');
|
||||
}
|
||||
});
|
||||
}, [posts]);
|
||||
|
||||
// 排序切换时回第一页
|
||||
useEffect(() => { setPage(1); }, [sort]);
|
||||
|
||||
useEffect(() => () => clearTimeout(sortTimerRef.current), []);
|
||||
|
||||
const handleSortChange = (nextSort) => {
|
||||
if (nextSort === selectedSort) return;
|
||||
|
||||
setSelectedSort(nextSort);
|
||||
clearTimeout(sortTimerRef.current);
|
||||
|
||||
// 快速切回当前排序时,直接重新展开尚未替换的列表。
|
||||
if (nextSort === sort) {
|
||||
pendingSortRef.current = null;
|
||||
setDrawerPhase('opening');
|
||||
sortTimerRef.current = setTimeout(() => setDrawerPhase('idle'), 360);
|
||||
return;
|
||||
}
|
||||
|
||||
setDrawerPhase('closing');
|
||||
sortTimerRef.current = setTimeout(() => {
|
||||
pendingSortRef.current = nextSort;
|
||||
setDrawerPhase('closed');
|
||||
setSort(nextSort);
|
||||
}, 220);
|
||||
};
|
||||
|
||||
const handleDelete = async (postId) => {
|
||||
if (!await confirmAction(t('feed.confirmDelete'))) return;
|
||||
try {
|
||||
await API.deletePost(postId);
|
||||
load(page);
|
||||
} catch (err) {
|
||||
toast(t('feed.deleteFailed', { msg: err.message }), 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const handleOpenUser = (event, post) => {
|
||||
event.stopPropagation();
|
||||
const header = event.currentTarget.closest('.post-header');
|
||||
openUser(
|
||||
post.username,
|
||||
{
|
||||
avatarElement: header?.querySelector('.post-avatar'),
|
||||
nameElement: header?.querySelector('.post-username'),
|
||||
},
|
||||
{
|
||||
username: post.username,
|
||||
avatar_url: post.avatar_url || avatar(post.username),
|
||||
sourcePostId: post.id,
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<main id="feed">
|
||||
<div className="feed-header">
|
||||
<div className="feed-header-left">
|
||||
<button className={'tab' + (selectedSort === 'latest' ? ' active' : '')} onClick={() => handleSortChange('latest')}>{t('feed.latest')}</button>
|
||||
<button className={'tab' + (selectedSort === 'hot' ? ' active' : '')} onClick={() => handleSortChange('hot')}>{t('feed.hot')}</button>
|
||||
</div>
|
||||
<button
|
||||
className="btn-primary fab-btn"
|
||||
onClick={() => {
|
||||
if (!currentUser) { toast(t('newPost.pleaseLogin'), 'warning'); return; }
|
||||
navigate('new');
|
||||
}}
|
||||
>
|
||||
<Icon name="plus" className="new-post-launch-icon" />
|
||||
<span className="new-post-launch-label">{t('feed.newPost')}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className={'feed-posts-drawer ' + drawerPhase}>
|
||||
<div className="feed-posts-drawer-inner">
|
||||
<div id="postList" ref={postListRef}>
|
||||
{posts === null ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />{t('feed.loading')}</div>
|
||||
) : error ? (
|
||||
<div style={{ textAlign: 'center', color: '#ef4444', padding: '40px 0' }}>{t('feed.loadFailed', { msg: error })}</div>
|
||||
) : posts.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '60px 0' }}>{t('feed.empty')}</div>
|
||||
) : (
|
||||
posts.map((p) => {
|
||||
const time = p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '';
|
||||
return (
|
||||
<div key={p.id} className="post-card" data-post-id={p.id} data-post-ref={p.post_number || p.id} data-username={p.username || ''} style={{ cursor: 'pointer' }}
|
||||
onClick={(e) => openPost(p.post_number || p.id, e.currentTarget, p)}>
|
||||
{p.is_pinned && (
|
||||
<div className="post-pin-state" style={{ width: 'fit-content', display: 'flex', alignItems: 'center', gap: 3, fontSize: 12, color: 'var(--primary)', fontWeight: 600, marginBottom: 4 }}><Icon name="pin" size={12} /> {t('feed.pinned')}</div>
|
||||
)}
|
||||
<div className="post-header">
|
||||
<img
|
||||
src={p.avatar_url || avatar(p.username)}
|
||||
className="post-avatar"
|
||||
alt={p.username || t('feed.anonymous')}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
style={{ cursor: 'pointer' }}
|
||||
onClick={(e) => handleOpenUser(e, p)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
handleOpenUser(e, p);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<span
|
||||
className="post-username"
|
||||
style={{ cursor: 'pointer', color: 'var(--primary)' }}
|
||||
onClick={(e) => handleOpenUser(e, p)}
|
||||
>
|
||||
{p.username || t('feed.anonymous')}
|
||||
</span>
|
||||
<span className="post-time">{time}</span>
|
||||
{p.edited_at && (
|
||||
<span className="post-edited-state" style={{ fontSize: 11, color: 'var(--text-light)', marginLeft: 6 }}>
|
||||
<span className="post-edited-label">{t('feed.deleted')}</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="post-title">{p.title || t('feed.noTitle')}</div>
|
||||
<div className="post-content" dangerouslySetInnerHTML={{ __html: renderMarkdown(p.content) }} />
|
||||
{p.images && p.images.length > 0 && (
|
||||
<div className="post-images">
|
||||
{p.images.map((img, i) => (
|
||||
<img key={i} src={img} className="post-image" alt="" style={{ cursor: 'pointer' }} onClick={(e) => { e.stopPropagation(); setViewerSrc(img); }} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="post-actions">
|
||||
<span>
|
||||
<Icon name="message" size={14} /> {p.reply_count || 0}
|
||||
</span>
|
||||
<button className="action-report" onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (!currentUser) { toast(t('newPost.pleaseLogin'), 'warning'); return; }
|
||||
onReport(p.id);
|
||||
}}>
|
||||
<Icon name="flag" size={14} /> {t('feed.report')}
|
||||
</button>
|
||||
{currentUser && (currentUser.id === p.user_id || currentUser.role === 'admin') && (
|
||||
<button className="action-delete" onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleDelete(p.id);
|
||||
}}>
|
||||
<Icon name="trash" size={14} /> {t('feed.delete')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{totalPages > 1 && posts && posts.length > 0 && (
|
||||
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 6, padding: '16px 0', marginTop: 8, borderTop: '1px solid var(--border)', flexWrap: 'wrap' }}>
|
||||
<button
|
||||
className="page-btn"
|
||||
disabled={page <= 1}
|
||||
onClick={() => load(page - 1)}
|
||||
style={{ padding: '6px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', color: 'var(--text)', cursor: page <= 1 ? 'not-allowed' : 'pointer', fontSize: 13, opacity: page <= 1 ? 0.4 : 1 }}
|
||||
>
|
||||
«
|
||||
</button>
|
||||
{Array.from({ length: totalPages }, (_, i) => i + 1).map((i) => (
|
||||
<button
|
||||
key={i}
|
||||
className="page-btn"
|
||||
disabled={i === page}
|
||||
onClick={() => load(i)}
|
||||
style={{
|
||||
padding: '6px 10px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 13, minWidth: 32, textAlign: 'center',
|
||||
background: i === page ? 'var(--primary)' : 'var(--surface)',
|
||||
color: i === page ? '#fff' : 'var(--text)',
|
||||
cursor: i === page ? 'default' : 'pointer',
|
||||
borderColor: i === page ? 'var(--primary)' : 'var(--border)',
|
||||
}}
|
||||
>
|
||||
{i}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
className="page-btn"
|
||||
disabled={page >= totalPages}
|
||||
onClick={() => load(page + 1)}
|
||||
style={{ padding: '6px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', color: 'var(--text)', cursor: page >= totalPages ? 'not-allowed' : 'pointer', fontSize: 13, opacity: page >= totalPages ? 0.4 : 1 }}
|
||||
>
|
||||
»
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{viewerSrc && <ImageViewer src={viewerSrc} onClose={() => setViewerSrc(null)} />}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// i18n 客户端 Provider:在 children 渲染前同步初始化 i18n
|
||||
// - lng 由 Server Component(layout)从 cookie / Accept-Language 推导传入
|
||||
// - 同步 init(initImmediate:false)→ SSR 与客户端首次渲染语言一致,无 hydration mismatch
|
||||
import { initI18n } from '@/lib/i18n';
|
||||
|
||||
export default function I18nProvider({ lng, children }) {
|
||||
// 函数体在 children 渲染前执行:useTranslation 组件拿到已初始化的 i18n
|
||||
initI18n(lng);
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -1,200 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 图标库 — SVG 内容逐字符提取自旧版 index.html (Feather Icons),与原版一致
|
||||
const S = {
|
||||
xmlns: 'http://www.w3.org/2000/svg', width: 16, height: 16, viewBox: '0 0 24 24',
|
||||
fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round',
|
||||
style: { display: 'inline', verticalAlign: 'middle' },
|
||||
};
|
||||
|
||||
export function Icon({ name, size = 16, ...rest }) {
|
||||
return <svg {...S} width={size} height={size} {...rest}>{PATHS[name] || null}</svg>;
|
||||
}
|
||||
|
||||
const PATHS = {
|
||||
message: (
|
||||
<>
|
||||
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
|
||||
</>
|
||||
),
|
||||
reply: (
|
||||
<>
|
||||
<path d="M9 14l-4-4 4-4"/><path d="M5 10h11a4 4 0 0 1 4 4v0"/>
|
||||
</>
|
||||
),
|
||||
chevronDown: (
|
||||
<>
|
||||
<path d="M6 9l6 6 6-6"/>
|
||||
</>
|
||||
),
|
||||
settings: (
|
||||
<>
|
||||
<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>
|
||||
</>
|
||||
),
|
||||
shieldAlert: (
|
||||
<>
|
||||
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M12 8v4"/><path d="M12 16h.01"/>
|
||||
</>
|
||||
),
|
||||
user: (
|
||||
<>
|
||||
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>
|
||||
</>
|
||||
),
|
||||
lock: (
|
||||
<>
|
||||
<rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>
|
||||
</>
|
||||
),
|
||||
moon: (
|
||||
<>
|
||||
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
|
||||
</>
|
||||
),
|
||||
sun: (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
|
||||
</>
|
||||
),
|
||||
logout: (
|
||||
<>
|
||||
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/>
|
||||
</>
|
||||
),
|
||||
book: (
|
||||
<>
|
||||
<path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/><path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/><line x1="18" y1="12" x2="18" y2="12"/>
|
||||
</>
|
||||
),
|
||||
link: (
|
||||
<>
|
||||
<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>
|
||||
</>
|
||||
),
|
||||
plus: (
|
||||
<>
|
||||
<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>
|
||||
</>
|
||||
),
|
||||
shield: (
|
||||
<>
|
||||
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
|
||||
</>
|
||||
),
|
||||
users: (
|
||||
<>
|
||||
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>
|
||||
</>
|
||||
),
|
||||
file: (
|
||||
<>
|
||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/>
|
||||
</>
|
||||
),
|
||||
plus2: (
|
||||
<>
|
||||
<path d="M12 5v14"/><path d="M5 12h14"/>
|
||||
</>
|
||||
),
|
||||
back: (
|
||||
<>
|
||||
<polyline points="15 18 9 12 15 6"/>
|
||||
</>
|
||||
),
|
||||
close: (
|
||||
<>
|
||||
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
|
||||
</>
|
||||
),
|
||||
trash: (
|
||||
<>
|
||||
<polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
|
||||
</>
|
||||
),
|
||||
success: (
|
||||
<>
|
||||
<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/>
|
||||
</>
|
||||
),
|
||||
error: (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/>
|
||||
</>
|
||||
),
|
||||
warning: (
|
||||
<>
|
||||
<path d="M12 9v4"/><path d="M12 17h.01"/><circle cx="12" cy="12" r="10"/>
|
||||
</>
|
||||
),
|
||||
pending: (
|
||||
<>
|
||||
<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
|
||||
</>
|
||||
),
|
||||
edit: (
|
||||
<>
|
||||
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
|
||||
</>
|
||||
),
|
||||
pin: (
|
||||
<>
|
||||
<path d="M21 10.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h8.5"/><polyline points="16 2 22 8 16 8"/><line x1="10" y1="14" x2="18" y2="14"/><line x1="10" y1="18" x2="14" y2="18"/>
|
||||
</>
|
||||
),
|
||||
camera: (
|
||||
<>
|
||||
<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/>
|
||||
</>
|
||||
),
|
||||
image: (
|
||||
<>
|
||||
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/>
|
||||
</>
|
||||
),
|
||||
key: (
|
||||
<>
|
||||
<path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/>
|
||||
</>
|
||||
),
|
||||
calendar: (
|
||||
<>
|
||||
<rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>
|
||||
</>
|
||||
),
|
||||
refresh: (
|
||||
<>
|
||||
<polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/>
|
||||
</>
|
||||
),
|
||||
list: (
|
||||
<>
|
||||
<line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/>
|
||||
</>
|
||||
),
|
||||
megaphone: (
|
||||
<>
|
||||
<path d="M17 18.5c0 1.5-1.5 3-3.5 3s-3.5-1.5-3.5-3c0-.5.5-1 1-1h5c.5 0 1 .5 1 1z"/><path d="M4 11h16v6H4z"/><path d="M8 17v3"/><path d="M16 17v3"/><path d="M9 11V7a3 3 0 0 1 6 0v4"/>
|
||||
</>
|
||||
),
|
||||
code: (
|
||||
<>
|
||||
<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>
|
||||
</>
|
||||
),
|
||||
upload: (
|
||||
<>
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/>
|
||||
</>
|
||||
),
|
||||
save: (
|
||||
<>
|
||||
<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/>
|
||||
</>
|
||||
),
|
||||
flag: (
|
||||
<>
|
||||
<path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" y1="22" x2="4" y2="15"/>
|
||||
</>
|
||||
),
|
||||
};
|
||||
@@ -1,35 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 图片查看器(点击帖子图片放大)
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export default function ImageViewer({ src, onClose }) {
|
||||
useEffect(() => {
|
||||
const onKey = (e) => { if (e.key === 'Escape') onClose(); };
|
||||
document.addEventListener('keydown', onKey);
|
||||
return () => document.removeEventListener('keydown', onKey);
|
||||
}, [onClose]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="modal active"
|
||||
style={{
|
||||
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.85)', zIndex: 9999,
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
cursor: 'pointer', animation: 'fadeIn 0.2s ease-out',
|
||||
}}
|
||||
onClick={onClose}
|
||||
>
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
style={{
|
||||
maxWidth: '90vw', maxHeight: '90vh', objectFit: 'contain',
|
||||
borderRadius: 8, boxShadow: '0 8px 32px rgba(0,0,0,0.5)',
|
||||
cursor: 'default', userSelect: 'none',
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 全屏加载页:初始化未完成时显示转圈,加载完成后淡出
|
||||
// 论坛名:容器由 React 渲染(SSR 即有),内联脚本在 DOMContentLoaded 时
|
||||
// 填充缓存名 → 首帧显示;suppressHydrationWarning 让 React 跳过该元素
|
||||
// 的文本检查(保留脚本填入的内容),hydrate 后由 AppProvider 状态接管。
|
||||
export default function LoadingScreen({ forumName, forumNameLoaded }) {
|
||||
return (
|
||||
<div className="loading-screen">
|
||||
<div className="loading-inner">
|
||||
<div className="loading-spinner" />
|
||||
<div className={'loading-title' + (forumNameLoaded ? ' loading-title-appear' : '')} id="loadingTitle" suppressHydrationWarning>
|
||||
{forumNameLoaded && forumName}
|
||||
</div>
|
||||
<div className="loading-sub">加载中...</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 消息页:通知列表(回复/删除/举报处理/系统)
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
|
||||
const TYPE_MAP = { reply: 'message', post_deleted: 'trash', report_handled: 'shield', system: 'megaphone' };
|
||||
|
||||
export default function MessagesPage() {
|
||||
const { currentUser } = useApp();
|
||||
const [notifications, setNotifications] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!currentUser) return;
|
||||
API.getNotifications()
|
||||
.then((data) => {
|
||||
setNotifications(data || []);
|
||||
setError(null);
|
||||
API.markAllNotificationsRead().catch(() => {});
|
||||
})
|
||||
.catch((e) => { setError(e.message); setNotifications([]); });
|
||||
}, [currentUser]);
|
||||
|
||||
if (!currentUser) {
|
||||
return <div className="page-slide active" style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>请先登录</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page-slide active">
|
||||
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
|
||||
<h2><Icon name="message" size={20} /> 消息</h2>
|
||||
</div>
|
||||
<div style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
|
||||
{error ? (
|
||||
<div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>加载失败:{error}</div>
|
||||
) : notifications === null ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>加载中...</div>
|
||||
) : notifications.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '60px 0' }}>
|
||||
<Icon name="message" size={48} />
|
||||
<p style={{ fontSize: 16 }}>暂无消息</p>
|
||||
<p style={{ fontSize: 13 }}>当有人回复你的帖子或处理你的举报时,会在这里通知你</p>
|
||||
</div>
|
||||
) : (
|
||||
notifications.map((n) => {
|
||||
const icon = TYPE_MAP[n.type] || 'pin';
|
||||
const time = n.created_at ? new Date(n.created_at).toLocaleString('zh-CN') : '';
|
||||
return (
|
||||
<div key={n.id} style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '14px 16px', borderBottom: '1px solid var(--border-light)', background: 'var(--surface)', borderRadius: 6, marginBottom: 6 }}>
|
||||
<span style={{ color: 'var(--text-secondary)', paddingTop: 2 }}><Icon name={icon} size={20} /></span>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ fontWeight: 600, fontSize: 14 }}>{n.title}</div>
|
||||
<div style={{ color: 'var(--text-secondary)', fontSize: 13, marginTop: 2 }}>{n.content}</div>
|
||||
{n.link && <a href={n.link} style={{ color: 'var(--primary)', fontSize: 13, textDecoration: 'none', marginTop: 4, display: 'inline-block' }}>查看详情 →</a>}
|
||||
<div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 4 }}>{time}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,237 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 登录/注册/举报 模态框
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
import CaptchaImage from './CaptchaImage';
|
||||
import { useToast } from './Toast';
|
||||
|
||||
export default function Modals({ modal, onClose, reportPostId }) {
|
||||
const { login, register, currentUser, refresh } = useApp();
|
||||
const { t } = useTranslation();
|
||||
const { toast } = useToast();
|
||||
|
||||
// 登录表单
|
||||
const [loginEmail, setLoginEmail] = useState('');
|
||||
const [loginPassword, setLoginPassword] = useState('');
|
||||
const [authMode, setAuthMode] = useState('login');
|
||||
const [resetEmail, setResetEmail] = useState('');
|
||||
const [resetRecoveryCode, setResetRecoveryCode] = useState('');
|
||||
const [resetPassword, setResetPassword] = useState('');
|
||||
const [resetPasswordConfirm, setResetPasswordConfirm] = useState('');
|
||||
|
||||
// 注册表单
|
||||
const [regUsername, setRegUsername] = useState('');
|
||||
const [regEmail, setRegEmail] = useState('');
|
||||
const [regPassword, setRegPassword] = useState('');
|
||||
const [regCaptcha, setRegCaptcha] = useState(null);
|
||||
const [regCaptchaInput, setRegCaptchaInput] = useState('');
|
||||
|
||||
// 举报表单
|
||||
const [reportReason, setReportReason] = useState('spam');
|
||||
|
||||
// 打开注册弹窗时从服务器获取验证码挑战(HMAC 签名)
|
||||
useEffect(() => {
|
||||
if (modal === 'register') {
|
||||
API.getCaptcha().then((c) => setRegCaptcha(c)).catch(() => {});
|
||||
}
|
||||
if (modal !== 'login') {
|
||||
setAuthMode('login');
|
||||
setResetEmail('');
|
||||
setResetRecoveryCode('');
|
||||
setResetPassword('');
|
||||
setResetPasswordConfirm('');
|
||||
}
|
||||
}, [modal]);
|
||||
|
||||
if (!modal) return null;
|
||||
|
||||
const close = (e) => {
|
||||
if (e && e.target !== e.currentTarget) return;
|
||||
onClose();
|
||||
};
|
||||
|
||||
const handleLogin = async () => {
|
||||
if (!loginEmail.trim() || !loginPassword) { toast('请填写完整信息', 'warning'); return; }
|
||||
try {
|
||||
const result = await login(loginEmail.trim(), loginPassword);
|
||||
if (result.user) {
|
||||
onClose();
|
||||
setLoginEmail('');
|
||||
setLoginPassword('');
|
||||
refresh();
|
||||
}
|
||||
} catch (err) {
|
||||
toast('登录失败:' + err.message, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const handleResetPassword = async () => {
|
||||
if (!resetEmail.trim() || !resetRecoveryCode.trim() || !resetPassword || !resetPasswordConfirm) {
|
||||
toast(t('auth.resetFillAll'), 'warning');
|
||||
return;
|
||||
}
|
||||
if (resetPassword.length < 6) {
|
||||
toast(t('auth.passwordTooShort'), 'warning');
|
||||
return;
|
||||
}
|
||||
if (resetPassword !== resetPasswordConfirm) {
|
||||
toast(t('auth.passwordMismatch'), 'warning');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await API.resetPassword(resetEmail.trim(), resetRecoveryCode.trim(), resetPassword);
|
||||
setAuthMode('login');
|
||||
setLoginEmail(resetEmail.trim());
|
||||
setLoginPassword('');
|
||||
setResetEmail('');
|
||||
setResetRecoveryCode('');
|
||||
setResetPassword('');
|
||||
setResetPasswordConfirm('');
|
||||
toast(t('auth.resetSuccess'), 'success');
|
||||
} catch (err) {
|
||||
toast(t('auth.resetFailed', { msg: err.message }), 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const returnToLogin = () => {
|
||||
setAuthMode('login');
|
||||
setResetEmail('');
|
||||
setResetRecoveryCode('');
|
||||
setResetPassword('');
|
||||
setResetPasswordConfirm('');
|
||||
};
|
||||
|
||||
const handleRegister = async () => {
|
||||
if (!regUsername.trim() || !regEmail.trim() || !regPassword) { toast('请填写完整信息', 'warning'); return; }
|
||||
if (regPassword.length < 6) { toast('密码至少6位', 'warning'); return; }
|
||||
if (!regCaptcha || !regCaptchaInput.trim()) {
|
||||
toast('请填写验证码', 'warning');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// 答案由服务端 HMAC 校验,前端不对比答案
|
||||
await register(regEmail.trim(), regPassword, regUsername.trim(), { id: regCaptcha.id, answer: regCaptchaInput.trim(), sig: regCaptcha.sig });
|
||||
onClose();
|
||||
setRegUsername('');
|
||||
setRegEmail('');
|
||||
setRegPassword('');
|
||||
setRegCaptchaInput('');
|
||||
toast('注册成功!', 'success');
|
||||
refresh();
|
||||
} catch (err) {
|
||||
toast('注册失败:' + err.message, 'error');
|
||||
// 失败后刷新验证码
|
||||
API.getCaptcha().then((c) => setRegCaptcha(c)).catch(() => {});
|
||||
setRegCaptchaInput('');
|
||||
}
|
||||
};
|
||||
|
||||
const handleReport = async () => {
|
||||
if (!reportPostId) return;
|
||||
try {
|
||||
await API.createReport(reportPostId, reportReason);
|
||||
onClose();
|
||||
toast('举报已提交,管理员将尽快处理', 'success');
|
||||
} catch (err) {
|
||||
toast('举报失败:' + err.message, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{modal === 'login' && authMode === 'login' && (
|
||||
<div className="modal active" onClick={close}>
|
||||
<div className="modal-content">
|
||||
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
|
||||
<h2 style={{ marginBottom: 16 }}>{t('auth.login')}</h2>
|
||||
<input type="email" placeholder={t('auth.email')} value={loginEmail} onChange={(e) => setLoginEmail(e.target.value)} />
|
||||
<input type="password" placeholder={t('auth.password')} value={loginPassword} onChange={(e) => setLoginPassword(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') handleLogin(); }} />
|
||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleLogin}>{t('auth.login')}</button>
|
||||
<button
|
||||
type="button"
|
||||
className="auth-forgot-link"
|
||||
onClick={() => {
|
||||
setResetEmail(loginEmail);
|
||||
setAuthMode('forgot');
|
||||
}}
|
||||
>
|
||||
{t('auth.forgotPassword')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{modal === 'login' && authMode === 'forgot' && (
|
||||
<div className="modal active" onClick={close}>
|
||||
<div className="modal-content">
|
||||
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
|
||||
<h2 style={{ marginBottom: 16 }}>{t('auth.resetTitle')}</h2>
|
||||
<p className="auth-reset-hint">{t('auth.resetHint')}</p>
|
||||
<input type="email" placeholder={t('auth.email')} value={resetEmail} onChange={(e) => setResetEmail(e.target.value)} />
|
||||
<input type="text" placeholder={t('auth.recoveryCode')} value={resetRecoveryCode} onChange={(e) => setResetRecoveryCode(e.target.value)} />
|
||||
<input type="password" placeholder={t('auth.newPassword')} value={resetPassword} onChange={(e) => setResetPassword(e.target.value)} />
|
||||
<input
|
||||
type="password"
|
||||
placeholder={t('auth.confirmPassword')}
|
||||
value={resetPasswordConfirm}
|
||||
onChange={(e) => setResetPasswordConfirm(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') handleResetPassword(); }}
|
||||
/>
|
||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleResetPassword}>{t('auth.resetPassword')}</button>
|
||||
<button type="button" className="auth-forgot-link" onClick={returnToLogin}>
|
||||
{t('auth.backToLogin')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{modal === 'register' && (
|
||||
<div className="modal active" onClick={close}>
|
||||
<div className="modal-content">
|
||||
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
|
||||
<h2 style={{ marginBottom: 16 }}>{t('auth.register')}</h2>
|
||||
<input type="text" placeholder={t('auth.username')} value={regUsername} onChange={(e) => setRegUsername(e.target.value)} />
|
||||
<input type="email" placeholder={t('auth.email')} value={regEmail} onChange={(e) => setRegEmail(e.target.value)} />
|
||||
<input type="password" placeholder={t('auth.passwordHint')} value={regPassword} onChange={(e) => setRegPassword(e.target.value)} />
|
||||
<div className="captcha-row" style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '12px 0' }}>
|
||||
{regCaptcha ? (
|
||||
<CaptchaImage captcha={regCaptcha} onRefresh={() => { API.getCaptcha().then((c) => setRegCaptcha(c)).catch(() => {}); setRegCaptchaInput(''); }} />
|
||||
) : (
|
||||
<span style={{ color: 'var(--text-light)' }}>{t('newPost.captchaLoading')}</span>
|
||||
)}
|
||||
<input type="text" placeholder="答案" style={{ width: 80, background: 'var(--bg)', color: 'var(--text)', border: '1px solid var(--border)', padding: '8px 12px', borderRadius: 4 }} value={regCaptchaInput} onChange={(e) => setRegCaptchaInput(e.target.value)} />
|
||||
</div>
|
||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleRegister}>{t('auth.register')}</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{modal === 'report' && currentUser && (
|
||||
<div className="modal active" onClick={close}>
|
||||
<div className="modal-content">
|
||||
<span className="close" onClick={onClose}><Icon name="close" size={20} /></span>
|
||||
<h2 style={{ marginBottom: 16 }}><Icon name="shieldAlert" size={20} /> {t('post.reportTitle')}</h2>
|
||||
<p style={{ fontSize: 14, color: '#64748b', marginBottom: 12 }}>{t('post.reportReason')}</p>
|
||||
<select
|
||||
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, marginBottom: 16, background: 'var(--bg)', color: 'var(--text)' }}
|
||||
value={reportReason}
|
||||
onChange={(e) => setReportReason(e.target.value)}
|
||||
>
|
||||
<option value="spam">{t('report.spam')}</option>
|
||||
<option value="abuse">{t('report.abuse')}</option>
|
||||
<option value="illegal">{t('report.illegal')}</option>
|
||||
<option value="nsfw">{t('report.nsfw')}</option>
|
||||
<option value="other">{t('report.other')}</option>
|
||||
</select>
|
||||
<button className="btn-primary" style={{ width: '100%' }} onClick={handleReport}>{t('post.submitReport')}</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 导航栏:论坛名、自定义页面链接、登录/注册、私信、用户菜单、主题切换
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
import { API } from '@/lib/api';
|
||||
import { DMButton } from './chat/ChatManager';
|
||||
import { useToast } from './Toast';
|
||||
|
||||
export default function Navbar({ onOpenModal }) {
|
||||
const { currentUser, forumName, theme, toggleTheme, navigate, openCustomPage, logout } = useApp();
|
||||
const { t } = useTranslation();
|
||||
const { toast, confirmAction } = useToast();
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
const [customPages, setCustomPages] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
API.getCustomPages().then(setCustomPages).catch(() => {});
|
||||
}, []);
|
||||
|
||||
// 点击菜单外部关闭下拉(检查目标是否在菜单/头像内,避免 React 合成事件与原生监听冲突)
|
||||
useEffect(() => {
|
||||
const closeMenu = (e) => {
|
||||
const menu = document.getElementById('userDropdown');
|
||||
const avatarEl = document.getElementById('userDropdown')?.querySelector('.avatar');
|
||||
if (menu && menu.contains(e.target)) return;
|
||||
if (avatarEl && avatarEl.contains(e.target)) return;
|
||||
setMenuOpen(false);
|
||||
};
|
||||
document.addEventListener('click', closeMenu);
|
||||
return () => document.removeEventListener('click', closeMenu);
|
||||
}, []);
|
||||
|
||||
const avatarSrc = currentUser?.avatar_url ||
|
||||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(currentUser?.username || 'U') +
|
||||
'&background=6366f1&color=fff';
|
||||
|
||||
const goPage = (page) => {
|
||||
if (page === 'admin' && currentUser?.role !== 'admin') {
|
||||
toast('无权限访问', 'warning');
|
||||
return;
|
||||
}
|
||||
setMenuOpen(false);
|
||||
navigate(page);
|
||||
};
|
||||
|
||||
const openMessages = (e) => {
|
||||
e.preventDefault();
|
||||
setMenuOpen(false);
|
||||
// 消息页展示通知列表,私信使用导航栏按钮。
|
||||
navigate('messages');
|
||||
};
|
||||
|
||||
return (
|
||||
<nav id="navbar">
|
||||
<div className="nav-left">
|
||||
<span className="forum-name" onClick={() => navigate('feed')} style={{ cursor: 'pointer' }}>
|
||||
{forumName}
|
||||
</span>
|
||||
<span id="customNavLinks" style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginLeft: 16 }}>
|
||||
{customPages.map((p) => (
|
||||
<a
|
||||
key={p.id}
|
||||
href={'/' + encodeURIComponent(p.name)}
|
||||
className="custom-page-nav-link"
|
||||
data-custom={p.name}
|
||||
onClick={(e) => { e.preventDefault(); openCustomPage(p.name); }}
|
||||
style={{ color: 'var(--text-secondary)', textDecoration: 'none', fontSize: 14, padding: '4px 10px', borderRadius: 4, transition: 'color 0.15s' }}
|
||||
onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--text)'; }}
|
||||
onMouseLeave={(e) => { e.currentTarget.style.color = 'var(--text-secondary)'; }}
|
||||
>
|
||||
{p.title}
|
||||
</a>
|
||||
))}
|
||||
</span>
|
||||
</div>
|
||||
<div className="nav-right">
|
||||
<DMButton />
|
||||
<div id="userMenu">
|
||||
{!currentUser ? (
|
||||
<div id="authButtons">
|
||||
<button className="btn-ghost" onClick={() => onOpenModal('login')}>{t('nav.login')}</button>
|
||||
<button className="btn-primary" onClick={() => onOpenModal('register')}>{t('nav.register')}</button>
|
||||
</div>
|
||||
) : (
|
||||
<div id="userDropdown" style={{ display: 'block' }}>
|
||||
<img
|
||||
className="avatar"
|
||||
src={avatarSrc}
|
||||
alt="avatar"
|
||||
onClick={(e) => { e.stopPropagation(); setMenuOpen(!menuOpen); }}
|
||||
/>
|
||||
{menuOpen && (
|
||||
<div className="dropdown-menu show" onClick={(e) => e.stopPropagation()}>
|
||||
<a href="#" onClick={openMessages}>
|
||||
<Icon name="message" /> {t('nav.messages')}
|
||||
</a>
|
||||
<a href="#" onClick={(e) => { e.preventDefault(); goPage('settings'); }}>
|
||||
<Icon name="settings" /> {t('nav.settings')}
|
||||
</a>
|
||||
{currentUser.role === 'admin' && (
|
||||
<a href="#" onClick={(e) => { e.preventDefault(); goPage('admin'); }}>
|
||||
<Icon name="shieldAlert" /> {t('nav.admin')}
|
||||
</a>
|
||||
)}
|
||||
<hr />
|
||||
<a
|
||||
href="#"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
toggleTheme();
|
||||
setMenuOpen(false);
|
||||
}}
|
||||
>
|
||||
<Icon name={theme === 'dark' ? 'sun' : 'moon'} /> {theme === 'dark' ? t('nav.lightMode') : t('nav.darkMode')}
|
||||
</a>
|
||||
<hr />
|
||||
<a
|
||||
href="#"
|
||||
onClick={async (e) => {
|
||||
e.preventDefault();
|
||||
if (await confirmAction(t('nav.logoutConfirm'))) {
|
||||
setMenuOpen(false);
|
||||
logout();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Icon name="logout" /> {t('nav.logout')}
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -1,230 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 发帖页
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API, uploadImage } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
import { useToast } from './Toast';
|
||||
import CaptchaImage from './CaptchaImage';
|
||||
import { compressImage, DIRECT_IMAGE_LIMIT, MAX_IMAGE_SOURCE_SIZE } from '@/lib/compress-image';
|
||||
|
||||
export default function NewPost() {
|
||||
const { currentUser, navigate, refresh } = useApp();
|
||||
const { t } = useTranslation();
|
||||
const { toast } = useToast();
|
||||
const [title, setTitle] = useState('');
|
||||
const [content, setContent] = useState('');
|
||||
const [images, setImages] = useState([]); // 上传后的 URL 列表
|
||||
const [previews, setPreviews] = useState([]); // 本地预览 dataURL
|
||||
const [captcha, setCaptcha] = useState(null);
|
||||
const [captchaInput, setCaptchaInput] = useState('');
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [uploadStage, setUploadStage] = useState('uploading');
|
||||
const launchTitle = t('feed.newPost');
|
||||
const [headingText, setHeadingText] = useState(launchTitle);
|
||||
const [headingPhase, setHeadingPhase] = useState('idle');
|
||||
const terminalStartedRef = useRef(false);
|
||||
|
||||
useEffect(() => { API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {}); }, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!terminalStartedRef.current) setHeadingText(launchTitle);
|
||||
}, [launchTitle]);
|
||||
|
||||
useEffect(() => {
|
||||
if (headingPhase === 'idle') return undefined;
|
||||
|
||||
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
|
||||
if (reduceMotion) {
|
||||
if (headingText !== title) setHeadingText(title);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (headingPhase === 'erasing') {
|
||||
if (!headingText) {
|
||||
setHeadingPhase('typing');
|
||||
return undefined;
|
||||
}
|
||||
const timer = window.setTimeout(() => setHeadingText((text) => text.slice(0, -1)), 48);
|
||||
return () => window.clearTimeout(timer);
|
||||
}
|
||||
|
||||
if (headingText === title) return undefined;
|
||||
|
||||
let commonLength = 0;
|
||||
while (
|
||||
commonLength < headingText.length
|
||||
&& commonLength < title.length
|
||||
&& headingText[commonLength] === title[commonLength]
|
||||
) {
|
||||
commonLength += 1;
|
||||
}
|
||||
|
||||
const needsErasing = headingText.length > commonLength;
|
||||
const timer = window.setTimeout(() => {
|
||||
setHeadingText((text) => (
|
||||
needsErasing ? text.slice(0, -1) : title.slice(0, text.length + 1)
|
||||
));
|
||||
}, needsErasing ? 38 : 64);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [headingPhase, headingText, title]);
|
||||
|
||||
const handleTitleChange = (event) => {
|
||||
const nextTitle = event.target.value;
|
||||
setTitle(nextTitle);
|
||||
|
||||
if (!terminalStartedRef.current && nextTitle.length > 0) {
|
||||
terminalStartedRef.current = true;
|
||||
if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) {
|
||||
setHeadingText(nextTitle);
|
||||
setHeadingPhase('typing');
|
||||
} else {
|
||||
setHeadingPhase('erasing');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleFiles = async (files) => {
|
||||
setUploading(true);
|
||||
try {
|
||||
const newPreviews = [];
|
||||
for (const file of files) {
|
||||
if (!file.type.startsWith('image/')) continue;
|
||||
if (file.size > MAX_IMAGE_SOURCE_SIZE) {
|
||||
toast(t('newPost.imageTooLarge'), 'warning');
|
||||
continue;
|
||||
}
|
||||
|
||||
let uploadFile = file;
|
||||
if (file.size > DIRECT_IMAGE_LIMIT) {
|
||||
setUploadStage('compressing');
|
||||
try {
|
||||
uploadFile = await compressImage(file, { maxDimension: 4096 });
|
||||
} catch {
|
||||
toast(t('newPost.imageCompressFailed'), 'error');
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
setUploadStage('uploading');
|
||||
const dataUrl = await new Promise((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => resolve(e.target.result);
|
||||
reader.readAsDataURL(uploadFile);
|
||||
});
|
||||
newPreviews.push(dataUrl);
|
||||
const url = await uploadImage(uploadFile);
|
||||
setImages((prev) => [...prev, url]);
|
||||
}
|
||||
setPreviews((prev) => [...prev, ...newPreviews]);
|
||||
} catch (err) {
|
||||
toast('上传失败:' + err.message, 'error');
|
||||
} finally {
|
||||
setUploading(false);
|
||||
setUploadStage('uploading');
|
||||
}
|
||||
};
|
||||
|
||||
// 拖拽上传
|
||||
const [dragOver, setDragOver] = useState(false);
|
||||
const fileInputRef = useRef(null);
|
||||
const dropZoneStyle = {
|
||||
border: '2px dashed ' + (dragOver ? 'var(--primary)' : 'var(--border)'),
|
||||
borderRadius: 8, padding: 24, textAlign: 'center', cursor: 'pointer',
|
||||
transition: 'all 0.3s', margin: '8px 0 12px',
|
||||
background: dragOver ? 'var(--primary-bg)' : 'var(--bg)',
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!currentUser || !currentUser.id) {
|
||||
toast('请先登录', 'error');
|
||||
navigate('feed');
|
||||
return;
|
||||
}
|
||||
if (!content.trim()) { toast('请填写内容', 'error'); return; }
|
||||
if (!captcha || !captchaInput.trim()) { toast('请填写验证码', 'error'); return; }
|
||||
try {
|
||||
// 答案由服务端 HMAC 校验
|
||||
await API.createPost(title.trim() || '无标题', content.trim(), images, { id: captcha.id, answer: captchaInput.trim(), sig: captcha.sig });
|
||||
toast('发布成功', 'success');
|
||||
navigate('feed');
|
||||
refresh();
|
||||
} catch (err) {
|
||||
toast('发布失败:' + err.message, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div id="pageNew" className="page-slide active">
|
||||
<div className="page-header new-post-page-header" style={{ maxWidth: 600, margin: '0 auto', width: '100%' }}>
|
||||
<h2 className="new-post-heading">
|
||||
<Icon name="plus" size={20} className="new-post-title-icon" />
|
||||
<span className="new-post-title-label">{headingText}</span>
|
||||
{headingPhase !== 'idle' && <span className="new-post-terminal-cursor" aria-hidden="true" />}
|
||||
</h2>
|
||||
</div>
|
||||
<div className="new-post-form-body" style={{ maxWidth: 600, margin: '0 auto', width: '100%' }}>
|
||||
<input
|
||||
type="text"
|
||||
placeholder={t('newPost.title')}
|
||||
style={{ width: '100%', padding: '10px 14px', border: '1.5px solid var(--border)', borderRadius: 6, fontSize: 15, fontWeight: 600, marginBottom: 12, fontFamily: 'inherit', background: 'var(--bg)', color: 'var(--text)' }}
|
||||
value={title}
|
||||
onChange={handleTitleChange}
|
||||
/>
|
||||
<textarea
|
||||
rows={6}
|
||||
placeholder={t('newPost.content')}
|
||||
style={{ width: '100%', padding: 12, border: '1.5px solid var(--border)', borderRadius: 6, fontSize: 15, fontFamily: 'inherit', resize: 'vertical', background: 'var(--bg)', color: 'var(--text)' }}
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
/>
|
||||
<div id="imagePreview" style={{ display: 'flex', flexWrap: 'wrap', gap: 8, margin: '8px 0' }}>
|
||||
{previews.map((src, i) => (
|
||||
<img key={i} src={src} alt="" style={{ width: 80, height: 80, objectFit: 'cover', borderRadius: 4, border: '1px solid var(--border)' }} />
|
||||
))}
|
||||
</div>
|
||||
<div
|
||||
id="dropZone"
|
||||
style={dropZoneStyle}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
|
||||
onDragLeave={(e) => { e.preventDefault(); setDragOver(false); }}
|
||||
onDrop={(e) => { e.preventDefault(); setDragOver(false); if (e.dataTransfer.files) handleFiles(Array.from(e.dataTransfer.files)); }}
|
||||
>
|
||||
{!uploading && !dragOver && <Icon name="image" size={32} style={{ display: 'block', margin: '0 auto 8px', color: 'var(--text-secondary)' }} />}
|
||||
<div style={{ fontSize: 13, color: 'var(--text-secondary)' }}>
|
||||
{uploading ? t(`newPost.${uploadStage}`) : (dragOver ? t('newPost.drop') : t('newPost.dropHint'))}
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
type="file"
|
||||
id="fileInput"
|
||||
accept="image/*"
|
||||
multiple
|
||||
ref={fileInputRef}
|
||||
style={{ display: 'none' }}
|
||||
onChange={(e) => { if (e.target.files) handleFiles(Array.from(e.target.files)); }}
|
||||
/>
|
||||
<div className="captcha-row" style={{ margin: '12px 0', display: 'flex', alignItems: 'center', gap: 10 }}>
|
||||
{captcha ? (
|
||||
<CaptchaImage captcha={captcha} onRefresh={() => { API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {}); setCaptchaInput(''); }} />
|
||||
) : (
|
||||
<span style={{ color: 'var(--text-light)' }}>{t('newPost.captchaLoading')}</span>
|
||||
)}
|
||||
<input
|
||||
type="text"
|
||||
placeholder={t('newPost.answer')}
|
||||
style={{ width: 80, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--bg)', color: 'var(--text)', outline: 'none' }}
|
||||
value={captchaInput}
|
||||
onChange={(e) => setCaptchaInput(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<button className="btn-primary" style={{ padding: '10px 32px', fontSize: 15 }} onClick={handleSubmit}>
|
||||
{uploading ? t('newPost.uploading') : t('newPost.publish')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,320 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 帖子详情页
|
||||
import { useEffect, useState, useCallback, useMemo, useRef } from 'react';
|
||||
import { API, uploadImage } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import ReplyList from './ReplyList';
|
||||
import Sidebar from './Sidebar';
|
||||
import { Icon } from './Icons';
|
||||
import ImageViewer from './ImageViewer';
|
||||
import { renderMarkdown } from '@/lib/markdown';
|
||||
import { useToast } from './Toast';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { compressImage, DIRECT_IMAGE_LIMIT, MAX_IMAGE_SOURCE_SIZE } from '@/lib/compress-image';
|
||||
|
||||
function avatar(username) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
}
|
||||
|
||||
export default function PostDetail({ postId, initialPost = null }) {
|
||||
const { currentUser, navigate, openUser, returnFromPost, refreshKey } = useApp();
|
||||
const { t, i18n } = useTranslation();
|
||||
const { toast, confirmAction } = useToast();
|
||||
const [post, setPost] = useState(initialPost);
|
||||
const [error, setError] = useState(null);
|
||||
const [viewerSrc, setViewerSrc] = useState(null);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [editTitle, setEditTitle] = useState('');
|
||||
const [editContent, setEditContent] = useState('');
|
||||
const [editImages, setEditImages] = useState([]);
|
||||
const [editUploading, setEditUploading] = useState(false);
|
||||
const [editUploadStage, setEditUploadStage] = useState('uploading');
|
||||
const editImageInputRef = useRef(null);
|
||||
// 评论抽屉:帖子加载完成后自动展开(动画完整播放)
|
||||
const [repliesOpen, setRepliesOpen] = useState(false);
|
||||
useEffect(() => {
|
||||
if (post && !repliesOpen) {
|
||||
// 延迟到帖子内容渲染后,让抽屉动画平滑播放
|
||||
const t = setTimeout(() => setRepliesOpen(true), 60);
|
||||
return () => clearTimeout(t);
|
||||
}
|
||||
}, [post]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setError(null);
|
||||
try {
|
||||
const data = await API.getPost(postId);
|
||||
setPost(data);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
}
|
||||
}, [postId, refreshKey]);
|
||||
|
||||
const initialRefreshKey = useRef(refreshKey);
|
||||
useEffect(() => {
|
||||
const initialReference = initialPost?.post_number || initialPost?.id;
|
||||
if (String(initialReference || '') === String(postId) && refreshKey === initialRefreshKey.current) return;
|
||||
load();
|
||||
}, [initialPost?.id, initialPost?.post_number, load, postId, refreshKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!post?.post_number || !window.location.pathname.startsWith('/post/')) return;
|
||||
const canonicalPath = `/post/${post.post_number}`;
|
||||
if (window.location.pathname === canonicalPath) return;
|
||||
const url = new URL(window.location);
|
||||
url.pathname = canonicalPath;
|
||||
window.history.replaceState(
|
||||
{ ...window.history.state, page: 'post', postId: String(post.post_number) },
|
||||
'',
|
||||
url
|
||||
);
|
||||
}, [post?.post_number]);
|
||||
const renderedContent = useMemo(() => renderMarkdown(post?.content), [post?.content]);
|
||||
const renderedSignature = useMemo(() => renderMarkdown(post?.signature), [post?.signature]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div id="pagePost" className="page-slide active" style={{ padding: '40px 0', textAlign: 'center', color: '#ef4444' }}>
|
||||
加载失败:{error}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!post) {
|
||||
return <div id="pagePost" className="page-slide active" style={{ textAlign: 'center', color: '#94a3b8' }}><span className="spinner-sm" />加载中...</div>;
|
||||
}
|
||||
|
||||
const time = post.created_at ? new Date(post.created_at).toLocaleString('zh-CN') : '';
|
||||
// 作者本人 或 管理员 可删除/编辑
|
||||
const canDelete = currentUser && (currentUser.id === post.user_id || currentUser.role === 'admin');
|
||||
const canEdit = currentUser && currentUser.id === post.user_id;
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!await confirmAction('确定要删除这条帖子吗?')) return;
|
||||
try {
|
||||
await API.deletePost(postId);
|
||||
toast('删除成功', 'success');
|
||||
navigate('feed');
|
||||
} catch (err) {
|
||||
toast('删除失败:' + err.message, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const handleTogglePin = async () => {
|
||||
if (!await confirmAction('确定要' + (post.is_pinned ? '取消' : '') + '置顶吗?', { danger: false })) return;
|
||||
try {
|
||||
await API.togglePinPost(postId);
|
||||
load();
|
||||
} catch (err) {
|
||||
toast('操作失败:' + err.message, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = () => {
|
||||
setEditTitle(post.title || '');
|
||||
setEditContent(post.content || '');
|
||||
setEditImages(post.images || []);
|
||||
setEditing(true);
|
||||
};
|
||||
|
||||
const handleSaveEdit = async () => {
|
||||
if (!editContent.trim()) { toast('请填写内容', 'warning'); return; }
|
||||
try {
|
||||
await API.updatePost(postId, editTitle.trim() || '无标题', editContent.trim(), editImages);
|
||||
setEditing(false);
|
||||
load();
|
||||
} catch (err) {
|
||||
toast('编辑失败:' + err.message, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
// 编辑时上传新图片
|
||||
const handleEditUpload = async (file) => {
|
||||
if (!file) return;
|
||||
if (!file.type.startsWith('image/')) { toast('请选择图片文件', 'warning'); return; }
|
||||
if (file.size > MAX_IMAGE_SOURCE_SIZE) { toast(t('post.imageTooLarge'), 'warning'); return; }
|
||||
setEditUploading(true);
|
||||
try {
|
||||
let uploadFile = file;
|
||||
if (file.size > DIRECT_IMAGE_LIMIT) {
|
||||
setEditUploadStage('compressing');
|
||||
uploadFile = await compressImage(file, { maxDimension: 4096 });
|
||||
}
|
||||
setEditUploadStage('uploading');
|
||||
const url = await uploadImage(uploadFile);
|
||||
setEditImages((prev) => [...prev, url]);
|
||||
} catch (err) {
|
||||
toast(
|
||||
err.message === 'compression_failed'
|
||||
? t('post.imageCompressFailed')
|
||||
: t('post.imageUploadFailed', { msg: err.message }),
|
||||
'error'
|
||||
);
|
||||
} finally {
|
||||
setEditUploading(false);
|
||||
setEditUploadStage('uploading');
|
||||
}
|
||||
};
|
||||
|
||||
// 编辑时删除图片
|
||||
const handleEditRemoveImage = (url) => {
|
||||
setEditImages((prev) => prev.filter((u) => u !== url));
|
||||
};
|
||||
|
||||
const handleOpenUser = (event) => {
|
||||
const header = event.currentTarget.closest('.post-header');
|
||||
openUser(
|
||||
post.username,
|
||||
{
|
||||
avatarElement: header?.querySelector('.post-avatar'),
|
||||
nameElement: header?.querySelector('.post-username'),
|
||||
},
|
||||
{
|
||||
username: post.username,
|
||||
avatar_url: post.avatar_url || avatar(post.username),
|
||||
sourcePostId: post.id,
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div id="pagePost" className="page-slide active">
|
||||
<div className="page-header post-page-header">
|
||||
<button className="back-btn" onClick={returnFromPost}>
|
||||
<Icon name="back" size={16} /> 返回
|
||||
</button>
|
||||
<h2>{post.title || '帖子详情'}</h2>
|
||||
</div>
|
||||
<div className="post-page-layout">
|
||||
<Sidebar id="postSidebar" />
|
||||
<div id="postDetailContent" className="post-page-main">
|
||||
<div className="post-detail-card" data-username={post.username || ''}>
|
||||
<div className="post-header">
|
||||
<img
|
||||
src={post.avatar_url || avatar(post.username)}
|
||||
className="post-avatar"
|
||||
alt={post.username || '匿名用户'}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
style={{ cursor: 'pointer' }}
|
||||
onClick={handleOpenUser}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault();
|
||||
handleOpenUser(event);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<span
|
||||
className="post-username"
|
||||
style={{ cursor: 'pointer', color: 'var(--primary)' }}
|
||||
onClick={handleOpenUser}
|
||||
>
|
||||
{post.username || '匿名用户'}
|
||||
</span>
|
||||
<span className="post-time">{time}</span>
|
||||
{post.edited_at && (
|
||||
<span className="post-edited-state" style={{ fontSize: 12, color: 'var(--text-light)', marginLeft: 8 }}>
|
||||
<span className="post-edited-label">{t('feed.deleted')}</span>
|
||||
<span className="post-edited-detail">
|
||||
{' '}{new Date(post.edited_at).toLocaleString(i18n.language === 'en' ? 'en-US' : 'zh-CN')}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
{post.is_pinned && (
|
||||
<span className="post-pin-state" style={{ fontSize: 12, color: 'var(--primary)', marginLeft: 8, display: 'inline-flex', alignItems: 'center', gap: 3 }}><Icon name="pin" size={12} /> 置顶</span>
|
||||
)}
|
||||
<div className="post-detail-controls" style={{ display: 'flex', gap: 4, marginLeft: 'auto' }}>
|
||||
{currentUser && currentUser.role === 'admin' && (
|
||||
<button className="btn-sm btn-secondary" style={{ padding: '4px 10px' }} onClick={handleTogglePin}>
|
||||
<Icon name="pin" size={12} /> {post.is_pinned ? '取消置顶' : '置顶'}
|
||||
</button>
|
||||
)}
|
||||
{canEdit && (
|
||||
<button className="btn-sm btn-secondary" style={{ padding: '4px 10px' }} onClick={handleEdit}>
|
||||
<Icon name="edit" size={12} /> 编辑
|
||||
</button>
|
||||
)}
|
||||
{canDelete && (
|
||||
<button className="btn-sm btn-danger" style={{ padding: '4px 10px' }} onClick={handleDelete}>
|
||||
<Icon name="trash" size={14} /> 删除
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="post-content" dangerouslySetInnerHTML={{ __html: renderedContent }} />
|
||||
{post.images && post.images.length > 0 && (
|
||||
<div className="post-images">
|
||||
{post.images.map((img, i) => (
|
||||
<img key={i} src={img} className="post-image" alt="" style={{ cursor: 'pointer' }} onClick={() => setViewerSrc(img)} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{post.signature && (
|
||||
<div className="post-detail-signature" style={{ marginTop: 16, paddingTop: 12, borderTop: '1px solid var(--border-light)', fontSize: 12, color: 'var(--text-secondary)' }} dangerouslySetInnerHTML={{ __html: renderedSignature }} />
|
||||
)}
|
||||
</div>
|
||||
<div style={{ maxWidth: 700, margin: '0 auto', width: '100%', marginTop: 16 }}>
|
||||
{/* 评论抽屉:帖子加载完成后自动展开 */}
|
||||
<div className={'replies-drawer' + (repliesOpen ? ' open' : '')}>
|
||||
<div className="replies-drawer-inner">
|
||||
<ReplyList postId={postId} onRefresh={load} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 编辑帖子 modal */}
|
||||
{editing && (
|
||||
<div className="modal active" style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) setEditing(false); }}>
|
||||
<div className="modal-content" style={{ maxWidth: 600, position: 'relative' }}>
|
||||
<span className="close" style={{ position: 'absolute', top: 12, right: 16, cursor: 'pointer', color: 'var(--text-light)' }} onClick={() => setEditing(false)}><Icon name="close" size={20} /></span>
|
||||
<h2 style={{ marginBottom: 16 }}><Icon name="edit" size={20} /> 编辑帖子</h2>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="标题"
|
||||
value={editTitle}
|
||||
onChange={(e) => setEditTitle(e.target.value)}
|
||||
style={{ width: '100%', padding: '10px 14px', border: '1px solid var(--border)', borderRadius: 6, fontSize: 15, fontWeight: 600, marginBottom: 12, background: 'var(--bg)', color: 'var(--text)' }}
|
||||
/>
|
||||
<textarea
|
||||
rows={6}
|
||||
placeholder="说点什么..."
|
||||
value={editContent}
|
||||
onChange={(e) => setEditContent(e.target.value)}
|
||||
style={{ width: '100%', padding: 12, border: '1px solid var(--border)', borderRadius: 6, fontSize: 15, fontFamily: 'inherit', resize: 'vertical', background: 'var(--bg)', color: 'var(--text)' }}
|
||||
/>
|
||||
{/* 图片管理:查看/删除已有图片 + 上传新图片 */}
|
||||
{editImages.length > 0 && (
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 10 }}>
|
||||
{editImages.map((img, i) => (
|
||||
<div key={img + i} style={{ position: 'relative' }}>
|
||||
<img src={img} alt="" style={{ width: 72, height: 72, objectFit: 'cover', borderRadius: 6, border: '1px solid var(--border)' }} />
|
||||
<button
|
||||
type="button"
|
||||
title="删除图片"
|
||||
onClick={() => handleEditRemoveImage(img)}
|
||||
style={{ position: 'absolute', top: -6, right: -6, width: 20, height: 20, borderRadius: '50%', background: '#ef4444', color: '#fff', border: 'none', cursor: 'pointer', lineHeight: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}
|
||||
><Icon name="close" size={12} /></button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
|
||||
<button type="button" className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={() => editImageInputRef.current?.click()}>
|
||||
{editUploading ? t(`post.image${editUploadStage === 'compressing' ? 'Compressing' : 'Uploading'}`) : <><Icon name="camera" size={14} /> {t('post.imageUpload')}</>}
|
||||
</button>
|
||||
<input type="file" ref={editImageInputRef} accept="image/*" multiple style={{ display: 'none' }} onChange={(e) => { const files = e.target.files; if (files && files.length > 0) { [...files].forEach((f) => handleEditUpload(f)); e.target.value = ''; } }} />
|
||||
</div>
|
||||
<button className="btn-primary" style={{ padding: '10px 32px', fontSize: 15, marginTop: 12, width: '100%' }} onClick={handleSaveEdit}>保存</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 图片查看器 */}
|
||||
{viewerSrc && <ImageViewer src={viewerSrc} onClose={() => setViewerSrc(null)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 恢复码管理:查看 + 重新生成
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '@/lib/api';
|
||||
import { Icon } from './Icons';
|
||||
import { useToast } from './Toast';
|
||||
|
||||
export default function RecoveryCodes() {
|
||||
const { t } = useTranslation();
|
||||
const { toast, confirmAction } = useToast();
|
||||
const [count, setCount] = useState(0);
|
||||
const [modal, setModal] = useState(null); // null | {codes, isNew}
|
||||
const [modalClosing, setModalClosing] = useState(false);
|
||||
|
||||
const closeModal = () => {
|
||||
setModalClosing(true);
|
||||
setTimeout(() => {
|
||||
setModal(null);
|
||||
setModalClosing(false);
|
||||
}, 340);
|
||||
};
|
||||
|
||||
const loadCount = () => {
|
||||
API.getRecoveryCodeCount().then((d) => setCount(d.count || 0)).catch(() => {});
|
||||
};
|
||||
useEffect(loadCount, []);
|
||||
|
||||
const regenerate = async () => {
|
||||
if (!await confirmAction(t('recovery.confirmRegenerate'))) return;
|
||||
try {
|
||||
const d = await API.generateRecoveryCodes();
|
||||
setModal({ codes: d.codes || [], isNew: true });
|
||||
loadCount();
|
||||
} catch (err) {
|
||||
toast(t('recovery.genFailed', { msg: err.message }), 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const view = async () => {
|
||||
try {
|
||||
// 生成后直接展示;若已有恢复码则重新生成展示(与原版一致:查看即生成新码)
|
||||
const d = await API.generateRecoveryCodes();
|
||||
setModal({ codes: d.codes || [], isNew: false });
|
||||
loadCount();
|
||||
} catch (err) {
|
||||
toast(t('recovery.fetchFailed', { msg: err.message }), 'error');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ marginTop: 16, background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
|
||||
<h3 style={{ fontSize: 16, marginBottom: 8 }}><Icon name="key" size={16} /> {t('recovery.title')}</h3>
|
||||
<p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 12 }}>{t('recovery.desc')}</p>
|
||||
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={view}><Icon name="list" size={14} /> {t('recovery.view')}</button>
|
||||
<button className="btn-secondary" style={{ padding: '8px 16px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={regenerate}><Icon name="refresh" size={14} /> {t('recovery.regenerate')}</button>
|
||||
</div>
|
||||
<div id="recoveryCodesStatus" style={{ fontSize: 13, color: 'var(--text-light)', marginTop: 8 }}>{t('recovery.remaining', { count })}</div>
|
||||
|
||||
{modal && (
|
||||
<div className={'modal active' + (modalClosing ? ' closing' : '')} style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) closeModal(); }}>
|
||||
<div className="modal-content" style={{ maxWidth: 480, position: 'relative' }}>
|
||||
<span className="close" style={{ position: 'absolute', top: 12, right: 16, cursor: 'pointer', color: 'var(--text-light)' }} onClick={closeModal}><Icon name="close" size={20} /></span>
|
||||
<h2 style={{ marginBottom: 12 }}>{modal.isNew ? t('recovery.newCodes') : t('recovery.title')}</h2>
|
||||
<p style={{ fontSize: 13, color: '#ef4444', marginBottom: 12, display: 'flex', alignItems: 'flex-start', gap: 6 }}><Icon name="warning" size={14} /> {t('recovery.saveWarning')}</p>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
|
||||
{modal.codes.map((c, i) => (
|
||||
<code key={i} style={{ background: 'var(--bg)', padding: '8px 12px', borderRadius: 6, fontSize: 13, textAlign: 'center', userSelect: 'all' }}>{c}</code>
|
||||
))}
|
||||
</div>
|
||||
<button className="btn-primary" style={{ width: '100%', padding: 10, marginTop: 16 }} onClick={closeModal}>{t('recovery.saved')}</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,219 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 回复列表 + 发表回复表单
|
||||
import { useEffect, useState, useCallback, useRef } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
import { renderMarkdown } from '@/lib/markdown';
|
||||
import CaptchaImage from './CaptchaImage';
|
||||
import { useToast } from './Toast';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
function avatar(username) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || '匿名用户') +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
}
|
||||
|
||||
export default function ReplyList({ postId, onRefresh }) {
|
||||
const { currentUser, openUser } = useApp();
|
||||
const { toast, confirmAction } = useToast();
|
||||
const { t } = useTranslation();
|
||||
const [replies, setReplies] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showLoading, setShowLoading] = useState(false);
|
||||
const [content, setContent] = useState('');
|
||||
const [captcha, setCaptcha] = useState(null);
|
||||
const [captchaInput, setCaptchaInput] = useState('');
|
||||
// 正在回复的用户(hover 回复按钮 → 回填到回复框)
|
||||
const [replyTo, setReplyTo] = useState(null);
|
||||
const replyAreaRef = useRef(null);
|
||||
const replyInputRef = useRef(null);
|
||||
const loadRequestRef = useRef(0);
|
||||
|
||||
// 点击"回复":记录目标回复 ID,滚动到回复框并聚焦
|
||||
const startReply = (replyId) => {
|
||||
setReplyTo(replyId);
|
||||
setTimeout(() => {
|
||||
replyAreaRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
replyInputRef.current?.focus();
|
||||
}, 120);
|
||||
};
|
||||
|
||||
const load = useCallback(async ({ reset = false } = {}) => {
|
||||
const requestId = ++loadRequestRef.current;
|
||||
if (reset) setReplies(null);
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await API.getReplies(postId);
|
||||
if (requestId !== loadRequestRef.current) return;
|
||||
setReplies(data || []);
|
||||
} catch {
|
||||
if (requestId !== loadRequestRef.current) return;
|
||||
setReplies([]);
|
||||
} finally {
|
||||
if (requestId === loadRequestRef.current) setLoading(false);
|
||||
}
|
||||
}, [postId]);
|
||||
|
||||
useEffect(() => {
|
||||
load({ reset: true });
|
||||
return () => { loadRequestRef.current += 1; };
|
||||
}, [load]);
|
||||
|
||||
// 快请求不闪加载态;慢请求的加载动画由 CSS 等帖子 View Transition 结束后再淡入。
|
||||
useEffect(() => {
|
||||
if (!loading) {
|
||||
setShowLoading(false);
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(() => setShowLoading(true), 180);
|
||||
return () => clearTimeout(timer);
|
||||
}, [loading]);
|
||||
|
||||
useEffect(() => { API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {}); }, [postId]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!currentUser) { toast('请先登录', 'warning'); return; }
|
||||
if (!content.trim()) { toast('请填写回复内容', 'warning'); return; }
|
||||
if (!captcha || !captchaInput.trim()) { toast('请填写验证码', 'warning'); return; }
|
||||
try {
|
||||
// 答案由服务端 HMAC 校验
|
||||
await API.createReply(
|
||||
postId,
|
||||
content.trim(),
|
||||
{ id: captcha.id, answer: captchaInput.trim(), sig: captcha.sig },
|
||||
replyTo,
|
||||
replyToObj?.username
|
||||
);
|
||||
setContent('');
|
||||
setCaptchaInput('');
|
||||
setReplyTo(null);
|
||||
API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {});
|
||||
load();
|
||||
onRefresh();
|
||||
} catch (err) {
|
||||
toast('回复失败:' + err.message, 'error');
|
||||
API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {});
|
||||
setCaptchaInput('');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (replyId) => {
|
||||
if (!await confirmAction('确定要删除这条回复吗?')) return;
|
||||
try {
|
||||
await API.deleteReply(replyId);
|
||||
load();
|
||||
} catch (err) {
|
||||
toast('删除失败:' + err.message, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
// 计算每条回复的嵌套深度(按 reply_to_id 精确追踪回复链)
|
||||
const loadedReplies = replies || [];
|
||||
const replyDepths = (() => {
|
||||
const map = {};
|
||||
const getDepth = (r) => {
|
||||
if (map[r.id] !== undefined) return map[r.id];
|
||||
if (!r.reply_to_id) { map[r.id] = 0; return 0; }
|
||||
const parent = loadedReplies.find((x) => x.id === r.reply_to_id);
|
||||
const d = parent ? getDepth(parent) + 1 : 0;
|
||||
map[r.id] = d;
|
||||
return d;
|
||||
};
|
||||
loadedReplies.forEach((r) => getDepth(r));
|
||||
return map;
|
||||
})();
|
||||
|
||||
// 正在回复的目标回复对象(用于显示 @用户名)
|
||||
const replyToObj = replyTo ? loadedReplies.find((x) => x.id === replyTo) : null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{loading && replies === null ? (
|
||||
showLoading && (
|
||||
<div className="reply-loading-state" role="status" aria-live="polite">
|
||||
<span className="reply-loading-spinner" aria-hidden="true" />
|
||||
<span>{t('reply.loading')}</span>
|
||||
</div>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
<div className="post-reply-count" style={{ marginTop: 20, fontSize: 14, color: '#64748b' }}>
|
||||
<Icon name="message" size={14} /> {loadedReplies.length} 条回复
|
||||
</div>
|
||||
<div style={{ marginTop: 12 }}>
|
||||
{loadedReplies.length === 0 ? (
|
||||
<div style={{ color: '#94a3b8', padding: '20px 0', textAlign: 'center' }}><Icon name="message" size={16} /> 还没有回复,快来发表第一条回复吧</div>
|
||||
) : (
|
||||
loadedReplies.map((r) => {
|
||||
const rTime = r.created_at ? new Date(r.created_at).toLocaleString('zh-CN') : '';
|
||||
const nestDepth = Math.min(replyDepths[r.id] || 0, 5);
|
||||
return (
|
||||
<div key={r.id} className="reply-item" data-username={r.username} data-reply-id={r.id} style={{ marginLeft: nestDepth ? nestDepth * 18 : 0 }}>
|
||||
<div className="reply-header">
|
||||
<img src={r.avatar_url || avatar(r.username)} className="reply-avatar" alt="" />
|
||||
<span
|
||||
className="reply-username"
|
||||
style={{ cursor: 'pointer', color: 'var(--primary)' }}
|
||||
onClick={() => openUser(r.username)}
|
||||
>
|
||||
{r.username || '匿名用户'}
|
||||
</span>
|
||||
<span className="reply-time">{rTime}</span>
|
||||
<button className="reply-btn" onClick={() => startReply(r.id)} title="回复">
|
||||
<Icon name="reply" size={13} />
|
||||
</button>
|
||||
{currentUser && (currentUser.id === r.user_id || currentUser.role === 'admin') && (
|
||||
<button className="btn-sm btn-danger reply-delete-btn" onClick={() => handleDelete(r.id)}>
|
||||
<Icon name="trash" size={12} /> 删除
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="reply-content" dangerouslySetInnerHTML={{ __html: renderMarkdown(r.content) }} />
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div id="replyArea" ref={replyAreaRef} style={{ marginTop: 24, borderTop: '1px solid var(--border)', paddingTop: 20 }}>
|
||||
<h3 style={{ fontSize: 16, marginBottom: 12 }}><Icon name="message" size={16} /> 发表回复</h3>
|
||||
{replyTo && replyToObj && (
|
||||
<div className="reply-preview-bar">
|
||||
<Icon name="reply" size={13} />
|
||||
<span>回复</span>
|
||||
<strong>@{replyToObj.username}</strong>
|
||||
<button className="reply-preview-cancel" onClick={() => setReplyTo(null)}>取消</button>
|
||||
</div>
|
||||
)}
|
||||
<textarea
|
||||
ref={replyInputRef}
|
||||
rows={3}
|
||||
placeholder="写下你的回复..."
|
||||
style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, fontFamily: 'inherit', resize: 'vertical', background: 'var(--bg)', color: 'var(--text)' }}
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) handleSubmit(); }}
|
||||
/>
|
||||
<div className="captcha-row" style={{ margin: '10px 0', display: 'flex', alignItems: 'center', gap: 10 }}>
|
||||
{captcha ? (
|
||||
<CaptchaImage captcha={captcha} onRefresh={() => { API.getCaptcha().then((c) => setCaptcha(c)).catch(() => {}); setCaptchaInput(''); }} />
|
||||
) : (
|
||||
<span style={{ color: 'var(--text-light)' }}>验证码加载中...</span>
|
||||
)}
|
||||
<input
|
||||
type="text"
|
||||
placeholder="答案"
|
||||
style={{ width: 80, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--bg)', color: 'var(--text)', outline: 'none' }}
|
||||
value={captchaInput}
|
||||
onChange={(e) => setCaptchaInput(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<button className="btn-primary" style={{ padding: '8px 24px' }} onClick={handleSubmit}>提交回复</button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 个人设置页:侧边栏布局 + 上下滑动平滑切换
|
||||
// - 三个面板纵向排列在滚动容器里,scroll-snap 每次滑动对齐一个面板
|
||||
// - 点侧边栏导航 → 平滑滚动到对应面板;滚动结束 → 自动更新导航高亮
|
||||
import { useState, useRef, useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Icon } from './Icons';
|
||||
import SettingsProfile from './SettingsProfile';
|
||||
import AccountSecurity from './AccountSecurity';
|
||||
import RecoveryCodes from './RecoveryCodes';
|
||||
|
||||
const NAV = [
|
||||
{ key: 'profile', labelKey: 'settings.profile', icon: 'user' },
|
||||
{ key: 'security', labelKey: 'settings.security', icon: 'shieldAlert' },
|
||||
{ key: 'recovery', labelKey: 'settings.recovery', icon: 'lock' },
|
||||
];
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { t } = useTranslation();
|
||||
const [tab, setTab] = useState('profile');
|
||||
const scrollRef = useRef(null);
|
||||
const scrollTicking = useRef(false);
|
||||
|
||||
// 滚动结束(或对齐后)更新高亮
|
||||
const handleScroll = useCallback(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el || scrollTicking.current) return;
|
||||
scrollTicking.current = true;
|
||||
requestAnimationFrame(() => {
|
||||
scrollTicking.current = false;
|
||||
const idx = Math.round(el.scrollTop / el.clientHeight);
|
||||
const key = NAV[Math.min(Math.max(idx, 0), NAV.length - 1)]?.key;
|
||||
if (key) setTab(key);
|
||||
});
|
||||
}, []);
|
||||
|
||||
// 点击导航 → 平滑滚动到对应面板
|
||||
const goTo = (key, e) => {
|
||||
if (e) e.preventDefault();
|
||||
setTab(key);
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
const idx = NAV.findIndex((n) => n.key === key);
|
||||
el.scrollTo({ top: idx * el.clientHeight, behavior: 'smooth' });
|
||||
};
|
||||
|
||||
return (
|
||||
<div id="pageSettings" className="page-slide active" style={{ overflow: 'hidden', height: '100vh', display: 'flex', flexDirection: 'column' }}>
|
||||
<div className="page-header" style={{ width: '100%', flexShrink: 0 }}>
|
||||
<h2><Icon name="settings" size={20} /> {t('settings.title')}</h2>
|
||||
</div>
|
||||
<div className="settings-layout" style={{ width: '100%', display: 'flex', gap: 28, alignItems: 'flex-start', flex: 1, minHeight: 0 }}>
|
||||
<aside className="settings-sidebar" style={{ width: 200, flexShrink: 0 }}>
|
||||
<nav className="settings-nav">
|
||||
{NAV.map((n) => (
|
||||
<a
|
||||
key={n.key}
|
||||
href="#"
|
||||
className={'settings-nav-item' + (tab === n.key ? ' active' : '')}
|
||||
data-settings-tab={n.key}
|
||||
onClick={(e) => goTo(n.key, e)}
|
||||
>
|
||||
<span className="nav-icon"><Icon name={n.icon} size={18} /></span>
|
||||
{t(n.labelKey)}
|
||||
</a>
|
||||
))}
|
||||
</nav>
|
||||
</aside>
|
||||
<main className="settings-content" id="settingsContent" style={{ overflow: 'hidden', padding: 0, alignSelf: 'stretch', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
|
||||
<div
|
||||
ref={scrollRef}
|
||||
onScroll={handleScroll}
|
||||
style={{
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
overflowY: 'auto',
|
||||
scrollSnapType: 'y mandatory',
|
||||
scrollBehavior: 'smooth',
|
||||
scrollbarWidth: 'none',
|
||||
msOverflowStyle: 'none',
|
||||
}}
|
||||
>
|
||||
<div style={{ scrollSnapAlign: 'start', minHeight: '100%', padding: '20px 24px' }} data-panel="profile">
|
||||
<SettingsProfile />
|
||||
</div>
|
||||
<div style={{ scrollSnapAlign: 'start', minHeight: '100%', padding: '20px 24px', borderTop: '1px solid var(--glass-border)' }} data-panel="security">
|
||||
<AccountSecurity />
|
||||
</div>
|
||||
<div style={{ scrollSnapAlign: 'start', minHeight: '100%', padding: '20px 24px', borderTop: '1px solid var(--glass-border)' }} data-panel="recovery">
|
||||
<RecoveryCodes />
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 设置 - 个人资料(头像 + 用户名/简介/签名 + 语言)
|
||||
import { useState, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API, uploadImage } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { setAppLanguage } from '@/lib/i18n';
|
||||
import { Icon } from './Icons';
|
||||
import { useToast } from './Toast';
|
||||
|
||||
export default function SettingsProfile() {
|
||||
const { currentUser, setCurrentUser } = useApp();
|
||||
const { t, i18n } = useTranslation();
|
||||
const { toast } = useToast();
|
||||
const [username, setUsername] = useState(currentUser?.username || '');
|
||||
const [bio, setBio] = useState(currentUser?.bio || '');
|
||||
const [signature, setSignature] = useState(currentUser?.signature || '');
|
||||
const [avatarUrl, setAvatarUrl] = useState(currentUser?.avatar_url || '');
|
||||
const [avatarStatus, setAvatarStatus] = useState(null);
|
||||
const avatarInputRef = useRef(null);
|
||||
|
||||
const handleAvatar = async (file) => {
|
||||
if (!file) return;
|
||||
if (!file.type.startsWith('image/')) { setAvatarStatus({ ok: false, msg: t('settings.avatarFileRequired') }); return; }
|
||||
if (file.size > 5 * 1024 * 1024) { setAvatarStatus({ ok: false, msg: t('settings.avatarTooLarge') }); return; }
|
||||
try {
|
||||
const url = await uploadImage(file);
|
||||
await API.updateAvatar(currentUser.id, url);
|
||||
setAvatarUrl(url);
|
||||
setCurrentUser({ ...currentUser, avatar_url: url });
|
||||
setAvatarStatus({ ok: true, msg: t('settings.avatarUpdated') });
|
||||
} catch (err) {
|
||||
setAvatarStatus({ ok: false, msg: err.message });
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!currentUser) { toast(t('settings.pleaseLogin'), 'warning'); return; }
|
||||
if (!username.trim()) { toast(t('settings.usernameRequired'), 'warning'); return; }
|
||||
try {
|
||||
const data = await API.updateProfile(currentUser.id, username.trim(), bio.trim(), signature.trim());
|
||||
if (data.error) throw new Error(data.error);
|
||||
setCurrentUser({ ...currentUser, username: username.trim(), bio: bio.trim(), signature: signature.trim() });
|
||||
toast(t('settings.saved'), 'success');
|
||||
} catch (err) {
|
||||
toast(t('settings.saveFailed', { msg: err.message }), 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const avatarSrc = avatarUrl ||
|
||||
'https://ui-avatars.com/api/?name=' + encodeURIComponent(currentUser?.username || 'U') + '&background=6366f1&color=fff&size=128';
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* 头像 */}
|
||||
<div style={{ textAlign: 'center', marginBottom: 24 }}>
|
||||
<div style={{ position: 'relative', display: 'inline-block' }}>
|
||||
<img className="settings-profile-avatar" src={avatarSrc} style={{ width: 100, height: 100, borderRadius: '50%', objectFit: 'cover', border: '3px solid var(--primary)' }} alt="" />
|
||||
<button
|
||||
style={{ position: 'absolute', bottom: 0, right: 0, background: 'var(--primary)', color: '#fff', border: 'none', borderRadius: '50%', width: 32, height: 32, cursor: 'pointer', fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 2px 8px rgba(99,102,241,0.4)' }}
|
||||
onClick={() => avatarInputRef.current?.click()}
|
||||
aria-label={t('settings.changeAvatar')}
|
||||
title={t('settings.changeAvatar')}
|
||||
>
|
||||
<Icon name="camera" size={16} />
|
||||
</button>
|
||||
</div>
|
||||
<input type="file" ref={avatarInputRef} accept="image/*" style={{ display: 'none' }} onChange={(e) => { if (e.target.files?.[0]) handleAvatar(e.target.files[0]); }} />
|
||||
<h2 className="settings-profile-name" style={{ margin: '12px 0 4px', fontSize: 14, fontWeight: 600, color: 'var(--primary)' }}>{currentUser?.username}</h2>
|
||||
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{bio || t('user.bioEmpty')}</p>
|
||||
{avatarStatus && (
|
||||
<div style={{ fontSize: 13, marginTop: 8, color: avatarStatus.ok ? '#22c55e' : '#ef4444', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5 }}><Icon name={avatarStatus.ok ? 'success' : 'error'} size={14} /> {avatarStatus.msg}</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 基本资料 */}
|
||||
<div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20 }}>
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('settings.username')}</label>
|
||||
<input type="text" value={username} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }} onChange={(e) => setUsername(e.target.value)} />
|
||||
</div>
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('settings.bio')}</label>
|
||||
<textarea rows={3} value={bio} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', resize: 'vertical' }} onChange={(e) => setBio(e.target.value)} />
|
||||
</div>
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('settings.signature')} <span style={{ color: 'var(--text-light)', fontWeight: 400 }}>({t('settings.signatureHint')})</span></label>
|
||||
<textarea rows={2} value={signature} placeholder={t('settings.signaturePlaceholder')} style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', resize: 'vertical', fontFamily: 'inherit' }} onChange={(e) => setSignature(e.target.value)} />
|
||||
</div>
|
||||
<button className="btn-primary" style={{ width: '100%', padding: 10 }} onClick={handleSave}>{t('settings.save')}</button>
|
||||
</div>
|
||||
|
||||
{/* 语言设置 */}
|
||||
<div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 20, marginTop: 16 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 8 }}>{t('settings.language')}</label>
|
||||
<div className="feed-header-left language-toggle" style={{ display: 'inline-flex' }}>
|
||||
<button
|
||||
className={'tab' + (i18n.language.startsWith('zh') ? ' active' : '')}
|
||||
aria-pressed={i18n.language.startsWith('zh')}
|
||||
onClick={() => setAppLanguage('zh')}
|
||||
>
|
||||
{t('settings.languageZh')}
|
||||
</button>
|
||||
<button
|
||||
className={'tab' + (i18n.language.startsWith('en') ? ' active' : '')}
|
||||
aria-pressed={i18n.language.startsWith('en')}
|
||||
onClick={() => setAppLanguage('en')}
|
||||
>
|
||||
{t('settings.languageEn')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 侧边栏:社区统计 + 友情链接
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { Icon } from './Icons';
|
||||
|
||||
const emptyStats = { posts: 0, users: 0, topics: 0, online: 0 };
|
||||
let cachedStats = null;
|
||||
let cachedLinks = null;
|
||||
|
||||
export default function Sidebar({ id = 'sidebar' }) {
|
||||
const [stats, setStats] = useState(() => cachedStats || emptyStats);
|
||||
const [links, setLinks] = useState(() => cachedLinks || []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!cachedStats) {
|
||||
API.getStats().then((nextStats) => {
|
||||
cachedStats = nextStats;
|
||||
setStats(nextStats);
|
||||
}).catch(() => {});
|
||||
}
|
||||
if (!cachedLinks) {
|
||||
API.getLinks().then((nextLinks) => {
|
||||
cachedLinks = nextLinks;
|
||||
setLinks(nextLinks);
|
||||
}).catch(() => {});
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<aside id={id} className="sidebar">
|
||||
<div className="stats-box">
|
||||
<h4>
|
||||
<Icon name="book" size={14} /> 社区统计
|
||||
</h4>
|
||||
<div className="stat-item"><span>主题</span><span>{stats.topics || 0}</span></div>
|
||||
<div className="stat-item"><span>帖子</span><span>{stats.posts || 0}</span></div>
|
||||
<div className="stat-item"><span>用户</span><span>{stats.users || 0}</span></div>
|
||||
<div className="stat-item"><span>在线</span><span>{stats.online || 0}</span></div>
|
||||
</div>
|
||||
<div className="links-box">
|
||||
<h4>
|
||||
<Icon name="link" size={14} /> 友情链接
|
||||
</h4>
|
||||
<ul id={id === 'sidebar' ? 'friendlyLinks' : undefined} className="friendly-links">
|
||||
{links.length === 0 ? (
|
||||
<li style={{ color: '#94a3b8', fontSize: 13 }}>暂无链接</li>
|
||||
) : (
|
||||
links.map((l) => (
|
||||
<li key={l.id}><a href={l.url} target="_blank" rel="noreferrer">{l.title}</a></li>
|
||||
))
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// Toast 通知系统:右上角弹出,自动消失(替代 alert)
|
||||
// 用法:const { toast } = useToast(); toast('发布成功', 'success');
|
||||
// 注意:不用 createPortal(SSR 时 document 不存在会造成 hydration mismatch,
|
||||
// 导致整树重建)。toast-container 是 position:fixed,渲染位置不影响视觉。
|
||||
import { createContext, useContext, useState, useCallback, useRef, useEffect } from 'react';
|
||||
import { Icon } from './Icons';
|
||||
|
||||
const ToastContext = createContext(null);
|
||||
|
||||
export function useToast() {
|
||||
return useContext(ToastContext);
|
||||
}
|
||||
|
||||
let idCounter = 0;
|
||||
|
||||
export function ToastProvider({ children }) {
|
||||
const [toasts, setToasts] = useState([]);
|
||||
const [dialog, setDialog] = useState(null);
|
||||
const timersRef = useRef({});
|
||||
const dialogTimerRef = useRef(null);
|
||||
const dialogResolverRef = useRef(null);
|
||||
|
||||
const removeToast = useCallback((id) => {
|
||||
setToasts((prev) => prev.filter((item) => item.id !== id));
|
||||
delete timersRef.current[id];
|
||||
}, []);
|
||||
|
||||
const dismiss = useCallback((id) => {
|
||||
if (timersRef.current[id]) clearTimeout(timersRef.current[id]);
|
||||
setToasts((prev) => prev.map((item) => item.id === id ? { ...item, closing: true } : item));
|
||||
timersRef.current[id] = setTimeout(() => removeToast(id), 220);
|
||||
}, [removeToast]);
|
||||
|
||||
const toast = useCallback((message, type = 'success', duration = 3000) => {
|
||||
const id = ++idCounter;
|
||||
setToasts((prev) => [...prev, { id, message, type, closing: false }]);
|
||||
if (timersRef.current[id]) clearTimeout(timersRef.current[id]);
|
||||
timersRef.current[id] = setTimeout(() => dismiss(id), duration);
|
||||
}, [dismiss]);
|
||||
|
||||
const confirmAction = useCallback((message, options = {}) => {
|
||||
if (dialogResolverRef.current) dialogResolverRef.current(false);
|
||||
const isEnglish = localStorage.getItem('forumlify-lang') === 'en';
|
||||
setDialog({
|
||||
message,
|
||||
title: options.title || (isEnglish ? 'Confirm action' : '确认操作'),
|
||||
confirmLabel: options.confirmLabel || (isEnglish ? 'Confirm' : '确定'),
|
||||
cancelLabel: options.cancelLabel || (isEnglish ? 'Cancel' : '取消'),
|
||||
danger: options.danger !== false,
|
||||
closing: false,
|
||||
});
|
||||
return new Promise((resolve) => {
|
||||
dialogResolverRef.current = resolve;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const closeDialog = useCallback((result) => {
|
||||
setDialog((current) => current ? { ...current, closing: true } : current);
|
||||
if (dialogTimerRef.current) clearTimeout(dialogTimerRef.current);
|
||||
dialogTimerRef.current = setTimeout(() => {
|
||||
setDialog(null);
|
||||
const resolve = dialogResolverRef.current;
|
||||
dialogResolverRef.current = null;
|
||||
if (resolve) resolve(result);
|
||||
}, 340);
|
||||
}, []);
|
||||
|
||||
useEffect(() => () => {
|
||||
Object.values(timersRef.current).forEach(clearTimeout);
|
||||
if (dialogTimerRef.current) clearTimeout(dialogTimerRef.current);
|
||||
if (dialogResolverRef.current) dialogResolverRef.current(false);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<ToastContext.Provider value={{ toast, confirmAction }}>
|
||||
{children}
|
||||
<div className="toast-container">
|
||||
{toasts.map((t) => (
|
||||
<div key={t.id} className={'toast toast-' + t.type + (t.closing ? ' closing' : '')} onClick={() => dismiss(t.id)} role="status">
|
||||
<Icon name={t.type === 'error' ? 'error' : t.type === 'warning' ? 'warning' : 'success'} size={16} />
|
||||
<span>{t.message}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{dialog && (
|
||||
<div className={'modal active feedback-confirm' + (dialog.closing ? ' closing' : '')} onClick={(e) => { if (e.target === e.currentTarget) closeDialog(false); }}>
|
||||
<div className="modal-content" role="alertdialog" aria-modal="true" aria-labelledby="feedbackConfirmTitle" aria-describedby="feedbackConfirmMessage">
|
||||
<h2 id="feedbackConfirmTitle"><Icon name="warning" size={20} /> {dialog.title}</h2>
|
||||
<p id="feedbackConfirmMessage">{dialog.message}</p>
|
||||
<div className="feedback-confirm-actions">
|
||||
<button className={dialog.danger ? 'btn-danger' : 'btn-primary'} onClick={() => closeDialog(true)}>{dialog.confirmLabel}</button>
|
||||
<button className="btn-secondary" onClick={() => closeDialog(false)}>{dialog.cancelLabel}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</ToastContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,155 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 用户主页:资料卡 + 该用户的帖子列表
|
||||
import { useEffect, useState, useCallback, useRef } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from './AppProvider';
|
||||
import { Icon } from './Icons';
|
||||
import { useOpenPrivateChat } from './chat/ChatManager';
|
||||
import { renderMarkdown } from '@/lib/markdown';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
function avatar(username, size = 128) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
||||
'&background=6366f1&color=fff&size=' + size;
|
||||
}
|
||||
|
||||
export default function UserProfile({ username, initialUser = null, initialPosts = null }) {
|
||||
const { currentUser, openPost } = useApp();
|
||||
const { t, i18n } = useTranslation();
|
||||
const openPrivateChat = useOpenPrivateChat();
|
||||
const [user, setUser] = useState(initialUser);
|
||||
const [posts, setPosts] = useState(initialPosts || []);
|
||||
const [error, setError] = useState(null);
|
||||
const postsRef = useRef(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setError(null);
|
||||
try {
|
||||
const u = await API.getUserProfile(username);
|
||||
if (u.error || !u.id) {
|
||||
setError(u.error || '用户不存在');
|
||||
return;
|
||||
}
|
||||
setUser(u);
|
||||
const result = await API.getPosts('latest', u.id);
|
||||
setPosts(result.data || []);
|
||||
} catch (err) {
|
||||
setError(err.message || '加载失败');
|
||||
}
|
||||
}, [username]);
|
||||
|
||||
useEffect(() => {
|
||||
setUser(initialUser);
|
||||
setPosts(initialPosts || []);
|
||||
load();
|
||||
}, [initialPosts, initialUser, load]);
|
||||
|
||||
useEffect(() => {
|
||||
const contents = postsRef.current?.querySelectorAll('.user-post-preview') || [];
|
||||
contents.forEach((element) => {
|
||||
element.classList.toggle('has-fade', element.scrollHeight > element.clientHeight + 4);
|
||||
});
|
||||
}, [posts]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div id="pageUser" className="page-slide active">
|
||||
<div style={{ textAlign: 'center', color: '#ef4444', padding: '40px 0' }}>加载失败:{error}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!user) {
|
||||
return <div id="pageUser" className="page-slide active" style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />加载中...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div id="pageUser" className="page-slide active">
|
||||
<div className="page-header" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
|
||||
<h2><Icon name="users" size={20} /> 用户主页</h2>
|
||||
</div>
|
||||
<div id="userProfileContent" style={{ maxWidth: 700, margin: '0 auto', width: '100%' }}>
|
||||
<div className="user-profile-card" data-username={user.username || ''} style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 8, padding: 32, textAlign: 'center' }}>
|
||||
<img className="user-profile-avatar" src={user.avatar_url || avatar(user.username)} style={{ width: 96, height: 96, borderRadius: '50%', objectFit: 'cover', border: '3px solid var(--primary)' }} alt={user.username || ''} />
|
||||
<h2 className="user-profile-name" style={{ margin: '16px 0 4px', fontSize: 24, color: 'var(--text)' }}>{user.username}</h2>
|
||||
{user.id && (
|
||||
<div className="user-profile-details">
|
||||
<p style={{ color: 'var(--text-secondary)', fontSize: 14 }}>{user.bio || '这个人很懒,什么都没写'}</p>
|
||||
{currentUser && currentUser.username !== user.username && (
|
||||
<button
|
||||
className="btn-primary"
|
||||
style={{ marginTop: 12, padding: '8px 20px' }}
|
||||
onClick={() => openPrivateChat(user.id, user.username)}
|
||||
>
|
||||
<Icon name="message" size={14} /> 发私信
|
||||
</button>
|
||||
)}
|
||||
<div style={{ display: 'flex', justifyContent: 'center', gap: 32, marginTop: 16, fontSize: 14, color: 'var(--text-secondary)', flexWrap: 'wrap' }}>
|
||||
<span><Icon name="calendar" size={14} /> 加入于 {user.created_at ? new Date(user.created_at).toLocaleDateString('zh-CN') : '未知'}</span>
|
||||
<span><Icon name="file" size={14} /> 发了 {posts.length} 个帖子</span>
|
||||
{user.role === 'admin' && <span style={{ color: 'var(--primary)', fontWeight: 600 }}><Icon name="shield" size={14} /> 管理员</span>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{user.id && (
|
||||
<div className="user-profile-posts" ref={postsRef}>
|
||||
<h3 style={{ margin: '24px 0 16px', fontSize: 18 }}><Icon name="file" size={18} /> 发布的帖子</h3>
|
||||
{posts.length === 0 ? (
|
||||
<div style={{ color: '#94a3b8', padding: '20px 0', textAlign: 'center' }}>还没有发帖</div>
|
||||
) : (
|
||||
posts.map((p) => {
|
||||
const time = p.created_at ? new Date(p.created_at).toLocaleString(i18n.language === 'en' ? 'en-US' : 'zh-CN') : '';
|
||||
return (
|
||||
<div
|
||||
key={p.id}
|
||||
className="post-card user-post-card"
|
||||
data-post-id={p.id}
|
||||
data-post-ref={p.post_number || p.id}
|
||||
data-username={user.username || ''}
|
||||
style={{ cursor: 'pointer' }}
|
||||
onClick={(event) => openPost(p.post_number || p.id, event.currentTarget, p, {
|
||||
view: 'user',
|
||||
username: user.username,
|
||||
user,
|
||||
posts,
|
||||
scrollTop: document.getElementById('pageUser')?.scrollTop || 0,
|
||||
})}
|
||||
>
|
||||
{p.is_pinned && (
|
||||
<div className="post-pin-state" style={{ width: 'fit-content', display: 'flex', alignItems: 'center', gap: 3, fontSize: 12, color: 'var(--primary)', fontWeight: 600, marginBottom: 4 }}>
|
||||
<Icon name="pin" size={12} /> {t('feed.pinned')}
|
||||
</div>
|
||||
)}
|
||||
<div className="post-header">
|
||||
<img src={p.avatar_url || user.avatar_url || avatar(user.username, 64)} className="post-avatar" alt="" />
|
||||
<span className="post-username" style={{ color: 'var(--primary)' }}>{user.username}</span>
|
||||
<span className="post-time">{time}</span>
|
||||
{p.edited_at && (
|
||||
<span className="post-edited-state" style={{ fontSize: 11, color: 'var(--text-light)', marginLeft: 6 }}>
|
||||
<span className="post-edited-label">{t('feed.deleted')}</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="post-title">{p.title || t('feed.noTitle')}</div>
|
||||
<div className="post-content user-post-preview" dangerouslySetInnerHTML={{ __html: renderMarkdown(p.content) }} />
|
||||
{p.images && p.images.length > 0 && (
|
||||
<div className="post-images">
|
||||
{p.images.map((image, index) => (
|
||||
<img key={image + index} src={image} className="post-image" alt="" />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="post-actions">
|
||||
<span><Icon name="message" size={14} /> {p.reply_count || 0}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 自定义 CSS(上传 style.css 覆盖默认样式)
|
||||
import { useState, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '@/lib/api';
|
||||
import { Icon } from '../Icons';
|
||||
import { useToast } from '../Toast';
|
||||
|
||||
export default function AdminCustomCss() {
|
||||
const { t } = useTranslation();
|
||||
const { confirmAction } = useToast();
|
||||
const [status, setStatus] = useState(null);
|
||||
const [dragOver, setDragOver] = useState(false);
|
||||
const [pendingFile, setPendingFile] = useState(null); // 待确认的 CSS 文件
|
||||
const fileInputRef = useRef(null);
|
||||
|
||||
const handleFile = async (file) => {
|
||||
if (!file) return;
|
||||
if (file.name !== 'style.css') {
|
||||
setStatus({ ok: false, msg: t('admin.css.filenameInvalid') });
|
||||
return;
|
||||
}
|
||||
if (file.size > 1024 * 1024) {
|
||||
setStatus({ ok: false, msg: t('admin.css.sizeInvalid') });
|
||||
return;
|
||||
}
|
||||
// 上传前警告确认(与原版一致)
|
||||
setPendingFile(file);
|
||||
};
|
||||
|
||||
const doUpload = async () => {
|
||||
try {
|
||||
await API.uploadCustomCss(pendingFile);
|
||||
setStatus({ ok: true, msg: t('admin.css.active') });
|
||||
const link = document.getElementById('custom-css-link');
|
||||
if (link) link.href = '/api/custom-css?t=' + Date.now();
|
||||
} catch (err) {
|
||||
setStatus({ ok: false, msg: err.message });
|
||||
} finally {
|
||||
setPendingFile(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!await confirmAction(t('admin.css.confirmDelete'))) return;
|
||||
try {
|
||||
await API.deleteCustomCss();
|
||||
setStatus({ ok: true, msg: t('admin.css.deleted') });
|
||||
const link = document.getElementById('custom-css-link');
|
||||
if (link) link.remove();
|
||||
} catch (err) {
|
||||
setStatus({ ok: false, msg: err.message });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<h3 style={{ marginBottom: 16 }}><Icon name="code" size={16} /> {t('admin.css.title')}</h3>
|
||||
<p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 12 }}>
|
||||
{t('admin.css.description')}
|
||||
</p>
|
||||
<div
|
||||
style={{
|
||||
border: '2px dashed ' + (dragOver ? 'var(--primary)' : 'var(--border)'),
|
||||
borderRadius: 8, padding: 32, textAlign: 'center', cursor: 'pointer',
|
||||
transition: 'all 0.3s', background: dragOver ? 'var(--primary-bg)' : 'var(--bg)',
|
||||
}}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
|
||||
onDragLeave={() => setDragOver(false)}
|
||||
onDrop={(e) => { e.preventDefault(); setDragOver(false); if (e.dataTransfer.files?.[0]) handleFile(e.dataTransfer.files[0]); }}
|
||||
>
|
||||
<span style={{ fontSize: 13, color: 'var(--text-secondary)' }}>
|
||||
<Icon name="upload" size={14} /> {dragOver ? t('admin.css.releaseUpload') : t('admin.css.uploadHint')}
|
||||
</span>
|
||||
</div>
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
accept=".css"
|
||||
style={{ display: 'none' }}
|
||||
onChange={(e) => { if (e.target.files?.[0]) handleFile(e.target.files[0]); }}
|
||||
/>
|
||||
{status && (
|
||||
<div style={{ fontSize: 13, marginTop: 8, color: status.ok ? '#22c55e' : '#ef4444', display: 'flex', alignItems: 'center', gap: 5 }}><Icon name={status.ok ? 'success' : 'error'} size={14} /> {status.msg}</div>
|
||||
)}
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
|
||||
<button className="btn-primary" style={{ padding: '8px 20px' }} onClick={() => fileInputRef.current?.click()}><Icon name="save" size={14} /> {t('admin.css.save')}</button>
|
||||
<button className="btn-secondary" style={{ padding: '8px 20px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={handleDelete}><Icon name="trash" size={14} /> {t('admin.css.delete')}</button>
|
||||
</div>
|
||||
|
||||
{/* 上传前警告确认 */}
|
||||
{pendingFile && (
|
||||
<div className="modal active" style={{ display: 'flex' }} onClick={() => setPendingFile(null)}>
|
||||
<div className="modal-content" style={{ maxWidth: 420 }} onClick={(e) => e.stopPropagation()}>
|
||||
<h2 style={{ marginBottom: 12 }}><Icon name="warning" size={20} /> {t('admin.css.warningTitle')}</h2>
|
||||
<p style={{ fontSize: 14, color: 'var(--text-secondary)', marginBottom: 16 }}>
|
||||
{t('admin.css.warningBody')}
|
||||
</p>
|
||||
<p style={{ fontSize: 13, color: 'var(--text-light)', marginBottom: 20 }}>
|
||||
{t('admin.css.warningHelp')}
|
||||
</p>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button className="btn-primary" style={{ padding: '8px 24px' }} onClick={doUpload}><Icon name="upload" size={14} /> {t('admin.css.continueUpload')}</button>
|
||||
<button className="btn-secondary" style={{ padding: '8px 24px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--surface)', cursor: 'pointer', color: 'var(--text)' }} onClick={() => setPendingFile(null)}>{t('admin.common.cancel')}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 自定义页面管理(列表)
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '@/lib/api';
|
||||
import CustomPageEditor from './CustomPageEditor';
|
||||
import { Icon } from '../Icons';
|
||||
import { useToast } from '../Toast';
|
||||
|
||||
export default function AdminCustomPages() {
|
||||
const { t } = useTranslation();
|
||||
const { toast, confirmAction } = useToast();
|
||||
const [pages, setPages] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
const [editing, setEditing] = useState(null); // null | 'new' | page对象
|
||||
|
||||
const load = () => {
|
||||
API.adminGetCustomPages()
|
||||
.then((data) => { setPages(data || []); setError(null); })
|
||||
.catch((e) => { setError(e.message); setPages([]); });
|
||||
};
|
||||
|
||||
useEffect(load, []);
|
||||
|
||||
const handleDelete = async (p) => {
|
||||
if (!await confirmAction(t('admin.page.confirmDelete'))) return;
|
||||
try {
|
||||
await API.adminDeleteCustomPage(p.id);
|
||||
load();
|
||||
} catch (err) {
|
||||
toast(t('admin.common.deleteFailed', { msg: err.message }), 'error');
|
||||
}
|
||||
};
|
||||
|
||||
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>{t('admin.common.loadFailed', { msg: error })}</div>;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
|
||||
<h3 style={{ margin: 0 }}><Icon name="file" size={16} /> {t('admin.page.title')}</h3>
|
||||
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={() => setEditing('new')}><Icon name="plus" size={14} /> {t('admin.page.add')}</button>
|
||||
</div>
|
||||
<div id="customPageList">
|
||||
{pages === null ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />{t('admin.common.loading')}</div>
|
||||
) : pages.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}>{t('admin.page.empty')}</div>
|
||||
) : (
|
||||
<div style={{ overflowX: 'auto' }}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
|
||||
<thead>
|
||||
<tr style={{ textAlign: 'left', borderBottom: '2px solid var(--border)' }}>
|
||||
<th style={{ padding: '8px 12px' }}>{t('admin.page.name')}</th>
|
||||
<th style={{ padding: '8px 12px' }}>{t('admin.page.columnTitle')}</th>
|
||||
<th style={{ padding: '8px 12px' }}>{t('admin.page.url')}</th>
|
||||
<th style={{ padding: '8px 12px' }}>{t('admin.common.status')}</th>
|
||||
<th style={{ padding: '8px 12px', textAlign: 'center' }}>{t('admin.common.actions')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{pages.map((p) => (
|
||||
<tr key={p.id} style={{ borderBottom: '1px solid var(--border-light)' }}>
|
||||
<td style={{ padding: '8px 12px' }}><code style={{ background: 'var(--bg)', padding: '2px 6px', borderRadius: 4, fontSize: 12 }}>{p.name}</code></td>
|
||||
<td style={{ padding: '8px 12px' }}>{p.title}</td>
|
||||
<td style={{ padding: '8px 12px' }}><code style={{ background: 'var(--bg)', padding: '2px 6px', borderRadius: 4, fontSize: 12 }}>?custom={p.name}</code></td>
|
||||
<td style={{ padding: '8px 12px' }}>
|
||||
<span style={{ color: p.enabled ? '#22c55e' : '#ef4444', display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name={p.enabled ? 'success' : 'error'} size={13} /> {p.enabled ? t('admin.common.enabled') : t('admin.common.disabled')}</span>
|
||||
</td>
|
||||
<td style={{ padding: '8px 12px', textAlign: 'center', display: 'flex', gap: 6, justifyContent: 'center' }}>
|
||||
<button className="btn-sm btn-secondary" title={t('admin.page.edit')} aria-label={t('admin.page.edit')} onClick={() => setEditing(p)}><Icon name="edit" size={13} /></button>
|
||||
<button className="btn-sm btn-danger" title={t('admin.page.delete')} aria-label={t('admin.page.delete')} onClick={() => handleDelete(p)}><Icon name="trash" size={13} /></button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{editing && (
|
||||
<CustomPageEditor
|
||||
page={editing === 'new' ? null : editing}
|
||||
onClose={() => setEditing(null)}
|
||||
onSaved={() => { setEditing(null); load(); }}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 论坛设置
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { applyFavicon } from '@/lib/favicon';
|
||||
import { compressFavicon, DIRECT_IMAGE_LIMIT, MAX_IMAGE_SOURCE_SIZE } from '@/lib/compress-image';
|
||||
import { useApp } from '../AppProvider';
|
||||
import { Icon } from '../Icons';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useToast } from '../Toast';
|
||||
|
||||
export default function AdminForumSettings() {
|
||||
const { updateForumName } = useApp();
|
||||
const { t } = useTranslation();
|
||||
const { toast } = useToast();
|
||||
// 初始为空:收到服务器返回的论坛名后才显示,避免默认名一闪而过
|
||||
const [name, setName] = useState('');
|
||||
const [faviconUrl, setFaviconUrl] = useState('');
|
||||
const [faviconVersion, setFaviconVersion] = useState('');
|
||||
const [versionCommit, setVersionCommit] = useState('unknown');
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [uploadStage, setUploadStage] = useState('uploading');
|
||||
const [dragOver, setDragOver] = useState(false);
|
||||
const [result, setResult] = useState(null); // {ok, msg}
|
||||
const fileInputRef = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
API.getSettings()
|
||||
.then((data) => {
|
||||
if (data.forum_name) setName(data.forum_name);
|
||||
if (data.favicon_url) setFaviconUrl(data.favicon_url);
|
||||
if (data.favicon_version) setFaviconVersion(data.favicon_version);
|
||||
if (data.version_commit) setVersionCommit(data.version_commit);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const handleFavicon = async (file) => {
|
||||
if (!file || uploading) return;
|
||||
if (file.size > MAX_IMAGE_SOURCE_SIZE) {
|
||||
toast(t('admin.forum.faviconTooLarge'), 'warning');
|
||||
return;
|
||||
}
|
||||
const extension = file.name.split('.').pop()?.toLowerCase();
|
||||
const acceptedMime = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/x-icon', 'image/vnd.microsoft.icon'].includes(file.type);
|
||||
if (!acceptedMime && extension !== 'ico') {
|
||||
toast(t('admin.forum.faviconInvalid'), 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
setUploading(true);
|
||||
try {
|
||||
let uploadFile = file;
|
||||
if (file.size > DIRECT_IMAGE_LIMIT) {
|
||||
setUploadStage('compressing');
|
||||
try {
|
||||
uploadFile = await compressFavicon(file);
|
||||
} catch {
|
||||
toast(t('admin.forum.faviconCompressFailed'), 'error');
|
||||
return;
|
||||
}
|
||||
}
|
||||
setUploadStage('uploading');
|
||||
const data = await API.uploadFavicon(uploadFile);
|
||||
setFaviconUrl(data.favicon_url);
|
||||
setFaviconVersion(data.favicon_version);
|
||||
applyFavicon(data.favicon_url, data.favicon_version);
|
||||
toast(t('admin.forum.faviconSaved'), 'success');
|
||||
} catch (error) {
|
||||
toast(t('admin.forum.faviconSaveFailed', { msg: error.message }), 'error');
|
||||
} finally {
|
||||
setUploading(false);
|
||||
setUploadStage('uploading');
|
||||
if (fileInputRef.current) fileInputRef.current.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
const faviconSrc = faviconUrl
|
||||
? `${faviconUrl}${faviconUrl.includes('?') ? '&' : '?'}v=${encodeURIComponent(faviconVersion)}`
|
||||
: '';
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!name.trim()) { toast(t('admin.forum.nameRequired'), 'warning'); return; }
|
||||
try {
|
||||
await API.updateSettings(name.trim());
|
||||
updateForumName(name.trim());
|
||||
setResult({ ok: true, msg: t('admin.forum.saved') });
|
||||
} catch {
|
||||
setResult({ ok: false, msg: t('admin.forum.saveFailed') });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<h3 style={{ marginBottom: 16 }}><Icon name="settings" size={16} /> {t('admin.forum.title')}</h3>
|
||||
<div className="admin-forum-settings">
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 6 }}>{t('admin.forum.nameLabel')}</label>
|
||||
<input
|
||||
type="text"
|
||||
style={{ width: '100%', padding: '10px 14px', border: '1.5px solid var(--border)', borderRadius: 6, fontSize: 15, marginBottom: 12, fontFamily: 'inherit', background: 'var(--bg)', color: 'var(--text)' }}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
<button className="btn-primary" style={{ padding: '10px 24px' }} onClick={handleSave}><Icon name="save" size={14} /> {t('admin.forum.save')}</button>
|
||||
{result && (
|
||||
<span style={{ marginLeft: 12, fontSize: 14, color: result.ok ? '#22c55e' : '#ef4444' }}><Icon name={result.ok ? 'success' : 'error'} size={14} /> {result.msg}</span>
|
||||
)}
|
||||
|
||||
<div className="admin-forum-divider" />
|
||||
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 6 }}>{t('admin.forum.faviconLabel')}</label>
|
||||
<p className="admin-forum-hint">{t('admin.forum.faviconHint')}</p>
|
||||
<div className="admin-favicon-row">
|
||||
<div className="admin-favicon-preview" aria-label={t('admin.forum.faviconPreview')}>
|
||||
{faviconSrc ? <img src={faviconSrc} alt="" /> : <Icon name="image" size={24} />}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={'admin-favicon-upload' + (dragOver ? ' drag-over' : '')}
|
||||
disabled={uploading}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
onDragOver={(event) => { event.preventDefault(); setDragOver(true); }}
|
||||
onDragLeave={() => setDragOver(false)}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault();
|
||||
setDragOver(false);
|
||||
handleFavicon(event.dataTransfer.files?.[0]);
|
||||
}}
|
||||
>
|
||||
{!uploading && !dragOver && <Icon name="image" size={32} />}
|
||||
<span>{uploading ? t(`admin.forum.favicon${uploadStage === 'compressing' ? 'Compressing' : 'Uploading'}`) : (dragOver ? t('admin.forum.faviconDrop') : t('admin.forum.faviconUpload'))}</span>
|
||||
</button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".png,.jpg,.jpeg,.gif,.webp,.ico,image/png,image/jpeg,image/gif,image/webp,image/x-icon"
|
||||
hidden
|
||||
onChange={(event) => handleFavicon(event.target.files?.[0])}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="admin-forum-divider" />
|
||||
|
||||
<div className="admin-version-row">
|
||||
<span className="admin-version-label"><Icon name="code" size={14} /> {t('admin.forum.versionLabel')}</span>
|
||||
<span className="admin-version-value">{versionCommit}</span>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 友情链接管理
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '@/lib/api';
|
||||
import { Icon } from '../Icons';
|
||||
import { useToast } from '../Toast';
|
||||
|
||||
export default function AdminLinks() {
|
||||
const { t } = useTranslation();
|
||||
const { toast, confirmAction } = useToast();
|
||||
const [links, setLinks] = useState([]);
|
||||
const [title, setTitle] = useState('');
|
||||
const [url, setUrl] = useState('');
|
||||
|
||||
const load = () => { API.getLinks().then(setLinks).catch(() => {}); };
|
||||
useEffect(load, []);
|
||||
|
||||
const handleAdd = async () => {
|
||||
if (!title.trim() || !url.trim()) { toast(t('admin.link.incomplete'), 'warning'); return; }
|
||||
try {
|
||||
await API.addLink(title.trim(), url.trim());
|
||||
setTitle('');
|
||||
setUrl('');
|
||||
load();
|
||||
} catch (err) {
|
||||
toast(t('admin.link.addFailed', { msg: err.message }), 'error');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id) => {
|
||||
if (!await confirmAction(t('admin.link.confirmDelete'))) return;
|
||||
try {
|
||||
await API.deleteLink(id);
|
||||
load();
|
||||
} catch (err) {
|
||||
toast(t('admin.common.deleteFailed', { msg: err.message }), 'error');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div style={{ marginBottom: 16, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
|
||||
<input
|
||||
type="text" placeholder={t('admin.link.namePlaceholder')}
|
||||
style={{ flex: 1, minWidth: 120, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--bg)', color: 'var(--text)' }}
|
||||
value={title} onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
type="url" placeholder={t('admin.link.urlPlaceholder')}
|
||||
style={{ flex: 2, minWidth: 160, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, background: 'var(--bg)', color: 'var(--text)' }}
|
||||
value={url} onChange={(e) => setUrl(e.target.value)}
|
||||
/>
|
||||
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={handleAdd}>{t('admin.link.add')}</button>
|
||||
</div>
|
||||
<div id="linkList">
|
||||
{links.length === 0 ? (
|
||||
<div style={{ color: '#94a3b8', fontSize: 13 }}>{t('admin.link.empty')}</div>
|
||||
) : (
|
||||
links.map((l) => (
|
||||
<div key={l.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '8px 0', borderBottom: '1px solid var(--border)' }}>
|
||||
<span><a href={l.url} target="_blank" rel="noreferrer" style={{ color: '#6366f1', textDecoration: 'none' }}>{l.title}</a></span>
|
||||
<button className="btn-sm btn-danger" onClick={() => handleDelete(l.id)}>
|
||||
<Icon name="trash" size={12} /> {t('admin.common.delete')}
|
||||
</button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 事件日志
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '@/lib/api';
|
||||
|
||||
export default function AdminLogs() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const [logs, setLogs] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const load = () => {
|
||||
API.getEventLogs()
|
||||
.then((data) => { setLogs(data || []); setError(null); })
|
||||
.catch((e) => { setError(e.message); setLogs([]); });
|
||||
};
|
||||
|
||||
useEffect(load, []);
|
||||
|
||||
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>{t('admin.common.loadFailed', { msg: error })}</div>;
|
||||
if (!logs) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />{t('admin.common.loading')}</div>;
|
||||
if (logs.length === 0) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 40 }}>{t('admin.log.empty')}</div>;
|
||||
|
||||
const dateLocale = i18n.resolvedLanguage === 'en' ? 'en-US' : 'zh-CN';
|
||||
|
||||
return (
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
|
||||
<thead>
|
||||
<tr style={{ textAlign: 'left', borderBottom: '1px solid var(--border)' }}>
|
||||
<th>{t('admin.log.time')}</th><th>{t('admin.log.user')}</th><th>{t('admin.log.action')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{logs.map((l) => (
|
||||
<tr key={l.id} style={{ borderBottom: '1px solid #f1f5f9' }}>
|
||||
<td style={{ padding: '6px 0' }}>{new Date(l.created_at).toLocaleString(dateLocale)}</td>
|
||||
<td style={{ padding: '6px 0' }}>{l.username || t('admin.log.system')}</td>
|
||||
<td style={{ padding: '6px 0' }}>{l.action}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 举报处理
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '@/lib/api';
|
||||
import { Icon } from '../Icons';
|
||||
import { useToast } from '../Toast';
|
||||
|
||||
export default function AdminReports() {
|
||||
const { t } = useTranslation();
|
||||
const { toast, confirmAction } = useToast();
|
||||
const [reports, setReports] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const load = () => {
|
||||
API.getReports()
|
||||
.then((data) => { setReports(data || []); setError(null); })
|
||||
.catch((e) => { setError(e.message); setReports([]); });
|
||||
};
|
||||
|
||||
useEffect(load, []);
|
||||
|
||||
const handleAction = async (r, action) => {
|
||||
const status = action === 'approve' ? 'approved' : 'rejected';
|
||||
const note = action === 'approve' ? t('admin.report.approvedNote') : t('admin.report.rejectedNote');
|
||||
if (action === 'approve' && !await confirmAction(t('admin.report.confirmApprove'))) return;
|
||||
try {
|
||||
await API.updateReport(r.id, status, note);
|
||||
if (action === 'approve' && r.post_id) {
|
||||
API.deletePost(r.post_id).catch(() => {});
|
||||
}
|
||||
load();
|
||||
} catch (err) {
|
||||
toast(t('admin.common.operationFailed', { msg: err.message }), 'error');
|
||||
}
|
||||
};
|
||||
|
||||
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>{t('admin.common.loadFailed', { msg: error })}</div>;
|
||||
if (!reports) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />{t('admin.common.loading')}</div>;
|
||||
if (reports.length === 0) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 40 }}><Icon name="success" size={16} /> {t('admin.report.empty')}</div>;
|
||||
|
||||
const statusLabels = {
|
||||
pending: t('admin.report.statusPending'),
|
||||
approved: t('admin.report.statusApproved'),
|
||||
rejected: t('admin.report.statusRejected'),
|
||||
};
|
||||
const statusIcons = { pending: 'pending', approved: 'success', rejected: 'error' };
|
||||
|
||||
return reports.map((r) => (
|
||||
<div key={r.id} className="report-item">
|
||||
<div>{t('admin.report.reportedPost', { name: r.reporter_name || t('admin.report.anonymous') })}</div>
|
||||
<div style={{ fontSize: 13, color: '#64748b', margin: '4px 0' }}>{t('admin.report.reason', { reason: r.reason })}</div>
|
||||
<div style={{ fontSize: 13, color: '#64748b', margin: '4px 0' }}>
|
||||
{t('admin.report.post', {
|
||||
title: r.post_title || t('admin.report.untitled'),
|
||||
content: (r.post_content || '').substring(0, 30) + ((r.post_content || '').length > 30 ? '...' : ''),
|
||||
})}
|
||||
</div>
|
||||
<div style={{ fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4 }}>
|
||||
{statusIcons[r.status] && <Icon name={statusIcons[r.status]} size={13} />} {t('admin.common.status')}: {statusLabels[r.status] || r.status}
|
||||
</div>
|
||||
{r.handler_name && (
|
||||
<div style={{ fontSize: 12, color: '#94a3b8' }}>
|
||||
{t('admin.report.handler', { name: r.handler_name })}{r.handler_note ? ' (' + r.handler_note + ')' : ''}
|
||||
</div>
|
||||
)}
|
||||
{r.status === 'pending' && (
|
||||
<div className="report-actions">
|
||||
<button className="btn-sm btn-danger" onClick={() => handleAction(r, 'approve')}>
|
||||
<Icon name="trash" size={12} /> {t('admin.report.deletePost')}
|
||||
</button>
|
||||
<button className="btn-sm btn-secondary" onClick={() => handleAction(r, 'reject')}>
|
||||
<Icon name="close" size={12} /> {t('admin.report.reject')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
));
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 用户管理
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from '../AppProvider';
|
||||
import { useToast } from '../Toast';
|
||||
|
||||
export default function AdminUsers() {
|
||||
const { currentUser } = useApp();
|
||||
const { t, i18n } = useTranslation();
|
||||
const { toast, confirmAction } = useToast();
|
||||
const [users, setUsers] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const load = () => {
|
||||
API.getUsers()
|
||||
.then((data) => { setUsers(data || []); setError(null); })
|
||||
.catch((e) => { setError(e.message); setUsers([]); });
|
||||
};
|
||||
|
||||
useEffect(load, []);
|
||||
|
||||
const handleRole = async (u, role) => {
|
||||
const roleName = role === 'admin' ? t('admin.user.roleAdmin') : t('admin.user.roleUser');
|
||||
if (!await confirmAction(t('admin.user.confirmRole', { role: roleName }), { danger: false })) return;
|
||||
try {
|
||||
await API.updateUserRole(u.id, role);
|
||||
load();
|
||||
} catch (err) {
|
||||
toast(t('admin.common.operationFailed', { msg: err.message }), 'error');
|
||||
}
|
||||
};
|
||||
|
||||
if (error) return <div style={{ textAlign: 'center', color: '#ef4444', padding: 20 }}>{t('admin.common.loadFailed', { msg: error })}</div>;
|
||||
if (!users) return <div style={{ textAlign: 'center', color: '#94a3b8', padding: 20 }}><span className="spinner-sm" />{t('admin.common.loading')}</div>;
|
||||
|
||||
const dateLocale = i18n.resolvedLanguage === 'en' ? 'en-US' : 'zh-CN';
|
||||
|
||||
return (
|
||||
<>
|
||||
<div style={{ marginBottom: 12, fontSize: 13, color: '#94a3b8' }}>{t('admin.user.count', { count: users.length })}</div>
|
||||
<div style={{ overflowX: 'auto' }}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
|
||||
<thead>
|
||||
<tr style={{ textAlign: 'left', borderBottom: '2px solid var(--border)' }}>
|
||||
<th style={{ padding: '10px 12px' }}>{t('admin.user.user')}</th>
|
||||
<th style={{ padding: '10px 12px' }}>{t('admin.user.role')}</th>
|
||||
<th style={{ padding: '10px 12px' }}>{t('admin.user.registeredAt')}</th>
|
||||
<th style={{ padding: '10px 12px', textAlign: 'center' }}>{t('admin.common.actions')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((u) => {
|
||||
const isAdmin = u.role === 'admin';
|
||||
const isCurrent = currentUser && currentUser.id === u.id;
|
||||
return (
|
||||
<tr key={u.id} data-username={u.username || ''} style={{ borderBottom: '1px solid #f1f5f9' }}>
|
||||
<td style={{ padding: '10px 12px' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<img
|
||||
src={u.avatar_url || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(u.username) + '&background=6366f1&color=fff&size=64'}
|
||||
className="admin-user-avatar"
|
||||
style={{ width: 28, height: 28, borderRadius: '50%', objectFit: 'cover' }}
|
||||
alt=""
|
||||
/>
|
||||
<span className="admin-user-name" style={{ fontWeight: 500 }}>{u.username}</span>
|
||||
{isCurrent && <span style={{ fontSize: 11, color: '#94a3b8', background: '#eef2ff', padding: '1px 8px', borderRadius: 4 }}>{t('admin.user.you')}</span>}
|
||||
</div>
|
||||
</td>
|
||||
<td style={{ padding: '10px 12px' }}>
|
||||
<span style={{
|
||||
display: 'inline-block', padding: '2px 10px', borderRadius: 4, fontSize: 12, fontWeight: 500,
|
||||
...(isAdmin ? { background: '#6366f1', color: '#fff' } : { background: 'var(--border)', color: 'var(--text-secondary)' }),
|
||||
}}>
|
||||
{isAdmin ? (u.is_super ? t('admin.user.roleSuper') : t('admin.user.roleAdmin')) : t('admin.user.roleUser')}
|
||||
</span>
|
||||
</td>
|
||||
<td style={{ padding: '10px 12px', color: '#94a3b8', fontSize: 13 }}>
|
||||
{u.created_at ? new Date(u.created_at).toLocaleDateString(dateLocale) : '—'}
|
||||
</td>
|
||||
<td style={{ padding: '10px 12px', textAlign: 'center' }}>
|
||||
{u.is_super ? (
|
||||
<span style={{ fontSize: 12, color: '#94a3b8' }}>{t('admin.user.cannotSuper')}</span>
|
||||
) : isCurrent ? (
|
||||
<span style={{ fontSize: 12, color: '#94a3b8' }}>{t('admin.user.cannotSelf')}</span>
|
||||
) : isAdmin ? (
|
||||
<button className="btn-sm btn-secondary" style={{ padding: '4px 12px' }} onClick={() => handleRole(u, 'user')}>{t('admin.user.makeUser')}</button>
|
||||
) : (
|
||||
<button className="btn-sm btn-primary" style={{ padding: '4px 12px', background: '#6366f1', color: '#fff', border: 'none', borderRadius: 4, cursor: 'pointer' }} onClick={() => handleRole(u, 'admin')}>{t('admin.user.makeAdmin')}</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 管理后台 - 自定义页面编辑器(modal)
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '@/lib/api';
|
||||
import { Icon } from '../Icons';
|
||||
import { useToast } from '../Toast';
|
||||
|
||||
export default function CustomPageEditor({ page, onClose, onSaved }) {
|
||||
const { t } = useTranslation();
|
||||
const { toast } = useToast();
|
||||
const isEdit = !!page;
|
||||
const [name, setName] = useState(page?.name || '');
|
||||
const [title, setTitle] = useState(page?.title || '');
|
||||
const [content, setContent] = useState(page?.content || '');
|
||||
const [enabled, setEnabled] = useState(page?.enabled !== false);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!name.trim()) { toast(t('admin.page.nameRequired'), 'warning'); return; }
|
||||
if (!title.trim()) { toast(t('admin.page.titleRequired'), 'warning'); return; }
|
||||
if (!content.trim()) { toast(t('admin.page.contentRequired'), 'warning'); return; }
|
||||
if (!/^[a-zA-Z0-9\-_]+$/.test(name.trim())) {
|
||||
toast(t('admin.page.nameInvalid'), 'warning');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (isEdit) {
|
||||
await API.adminUpdateCustomPage(page.id, title.trim(), content.trim(), enabled);
|
||||
} else {
|
||||
await API.adminCreateCustomPage(name.trim(), title.trim(), content.trim());
|
||||
}
|
||||
onSaved();
|
||||
} catch (err) {
|
||||
toast(t('admin.common.saveFailed', { msg: err.message }), 'error');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="modal active" style={{ display: 'flex' }} onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
|
||||
<div className="modal-content" style={{ maxWidth: 600, maxHeight: '90vh', overflowY: 'auto', position: 'relative' }}>
|
||||
<span className="close" style={{ position: 'absolute', top: 12, right: 16, cursor: 'pointer', color: 'var(--text-light)' }} onClick={onClose}><Icon name="close" size={20} /></span>
|
||||
<h2 style={{ marginBottom: 16 }}><Icon name={isEdit ? 'edit' : 'file'} size={20} /> {isEdit ? t('admin.page.editTitle') : t('admin.page.addTitle')}</h2>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('admin.page.nameLabel')}</label>
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
readOnly={isEdit}
|
||||
placeholder={t('admin.page.namePlaceholder')}
|
||||
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: isEdit ? 'var(--border-light)' : 'var(--bg)', color: 'var(--text)' }}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
{isEdit
|
||||
? <div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}><Icon name="warning" size={12} /> {t('admin.page.nameLocked')}</div>
|
||||
: <div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>{t('admin.page.nameHint')}</div>}
|
||||
</div>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('admin.page.navTitleLabel')}</label>
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
placeholder={t('admin.page.navTitlePlaceholder')}
|
||||
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('admin.common.status')}</label>
|
||||
<select
|
||||
value={String(enabled)}
|
||||
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 14, background: 'var(--bg)', color: 'var(--text)' }}
|
||||
onChange={(e) => setEnabled(e.target.value === 'true')}
|
||||
>
|
||||
<option value="true">{t('admin.common.enabled')}</option>
|
||||
<option value="false">{t('admin.common.disabled')}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div style={{ marginBottom: 12 }}>
|
||||
<label style={{ fontWeight: 600, fontSize: 14, display: 'block', marginBottom: 4 }}>{t('admin.page.contentLabel')}</label>
|
||||
<textarea
|
||||
rows={12}
|
||||
value={content}
|
||||
style={{ width: '100%', padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 13, fontFamily: 'monospace', background: 'var(--bg)', color: 'var(--text)', resize: 'vertical' }}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
/>
|
||||
<div style={{ fontSize: 12, color: 'var(--text-light)', marginTop: 2 }}>{t('admin.page.contentHelp')}</div>
|
||||
</div>
|
||||
<button className="btn-primary" style={{ padding: '10px 24px', width: '100%' }} onClick={handleSave}>{t('admin.common.save')}</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 私信管理器:会话列表 modal + 聊天窗口 modal + 未读 badge
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from '../AppProvider';
|
||||
import { Icon } from '../Icons';
|
||||
import ConversationList from './ConversationList';
|
||||
import ChatWindow from './ChatWindow';
|
||||
import { useToast } from '../Toast';
|
||||
|
||||
// 私信按钮(含未读 badge),渲染在导航栏内
|
||||
export function DMButton() {
|
||||
const { currentUser } = useApp();
|
||||
const [unread, setUnread] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!currentUser) { setUnread(0); return; }
|
||||
const update = () => {
|
||||
API.getConversations()
|
||||
.then((cs) => setUnread((cs || []).reduce((s, c) => s + (c.unread_count || 0), 0)))
|
||||
.catch(() => {});
|
||||
};
|
||||
update();
|
||||
const t = setInterval(update, 30000);
|
||||
return () => clearInterval(t);
|
||||
}, [currentUser]);
|
||||
|
||||
if (!currentUser) return null; // 未登录不显示私信按钮
|
||||
|
||||
return (
|
||||
<button
|
||||
className="nav-icon-btn"
|
||||
title="私信"
|
||||
style={{ position: 'relative', padding: '6px 8px', background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-secondary)', borderRadius: 4, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}
|
||||
onClick={() => window.dispatchEvent(new CustomEvent('forumlify-open-messages'))}
|
||||
>
|
||||
<Icon name="message" size={20} />
|
||||
{unread > 0 && (
|
||||
<span style={{ position: 'absolute', top: -2, right: -2, background: '#ef4444', color: '#fff', borderRadius: '50%', padding: '2px 6px', fontSize: 10, fontWeight: 600, minWidth: 18, textAlign: 'center', lineHeight: 1.4 }}>
|
||||
{unread > 99 ? '99+' : unread}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// 私信 modals 容器(会话列表 + 聊天窗口)
|
||||
export default function ChatManager() {
|
||||
const [listOpen, setListOpen] = useState(false);
|
||||
const [chat, setChat] = useState(null); // {conversationId, otherUserId, otherUsername}
|
||||
const [refreshKey, setRefreshKey] = useState(0);
|
||||
|
||||
const refreshList = useCallback(() => setRefreshKey((k) => k + 1), []);
|
||||
|
||||
// 监听事件:打开会话列表 / 打开聊天
|
||||
useEffect(() => {
|
||||
const handler = (e) => {
|
||||
setChat(e.detail);
|
||||
setListOpen(false);
|
||||
};
|
||||
const openList = () => setListOpen(true);
|
||||
window.addEventListener('forumlify-open-chat', handler);
|
||||
window.addEventListener('forumlify-open-messages', openList);
|
||||
return () => {
|
||||
window.removeEventListener('forumlify-open-chat', handler);
|
||||
window.removeEventListener('forumlify-open-messages', openList);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const openChat = (conversationId, otherUserId, otherUsername) => {
|
||||
setChat({ conversationId, otherUserId, otherUsername });
|
||||
setListOpen(false);
|
||||
};
|
||||
|
||||
const closeChat = () => {
|
||||
setChat(null);
|
||||
refreshList();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{listOpen && (
|
||||
<ConversationList
|
||||
onOpenChat={openChat}
|
||||
onClose={() => setListOpen(false)}
|
||||
/>
|
||||
)}
|
||||
{chat && (
|
||||
<ChatWindow
|
||||
conversationId={chat.conversationId}
|
||||
otherUserId={chat.otherUserId}
|
||||
otherUsername={chat.otherUsername}
|
||||
onClose={closeChat}
|
||||
onRefreshList={refreshList}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// 供其他组件调用的打开私信(通过自定义事件桥接)
|
||||
export function useOpenPrivateChat() {
|
||||
const { currentUser } = useApp();
|
||||
const { toast } = useToast();
|
||||
const open = async (otherUserId, otherUsername) => {
|
||||
if (!currentUser) { toast('请先登录', 'warning'); return; }
|
||||
try {
|
||||
const result = await API.getOrCreateConversation(otherUserId);
|
||||
window.dispatchEvent(new CustomEvent('forumlify-open-chat', {
|
||||
detail: { conversationId: result.id, otherUserId, otherUsername },
|
||||
}));
|
||||
} catch (err) {
|
||||
toast('打开私信失败:' + err.message, 'error');
|
||||
}
|
||||
};
|
||||
return open;
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 私信 - 聊天窗口(3 秒轮询新消息)
|
||||
import { useEffect, useState, useRef, useCallback } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { useApp } from '../AppProvider';
|
||||
import { Icon } from '../Icons';
|
||||
import { useToast } from '../Toast';
|
||||
|
||||
function avatar(username) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
}
|
||||
|
||||
export default function ChatWindow({ conversationId, otherUserId, otherUsername, onClose, onRefreshList }) {
|
||||
const { currentUser } = useApp();
|
||||
const { toast } = useToast();
|
||||
const [messages, setMessages] = useState(null);
|
||||
const [content, setContent] = useState('');
|
||||
const containerRef = useRef(null);
|
||||
|
||||
const load = useCallback(async (silent = false) => {
|
||||
if (!silent) setMessages(null);
|
||||
try {
|
||||
const data = await API.getMessages(conversationId);
|
||||
setMessages(data || []);
|
||||
} catch {
|
||||
if (!silent) setMessages([]);
|
||||
}
|
||||
}, [conversationId]);
|
||||
|
||||
useEffect(() => { load(); }, [load]);
|
||||
|
||||
// 3 秒轮询
|
||||
useEffect(() => {
|
||||
const t = setInterval(() => load(true), 3000);
|
||||
return () => clearInterval(t);
|
||||
}, [load]);
|
||||
|
||||
// 自动滚动到底部
|
||||
useEffect(() => {
|
||||
if (containerRef.current) containerRef.current.scrollTop = containerRef.current.scrollHeight;
|
||||
}, [messages]);
|
||||
|
||||
const send = async () => {
|
||||
if (!content.trim()) return;
|
||||
try {
|
||||
await API.sendMessage(conversationId, content.trim());
|
||||
setContent('');
|
||||
load();
|
||||
onRefreshList();
|
||||
} catch (err) {
|
||||
toast('发送失败:' + err.message, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="modal active" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
|
||||
<div className="modal-content" style={{ display: 'flex', flexDirection: 'column', height: '70vh', maxHeight: '70vh', padding: 0, overflow: 'hidden' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px', borderBottom: '1px solid var(--border)' }}>
|
||||
<span id="chatTitle" style={{ fontWeight: 600, fontSize: 16 }}>{otherUsername}</span>
|
||||
<span className="close" onClick={onClose} style={{ cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}><Icon name="close" size={20} /></span>
|
||||
</div>
|
||||
<div id="chatMessages" ref={containerRef} style={{ flex: 1, overflowY: 'auto', padding: 16, minHeight: 0 }}>
|
||||
{messages === null ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />加载中...</div>
|
||||
) : messages.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>还没有消息,打个招呼吧 👋</div>
|
||||
) : (
|
||||
messages.map((m) => {
|
||||
const isMine = m.sender_id === currentUser?.id;
|
||||
const time = m.created_at ? new Date(m.created_at).toLocaleString('zh-CN') : '';
|
||||
return (
|
||||
<div key={m.id} style={{ display: 'flex', justifyContent: isMine ? 'flex-end' : 'flex-start', marginBottom: 12 }}>
|
||||
{!isMine && (
|
||||
<img src={m.sender_avatar_url || avatar(m.sender_username)} style={{ width: 32, height: 32, borderRadius: '50%', objectFit: 'cover', marginRight: 8, flexShrink: 0 }} alt="" />
|
||||
)}
|
||||
<div style={{ maxWidth: '70%' }}>
|
||||
<div style={{
|
||||
background: isMine ? 'var(--primary)' : 'var(--surface)',
|
||||
color: isMine ? '#fff' : 'var(--text)',
|
||||
padding: '10px 14px', borderRadius: 12,
|
||||
border: isMine ? 'none' : '1px solid var(--border)',
|
||||
wordBreak: 'break-word',
|
||||
}}>
|
||||
{m.content}
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: 'var(--text-light)', marginTop: 4, textAlign: isMine ? 'right' : 'left' }}>
|
||||
{time} {isMine && <Icon name="success" size={10} aria-label={m.is_read ? '已读' : '已发送'} />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 8, padding: '12px 16px', borderTop: '1px solid var(--border)', flexShrink: 0 }}>
|
||||
<input
|
||||
type="text"
|
||||
id="chatInput"
|
||||
placeholder="输入消息..."
|
||||
style={{ flex: 1, padding: '8px 12px', border: '1px solid var(--border)', borderRadius: 6, fontSize: 14, background: 'var(--bg)', color: 'var(--text)', outline: 'none' }}
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === 'Enter') send(); }}
|
||||
/>
|
||||
<button className="btn-primary" style={{ padding: '8px 16px' }} onClick={send}>发送</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
'use client';
|
||||
|
||||
// 私信 - 会话列表
|
||||
import { useEffect, useState } from 'react';
|
||||
import { API } from '@/lib/api';
|
||||
import { Icon } from '../Icons';
|
||||
|
||||
function avatar(username) {
|
||||
return 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username || 'U') +
|
||||
'&background=6366f1&color=fff&size=64';
|
||||
}
|
||||
|
||||
export default function ConversationList({ onOpenChat, onClose }) {
|
||||
const [conversations, setConversations] = useState(null);
|
||||
|
||||
const load = () => {
|
||||
API.getConversations()
|
||||
.then((data) => setConversations(data || []))
|
||||
.catch(() => setConversations([]));
|
||||
};
|
||||
|
||||
useEffect(load, []);
|
||||
|
||||
return (
|
||||
<div className="modal active" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
|
||||
<div className="modal-content" style={{ display: 'flex', flexDirection: 'column', height: '70vh', maxHeight: '70vh', padding: 0, overflow: 'hidden' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px', borderBottom: '1px solid var(--border)' }}>
|
||||
<h2 style={{ fontSize: 18, margin: 0 }}><Icon name="message" size={18} style={{ verticalAlign: -3, marginRight: 6 }} /> 私信</h2>
|
||||
<span className="close" onClick={onClose} style={{ cursor: 'pointer', color: 'var(--text-light)', lineHeight: 1 }}><Icon name="close" size={20} /></span>
|
||||
</div>
|
||||
<div id="messageListContent" style={{ flex: 1, overflowY: 'auto', padding: 0 }}>
|
||||
{conversations === null ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}><span className="spinner-sm" />加载中...</div>
|
||||
) : conversations.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0' }}>暂无私信</div>
|
||||
) : (
|
||||
conversations.map((c) => {
|
||||
const unread = c.unread_count || 0;
|
||||
const lastMsg = c.last_message || '暂无消息';
|
||||
const time = c.last_message_time ? new Date(c.last_message_time).toLocaleString('zh-CN') : '';
|
||||
return (
|
||||
<div
|
||||
key={c.id}
|
||||
className="message-list-item"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', borderBottom: '1px solid var(--border)', cursor: 'pointer', transition: 'background 0.15s' }}
|
||||
onClick={() => onOpenChat(c.id, c.other_user_id, c.other_username)}
|
||||
>
|
||||
<img src={c.other_avatar_url || avatar(c.other_username)} style={{ width: 40, height: 40, borderRadius: '50%', objectFit: 'cover' }} alt="" />
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<span style={{ fontWeight: 600 }}>{c.other_username}</span>
|
||||
<span style={{ fontSize: 12, color: 'var(--text-light)' }}>{time}</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
|
||||
<span style={{ fontSize: 13, color: 'var(--text-secondary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 200 }}>{lastMsg}</span>
|
||||
{unread > 0 && (
|
||||
<span style={{ background: '#ef4444', color: '#fff', borderRadius: '50%', padding: '2px 8px', fontSize: 11, fontWeight: 600 }}>{unread}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user