53 Commits

Author SHA1 Message Date
c958dcfd80 chore: 发布 Docker 镜像版本 1.1.7
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 03:01:36 +08:00
84bfbd9a3e fix: 帖子详情右栏默认头像与全站配色一致
作者卡占位头像改为深绿底白字,与 post-avatar 默认样式统一。
2026-09-02 02:50:23 +08:00
500e452c2f feat: 重设计私信页并优化开源展柜体验
私信改为飞书风布局,支持缩略图表情/图片、按会话草稿与用户搜索发起会话;主页发私信直达消息页。开源展柜修复空列表粘滞并改版目录式 UI。
2026-09-02 02:45:29 +08:00
1c0f7ede55 fix: 待审通知实时回填审核态并重构消息页体验 2026-09-02 01:39:27 +08:00
2e9c42a34c chore: 发布 Docker 镜像版本 1.1.6
同步更新日志与 README 下载链接;含编辑器链接/图片选择器与首页最新活动排序。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 22:02:00 +08:00
dff60dde6a fix: 首页默认排序改为最近活动时间线
reply 按发帖与最后评论的较晚时间混排,零回复新帖不再沉底;默认文案改为「最新」。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 21:54:44 +08:00
ea9e0058d4 fix: 链接对话框站内搜索收进高级选项
默认只显示网址与文字;展开高级选项后再搜站内内容,点选时同步更新链接文字。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 21:33:24 +08:00
d5aa36416c feat: 增强编辑器链接对话框并统一图片插入选择器
链接支持网址/文字与站内搜索,新标签由全站设置控制;文章与评论共用已上传图片选择器。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 21:22:03 +08:00
2159280af5 style: 三栏主滚动区统一细绿色滚动条
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 19:12:24 +08:00
bc9a031890 feat: 单页详情右侧栏与帖子共用目录布局
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 18:34:59 +08:00
0d81787125 fix: 从正文同步派生帖子目录,避免预取缓存竞态导致空树
EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 18:25:42 +08:00
68713c053b docs: 增加更新日志并指向 Gitea Release 下载
让 Docker 与 Windows/Linux 用户能对照同一版本号获取新包。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 18:09:41 +08:00
94823c0821 chore: 发布 Docker 镜像版本 1.1.5
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 08:16:29 +08:00
b608ec85ba fix: 桌面隐藏导航汉堡,恢复评论数与共 N 条右对齐
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 08:11:29 +08:00
6048d71759 fix: 帖行评论数勿贴右缘,手机 SSR 顶栏/页脚与 React 同构
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 08:06:57 +08:00
37d14a22d5 fix: 发版后软刷新检测入口壳并在 chunk 404 时硬刷新
避免 Logo/下拉刷新仍跑旧 index.js,以及站内消息预取失败弹出英文 toast。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 07:53:39 +08:00
a02d103cfe fix: 排序栏 count 紧跟标签,FeedSortBar 与 SSR 统一为 a 标签
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 07:48:18 +08:00
21c6233fc0 feat: 排序标签强制刷新、推荐帖仅 featured,软刷新同步 limits/品牌文案
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 07:32:21 +08:00
4ca5c17e2e fix: 拆除爬虫专用 HTML,并补齐 /favicon.ico 与 head 图标注入
人机统一走 SPA/首页 SSR;约定路径与 link rel=icon 便于爬虫识别站点图标。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 07:15:06 +08:00
cf7a37eccc chore: 忽略 lucide path 抽取临时文件
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 07:08:47 +08:00
44eed97fe0 feat: 首页 Go SSR 与 React hydrate 同构,消壳层与帖行闪动
补齐侧栏/右栏图标与徽章、鉴权种子、StaticFeedList,并修正嵌套 a 与标题徽章对齐。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 07:07:38 +08:00
9e134916a4 fix: 软刷新齐套前保留旧画面,避免一点击就卸光
Logo/下拉静默预热后一次覆盖;commit 不再先 reset/loading;顺带会话预取与可配置 Feed 排序标签。
2026-09-01 04:56:10 +08:00
ba60a9b1c4 feat: 调整 Feed 排序为新评论/新帖子/推荐帖
默认按新评论;推荐排序优先 featured,并将用户可见「精华」文案改为「推荐」。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 01:59:01 +08:00
132ca5c82c fix: 用 Zustand 缓存 Feed 列表,返回时恢复滚动且不重复请求
点击 Logo 仍强制刷新;后退忽略 history 上的 refreshFeed,并支持过期静默刷新与下拉刷新。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 01:50:33 +08:00
185649db7c fix: 增加手机端排序栏顶部间距
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-31 23:56:40 +08:00
9d926750b2 chore: 发布 Docker 镜像 1.1.4
含城市中文映射补全与监控概览双通道口径对齐。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-31 09:07:50 +08:00
a91d917fa9 fix: 对齐监控概览双通道口径文案与诊断抽样
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-31 08:58:03 +08:00
34f3d088ad fix: 补全 IP2Location 中国城市中文映射并按省消歧
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-31 08:40:12 +08:00
c6ce44f8b4 chore: 发布 Docker 镜像 1.1.3
包含网站监控与独立 monitor.db。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-31 07:58:54 +08:00
429956c594 feat: 管理端网站监控,浏览量写入独立 monitor.db
请求日志按日 JSONL;page_views 不进主库,避免统计数据撑大 jiang13.db。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-31 07:55:45 +08:00
16b6a18096 chore: 发布 Docker 镜像 1.1.2
包含可选社区上报、精选展柜与仪表盘支持条。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-31 04:26:26 +08:00
95c2154087 feat: 可选社区上报与官方精选展柜
默认关闭,仪表盘一键开关;枢纽由运维配置收报,人工精选后展示于 /showcase。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-31 04:22:59 +08:00
0abfb32194 chore: 发布 Docker 镜像 1.1.1
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-31 00:25:20 +08:00
bcfd306643 feat: 评论管理操作收进更多菜单,减少管理员界面杂乱
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-31 00:08:16 +08:00
335b708b04 chore: 发布 Docker 镜像 1.1.0
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 23:27:52 +08:00
a83f8bd670 feat: 帖子管理收进右上角菜单,手机端评论输入默认折叠
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-30 22:58:55 +08:00
4dc3bbb13f fix: 单页正文改用 post-detail-content 对齐帖子排版
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 19:33:09 +08:00
8cfe31da61 fix: 锁死页面双指缩放,正文原图与灯箱 pinch 放大
禁止手机/平板整页捏合缩放;帖子与单页正文直接显示原图(含外链可点开灯箱),灯箱内支持双指缩放与拖动。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 19:11:00 +08:00
7965768f3d fix: 注册用户无头像时不再误用游客灰底样式
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 04:05:14 +08:00
012cac23de feat: 去掉 Feed 顶栏统计并强化开源码桶
按帖子列表风格展示码桶,补齐语言/Star/Fork 与论坛作者关联回填,避免未绑定仓库与空列表。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 03:58:04 +08:00
d929bf96aa fix: 首页帖子列表标题去掉加粗
保留 15px 字号,字重改回 400。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 03:11:47 +08:00
cce9fb9ed8 feat: 友链入口迁至站点区并支持左右页脚独立开关
修复左侧栏/页脚开关无法关闭的问题,改为专用设置接口可靠写入。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 03:04:22 +08:00
9eefe24a33 feat: 优化单页编辑、列表留白与友链申请体验
单页全屏编辑并禁用内容门控;对齐 Feed 留白;友链申请区前置并收敛弹框样式;略增大帖子列表标题字号。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 02:39:24 +08:00
f559fc4c4b fix: 适配手机端搜索入口与底部 Sheet 面板
顶栏改为可伸展搜索 pill,面板改为自底部滑出并优化筛选条与触控布局。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-27 23:39:32 +08:00
55b1831da2 feat: 重设计搜索帖子 UI/UX,新增筛选面板与结果页 chips
将高级筛选移入独立面板,统一 URL 状态与清除逻辑,并优化移动端搜索与空结果反馈。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-27 19:21:55 +08:00
c6df703b96 fix: 占位头像默认白字并保留 hover 描边反馈
修复 user-link inherit 覆盖 post-avatar 白字的问题,头像链接 hover 时用淡绿描边替代变绿字。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-27 19:01:18 +08:00
7cc574f9a1 feat: 优化首页帖子列表并新增右侧栏最新注册组件
首页列表精简 meta 与统计展示,板块色标前移并淡化;有回复时显示最后回复人。右侧栏新增最新注册(4 列头像网格),友链改为标签块并排换行。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-27 18:50:09 +08:00
2208af7070 feat: 增加友链申请、独立页面、投票/悬赏/抽奖帖与侧栏签到,并统一开发数据目录
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-27 06:23:54 +08:00
df19752a1e chore: 移除 GitHub Actions 工作流,避免 Gitea 检查失败
仓库托管在 Gitea,镜像改由本地手动构建推送到 Docker Hub。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-23 18:37:01 +08:00
c07d1fd2bd feat: 新增 Docker 容器化部署,支持 Docker Hub 镜像发布
Some checks failed
Docker / docker (push) Has been cancelled
多阶段 Dockerfile、Compose、/health 探活与 JIANG13_* 环境变量;
entrypoint 自动修正 /data 卷权限,适配 1Panel 等平台;更新 README 部署文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-23 18:30:53 +08:00
4f85a86077 fix: 修复生产环境表情无法显示的问题
1. 后端新增/stickers路由静态文件服务,设置1天缓存
2. 排除/stickers前缀的SPA路由拦截
3. 优化评论区表情按钮样式与可访问性
4. 移除编辑器中未使用的标题工具与引用工具
2026-08-12 02:49:26 +08:00
f0650a9c39 fix(post-detail): 修复评论定位不准确和重试机制缺失问题
将jumpToFloor改为使用pageRef.scrollTo替代scrollIntoView适配自定义滚动容器,同时为floor锚点定位添加完善的重试机制,对齐heading锚点的处理逻辑
2026-08-11 22:52:55 +08:00
4f42a2faff fix(comment): 修复评论框提交后重置和聚焦的问题
1. 为CommentEditor的focus方法添加preventScroll可选参数并透传调用
2. 使用ref记录上次提交计数,避免首次挂载时重复清空输入框
3. 仅在submitCount实际变化时重置表单并聚焦编辑器
2026-08-08 15:09:43 +08:00
195 changed files with 32374 additions and 3044 deletions

25
.dockerignore Normal file
View File

@@ -0,0 +1,25 @@
# Git 与编辑器
.git
.gitignore
.idea
.vscode
.cursor
# 运行时数据与本地配置
data/
app.ini
tmp-cookie.txt
# 编译产物与前端缓存
dist/
frontend/node_modules/
frontend/dist/
embed_static/static/spa/
node_modules/
.vite/
# 文档与截图(不参与镜像构建)
docs/
# 计划文件
*.plan.md

3
.gitignore vendored
View File

@@ -23,3 +23,6 @@ tmp-cookie.txt
*.swp
Thumbs.db
.DS_Store
# Lucide path <20><>ȡ<EFBFBD><C8A1>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD>
frontend/tmp-lucide-paths.json

View File

@@ -0,0 +1,138 @@
# 修复主页右侧栏评论点击定位问题
## 问题描述
用户在主页右侧栏点击评论时,如果该评论不是帖子的第一个评论(`floor > 0`),页面跳转后没有定位到该评论上。
## 根因分析
### 问题 1:`jumpToFloor` 使用 `scrollIntoView` 而非 `pageRef.scrollTo`
**文件**: [PostDetailPage.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/pages/PostDetailPage.tsx#L235-L242)
当前 `jumpToFloor` 函数使用 `el.scrollIntoView()` 来滚动:
```typescript
const jumpToFloor = useCallback((floor: number) => {
const el = document.getElementById(`floor-${floor}`);
if (!el) return;
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
// ...
}, []);
```
但是页面使用了自定义滚动容器 `pageRef`(类名为 `.post-detail-page`),且 `useGlobalWheelScroll` 钩子拦截了滚轮事件,将其转换为对 `pageRef.scrollTop` 的直接操作。这导致原生 `scrollIntoView` 可能无法正确触发滚动。
对比 `jumpToHeadingHash` 函数(第 244-262 行),它正确地使用了 `pageRef.scrollTo()`:
```typescript
const jumpToHeadingHash = useCallback((hash: string, smooth = false) => {
// ...
const root = pageRef.current;
if (root) {
const rootRect = root.getBoundingClientRect();
const elRect = el.getBoundingClientRect();
const top = root.scrollTop + (elRect.top - rootRect.top) - 12;
root.scrollTo({ top: Math.max(0, top), behavior });
}
// ...
}, []);
```
### 问题 2:`#floor-N` 定位缺少重试机制
**文件**: [PostDetailPage.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/pages/PostDetailPage.tsx#L264-L273)
当前 `#floor-N` 定位只有一次 80ms 延迟,没有重试机制:
```typescript
useEffect(() => {
if (loading || !post) return;
const m = location.hash.match(/^#floor-(\d+)$/);
if (!m) return;
const floor = Number(m[1]);
if (!floor) return;
const t = window.setTimeout(() => jumpToFloor(floor), 80);
return () => clearTimeout(t);
}, [loading, post, comments, location.hash, jumpToFloor]);
```
对比 `#heading-N` 定位(第 275-299 行),它有完善的重试机制(最多 30 次,每次 50ms)。
## 修改方案
### 修改 1:修改 `jumpToFloor` 函数使用 `pageRef.scrollTo`
将 `jumpToFloor` 函数改为使用与 `jumpToHeadingHash` 相同的滚动方式:
```typescript
const jumpToFloor = useCallback((floor: number) => {
const el = document.getElementById(`floor-${floor}`);
if (!el) return false;
const root = pageRef.current;
if (root) {
const rootRect = root.getBoundingClientRect();
const elRect = el.getBoundingClientRect();
const top = root.scrollTop + (elRect.top - rootRect.top) - 12;
root.scrollTo({ top: Math.max(0, top), behavior: 'smooth' });
} else {
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
setHighlightFloor(floor);
clearTimeout(highlightTimer.current);
highlightTimer.current = setTimeout(() => setHighlightFloor(null), 2000);
return true;
}, []);
```
### 修改 2:为 `#floor-N` 定位添加重试机制
将 `#floor-N` 定位的 `useEffect` 改为类似 `#heading-N` 的重试机制:
```typescript
useEffect(() => {
if (loading || !post) return;
const m = location.hash.match(/^#floor-(\d+)$/);
if (!m) return;
const floor = Number(m[1]);
if (!floor) return;
let cancelled = false;
let attempts = 0;
let timer = 0;
const tryJump = () => {
if (cancelled) return;
if (jumpToFloor(floor)) return;
attempts += 1;
if (attempts < 30) {
timer = window.setTimeout(tryJump, 50);
}
};
timer = window.setTimeout(tryJump, 0);
return () => {
cancelled = true;
window.clearTimeout(timer);
};
}, [loading, post, comments, location.hash, jumpToFloor]);
```
## 涉及文件
- `frontend/src/pages/PostDetailPage.tsx`:修改 `jumpToFloor` 函数和 `#floor-N` 定位的 `useEffect`
## 风险评估
- **低风险**:修改仅限于评论定位逻辑,不影响其他功能
- **需测试**:需要验证页面加载时评论定位是否正常工作,以及页面内部导航时是否正常
## 测试步骤
1. 进入主页,点击右侧栏的一个非第一条评论
2. 验证页面跳转到帖子详情后,是否正确定位到目标评论
3. 验证评论高亮效果是否正常显示
4. 测试第一条评论(floor=0)的定位是否仍然正常工作
5. 在帖子详情页直接加载带 hash 的 URL(如 `/post/123#floor-5`),验证定位效果

View File

@@ -0,0 +1,55 @@
# 修复生产环境表情图片无法显示 Implementation Plan
## Repository Research
### 问题分析
表情图片在生产部署后无法加载,原因是 **Go 后端缺少 `/stickers/*` 路由的静态文件服务注册**。
当前架构:
1. 前端 emoji 数据中的 URL 为 `/stickers/{platform}/{file}.avif`(在 [emojiData.ts](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/data/stickers/emojiData.ts) 中通过 `toLocalUrl()` 生成)
2. Vite 构建时将 `frontend/public/stickers/` 原样复制到 `embed_static/static/spa/stickers/`
3. Go 的 `//go:embed static/*` 会将 `embed_static/static/` 下所有文件(包括 stickers)打包进二进制
4. 但 [embed.go](file:///c:/Users/freefire/Documents/jiang13-forum/embed_static/embed.go) 的 `SetupEmbed()` **只注册了 `/assets/*filepath` 路由**(用于 JS/CSS chunk),没有注册 `/stickers/*filepath`
5. 同时 `IsSPARoute()` 函数也没有排除 `/stickers` 前缀,导致请求被 SPA NoRoute fallback 处理,返回 index.html 而非图片
开发模式之所以正常,是因为 Vite dev server 自动托管了 `public/stickers/` 下的静态文件。
### 当前代码状态
- `embed.go` 第 13 行: `//go:embed static/*` — 正确嵌入了所有静态资源(含 stickers)
- `embed.go` 第 33-43 行: `SetupEmbed()` — 只处理了 `static/spa/assets`,缺少 stickers 路由
- `embed.go` 第 63-77 行: `IsSPARoute()` — 缺少 `/stickers` 前缀排除
## Files and Modules
- `embed_static/embed.go`: 新增 `/stickers/*filepath` 文件服务路由;在 `IsSPARoute` 中排除 `/stickers` 前缀
## Implementation Steps
1. **在 `SetupEmbed` 中注册 `/stickers` 路由**
- 参照现有 `/assets` 路由的模式,添加对 `static/spa/stickers` 子目录的文件服务
- 使用 `fs.Sub(staticFS, "static/spa/stickers")` 获取 stickers 子文件系统
- 注册 `GET /stickers/*filepath` 路由,直接透传,不设置长期缓存(表情可能更新)
2. **在 `IsSPARoute` 中排除 `/stickers` 前缀**
- 在现有 `strings.HasPrefix(path, "/assets")` 附近添加 `strings.HasPrefix(path, "/stickers")`
- 确保表情请求不会被 SPA fallback 拦截
## Dependencies and Considerations
- stickers 目录下存储的是 `.avif` 图片文件,不需要设置特殊 MIME type(http.FileServer 会根据扩展名自动识别)
- stickers 资源不含哈希指纹,不应设置 `immutable` 缓存头(与 `/assets` 不同),但可以设置短过期缓存
- 需确保 `fs.Sub` 路径与实际构建输出路径一致:`embed_static/static/spa/stickers/`
## Validation
- 重新构建前端:`cd frontend && npm run build`
- 重新构建 Go 二进制:`go build -o jiang13-linux-amd64`
- 部署后访问 `/stickers/tieba/tb_01.avif` 应能直接返回图片内容(HTTP 200)
- 在评论框中打开表情选择器,所有平台的表情应正常显示
## Risks
- **风险**: 如果未来在 `public/` 下新增其他静态资源目录(如 `avatars/`、`flags/` 等),需要同样在 `embed.go` 中注册对应路由
- **应对**: 可考虑后续重构为自动扫描 `public/` 下所有子目录并自动注册路由,或改为统一的 SPA 静态文件服务方案

55
Dockerfile Normal file
View File

@@ -0,0 +1,55 @@
# 姜十三论坛 — 多阶段构建:Node 前端 → Go 单二进制 → Alpine 运行镜像
# 不使用 # syntax=docker/dockerfile:1,避免构建前额外拉取 docker.io/docker/dockerfile
#
# 国内网络:默认经 DaoCloud 拉取基础镜像,npm/go 走国内代理
# 海外或已配置 Docker registry-mirrors 时可传空前缀:
# docker build --build-arg IMAGE_PREFIX= ...
ARG IMAGE_PREFIX=docker.m.daocloud.io/library/
ARG VERSION=dev
# ── Stage 1: 前端构建(Vite → embed_static/static/spa)────────────────────
FROM ${IMAGE_PREFIX}node:22-bookworm-slim AS frontend
WORKDIR /src/frontend
COPY frontend/package.json frontend/package-lock.json ./
RUN npm config set registry https://registry.npmmirror.com \
&& npm ci
COPY frontend/ ./
RUN npm run build
# ── Stage 2: Go 编译(纯 Go SQLite,CGO_ENABLED=0)────────────────────────
FROM ${IMAGE_PREFIX}golang:1.26-bookworm AS builder
ARG VERSION
ENV GOPROXY=https://goproxy.cn,direct
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
COPY --from=frontend /src/embed_static/static/spa ./embed_static/static/spa
RUN CGO_ENABLED=0 go build -trimpath \
-ldflags "-s -w -X main.version=${VERSION}" \
-o /out/jiang13 ./cmd/jiang13
# ── Stage 3: 运行镜像 ───────────────────────────────────────────────────────
FROM ${IMAGE_PREFIX}alpine:3.21
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
&& apk add --no-cache ca-certificates tzdata wget su-exec \
&& adduser -D -u 1000 -h /app jiang13
ENV TZ=Asia/Shanghai
WORKDIR /app
COPY --from=builder /out/jiang13 /app/jiang13
COPY docker-entrypoint.sh /docker-entrypoint.sh
RUN chown jiang13:jiang13 /app/jiang13 \
&& chmod +x /app/jiang13 /docker-entrypoint.sh
# 以 root 启动,entrypoint 修正 /data 卷权限后 su-exec 降权为 jiang13
VOLUME ["/data"]
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
CMD wget -qO- http://127.0.0.1:3000/health || exit 1
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["--work-path", "/app", "--data", "/data", "--port", "3000"]

View File

@@ -4,13 +4,15 @@
APP_NAME := jiang13
MAIN_PKG := ./cmd/jiang13
BUILD_DIR := dist
VERSION := 1.0.0
DEV_DATA_DIR := dist/data
VERSION := 1.1.7
LDFLAGS := -s -w -X main.version=$(VERSION)
REGISTRY_IMAGE := hangzhang714128/jiang13-forum
GO := go
GOFLAGS := -trimpath
.PHONY: all build build-windows build-linux build-darwin clean run dev tidy help frontend frontend-build
.PHONY: all build build-windows build-linux build-darwin clean run dev tidy help frontend frontend-build docker compose-up compose-down
all: build
@@ -54,22 +56,37 @@ build-all: frontend-build
tidy:
$(GO) mod tidy
## 本地运行(仅后端,使用已 embed 的前端)
## 本地运行(仅后端,使用已 embed 的前端;数据目录与 dist 二进制一致)
run:
$(GO) run $(MAIN_PKG)
@mkdir -p $(DEV_DATA_DIR)
$(GO) run $(MAIN_PKG) --data $(DEV_DATA_DIR)
## 前端热更新开发(后端 :3000 + Vite :5173,Ctrl+C 同时退出)
## 前端热更新开发(后端 :3000 + Vite :5173,Ctrl+C 同时退出;数据目录与 dist 二进制一致)
dev:
@echo "前端热更新: http://localhost:5173"
@echo "后端 API : http://localhost:3000"
@echo "数据目录 : $(DEV_DATA_DIR) (与 dist 二进制一致)"
@mkdir -p $(DEV_DATA_DIR)
@trap 'kill 0' INT; \
$(GO) run $(MAIN_PKG) & \
$(GO) run $(MAIN_PKG) --dev --data $(DEV_DATA_DIR) & \
cd frontend && (test -d node_modules || npm install) && npm run dev
## 清理编译产物
clean:
rm -rf $(BUILD_DIR)
## 构建 Docker 镜像
docker:
docker build --build-arg VERSION=$(VERSION) -t $(REGISTRY_IMAGE):$(VERSION) -t $(REGISTRY_IMAGE):latest .
## Docker Compose 启动
compose-up:
docker compose up -d --build
## Docker Compose 停止
compose-down:
docker compose down
help:
@echo "姜十三论坛编译命令:"
@echo " make build - 编译当前平台"
@@ -79,3 +96,6 @@ help:
@echo " make build-all - 编译全部平台"
@echo " make run - 仅启动后端(:3000)"
@echo " make dev - 前端热更新开发(:5173 + :3000)"
@echo " make docker - 构建 Docker 镜像"
@echo " make compose-up - Docker Compose 启动"
@echo " make compose-down - Docker Compose 停止"

135
README.md
View File

@@ -11,6 +11,7 @@
[![在线演示](https://img.shields.io/badge/Demo-bbs.iioio.com-18a058?style=flat-square)](https://bbs.iioio.com/)
[![License: MIT](https://img.shields.io/badge/License-MIT-18a058?style=flat-square)](LICENSE)
[![Docker](https://img.shields.io/badge/Docker-hangzhang714128%2Fjiang13--forum-2496ED?style=flat-square&logo=docker&logoColor=white)](https://hub.docker.com/r/hangzhang714128/jiang13-forum)
[![Go](https://img.shields.io/badge/Go-1.26-00ADD8?style=flat-square&logo=go&logoColor=white)](go.mod)
[![React](https://img.shields.io/badge/React-18-61DAFB?style=flat-square&logo=react&logoColor=white)](frontend/package.json)
[![SQLite](https://img.shields.io/badge/SQLite-内置-003B57?style=flat-square&logo=sqlite&logoColor=white)](#)
@@ -19,6 +20,7 @@
[快速开始](#-快速开始) ·
[界面预览](#-界面预览) ·
[功能亮点](#-功能亮点) ·
[更新日志](docs/site-posts/changelog.md) ·
[路线图](ROADMAP.md) ·
[参与贡献](CONTRIBUTING.md)
@@ -116,6 +118,7 @@
- **零依赖数据库** — SQLite 内建,数据目录由 `app.ini` 统一管理
- **跨平台** — Windows / Linux / macOS 一键编译
- **系统服务** — 内置 Linux systemd / Windows Service 注册
- **Docker 单容器** — 多阶段镜像,挂载 `data/` 即可持久化
---
@@ -152,9 +155,119 @@ build.bat -Target build-linux
build.bat -Target build-all
```
### 2. 启动
### 2. Docker 部署(推荐)
把二进制放到目标目录后直接运行(首次会在同目录生成 `app.ini`):
**一键启动(本地构建):**
```bash
docker compose up -d --build
```
```bat
.\build.bat -Target compose-up
```
```bash
make compose-up
```
浏览器打开 `http://localhost:3000/register` 注册;**首个用户自动成为管理员**。
版本变更与升级说明见 **[更新日志](docs/site-posts/changelog.md)**。Docker 与 Windows / Linux 单文件共用同一版本号。
- Docker 标签:[hub.docker.com/r/hangzhang714128/jiang13-forum/tags](https://hub.docker.com/r/hangzhang714128/jiang13-forum/tags)
- 预编译包:[Gitea Releases](https://git.iioio.com/freefire/jiang13-forum/releases)
**拉取已构建镜像(Docker Hub):**
```bash
docker pull hangzhang714128/jiang13-forum:latest
docker run -d --name jiang13 \
-p 3000:3000 \
-v jiang13-data:/data \
--restart unless-stopped \
hangzhang714128/jiang13-forum:latest
```
**数据持久化:** 容器内 `/data` 对应 SQLite、上传、日志与 JWT 密钥,与下方「数据目录」结构一致。可用 Docker volume 或绑定宿主机目录。镜像启动时会自动将 `/data` 卷属主修正为 uid `1000`(`jiang13` 用户),适配 1Panel 等面板挂载的目录。
**若使用旧版镜像仍报 permission denied**,可在宿主机执行:`chown -R 1000:1000 /你的数据目录`
**可选环境变量(容器编排):**
| 变量 | 说明 |
|------|------|
| `JIANG13_HTTP_PORT` | HTTP 端口(默认 `3000`) |
| `JIANG13_DATA` | 数据目录(默认 `/data`) |
| `JIANG13_JWT_SECRET` | JWT 密钥(留空则自动生成并写入 `/data/.jwt_secret`) |
| `JIANG13_CONFIG` | 配置文件路径 |
| `JIANG13_WORK_PATH` | 工作目录 |
| `JIANG13_COMMUNITY_HUB` | 维护者选项:设为 `1` 时本站作为社区枢纽收报。官方站 `bbs.iioio.com` 会按域名自动成为枢纽,无需此变量;仅非官网的枢纽镜像 / 预发需要显式开启(见 `app.ini.example`) |
**健康检查:** `GET /health` 返回 `{"status":"ok"}`,供 Docker / 负载均衡探活。
**发布镜像到 Docker Hub(手动):**
```bash
docker login
.\build.bat -Target docker # Windows
# make docker # Linux/macOS
docker push hangzhang714128/jiang13-forum:1.1.7
docker push hangzhang714128/jiang13-forum:latest
```
或直接构建:
```bash
docker build --build-arg VERSION=1.1.7 -t hangzhang714128/jiang13-forum:1.1.7 -t hangzhang714128/jiang13-forum:latest .
docker push hangzhang714128/jiang13-forum:1.1.7
docker push hangzhang714128/jiang13-forum:latest
```
停止服务:`docker compose down` / `.\build.bat -Target compose-down` / `make compose-down`
**构建失败(无法连接 auth.docker.io)?** Dockerfile 已默认经 DaoCloud 拉取基础镜像。若仍超时,可在 Docker Desktop → Settings → Docker Engine 添加:
```json
{
"registry-mirrors": ["https://docker.m.daocloud.io"]
}
```
保存并重启 Docker 后重试 `.\build.bat -Target docker`。PowerShell 中请用 `.\build.bat`(带 `.\` 前缀)。
**1Panel 部署提示:**
1. 容器镜像填 `hangzhang714128/jiang13-forum:latest`
2. 端口映射 `3000:3000`
3. 挂载数据卷到容器内 `/data`(镜像会自动修正目录权限)
4. 首次访问 `http://服务器IP:3000/register` 注册管理员
### 3. 直接启动(二进制)
不想自己编译时,从 [Gitea Releases](https://git.iioio.com/freefire/jiang13-forum/releases) 下载与 Docker 同版本号的文件即可:
| 文件 | 平台 |
|------|------|
| `jiang13-*-windows-amd64.exe` | Windows x64 |
| `jiang13-*-linux-amd64` | Linux x64 |
当前 **1.1.7:** [Windows](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/jiang13-1.1.7-windows-amd64.exe) · [Linux](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/jiang13-1.1.7-linux-amd64)
把文件放到目标目录后直接运行(首次会在同目录生成 `app.ini`):
```bash
# Windows
.\jiang13-1.1.7-windows-amd64.exe
# 或改名为 jiang13.exe 后:
.\jiang13.exe
# Linux
chmod +x jiang13-1.1.7-linux-amd64
./jiang13-1.1.7-linux-amd64
```
本地刚编译的产物在 `dist/`:
```bash
# Windows
@@ -172,7 +285,7 @@ cp app.ini.example /opt/jiang13/app.ini
./jiang13
```
### 3. 首次使用
### 4. 首次使用
1. 浏览器打开 `http://localhost:3000/register` 注册账号
2. **第一个注册的用户自动成为管理员**
@@ -208,7 +321,9 @@ JWT_SECRET =
| `--jwt-secret` | 自动生成 | JWT 签名密钥(留空则持久化到 `data/.jwt_secret`) |
| `--service` | (空) | `install` / `uninstall` / `start` / `stop` / `restart` / `status` |
### 4. 注册为系统服务(可选)
**环境变量(容器 / 编排,优先级低于命令行):** `JIANG13_HTTP_PORT`、`JIANG13_DATA`、`JIANG13_JWT_SECRET`、`JIANG13_CONFIG`、`JIANG13_WORK_PATH`、`JIANG13_COMMUNITY_HUB`(非官网枢纽镜像用;`bbs.iioio.com` 按域名自动为枢纽,见上表)
### 5. 注册为系统服务(可选)
将二进制与 `app.ini` 放到同一目录后注册即可。之后改端口或数据目录只需编辑 `app.ini` 并重启服务,不必重新安装。
@@ -260,6 +375,8 @@ make dev
浏览器访问 `http://localhost:5173`,API 自动代理到 `http://localhost:3000`。
开发后端与 `dist/jiang13` 共用数据目录 `dist/data`(SQLite、上传、JWT 密钥等),避免 dev 与 dist 运行数据不一致。
**何时需要完整构建:**
- 修改 Go 代码或要发布单二进制 → `build.bat` / `make build`
@@ -295,6 +412,10 @@ jiang13-forum/
├── cmd/jiang13/ # 程序入口(含系统服务注册)
├── config/ # app.ini 与命令行配置
├── app.ini.example # 配置文件示例
├── Dockerfile # 多阶段 Docker 构建
├── docker-compose.yml # 单容器 Compose 部署
├── docker-entrypoint.sh # 容器启动脚本(修正 /data 卷权限)
├── .dockerignore
├── model/ # GORM 模型与数据库迁移
├── service/ # 业务逻辑
├── handler/ # HTTP 处理器(前台 + 后台)
@@ -313,13 +434,15 @@ jiang13-forum/
```
data/
├── jiang13.db # SQLite 主数据库
├── jiang13.db # SQLite 主数据库(不含浏览量)
├── monitor.db # 网站监控 page_views
├── jiang13.log # 运行日志
├── filter_words.txt # 敏感词配置
├── .jwt_secret # JWT 密钥(自动生成)
├── logs/access/ # 网站监控请求日志(按日 jsonl)
├── uploads/avatars/ # 用户头像
├── uploads/posts/ # 帖子正文图片
└── jiang13_backup_*.db # 后台导出的备份
└── jiang13_backup_*.db # 后台导出的主库备份
```
---

View File

@@ -13,3 +13,13 @@ DATA = data
[security]
; 留空则自动生成并持久化到 data/.jwt_secret(勿把生产密钥提交到仓库)
JWT_SECRET =
; ---------------------------------------------------------------------------
; 维护者选项(默认关闭;普通自托管无需开启)
; 开启后本站可接收其它实例「自愿向官方演示站」的心跳,并在后台「公网实例」展示。
; 官方演示站 bbs.iioio.com 会按域名自动识别为枢纽,无需开启本项。
; 本开关仅用于非 bbs.iioio.com 的枢纽镜像 / 预发环境。
; 等价环境变量:JIANG13_COMMUNITY_HUB=1
; ---------------------------------------------------------------------------
; [community]
; HUB = false

View File

@@ -3,7 +3,7 @@
# .\build.ps1 -Target build-windows
param(
[ValidateSet('build', 'build-windows', 'build-linux', 'build-darwin', 'build-all', 'frontend', 'tidy', 'run', 'dev', 'clean', 'help')]
[ValidateSet('build', 'build-windows', 'build-linux', 'build-darwin', 'build-all', 'frontend', 'tidy', 'run', 'dev', 'clean', 'docker', 'compose-up', 'compose-down', 'help')]
[string]$Target = 'build'
)
@@ -11,7 +11,9 @@ $ErrorActionPreference = 'Stop'
$AppName = 'jiang13'
$MainPkg = './cmd/jiang13'
$BuildDir = 'dist'
$Version = '1.0.0'
$DevDataDir = 'dist/data'
$Version = '1.1.7'
$RegistryImage = 'hangzhang714128/jiang13-forum'
$Ldlags = "-s -w -X main.version=$Version"
function Ensure-Dir($path) {
@@ -76,6 +78,9 @@ switch ($Target) {
Write-Host '.\build.ps1 -Target dev backend + Vite HMR (recommended for frontend dev)'
Write-Host '.\build.ps1 -Target tidy'
Write-Host '.\build.ps1 -Target clean'
Write-Host '.\build.ps1 -Target docker build Docker image'
Write-Host '.\build.ps1 -Target compose-up docker compose up -d --build'
Write-Host '.\build.ps1 -Target compose-down docker compose down'
Write-Host ''
Write-Host 'Note: Windows "make" is often Embarcadero MAKE, not GNU Make.'
}
@@ -86,18 +91,21 @@ switch ($Target) {
Write-Host '[ok] cleaned dist' -ForegroundColor Green
}
'run' {
go run $MainPkg
Ensure-Dir $DevDataDir
go run $MainPkg --data $DevDataDir
}
'dev' {
$root = (Get-Location).Path
Ensure-Dir $DevDataDir
Write-Host ''
Write-Host '[dev] 前端开发 : http://localhost:5173 (Vite HMR)' -ForegroundColor Green
Write-Host '[dev] 后端 API : http://localhost:3000 (Go)' -ForegroundColor Green
Write-Host "[dev] 数据目录 : $DevDataDir (与 dist 二进制一致)" -ForegroundColor Green
Write-Host '[dev] 提示 : 请访问 5173 端口,Vite 会自动代理 API 到 3000' -ForegroundColor Yellow
Write-Host '[dev] 正在新窗口启动 Go 后端 (仅 API)...' -ForegroundColor Cyan
Start-Process powershell -ArgumentList @(
'-NoExit', '-Command',
"Set-Location '$root'; Write-Host '[backend] Go API on :3000' -ForegroundColor Cyan; go run $MainPkg --dev"
"Set-Location '$root'; Write-Host '[backend] Go API on :3000' -ForegroundColor Cyan; go run $MainPkg --dev --data '$DevDataDir'"
) | Out-Null
Start-Sleep -Seconds 2
Push-Location frontend
@@ -132,4 +140,20 @@ switch ($Target) {
Build-Go -OutFile "$AppName-darwin-arm64" -GoOS 'darwin' -GoArch 'arm64'
Write-Host '[ok] all platforms done' -ForegroundColor Green
}
'docker' {
Write-Host "[docker] build $RegistryImage`:$Version and latest" -ForegroundColor Cyan
docker build --build-arg "VERSION=$Version" -t "${RegistryImage}:$Version" -t "${RegistryImage}:latest" .
if ($LASTEXITCODE -ne 0) { throw 'docker build failed' }
Write-Host '[ok] docker image built' -ForegroundColor Green
}
'compose-up' {
docker compose up -d --build
if ($LASTEXITCODE -ne 0) { throw 'docker compose up failed' }
Write-Host '[ok] compose started' -ForegroundColor Green
}
'compose-down' {
docker compose down
if ($LASTEXITCODE -ne 0) { throw 'docker compose down failed' }
Write-Host '[ok] compose stopped' -ForegroundColor Green
}
}

View File

@@ -8,9 +8,14 @@ import (
"github.com/kardianos/service"
"git.iioio.com/freefire/jiang13-forum/config"
appsvc "git.iioio.com/freefire/jiang13-forum/service"
)
// version 由构建脚本通过 -ldflags "-X main.version=..." 注入
var version = "dev"
func main() {
appsvc.SetAppVersion(version)
cfg, err := config.Parse()
if err != nil {
log.Fatalf("配置解析失败: %v", err)

View File

@@ -12,6 +12,7 @@ import (
"github.com/kardianos/service"
"git.iioio.com/freefire/jiang13-forum/config"
forumsvc "git.iioio.com/freefire/jiang13-forum/service"
"git.iioio.com/freefire/jiang13-forum/model"
"git.iioio.com/freefire/jiang13-forum/router"
)
@@ -72,11 +73,18 @@ func (p *program) setup() error {
log.Println("========================================")
log.Println(" 姜十三论坛 Jiang13 Forum 启动中...")
log.Printf(" 版本: %s", version)
log.Println("========================================")
if err := model.InitDB(cfg.DBPath()); err != nil {
return fmt.Errorf("数据库初始化失败: %w", err)
}
if err := forumsvc.BackfillModerationNotifyRefs(); err != nil {
log.Printf("待审通知关联字段回填警告: %v", err)
}
if err := model.InitMonitorDB(cfg.MonitorDBPath()); err != nil {
return fmt.Errorf("监控库初始化失败: %w", err)
}
engine, err := router.Setup(cfg)
if err != nil {

View File

@@ -0,0 +1,410 @@
// 只读诊断:检查 Geo 库与 page_views 地理字段,或对指定 IP 试查中文映射结果。
//
// go run ./cmd/monitor-geo-check -db data/monitor.db
// go run ./cmd/monitor-geo-check -db data/monitor.db -ip 14.109.35.246
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"git.iioio.com/freefire/jiang13-forum/service"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func main() {
dbPath := flag.String("db", filepath.Join("data", "monitor.db"), "含 page_views 的 SQLite(默认 data/monitor.db)")
ipLookup := flag.String("ip", "", "对指定 IP 试查 BIN+ASN(不写库)")
flag.Parse()
abs, err := filepath.Abs(*dbPath)
if err != nil {
fatalf("解析路径失败: %v", err)
}
dataDir := filepath.Dir(abs)
if *ipLookup == "" {
if st, err := os.Stat(abs); err != nil || st.IsDir() {
fatalf("数据库不存在: %s", abs)
}
}
fmt.Printf("数据库: %s\n", abs)
fmt.Printf("数据目录: %s\n\n", dataDir)
suite := service.NewGeoIPService(dataDir)
defer suite.Close()
printGeoFiles(dataDir, suite)
if ip := strings.TrimSpace(*ipLookup); ip != "" {
lookupIP(suite, ip)
fmt.Println()
if _, err := os.Stat(abs); err != nil {
return
}
}
db, err := gorm.Open(sqlite.Open(abs), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
fatalf("打开数据库失败: %v", err)
}
sqlDB, err := db.DB()
if err != nil {
fatalf("获取连接失败: %v", err)
}
defer sqlDB.Close()
sqlDB.SetMaxOpenConns(1)
if !tableExists(db, "page_views") {
fatalf("表 page_views 不存在(请确认指向 data/monitor.db,或尚未写入过浏览量)")
}
have := columnSet(db)
printColumnPresence(have)
since := time.Now().AddDate(0, 0, -30)
var total, recentNonBot, withCountry, withRegion, withCity, withASN int64
_ = db.Table("page_views").Count(&total).Error
_ = db.Table("page_views").Where("created_at >= ? AND is_bot = ?", since, false).Count(&recentNonBot).Error
fmt.Println("=== page_views 统计(近 30 日非 bot)===")
fmt.Printf("总量: %d\n", total)
fmt.Printf("近 30 日非 bot: %d\n", recentNonBot)
if have["country"] {
_ = db.Table("page_views").Where("created_at >= ? AND is_bot = ? AND country <> ''", since, false).Count(&withCountry).Error
fmt.Printf("有国家: %d\n", withCountry)
} else {
fmt.Println("有国家: (列缺失)")
}
if have["region"] || have["region_iso"] {
cond := "created_at >= ? AND is_bot = ?"
parts := []string{}
if have["region"] {
parts = append(parts, "region <> ''")
}
if have["region_iso"] {
parts = append(parts, "region_iso <> ''")
}
_ = db.Table("page_views").
Where(cond+" AND ("+strings.Join(parts, " OR ")+")", since, false).
Count(&withRegion).Error
fmt.Printf("有省字段: %d\n", withRegion)
} else {
fmt.Println("有省字段: (列缺失)")
}
if have["city"] {
_ = db.Table("page_views").Where("created_at >= ? AND is_bot = ? AND city <> ''", since, false).Count(&withCity).Error
fmt.Printf("有城市: %d\n", withCity)
} else {
fmt.Println("有城市: (列缺失)")
}
if have["asn"] {
_ = db.Table("page_views").Where("created_at >= ? AND is_bot = ? AND asn > 0", since, false).Count(&withASN).Error
fmt.Printf("有 ASN: %d\n", withASN)
} else {
fmt.Println("有 ASN: (列缺失)")
}
fmt.Println()
fmt.Println("=== 近 30 日省级 Top(country / region / region_iso)===")
if !(have["region"] || have["region_iso"]) {
fmt.Println("(省列尚未迁移,跳过)")
} else {
type regionRow struct {
Country string
Region string
RegionISO string `gorm:"column:region_iso"`
Count int64
}
parts := []string{}
if have["region"] {
parts = append(parts, "region <> ''")
}
if have["region_iso"] {
parts = append(parts, "region_iso <> ''")
}
selParts := []string{}
groupParts := []string{}
if have["country"] {
selParts = append(selParts, "country")
groupParts = append(groupParts, "country")
} else {
selParts = append(selParts, "'' as country")
}
if have["region"] {
selParts = append(selParts, "region")
groupParts = append(groupParts, "region")
} else {
selParts = append(selParts, "'' as region")
}
if have["region_iso"] {
selParts = append(selParts, "region_iso")
groupParts = append(groupParts, "region_iso")
} else {
selParts = append(selParts, "'' as region_iso")
}
selParts = append(selParts, "COUNT(*) as count")
var regions []regionRow
_ = db.Table("page_views").
Select(strings.Join(selParts, ", ")).
Where("created_at >= ? AND is_bot = ? AND ("+strings.Join(parts, " OR ")+")", since, false).
Group(strings.Join(groupParts, ", ")).
Order("count DESC").
Limit(20).
Scan(&regions).Error
if len(regions) == 0 {
fmt.Println("(空)")
} else {
for i, r := range regions {
fmt.Printf("%2d. %s | %s | %s | %d\n", i+1, r.Country, r.Region, r.RegionISO, r.Count)
}
}
}
fmt.Println()
fmt.Println("=== 对账抽样(近 30 日非 bot)===")
printGeoReconcileSamples(db, have, since)
fmt.Println()
fmt.Println("=== 样例行(近 30 日,最多 10 条)===")
cols := []string{"id", "created_at", "path", "is_bot"}
for _, c := range []string{"ip", "country", "region", "region_iso", "city", "asn", "as_org"} {
if have[c] {
cols = append(cols, c)
}
}
type sample struct {
ID uint
CreatedAt time.Time
IP string
Country string
Region string
RegionISO string `gorm:"column:region_iso"`
City string
ASN uint
ASOrg string `gorm:"column:as_org"`
Path string
IsBot bool
}
var samples []sample
_ = db.Table("page_views").
Select(strings.Join(cols, ", ")).
Where("created_at >= ?", since).
Order("id DESC").
Limit(10).
Scan(&samples).Error
if len(samples) == 0 {
fmt.Println("(无近 30 日 pageview)")
} else {
for _, s := range samples {
fmt.Printf("#%d %s ip=%s country=%q region=%q iso=%q city=%q asn=%d org=%q bot=%v path=%s\n",
s.ID, s.CreatedAt.Format("2006-01-02 15:04:05"), s.IP,
s.Country, s.Region, s.RegionISO, s.City, s.ASN, s.ASOrg, s.IsBot, s.Path)
}
}
regionReady := have["region"] || have["region_iso"]
if !regionReady || withRegion == 0 {
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, "提示: 近 30 日无省级字段。中国地图「暂无省级访问数据」属预期。")
if !regionReady {
fmt.Fprintln(os.Stderr, "当前库缺 region/region_iso 列:请先启动一次主程序以完成 AutoMigrate。")
}
fmt.Fprintln(os.Stderr, "请确认数据目录已放置 IP2LOCATION-LITE-DB3.BIN 与 GeoLite2-ASN.mmdb,且有公网访问产生的 pageview。")
fmt.Fprintln(os.Stderr, "本机/私网 IP 通常解不出省,属正常。")
fmt.Fprintln(os.Stderr, "注意: 请求日志有地理 ≠ 概览地图/排行有数据(后者只读 page_views)。")
os.Exit(2)
}
}
func printGeoReconcileSamples(db *gorm.DB, have map[string]bool, since time.Time) {
type sample struct {
ID uint
CreatedAt time.Time
IP string
Country string
Region string
RegionISO string `gorm:"column:region_iso"`
City string
ASN uint
ASOrg string `gorm:"column:as_org"`
Path string
}
selCols := []string{"id", "created_at", "path"}
for _, c := range []string{"ip", "country", "region", "region_iso", "city", "asn", "as_org"} {
if have[c] {
selCols = append(selCols, c)
}
}
sel := strings.Join(selCols, ", ")
printBlock := func(title string, n int64, rows []sample) {
fmt.Printf("%s: %d\n", title, n)
if len(rows) == 0 {
return
}
for _, s := range rows {
fmt.Printf(" #%d %s ip=%s country=%q region=%q iso=%q city=%q asn=%d org=%q path=%s\n",
s.ID, s.CreatedAt.Format("2006-01-02 15:04:05"), s.IP,
s.Country, s.Region, s.RegionISO, s.City, s.ASN, s.ASOrg, s.Path)
}
}
if have["city"] {
var n int64
_ = db.Table("page_views").
Where("created_at >= ? AND is_bot = ? AND city <> '' AND city GLOB '[A-Za-z]*'", since, false).
Count(&n).Error
var rows []sample
_ = db.Table("page_views").
Select(sel).
Where("created_at >= ? AND is_bot = ? AND city <> '' AND city GLOB '[A-Za-z]*'", since, false).
Order("id DESC").
Limit(5).
Scan(&rows).Error
printBlock("英文城市名(可能未中文化)", n, rows)
} else {
fmt.Println("英文城市名: (city 列缺失)")
}
if have["region"] || have["region_iso"] {
cond := "created_at >= ? AND is_bot = ? AND country <> ''"
emptyParts := []string{}
if have["region"] {
emptyParts = append(emptyParts, "(region = '' OR region IS NULL OR region = '-')")
}
if have["region_iso"] {
emptyParts = append(emptyParts, "(region_iso = '' OR region_iso IS NULL)")
}
where := cond + " AND (" + strings.Join(emptyParts, " AND ") + ")"
var n int64
_ = db.Table("page_views").Where(where, since, false).Count(&n).Error
var rows []sample
_ = db.Table("page_views").
Select(sel).
Where(where, since, false).
Order("id DESC").
Limit(5).
Scan(&rows).Error
printBlock("有国家但省为空", n, rows)
} else {
fmt.Println("有国家但省为空: (省列缺失)")
}
if have["asn"] {
var n int64
_ = db.Table("page_views").
Where("created_at >= ? AND is_bot = ? AND (asn = 0 OR asn IS NULL)", since, false).
Count(&n).Error
var rows []sample
_ = db.Table("page_views").
Select(sel).
Where("created_at >= ? AND is_bot = ? AND (asn = 0 OR asn IS NULL)", since, false).
Order("id DESC").
Limit(5).
Scan(&rows).Error
printBlock("asn=0(无运营商)", n, rows)
} else {
fmt.Println("asn=0: (asn 列缺失)")
}
}
func printGeoFiles(dataDir string, suite *service.GeoIPService) {
fmt.Println("=== Geo 数据文件 ===")
v4, v6, asn, country := suite.Paths()
for _, item := range []struct {
name string
path string
ok bool
}{
{"IP2LOCATION-LITE-DB3.BIN", v4, suite.BINV4Available()},
{"IP2LOCATION-LITE-DB3.IPV6.BIN", v6, suite.BINV6Available()},
{"GeoLite2-ASN.mmdb", asn, suite.ASNAvailable()},
{"GeoLite2-Country.mmdb", country, suite.CountryAvailable()},
} {
st, err := os.Stat(item.path)
if err != nil {
fmt.Printf("%s: 不存在\n", item.name)
continue
}
loaded := "未加载"
if item.ok {
loaded = "已加载"
}
fmt.Printf("%s: 存在 (%d bytes, mtime %s) · %s\n", item.name, st.Size(), st.ModTime().Format(time.RFC3339), loaded)
}
fmt.Println()
}
func lookupIP(suite *service.GeoIPService, ipStr string) {
fmt.Printf("=== IP 试查 %s(中文映射后)===\n", ipStr)
info := suite.Lookup(ipStr)
if info.Country == "" && info.Region == "" && info.City == "" && info.ASN == 0 {
fmt.Println("未解析到地理信息(请确认 BIN/ASN 文件存在且 IP 为公网地址)")
return
}
fmt.Printf("国家 ISO: %s (%s)\n", info.Country, service.CountryLabelZh(info.Country))
if info.Region != "" || info.RegionISO != "" {
fmt.Printf("省/州: %s / %s\n", info.Region, info.RegionISO)
}
if info.City != "" {
fmt.Printf("城市: %s\n", info.City)
}
if info.ASN > 0 || info.ASOrg != "" {
fmt.Printf("ASN: AS%d %s\n", info.ASN, info.ASOrg)
}
}
func tableExists(db *gorm.DB, name string) bool {
var n int
err := db.Raw(
`SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?`, name,
).Scan(&n).Error
return err == nil && n > 0
}
func columnSet(db *gorm.DB) map[string]bool {
type colRow struct {
Name string `gorm:"column:name"`
}
var cols []colRow
_ = db.Raw(`PRAGMA table_info(page_views)`).Scan(&cols).Error
have := map[string]bool{}
for _, c := range cols {
have[c.Name] = true
}
return have
}
func printColumnPresence(have map[string]bool) {
need := []string{"ip", "country", "region", "region_iso", "city", "asn", "as_org"}
fmt.Println("=== page_views 列 ===")
missing := false
for _, n := range need {
if have[n] {
fmt.Printf("%s: 有\n", n)
} else {
fmt.Printf("%s: 缺失\n", n)
missing = true
}
}
fmt.Println()
if missing {
fmt.Fprintln(os.Stderr, "提示: 缺列时请先启动一次主程序以完成监控库 AutoMigrate。")
fmt.Fprintln(os.Stderr, "")
}
}
func fatalf(format string, args ...any) {
fmt.Fprintf(os.Stderr, format+"\n", args...)
os.Exit(1)
}

View File

@@ -32,11 +32,14 @@ type Config struct {
ServiceAction string
// 开发模式:后端代理前端请求到 Vite 开发服务器(非内嵌静态资源)
DevMode bool
// CommunityHub 维护者选项:开启后本站接收其它实例自愿上报(默认关闭)。
// 官方站 bbs.iioio.com 会按域名自动识别为枢纽,无需开启;本项仅给非官网枢纽镜像。
CommunityHub bool
}
// Parse 解析命令行与 app.ini,并初始化数据目录
// Parse 解析命令行、环境变量与 app.ini,并初始化数据目录
//
// 优先级(高 → 低):命令行显式参数 > app.ini > 内置默认值
// 优先级(高 → 低):命令行显式参数 > 环境变量 > app.ini > 内置默认值
func Parse() (*Config, error) {
configFlag := flag.String("config", "", "配置文件路径(默认:工作目录/app.ini)")
workFlag := flag.String("work-path", "", "工作目录(默认:可执行文件所在目录)")
@@ -52,12 +55,20 @@ func Parse() (*Config, error) {
return nil, fmt.Errorf("无效的 -service 动作 %q,可选:install|uninstall|start|stop|restart|status", *serviceFlag)
}
workPath, err := resolveWorkPath(*workFlag)
workPathInput := strings.TrimSpace(*workFlag)
if workPathInput == "" {
workPathInput = envOrDefault(envWorkPath)
}
workPath, err := resolveWorkPath(workPathInput)
if err != nil {
return nil, err
}
configFile, err := resolveConfigPath(workPath, *configFlag)
configInput := strings.TrimSpace(*configFlag)
if configInput == "" {
configInput = envOrDefault(envConfig)
}
configFile, err := resolveConfigPath(workPath, configInput)
if err != nil {
return nil, err
}
@@ -73,11 +84,17 @@ func Parse() (*Config, error) {
}
port := fileCfg.Port
if p := envIntOrZero(envHTTPPort); p > 0 {
port = p
}
if *portFlag > 0 {
port = *portFlag
}
dataInput := fileCfg.DataRel
if v := envOrDefault(envData); v != "" {
dataInput = v
}
if strings.TrimSpace(*dataFlag) != "" {
dataInput = *dataFlag
}
@@ -86,9 +103,17 @@ func Parse() (*Config, error) {
return nil, fmt.Errorf("解析数据目录失败: %w", err)
}
jwtSecret := strings.TrimSpace(*jwtFlag)
if jwtSecret == "" {
jwtSecret = fileCfg.JWTSecret
jwtSecret := fileCfg.JWTSecret
if v := envOrDefault(envJWTSecret); v != "" {
jwtSecret = v
}
if strings.TrimSpace(*jwtFlag) != "" {
jwtSecret = strings.TrimSpace(*jwtFlag)
}
communityHub := fileCfg.CommunityHub
if v := envBoolOrNil(envCommunityHub); v != nil {
communityHub = *v
}
cfg := &Config{
@@ -100,6 +125,7 @@ func Parse() (*Config, error) {
LogFile: filepath.Join(absData, "jiang13.log"),
ServiceAction: action,
DevMode: *devFlag,
CommunityHub: communityHub,
}
needDirs := action == "" || action == "install"
@@ -167,6 +193,7 @@ func ensureDataDirs(dataDir string) error {
filepath.Join(dataDir, "uploads", "avatars"),
filepath.Join(dataDir, "uploads", "posts"),
filepath.Join(dataDir, "uploads", "site"),
filepath.Join(dataDir, "logs", "access"),
} {
if err := os.MkdirAll(sub, 0755); err != nil {
return fmt.Errorf("创建上传目录失败: %w", err)
@@ -201,11 +228,16 @@ func validServiceAction(action string) bool {
}
}
// DBPath 返回 SQLite 数据库文件路径
// DBPath 返回主库 SQLite 路径
func (c *Config) DBPath() string {
return filepath.Join(c.DataDir, "jiang13.db")
}
// MonitorDBPath 返回监控独立库路径(page_views)
func (c *Config) MonitorDBPath() string {
return filepath.Join(c.DataDir, "monitor.db")
}
// AvatarUploadDir 返回头像上传目录
func (c *Config) AvatarUploadDir() string {
return filepath.Join(c.DataDir, "uploads", "avatars")

51
config/env.go Normal file
View File

@@ -0,0 +1,51 @@
package config
import (
"os"
"strconv"
"strings"
)
// 容器 / 编排常用环境变量(优先级:命令行 > 环境变量 > app.ini > 内置默认)
const (
envWorkPath = "JIANG13_WORK_PATH"
envConfig = "JIANG13_CONFIG"
envHTTPPort = "JIANG13_HTTP_PORT"
envData = "JIANG13_DATA"
envJWTSecret = "JIANG13_JWT_SECRET"
envCommunityHub = "JIANG13_COMMUNITY_HUB"
)
func envOrDefault(key string) string {
return strings.TrimSpace(os.Getenv(key))
}
func envIntOrZero(key string) int {
v := envOrDefault(key)
if v == "" {
return 0
}
n, err := strconv.Atoi(v)
if err != nil || n <= 0 || n > 65535 {
return 0
}
return n
}
// envBoolOrNil 解析布尔环境变量;未设置返回 nil
func envBoolOrNil(key string) *bool {
v := strings.ToLower(envOrDefault(key))
if v == "" {
return nil
}
switch v {
case "1", "true", "yes", "on":
t := true
return &t
case "0", "false", "no", "off":
f := false
return &f
default:
return nil
}
}

View File

@@ -21,6 +21,7 @@ type fileSettings struct {
Port int
DataRel string
JWTSecret string
CommunityHub bool // 维护者选项:是否作为社区枢纽收报
}
func defaultFileSettings() fileSettings {
@@ -62,6 +63,12 @@ func loadAppINI(path string) (fileSettings, error) {
out.JWTSecret = strings.TrimSpace(sec.Key("JWT_SECRET").String())
}
if sec, err := cfg.GetSection("community"); err == nil {
if k := sec.Key("HUB"); k.String() != "" {
out.CommunityHub = k.MustBool(false)
}
}
return out, nil
}

33
docker-compose.yml Normal file
View File

@@ -0,0 +1,33 @@
# 姜十三论坛 — Docker Compose 单服务部署
# 启动:docker compose up -d --build
# 或:make compose-up / build.bat -Target compose-up
services:
jiang13:
image: hangzhang714128/jiang13-forum:latest
build:
context: .
dockerfile: Dockerfile
args:
VERSION: dev
ports:
- "3000:3000"
volumes:
- jiang13-data:/data
# 可选:挂载自定义 app.ini(只读)
# - ./app.ini:/app/app.ini:ro
environment:
TZ: Asia/Shanghai
# 可选:固定 JWT 密钥(留空则自动生成并持久化到 /data/.jwt_secret)
# JIANG13_JWT_SECRET: your-secret-here
restart: unless-stopped
stop_grace_period: 15s
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:3000/health"]
interval: 30s
timeout: 5s
retries: 3
start_period: 15s
volumes:
jiang13-data:

15
docker-entrypoint.sh Normal file
View File

@@ -0,0 +1,15 @@
#!/bin/sh
set -e
# 宿主机 / 1Panel 挂载的 volume 常为 root 所有(uid 0),
# 而应用以 jiang13(uid 1000)运行,需在启动时修正 /data 权限后降权。
DATA_DIR="/data"
if [ "$(id -u)" = '0' ]; then
mkdir -p "$DATA_DIR"
chown -R jiang13:jiang13 "$DATA_DIR"
exec su-exec jiang13 /app/jiang13 "$@"
fi
exec /app/jiang13 "$@"

105
docs/docker-data.md Normal file
View File

@@ -0,0 +1,105 @@
# Docker 数据持久化说明
Docker 部署时**默认只挂载一个目录**,不是分别映射「数据库文件夹」和「附件文件夹」两个卷。
## 挂载对应关系
| 宿主机 | 容器内 |
|--------|--------|
| 任意目录或 named volume(如 `jiang13-data`) | **`/data`** |
**示例:**
```bash
docker run -d --name jiang13 \
-p 3000:3000 \
-v /你的路径/jiang13-data:/data \
--restart unless-stopped \
hangzhang714128/jiang13-forum:latest
```
或在 `docker-compose.yml` 中:
```yaml
volumes:
- jiang13-data:/data
# 或绑定宿主机目录:
# - ./data:/data
```
## `/data` 目录结构
数据库与附件都在同一个 `/data` 挂载内:
```
/data/
├── jiang13.db # SQLite 主数据库(不含浏览量)
├── monitor.db # 网站监控 page_views
├── uploads/ # 附件根目录
│ ├── avatars/ # 用户头像
│ └── posts/ # 帖子图片等
├── logs/
│ └── access/ # 网站监控请求日志(按日 jsonl)
│ └── YYYY-MM-DD.jsonl
├── IP2LOCATION-LITE-DB3.BIN # 可选:IPv4 城市库(监控)
├── IP2LOCATION-LITE-DB3.IPV6.BIN # 可选:IPv6 城市库
├── GeoLite2-ASN.mmdb # 可选:ASN/运营商
├── GeoLite2-Country.mmdb # 可选:国家兜底
├── .jwt_secret # JWT 密钥(自动生成)
├── filter_words.txt # 敏感词配置
└── jiang13.log # 运行日志(若启用)
```
| 用途 | 路径 |
|------|------|
| 主数据库 | `/data/jiang13.db` |
| 监控浏览量 | `/data/monitor.db` |
| 附件 | `/data/uploads/` |
| 请求日志(监控) | `/data/logs/access/` |
| 地理库(可选) | `/data/IP2LOCATION-LITE-DB3*.BIN`、`GeoLite2-ASN.mmdb` 等 |
官方镜像不要求拆成两个 volume;挂好 `/data` 即可同时持久化 SQLite、上传文件与监控日志。
地理库与 BIN **不内置**于 Docker 镜像。详见 [网站监控设计](monitor.md)。管理端展示完整客户端 IP(不做脱敏)。
## 设计说明:为何只挂一个 `/data`
对本项目(单容器、SQLite、默认可本地存附件)而言,**一个数据卷是合理默认**:
- 部署成本最低,不易漏挂导致「重启丢图 / 丢库」
- 备份、迁移时拷贝或快照整个 `/data` 即可恢复站点状态
- 密钥(`.jwt_secret`)、敏感词与库同目录,避免「库还在、登录全失效」这类半残状态
若你习惯「数据库文件夹 / 附件文件夹」分开填写:在本镜像中它们分别是 **`/data` 下的文件与子目录**,不是两个独立容器路径。
附件特别大、希望对象存储时:优先使用管理后台的 **S3 兼容存储**,而不是拆 Docker 卷。
## 后续计划(可选增强,非必须)
按优先级,仅在有明确需求时做:
1. **文档与面板提示(优先)**
- README / 1Panel 说明中固定话术:「只需挂载 `/data`;数据库=`jiang13.db`,监控=`monitor.db`,附件=`uploads/`」。
- 本页保持为权威说明,避免用户误以为漏了一个卷。
2. **进阶:同一 DataDir 下拆挂子路径(文档级,无需改代码)**
若必须把库与附件分到不同宿主机磁盘,可在仍使用容器 `/data` 的前提下分别绑定,例如:
```yaml
volumes:
# 推荐:父目录一次挂载
- /ssd/jiang13:/data
# 或仅把附件分到大容量盘(需保证 /data 下其余文件仍可写)
- /ssd/jiang13:/data
- /hdd/jiang13-uploads:/data/uploads
```
拆挂时仍要保证 `/data` 下 `.jwt_secret` 等文件可写;不熟悉 Docker 时请继续只用单个 `/data` 挂载。
3. **产品级:可配置上传根目录(中期)**
- 环境变量或 `app.ini` 支持 `upload_dir` 与 `data_dir` 分离。
- Docker 示例改为可选双卷;**默认仍单卷**,避免破坏现有部署。
4. **不做的事**
- 不为「看起来像 WordPress」而强制双卷。
- 不在未支持分离配置前,在 UI 里假装有两个独立数据根。

79
docs/monitor.md Normal file
View File

@@ -0,0 +1,79 @@
# 网站监控设计说明
管理端「网站监控」:轻量自建访问统计,对标 1Panel 思路——**请求流水写文件、访客地理写独立库**,开启后不拖慢前台读帖。
## 双通道数据
| 数据 | 存储 | 用途 |
|------|------|------|
| 请求日志 | `{DataDir}/logs/access/YYYY-MM-DD.jsonl` | 请求日志页、请求数/流量/4xx·5xx、实时曲线 |
| page_views | `{DataDir}/monitor.db`(SQLite) | 浏览量/访客、国家/省/城市/运营商排行与地图 |
请求日志**只写 jsonl**,不进 SQLite。删除过期 `.jsonl` 即释放磁盘。
`page_views` **不进主库** `jiang13.db`。后台「导出备份」只含主库,不含浏览量。
### 文件行格式(JSONL)
每行一条 JSON,字段包括:`t`(RFC3339)、`method`、`path`、`status`、`bytes`、`duration_ms`、`ip`、`ua`、`referer`、`country`、`region`、`region_iso`、`city`、`asn`、`as_org`、`is_bot`。
### 保留天数
- `monitor_retention_days`:仅 **page_views**(默认 30)
- `monitor_access_log_retention_days`:请求日志文件(默认 7)
## 地理数据文件
放在数据目录(与 `jiang13.db` 同级),有则加载、无则静默降级:
| 文件 | 用途 |
|------|------|
| `IP2LOCATION-LITE-DB3.BIN` | IPv4 国家/省/城市 |
| `IP2LOCATION-LITE-DB3.IPV6.BIN` | IPv6 国家/省/城市 |
| `GeoLite2-ASN.mmdb` | ASN / 运营商 |
| `GeoLite2-Country.mmdb` | 可选:BIN 未命中时国家兜底 |
CDN 头(如 `CF-IPCountry`)仅在本地库无国家码时补全。不落 Lat/Lon/Zip/TimeZone。管理端展示**完整客户端 IP**。
写入时做本地中文映射(省 / 中国城市按 IP2Location 英文名 / 运营商);同音城市(如苏州/宿州)按省份歧义。`country` 存 ISO2,展示用中文名。历史 `page_views` / 请求日志不会回写,仅影响新写入。
**口径提示:** 访客地图与城市/运营商排行只聚合 `page_views`(前台浏览);请求日志里的地理来自 access JSONL。仅有请求日志、没有前台浏览时,地图与排行可为空——属预期。
## 写入路径(性能)
1. 中间件:监控关闭或命中排除规则则直接放行;否则 `c.Next()` 后**仅入队**轻量字段(不查 BIN/ASN、不写盘)。
2. 后台 flush:出队 → Geo + 中文映射 → append 当日 jsonl + 更新内存实时环。
3. 队列上限 8192,满则丢弃新日志(保护内存与磁盘)。
4. pageview 信标 QPS 低,可在写入时同步 Geo 后写独立 `monitor.db`(不占用主库连接)。
**热路径零 Geo、零写库、零写文件。**
## 请求日志口径(排除规则)
默认只关心**前台访客**,排除管理员刷后台产生的壳请求:
- `/admin`、`/api/admin/`
- `/api/me`、`/api/site-branding`
- `/health`、`/uploads/`、`/media/`、静态后缀、`/api/monitor/pageview` 等
设置页可「恢复推荐排除规则」。不强制覆盖用户已保存的自定义列表。
浏览量/访客仍来自前台路由 pageview(后台路径本身不上报)。
## 实时与聚合
- 近 1 分钟 / 近 1 小时:内存环(flush 时更新),避免扫全文件。
- 今日请求数等:内存日累加器(进程内;重启后自新流量累积,论坛量级可接受)。
- 地理排行:仅 `page_views`。
## 诊断
```bash
go run ./cmd/monitor-geo-check -db data/monitor.db -ip 14.109.35.246
```
会输出 Geo 文件状态、近 30 日省级 Top,以及对账抽样(英文城市名、有国家但省为空、`asn=0`)。
## 明确不做
- 不用 CIDR;不把请求日志写入 SQLite;不把 page_views 写入主库
- 不做街道级地图;Docker 镜像不内置 BIN/MMDB

View File

@@ -18,6 +18,16 @@
把原先分篇的「上手 / 功能 / 部署」三帖 **删除**,避免与长文重复。
## 自定义单页(推荐)
站务帖之外,建议在后台 **单页管理** 发一篇更新日志,方便 Docker / Windows 用户对照版本:
| 文件 | 标题 | slug | 操作 |
| --- | --- | --- | --- |
| [changelog.md](./changelog.md) | 更新日志 | `changelog` | 发布;页脚展示(可选侧栏导航) |
访问路径:`/page/changelog`。
## 可选短文
若站务区希望不止一篇,见 [optional.md](./optional.md):

View File

@@ -0,0 +1,160 @@
# 更新日志
> 建议标题:更新日志
> 建议 slug:`changelog`
> 建议路径:`/page/changelog`
> 建议操作:后台「单页管理」新建并发布;勾选「页脚展示」(可选「侧栏导航」)
> 复制正文时:从下方第一个 `---` **之后**开始粘贴(Markdown 模式)
---
Docker 镜像、Windows exe、Linux 单文件 **共用同一版本号**。有新版本时,以本页为准。
**当前版本:1.1.7**(2026-09-02)
## 去哪看新版本
| 渠道 | 看什么 | 地址 |
| --- | --- | --- |
| 本页 | 版本号、变更说明、升级注意 | 本站 `/page/changelog` |
| Docker | 镜像标签(`latest` 与 `1.1.x`) | [Docker Hub · Tags](https://hub.docker.com/r/hangzhang714128/jiang13-forum/tags) |
| Windows / Linux | 预编译单文件(与 Docker 同版本) | [Gitea Releases](https://git.iioio.com/freefire/jiang13-forum/releases) |
| 源码 | 提交记录与自行编译 | [Gitea 仓库](https://git.iioio.com/freefire/jiang13-forum) |
**1.1.7 直接下载:**
- Windows x64:[jiang13-1.1.7-windows-amd64.exe](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/jiang13-1.1.7-windows-amd64.exe)
- Linux x64:[jiang13-1.1.7-linux-amd64](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/jiang13-1.1.7-linux-amd64)
- 校验文件:[SHA256SUMS.txt](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/SHA256SUMS.txt)
拉取指定版本镜像:
```bash
docker pull hangzhang714128/jiang13-forum:1.1.7
# 或始终跟随最新
docker pull hangzhang714128/jiang13-forum:latest
```
Windows:停掉正在跑的进程或服务,用新下载的 exe 覆盖原文件(可改名为 `jiang13.exe`),**不要动**旁边的 `data/` 与 `app.ini`,再启动即可。
Linux:赋予执行权限后放到原目录覆盖,同样保留 `data/` 与 `app.ini`。
## 升级注意
- 一般只需换镜像或换 exe,数据目录向后兼容。
- Docker 请继续挂载原来的 `/data` 卷,切勿新建空目录当「升级」。
- 升级后若页面样式异常,强制刷新浏览器(Ctrl+F5)。程序也会在前端资源失效时自动硬刷新。
---
## 1.1.7 — 2026-09-02
私信与开源展柜体验升级,待审通知的审核态更及时。
**新增 / 调整**
- 私信改为飞书风布局:缩略图表情/图片、按会话草稿、用户搜索发起会话
- 主页「发私信」直达消息页对应会话
- 开源展柜改为目录式 UI,空列表不再粘滞
- 消息页体验重构;待审通知打开后实时回填审核态
**修复**
- 帖子详情右栏默认头像改为深绿底白字,与列表默认头像配色一致
## 1.1.6 — 2026-09-01
编辑器插入体验与首页默认 Feed 排序更合理。
**新增 / 调整**
- 链接对话框支持网址、链接文字与站内帖子/单页搜索;站内搜索收进「高级选项」,点选同步链接文字
- 文章与评论共用统一图片插入选择器(上传 / 链接 / 已上传)
- 链接是否新标签打开交由全站设置,对话框不再单独开关
- 首页默认「最新」按发帖与最后评论的较晚时间混排,零回复新帖不再沉底
- 单页详情右侧栏与帖子共用目录布局;三栏主滚动区统一细绿色滚动条
**修复**
- 帖子目录从正文同步派生,避免预取缓存竞态导致空树
## 1.1.5 — 2026-09-01
首页首屏与交互更稳,Feed 排序语义更清楚。
本版起同时提供 **Docker 镜像** 与 **Windows / Linux 预编译单文件**(Gitea Release `v1.1.5`)。
**新增 / 调整**
- 首页改为 Go SSR 与 React hydrate(注水)同构,打开首页不再先闪一层空壳再跳内容
- Feed 排序改为:**新评论 / 新帖子 / 推荐帖**;推荐帖只出精华(featured)
- 点击排序会强制刷新列表;软刷新时同步站点限额与品牌文案
- 返回列表用缓存恢复滚动位置,不再重复请求
**修复**
- 发版后软刷新会检测入口壳;chunk(代码分片)404 时自动硬刷新,避免卡在旧页面
- 软刷新齐套前保留旧画面,避免一点击就把内容卸光
- 补齐 `/favicon.ico` 与页面 head 图标;拆除爬虫专用 HTML
- 桌面端隐藏多余的导航汉堡按钮
- 帖行评论数、列表「共 N 条」右对齐;排序栏数字紧跟标签
- 手机端 SSR 顶栏 / 页脚与 React 一致,减少闪动
## 1.1.4 — 2026-08-31
网站监控的地理信息与口径更准确。
- 补全 IP2Location(IP 地理位置库)中国城市中文名,同名城市按省消歧
- 对齐监控概览「双通道」口径文案与诊断抽样说明
## 1.1.3 — 2026-08-31
管理后台可看站点访问情况。
- 新增管理端 **网站监控**:浏览量写入独立 `monitor.db`,与主库分开
## 1.1.2 — 2026-08-31
可选接入官方社区展柜。
- 可选社区上报,以及官方精选展柜(自建站可出现在官方社区列表中)
## 1.1.1 — 2026-08-31
- 评论管理操作收进「更多」菜单,管理员界面更干净
## 1.1.0 — 2026-08-30
一批社区功能与界面整理,版本号从 1.0 跨到 1.1。
**新增**
- 友链申请、独立友链页;页脚左右区域可分别开关
- 自定义单页(后台「单页管理」,如本页)
- 投票帖、悬赏帖、抽奖帖
- 侧栏签到;右侧栏「最新注册」
- 搜索重设计:筛选面板、结果页 chips(筛选标签)
- 帖子管理收进右上角菜单;手机端评论输入默认折叠
**优化**
- 首页帖子列表密度与标题样式
- 开源码桶展示加强,去掉 Feed 顶栏统计
- 单页编辑、列表留白与友链申请体验
- 开发与发行版共用 `dist/data` 数据目录,避免两套数据打架
**修复**
- 手机端搜索入口与底部 Sheet(抽屉面板)
- 占位头像对比度;无头像用户不再误用游客灰底
- 页面双指缩放锁死,正文原图与灯箱仍可 pinch(捏合)放大
- 单页正文排版与帖子详情对齐
## 1.0.0 — 2026-08-23
首次发布 Docker 镜像 `hangzhang714128/jiang13-forum:1.0.0`。
当时已包含论坛核心能力:板块与发帖、楼层评论、点赞收藏、私信、TipTap 富文本、贴纸、修订历史、管理后台、OIDC(开放身份连接)/ SSO(单点登录)、邮件验证码、Gitea 仓库同步、SQLite 单二进制部署,以及 Docker 一键运行。
---
之后发版时:Docker 推 `x.y.z` + `latest`,Gitea 打 tag `vx.y.z` 并挂上对应 exe / linux 文件,再把新版本写到本页最上方。

View File

@@ -17,6 +17,7 @@ var (
spaTitleRe = regexp.MustCompile(`(?s)<title>.*?</title>`)
spaBrandTitleFn func() string
spaBrandJSONFn func() []byte // 站点品牌 JSON,注入 window.__J13_BRANDING__
spaBrandFaviconFn func() string // 站点 Favicon URL,注入 <link rel="icon">
)
// SetSPADocumentTitle 注册站点标题提供者,ServeSPA 会注入到入口 HTML,避免刷新闪烁
@@ -29,19 +30,58 @@ func SetSPABrandingJSON(fn func() []byte) {
spaBrandJSONFn = fn
}
// SetSPAFaviconURL 注册 Favicon URL 提供者,注入到入口 HTML 的 <link rel="icon">
func SetSPAFaviconURL(fn func() string) {
spaBrandFaviconFn = fn
}
// SetupEmbed 配置内嵌资源:React SPA 静态资源
func SetupEmbed(r *gin.Engine) error {
if sub, err := fs.Sub(staticFS, "static/spa/assets"); err == nil {
fileServer := http.StripPrefix("/assets", http.FileServer(http.FS(sub)))
r.GET("/assets/*filepath", func(c *gin.Context) {
// hashed 资源可长期缓存;发版后文件名变更,旧 URL 自然 404
c.Header("Cache-Control", "public, max-age=31536000, immutable")
// 仅 200 写 immutable,避免中间层把旧 chunk 的 404 长期缓存
w := &cacheOnOKWriter{ResponseWriter: c.Writer, cacheControl: "public, max-age=31536000, immutable"}
c.Writer = w
fileServer.ServeHTTP(c.Writer, c.Request)
})
}
if sub, err := fs.Sub(staticFS, "static/spa/stickers"); err == nil {
fileServer := http.StripPrefix("/stickers", http.FileServer(http.FS(sub)))
r.GET("/stickers/*filepath", func(c *gin.Context) {
// stickers 不含哈希指纹,设置适中的缓存
c.Header("Cache-Control", "public, max-age=86400")
fileServer.ServeHTTP(c.Writer, c.Request)
})
}
return nil
}
// cacheOnOKWriter 仅在最终状态码为 200 时写入长期 Cache-Control
type cacheOnOKWriter struct {
gin.ResponseWriter
cacheControl string
wroteHeader bool
}
func (w *cacheOnOKWriter) WriteHeader(code int) {
if !w.wroteHeader {
w.wroteHeader = true
if code == http.StatusOK {
w.Header().Set("Cache-Control", w.cacheControl)
}
}
w.ResponseWriter.WriteHeader(code)
}
func (w *cacheOnOKWriter) Write(b []byte) (int, error) {
if !w.wroteHeader {
w.WriteHeader(http.StatusOK)
}
return w.ResponseWriter.Write(b)
}
// ServeSPA 返回 React SPA 入口(仅注入站点默认标题)
func ServeSPA(c *gin.Context) {
ServeSPAWithMeta(c, nil)
@@ -61,7 +101,7 @@ func ServeSPANoIndex(c *gin.Context) {
// IsSPARoute 判断是否应由 SPA 处理
func IsSPARoute(path string) bool {
if path == "/robots.txt" || path == "/sitemap.xml" {
if path == "/health" || path == "/robots.txt" || path == "/sitemap.xml" {
return false
}
if strings.HasPrefix(path, "/api") ||
@@ -69,6 +109,7 @@ func IsSPARoute(path string) bool {
strings.HasPrefix(path, "/uploads") ||
strings.HasPrefix(path, "/media") ||
strings.HasPrefix(path, "/assets") ||
strings.HasPrefix(path, "/stickers") ||
strings.HasPrefix(path, "/oauth") ||
strings.HasPrefix(path, "/.well-known") {
return false

View File

@@ -5,12 +5,16 @@ import (
"encoding/json"
"html"
"net/http"
"regexp"
"strings"
"github.com/gin-gonic/gin"
)
// SPAPageMeta 注入到 SPA 入口 HTML 的 SEO / 社交预览元数据(仅 <head>,不写 #root,避免刷新闪屏)
var spaRootEmptyRe = regexp.MustCompile(`(?s)<div id="root">\s*</div>`)
// SPAPageMeta 注入到 SPA 入口 HTML 的 SEO / 社交预览元数据。
// 默认不写 #root;首页/板块文档 SSR 可填 RootHTML / BootJSON。
type SPAPageMeta struct {
Title string // 完整 <title>
Description string
@@ -23,6 +27,8 @@ type SPAPageMeta struct {
Robots string // 如 noindex,nofollow
JSONLD string // 已序列化的 JSON-LD 对象(不含 script 标签)
Status int // HTTP 状态码,0 视为 200
RootHTML string // 可选:写入 #root 的首屏 HTML(首页文档 SSR)
BootJSON []byte // 可选:window.__J13_HOME_BOOT__ 合法 JSON
}
// ServeSPAWithMeta 返回带页面级 meta / JSON-LD 的干净 SPA 入口
@@ -37,8 +43,9 @@ func ServeSPAWithMeta(c *gin.Context, meta *SPAPageMeta) {
return
}
data = applySPAPageMeta(data, meta)
// 入口 HTML 禁止长期缓存,否则发版后仍引用旧 chunk 哈希
c.Header("Cache-Control", "no-cache")
// 入口 HTML 禁止缓存,否则发版后仍引用旧 chunk 哈希(部分反代对 no-cache 仍会存)
c.Header("Cache-Control", "no-cache, no-store, must-revalidate")
c.Header("Pragma", "no-cache")
c.Data(status, "text/html; charset=utf-8", data)
}
@@ -56,15 +63,20 @@ func applySPAPageMeta(data []byte, meta *SPAPageMeta) []byte {
data = spaTitleRe.ReplaceAll(data, []byte("<title>"+escaped+"</title>"))
}
var head strings.Builder
writeMeta(&head, "description", meta.Description)
writeMeta(&head, "keywords", meta.Keywords)
// —— 静态 SEO HTML(meta / OG / JSON-LD / favicon),紧跟 </title>,不经 JS ——
var seo strings.Builder
writeMeta(&seo, "description", meta.Description)
writeMeta(&seo, "keywords", meta.Keywords)
if canonical := strings.TrimSpace(meta.Canonical); canonical != "" {
head.WriteString(`<link rel="canonical" href="` + html.EscapeString(canonical) + `"/>`)
seo.WriteString(`<link rel="canonical" href="` + html.EscapeString(canonical) + `"/>`)
}
if favicon := spaFaviconHref(); favicon != "" {
seo.WriteString(`<link rel="icon" href="` + html.EscapeString(favicon) + `"/>`)
seo.WriteString(`<link rel="shortcut icon" href="` + html.EscapeString(favicon) + `"/>`)
}
robots := strings.TrimSpace(meta.Robots)
if robots != "" {
writeMeta(&head, "robots", robots)
writeMeta(&seo, "robots", robots)
}
ogType := strings.TrimSpace(meta.OGType)
@@ -75,36 +87,63 @@ func applySPAPageMeta(data []byte, meta *SPAPageMeta) []byte {
if locale == "" {
locale = "zh_CN"
}
writeProp(&head, "og:type", ogType)
writeProp(&head, "og:site_name", meta.SiteName)
writeProp(&head, "og:locale", locale)
writeProp(&head, "og:title", firstNonEmpty(meta.Title, title))
writeProp(&head, "og:description", meta.Description)
writeProp(&head, "og:url", meta.Canonical)
writeProp(&head, "og:image", meta.OGImage)
writeMetaName(&head, "twitter:card", twitterCard(meta.OGImage))
writeMetaName(&head, "twitter:title", firstNonEmpty(meta.Title, title))
writeMetaName(&head, "twitter:description", meta.Description)
writeMetaName(&head, "twitter:image", meta.OGImage)
writeProp(&seo, "og:type", ogType)
writeProp(&seo, "og:site_name", meta.SiteName)
writeProp(&seo, "og:locale", locale)
writeProp(&seo, "og:title", firstNonEmpty(meta.Title, title))
writeProp(&seo, "og:description", meta.Description)
writeProp(&seo, "og:url", meta.Canonical)
writeProp(&seo, "og:image", meta.OGImage)
writeMetaName(&seo, "twitter:card", twitterCard(meta.OGImage))
writeMetaName(&seo, "twitter:title", firstNonEmpty(meta.Title, title))
writeMetaName(&seo, "twitter:description", meta.Description)
writeMetaName(&seo, "twitter:image", meta.OGImage)
if jsonld := strings.TrimSpace(meta.JSONLD); jsonld != "" {
head.WriteString(`<script type="application/ld+json">`)
head.WriteString(jsonld)
head.WriteString(`</script>`)
// 常规 HTML 节点;仅转义 < 防止提前闭合,不是用 JS 写入
seo.WriteString(`<script type="application/ld+json">`)
seo.WriteString(string(bytes.ReplaceAll([]byte(jsonld), []byte("<"), []byte(`\u003c`))))
seo.WriteString(`</script>`)
}
// 同步注入品牌配置,避免 React 首屏用默认名闪一下
if boot := spaBrandingBootScript(); boot != "" {
head.WriteString(boot)
if seo.Len() > 0 {
data = bytes.Replace(data, []byte("</title>"), []byte("</title>\n"+seo.String()), 1)
}
if head.Len() > 0 {
data = bytes.Replace(data, []byte("</head>"), []byte(head.String()+"</head>"), 1)
// —— 可执行 boot 脚本仍放在 </head> 前 ——
var boot strings.Builder
if s := spaBrandingBootScript(); s != "" {
boot.WriteString(s)
}
if s := spaHomeBootScript(meta.BootJSON); s != "" {
boot.WriteString(s)
}
if boot.Len() > 0 {
data = bytes.Replace(data, []byte("</head>"), []byte(boot.String()+"</head>"), 1)
}
if root := strings.TrimSpace(meta.RootHTML); root != "" {
data = injectSPARootHTML(data, root)
}
return data
}
// spaHomeBootScript 生成 window.__J13_HOME_BOOT__=...; 内联脚本(前端灌缓存,非 SEO)
func spaHomeBootScript(raw []byte) string {
raw = bytes.TrimSpace(raw)
if len(raw) == 0 || !json.Valid(raw) {
return ""
}
safe := bytes.ReplaceAll(raw, []byte("<"), []byte(`\u003c`))
return "<script>window.__J13_HOME_BOOT__=" + string(safe) + ";</script>"
}
// injectSPARootHTML 将首屏 HTML 写入 #root(允许空白)
func injectSPARootHTML(data []byte, rootHTML string) []byte {
return spaRootEmptyRe.ReplaceAll(data, []byte(`<div id="root">`+rootHTML+`</div>`))
}
// spaBrandingBootScript 生成 window.__J13_BRANDING__=...; 内联脚本
func spaBrandingBootScript() string {
if spaBrandJSONFn == nil {
@@ -114,7 +153,6 @@ func spaBrandingBootScript() string {
if len(raw) == 0 || !json.Valid(raw) {
return ""
}
// 防止 JSON 字符串中的 </script> 提前闭合标签
safe := bytes.ReplaceAll(raw, []byte("<"), []byte(`\u003c`))
return "<script>window.__J13_BRANDING__=" + string(safe) + ";</script>"
}
@@ -154,3 +192,11 @@ func firstNonEmpty(vals ...string) string {
}
return ""
}
// spaFaviconHref 当前站点配置的 Favicon(相对或绝对 URL)
func spaFaviconHref() string {
if spaBrandFaviconFn == nil {
return ""
}
return strings.TrimSpace(spaBrandFaviconFn())
}

View File

@@ -2,26 +2,10 @@
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="description" content="拾三一隅,自在交流" />
<title>姜十三论坛 - 拾三一隅,自在交流</title>
<style>
/* 关键布局样式:在 JS/CSS 包加载前即固定三栏结构,避免刷新时组件错位 */
html { scrollbar-gutter: stable; }
html, body, #root { height: 100%; margin: 0; }
body { overflow: hidden; font-size: 14px; line-height: 1.5; }
.app-shell { height: 100%; max-height: 100dvh; display: flex; flex-direction: column; overflow: hidden; }
.app-frame { flex: 1; min-height: 0; height: 100%; max-width: 1400px; width: 100%; margin: 0 auto; display: flex; flex-direction: column; overflow: hidden; }
.app-header { height: 56px; flex-shrink: 0; }
.site-footer { flex-shrink: 0; }
.app-body { flex: 1; display: flex; min-height: 0; width: 100%; overflow: hidden; }
.content-workspace { flex: 1; display: flex; min-width: 0; min-height: 0; overflow: hidden; }
.sidebar { width: 210px; flex-shrink: 0; }
.main-content { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
.aside-panel { width: 280px; flex-shrink: 0; }
@media (max-width: 1100px) { .aside-panel { display: none; } }
@media (max-width: 768px) { .sidebar { display: none; } }
</style>
<!-- 样式由 Vite 构建注入外链 CSS,不在此内联 style -->
<script>
(function () {
var theme = localStorage.getItem('j13-theme') || 'light';
@@ -29,6 +13,33 @@
document.documentElement.style.colorScheme = theme;
})();
</script>
<script>
/* 锁死手机/平板双指与手势缩放;头像裁剪 / 图片灯箱放行 pinch */
(function () {
function inZoomAllowArea(target) {
return !!(
target &&
target.closest &&
target.closest('.avatar-crop-stage, .image-lightbox')
);
}
function blockGesture(e) {
if (inZoomAllowArea(e.target)) return;
if (e.cancelable) e.preventDefault();
}
function blockMultiTouch(e) {
if (e.touches && e.touches.length > 1) {
if (inZoomAllowArea(e.target)) return;
if (e.cancelable) e.preventDefault();
}
}
document.addEventListener('gesturestart', blockGesture, { passive: false });
document.addEventListener('gesturechange', blockGesture, { passive: false });
document.addEventListener('gestureend', blockGesture, { passive: false });
document.addEventListener('touchstart', blockMultiTouch, { passive: false });
document.addEventListener('touchmove', blockMultiTouch, { passive: false });
})();
</script>
</head>
<body>
<div id="root"></div>

View File

@@ -8,6 +8,9 @@
"name": "jiang13-forum-web",
"version": "1.0.0",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@hookform/resolvers": "^5.4.0",
"@radix-ui/react-alert-dialog": "^1.1.16",
"@radix-ui/react-dialog": "^1.1.16",
@@ -15,6 +18,8 @@
"@radix-ui/react-label": "^2.1.9",
"@radix-ui/react-slot": "^1.2.5",
"@radix-ui/react-switch": "^1.3.0",
"@svg-maps/china": "^2.0.0",
"@svg-maps/world": "^2.0.0",
"@tanstack/react-virtual": "^3.11.2",
"@tiptap/core": "^3.26.1",
"@tiptap/extension-code-block": "^3.26.1",
@@ -46,7 +51,8 @@
"tailwindcss": "^3.4.19",
"tailwindcss-animate": "^1.0.7",
"turndown": "^7.2.4",
"zod": "^4.4.3"
"zod": "^4.4.3",
"zustand": "^4.5.7"
},
"devDependencies": {
"@types/node": "^25.9.3",
@@ -352,6 +358,59 @@
"node": ">=6.9.0"
}
},
"node_modules/@dnd-kit/accessibility": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
"integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
"license": "MIT",
"dependencies": {
"tslib": "^2.0.0"
},
"peerDependencies": {
"react": ">=16.8.0"
}
},
"node_modules/@dnd-kit/core": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
"license": "MIT",
"dependencies": {
"@dnd-kit/accessibility": "^3.1.1",
"@dnd-kit/utilities": "^3.2.2",
"tslib": "^2.0.0"
},
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}
},
"node_modules/@dnd-kit/sortable": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz",
"integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==",
"license": "MIT",
"dependencies": {
"@dnd-kit/utilities": "^3.2.2",
"tslib": "^2.0.0"
},
"peerDependencies": {
"@dnd-kit/core": "^6.3.0",
"react": ">=16.8.0"
}
},
"node_modules/@dnd-kit/utilities": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
"integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
"license": "MIT",
"dependencies": {
"tslib": "^2.0.0"
},
"peerDependencies": {
"react": ">=16.8.0"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.21.5",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
@@ -1915,6 +1974,18 @@
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
"license": "MIT"
},
"node_modules/@svg-maps/china": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@svg-maps/china/-/china-2.0.0.tgz",
"integrity": "sha512-/B0a4hYJHRtfcUG+x6BudQFWhLQyPoaN2WbqfdEeWeXnwef6oXaE93Msrq2odu72c09vE+G4Ds9+n60Qsr4p1g==",
"license": "CC-BY-4.0"
},
"node_modules/@svg-maps/world": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@svg-maps/world/-/world-2.0.0.tgz",
"integrity": "sha512-VmYYnyygJ5Zhr48xPqukFBoq4aCBgVNIjBzqBnWKXSdHhrRK3pntdvbCa8lMsxwVCFzEw9a+smIMEGI2sC1xcQ==",
"license": "CC-BY-4.0"
},
"node_modules/@tanstack/react-virtual": {
"version": "3.14.2",
"resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.14.2.tgz",
@@ -4410,6 +4481,34 @@
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
},
"node_modules/zustand": {
"version": "4.5.7",
"resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",
"integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",
"license": "MIT",
"dependencies": {
"use-sync-external-store": "^1.2.2"
},
"engines": {
"node": ">=12.7.0"
},
"peerDependencies": {
"@types/react": ">=16.8",
"immer": ">=9.0.6",
"react": ">=16.8"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"immer": {
"optional": true
},
"react": {
"optional": true
}
}
}
}
}

View File

@@ -9,6 +9,9 @@
"preview": "vite preview"
},
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@hookform/resolvers": "^5.4.0",
"@radix-ui/react-alert-dialog": "^1.1.16",
"@radix-ui/react-dialog": "^1.1.16",
@@ -16,6 +19,8 @@
"@radix-ui/react-label": "^2.1.9",
"@radix-ui/react-slot": "^1.2.5",
"@radix-ui/react-switch": "^1.3.0",
"@svg-maps/china": "^2.0.0",
"@svg-maps/world": "^2.0.0",
"@tanstack/react-virtual": "^3.11.2",
"@tiptap/core": "^3.26.1",
"@tiptap/extension-code-block": "^3.26.1",
@@ -47,7 +52,8 @@
"tailwindcss": "^3.4.19",
"tailwindcss-animate": "^1.0.7",
"turndown": "^7.2.4",
"zod": "^4.4.3"
"zod": "^4.4.3",
"zustand": "^4.5.7"
},
"devDependencies": {
"@types/node": "^25.9.3",

View File

@@ -0,0 +1,60 @@
import fs from 'fs';
import path from 'path';
const iconsDir = path.join('node_modules/lucide-react/dist/esm/icons');
const names = [
'search', 'house', 'star', 'folder-git-2', 'link-2', 'earth', 'file-text',
'message-circle', 'tags', 'moon', 'clock', 'badge-check', 'sliders-horizontal',
'plus', 'sun', 'mail', 'calendar-check', 'check', 'gift', 'panel-right',
'user-plus', 'layout-dashboard',
'code-2', 'coffee', 'help-circle', 'message-square', 'lightbulb', 'book-open',
'gamepad-2', 'palette', 'music', 'camera', 'heart', 'zap', 'globe', 'users',
'briefcase', 'graduation-cap', 'shopping-bag', 'map-pin', 'megaphone', 'flame',
'folder', 'wrench', 'cpu',
];
function esc(v) {
return String(v).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
function nodeToInner(nodes) {
return nodes.map(([tag, attrs]) => {
let s = `<${tag}`;
for (const [k, v] of Object.entries(attrs)) {
if (k === 'key') continue;
s += ` ${k}="${esc(v)}"`;
}
return `${s}/>`;
}).join('');
}
function resolveIconFile(name) {
let f = path.join(iconsDir, `${name}.mjs`);
let src = fs.readFileSync(f, 'utf8');
const re = src.match(/export \{ default \} from '\.\/([^']+)';/);
if (re) {
f = path.join(iconsDir, re[1]);
src = fs.readFileSync(f, 'utf8');
}
return { f, src };
}
const out = {};
for (const n of names) {
try {
const { src } = resolveIconFile(n);
const m = src.match(/const __iconNode = (\[[\s\S]*?\]);/);
if (!m) {
console.error('no node', n);
continue;
}
// eslint-disable-next-line no-eval
const nodes = eval(m[1]);
out[n] = nodeToInner(nodes);
} catch (e) {
console.error('fail', n, e.message);
}
}
fs.writeFileSync('tmp-lucide-paths.json', JSON.stringify(out, null, 2));
console.log('wrote', Object.keys(out).length, 'icons');

View File

@@ -0,0 +1,168 @@
import fs from 'fs';
import path from 'path';
const paths = JSON.parse(fs.readFileSync('tmp-lucide-paths.json', 'utf8'));
function splitInner(inner) {
const tags = [];
const re = /<([a-z]+)([^>]*)\/>/g;
let m;
while ((m = re.exec(inner))) {
tags.push(`<${m[1]}${m[2]}/>`);
}
return tags;
}
function goFunc(name, size, key, className = '') {
const tags = splitInner(paths[key]);
const lines = tags.map((t) => `\t\t\`${t}\`,`).join('\n');
if (className) {
return `func ${name}() string {\n\treturn ssrSVGWithClass(${size}, "${className}",\n${lines}\n\t)\n}\n\n`;
}
return `func ${name}() string {\n\treturn ssrSVG(${size},\n${lines}\n\t)\n}\n\n`;
}
const boardKeys = [
'code-2', 'coffee', 'help-circle', 'message-square', 'lightbulb', 'book-open',
'gamepad-2', 'palette', 'music', 'camera', 'heart', 'zap', 'globe', 'users',
'briefcase', 'graduation-cap', 'shopping-bag', 'map-pin', 'megaphone', 'flame',
'star', 'folder', 'wrench', 'cpu',
];
const defaults = [
'code-2', 'coffee', 'help-circle', 'message-square',
'lightbulb', 'book-open', 'gamepad-2', 'palette',
];
let out = `package handler
import (
\t"strconv"
\t"strings"
\t"time"
)
// 内联 SVG:path 对齐 lucide-react@1.18(由 scripts/extract-lucide-paths.mjs 抽取)
func ssrSVG(size int, paths ...string) string {
\treturn ssrSVGWithClass(size, "", paths...)
}
func ssrSVGWithClass(size int, className string, paths ...string) string {
\tvar b strings.Builder
\tb.WriteString(\`<svg xmlns="http://www.w3.org/2000/svg" width="\`)
\tb.WriteString(strconv.Itoa(size))
\tb.WriteString(\`" height="\`)
\tb.WriteString(strconv.Itoa(size))
\tb.WriteString(\`" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"\`)
\tif className != "" {
\t\tb.WriteString(\` class="\`)
\t\tb.WriteString(className)
\t\tb.WriteString(\`"\`)
\t}
\tb.WriteString(\` aria-hidden="true">\`)
\tfor _, p := range paths {
\t\tb.WriteString(p)
\t}
\tb.WriteString(\`</svg>\`)
\treturn b.String()
}
`;
out += goFunc('ssrIconSearch', 16, 'search', 'header-search-icon');
out += goFunc('ssrIconSliders', 15, 'sliders-horizontal');
out += goFunc('ssrIconPlus', 16, 'plus');
out += goFunc('ssrIconMoon', 18, 'moon');
out += goFunc('ssrIconSun', 18, 'sun');
out += goFunc('ssrIconMail', 18, 'mail');
out += goFunc('ssrIconHome', 18, 'house');
out += goFunc('ssrIconStar', 18, 'star');
out += goFunc('ssrIconFolderGit', 18, 'folder-git-2');
out += goFunc('ssrIconLink2', 18, 'link-2');
out += goFunc('ssrIconEarth', 18, 'earth');
out += goFunc('ssrIconFileText', 18, 'file-text');
out += goFunc('ssrIconLayoutDashboard', 18, 'layout-dashboard');
out += goFunc('ssrIconMessageCircle', 16, 'message-circle');
out += goFunc('ssrIconClock', 16, 'clock');
out += goFunc('ssrIconBadgeCheck', 16, 'badge-check');
out += goFunc('ssrIconTags', 16, 'tags');
out += goFunc('ssrIconUserPlus', 16, 'user-plus');
out += goFunc('ssrIconCalendarCheck', 18, 'calendar-check');
out += goFunc('ssrIconCheck', 18, 'check');
out += goFunc('ssrIconGift', 15, 'gift');
out += goFunc('ssrIconPanelRight', 18, 'panel-right');
out += '// 板块图标 path(key 对齐 BOARD_ICON_OPTIONS / AllowedBoardIcons)\nvar ssrBoardIconInner = map[string]string{\n';
for (const k of boardKeys) {
out += `\t"${k}": \`${paths[k]}\`,\n`;
}
out += '}\n\n';
out += '// 与前端 DEFAULT_ICONS 顺序一致(按 themeIndex 回退)\nvar ssrBoardDefaultIcons = []string{\n';
for (const k of defaults) {
out += `\t"${k}",\n`;
}
out += '}\n\n';
out += `// ssrBoardIconSVG 输出板块 Lucide 图标;class 打在 svg 上(与 React BoardIconDisplay 一致)
func ssrBoardIconSVG(icon string, themeIndex int, className string) string {
\tkey := strings.TrimSpace(strings.ToLower(icon))
\tinner, ok := ssrBoardIconInner[key]
\tif !ok || inner == "" {
\t\tif themeIndex < 0 {
\t\t\tthemeIndex = 0
\t\t}
\t\tkey = ssrBoardDefaultIcons[themeIndex%len(ssrBoardDefaultIcons)]
\t\tinner = ssrBoardIconInner[key]
\t}
\treturn ssrSVGWithClass(18, className, inner)
}
// formatSSRRelativeTime 与前端 formatTime 同规则
func formatSSRRelativeTime(t time.Time) string {
\tif t.IsZero() {
\t\treturn ""
\t}
\tnow := time.Now()
\tdiffSec := now.Sub(t).Seconds()
\tif diffSec < 0 {
\t\tdiffSec = 0
\t}
\tif diffSec < 60 {
\t\treturn "刚刚"
\t}
\tif diffSec < 3600 {
\t\treturn strconv.Itoa(int(diffSec/60)) + "分钟前"
\t}
\tif diffSec < 86400 {
\t\treturn strconv.Itoa(int(diffSec/3600)) + "小时前"
\t}
\tdiffDay := int(diffSec / 86400)
\tif diffDay < 30 {
\t\treturn strconv.Itoa(diffDay) + "天前"
\t}
\tif t.Year() == now.Year() {
\t\treturn strconv.Itoa(int(t.Month())) + "月" + strconv.Itoa(t.Day()) + "日"
\t}
\treturn strconv.Itoa(t.Year()) + "年" + strconv.Itoa(int(t.Month())) + "月" + strconv.Itoa(t.Day()) + "日"
}
// formatSSRShortDateTime 与前端 formatShortDateTime 同规则(MM-DD HH:mm)
func formatSSRShortDateTime(t time.Time) string {
\tif t.IsZero() {
\t\treturn ""
\t}
\tlocal := t.Local()
\tpad := func(n int) string {
\t\tif n < 10 {
\t\t\treturn "0" + strconv.Itoa(n)
\t\t}
\t\treturn strconv.Itoa(n)
\t}
\treturn pad(int(local.Month())) + "-" + pad(local.Day()) + " " + pad(local.Hour()) + ":" + pad(local.Minute())
}
`;
const outPath = path.join('..', 'handler', 'ssr_icons.go');
fs.writeFileSync(outPath, out);
console.log('wrote', outPath, Object.keys(paths).length, 'icons');

View File

@@ -17,6 +17,7 @@ import PageLoader from './components/PageLoader';
import AuthPageFallback from './components/AuthPageFallback';
import { Toaster } from './components/ui/sonner';
import PullToRefresh from './components/PullToRefresh';
import TopProgressBar from './components/TopProgressBar';
import { lazyWithRetry } from './utils/lazyWithRetry';
const HomePage = lazyWithRetry(() => import('./pages/HomePage'));
@@ -31,6 +32,8 @@ const UserProfilePage = lazyWithRetry(() => import('./pages/UserProfilePage'));
const FavoritesPage = lazyWithRetry(() => import('./pages/FavoritesPage'));
const MessagesPage = lazyWithRetry(() => import('./pages/MessagesPage'));
const ProjectsPage = lazyWithRetry(() => import('./pages/ProjectsPage'));
const LinksPage = lazyWithRetry(() => import('./pages/LinksPage'));
const ShowcasePage = lazyWithRetry(() => import('./pages/ShowcasePage'));
const AdminDashboardPage = lazyWithRetry(() => import('./pages/admin/AdminDashboardPage'));
const AdminPostsPage = lazyWithRetry(() => import('./pages/admin/AdminPostsPage'));
const AdminCommentsPage = lazyWithRetry(() => import('./pages/admin/AdminCommentsPage'));
@@ -38,7 +41,13 @@ const AdminReportsPage = lazyWithRetry(() => import('./pages/admin/AdminReportsP
const AdminUsersPage = lazyWithRetry(() => import('./pages/admin/AdminUsersPage'));
const AdminBadgesPage = lazyWithRetry(() => import('./pages/admin/AdminBadgesPage'));
const AdminMediaPage = lazyWithRetry(() => import('./pages/admin/AdminMediaPage'));
const AdminMonitorPage = lazyWithRetry(() => import('./pages/admin/AdminMonitorPage'));
const AdminPagesPage = lazyWithRetry(() => import('./pages/admin/AdminPagesPage'));
const AdminSitePageEditPage = lazyWithRetry(() => import('./pages/admin/AdminSitePageEditPage'));
const AdminLinksPage = lazyWithRetry(() => import('./pages/admin/AdminLinksPage'));
const SitePageView = lazyWithRetry(() => import('./pages/SitePageView'));
const AdminSettingsPage = lazyWithRetry(() => import('./pages/admin/AdminSettingsPage'));
const AdminCommunityPage = lazyWithRetry(() => import('./pages/admin/AdminCommunityPage'));
const NotFoundPage = lazyWithRetry(() => import('./pages/NotFoundPage'));
const router = createBrowserRouter(
@@ -52,17 +61,24 @@ const router = createBrowserRouter(
<Route index element={<Navigate to="/admin/dashboard" replace />} />
<Route path="dashboard" element={<Suspense fallback={<PageLoader />}><AdminDashboardPage /></Suspense>} />
<Route path="boards" element={<Suspense fallback={<PageLoader />}><BoardsManagePage /></Suspense>} />
<Route path="pages/new" element={<Suspense fallback={<PageLoader />}><AdminSitePageEditPage /></Suspense>} />
<Route path="pages/:id/edit" element={<Suspense fallback={<PageLoader />}><AdminSitePageEditPage /></Suspense>} />
<Route path="pages" element={<Suspense fallback={<PageLoader />}><AdminPagesPage /></Suspense>} />
<Route path="links" element={<Suspense fallback={<PageLoader />}><AdminLinksPage /></Suspense>} />
<Route path="community" element={<Suspense fallback={<PageLoader />}><AdminCommunityPage /></Suspense>} />
<Route path="posts" element={<Suspense fallback={<PageLoader />}><AdminPostsPage /></Suspense>} />
<Route path="comments" element={<Suspense fallback={<PageLoader />}><AdminCommentsPage /></Suspense>} />
<Route path="reports" element={<Suspense fallback={<PageLoader />}><AdminReportsPage /></Suspense>} />
<Route path="users" element={<Suspense fallback={<PageLoader />}><AdminUsersPage /></Suspense>} />
<Route path="badges" element={<Suspense fallback={<PageLoader />}><AdminBadgesPage /></Suspense>} />
<Route path="media" element={<Suspense fallback={<PageLoader />}><AdminMediaPage /></Suspense>} />
<Route path="monitor" element={<Suspense fallback={<PageLoader />}><AdminMonitorPage /></Suspense>} />
<Route path="settings" element={<Suspense fallback={<PageLoader />}><AdminSettingsPage /></Suspense>} />
<Route path="*" element={<Suspense fallback={<PageLoader />}><NotFoundPage title="后台页面不存在" /></Suspense>} />
</Route>
<Route element={<MainLayout />}>
<Route path="/" element={<HomePage />} />
<Route path="/board/:id" element={<HomePage />} />
{/* :id 可为 123 或 123.html(伪静态后缀由后台配置) */}
<Route path="/post/:id" element={<PostDetailPage />} />
<Route path="/compose" element={<ComposePage />} />
@@ -71,8 +87,11 @@ const router = createBrowserRouter(
<Route path="/user/:id" element={<UserProfilePage />} />
<Route path="/favorites" element={<FavoritesPage />} />
<Route path="/projects" element={<ProjectsPage />} />
<Route path="/links" element={<LinksPage />} />
<Route path="/showcase" element={<Suspense fallback={null}><ShowcasePage /></Suspense>} />
<Route path="/messages" element={<MessagesPage />} />
<Route path="*" element={<Suspense fallback={<PageLoader />}><NotFoundPage /></Suspense>} />
<Route path="/page/:slug" element={<Suspense fallback={null}><SitePageView /></Suspense>} />
<Route path="*" element={<Suspense fallback={null}><NotFoundPage /></Suspense>} />
</Route>
<Route path="*" element={<Suspense fallback={<PageLoader fullScreen />}><NotFoundPage standalone /></Suspense>} />
</Route>,
@@ -85,6 +104,7 @@ export default function App() {
<AuthProvider>
<ErrorBoundary>
<RouterProvider router={router} />
<TopProgressBar />
<PullToRefresh />
<Toaster />
</ErrorBoundary>

View File

@@ -1,4 +1,4 @@
import type { User, UserPublic, UserActivityStats, Board, PostItem, Comment, RecentComment, ForumStats, TagCount, AdminDashboard, AdminSettings, ForumLimits, ForumLimitsPublic, PostDetailResponse, PostRevision, CommentRevision, MailConfig, OIDCConfig, OAuthClient, OAuthClientInput, GiteaProject, GiteaSyncConfig, StorageConfig, MediaListResult, SiteBranding, RegisterConfig, PrivateMessage, MessageConversation, PostReport, ReportReason, ReportStatus, BadgeDef, PointLedger, CheckInStatus, LotteryStatus } from './types';
import type { User, UserPublic, UserActivityStats, Board, PostItem, Comment, RecentComment, RecentUser, ForumStats, TagCount, AdminDashboard, AdminSettings, ForumLimits, ForumLimitsPublic, PostDetailResponse, PostRevision, CommentRevision, MailConfig, OIDCConfig, OAuthClient, OAuthClientInput, GiteaProject, GiteaSyncConfig, StorageConfig, MediaListResult, SiteBranding, RegisterConfig, PrivateMessage, MessageConversation, PostReport, ReportReason, ReportStatus, BadgeDef, PointLedger, CheckInStatus, LotteryStatus, SitePage, SitePageSummary, PollView, PostLotteryView, FriendLinkApply, CommunityConfig, CommunityInstance, CommunityShowcaseItem, MonitorConfig, MonitorOverview, MonitorGeoResult, MonitorStatItem, MonitorRealtime, MonitorLogItem } from './types';
const BASE = '';
@@ -25,12 +25,36 @@ export const api = {
me: () => request<{ user: User | null }>('/api/me'),
stats: () => request<ForumStats>('/api/stats'),
forumLimits: () => request<ForumLimitsPublic>('/api/forum-limits'),
/** 前台路由 pageview;失败静默(204 无 body) */
monitorPageview: (body: { path: string; referrer?: string }) => {
const payload = JSON.stringify(body);
try {
if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
const blob = new Blob([payload], { type: 'application/json' });
if (navigator.sendBeacon('/api/monitor/pageview', blob)) {
return Promise.resolve();
}
}
} catch {
/* 回退 fetch */
}
return fetch('/api/monitor/pageview', {
method: 'POST',
credentials: 'omit',
keepalive: true,
headers: { 'Content-Type': 'application/json' },
body: payload,
}).then(() => undefined).catch(() => undefined);
},
siteBranding: () => request<SiteBranding>('/api/site-branding'),
pages: () => request<{ pages: SitePageSummary[] }>('/api/pages'),
page: (slug: string) => request<{ page: SitePage }>(`/api/pages/${encodeURIComponent(slug)}`),
boards: () => request<{ boards: Board[] }>('/api/boards'),
projects: (params?: { page?: number; limit?: number }) => {
projects: (params?: { page?: number; limit?: number; q?: string }) => {
const q = new URLSearchParams();
if (params?.page) q.set('page', String(params.page));
if (params?.limit) q.set('limit', String(params.limit));
if (params?.q?.trim()) q.set('q', params.q.trim());
const qs = q.toString();
return request<{ projects: GiteaProject[]; total: number; page: number; total_pages: number }>(
`/api/projects${qs ? `?${qs}` : ''}`,
@@ -40,7 +64,6 @@ export const api = {
const q = new URLSearchParams(params as Record<string, string>).toString();
return request<{ posts: PostItem[]; total: number; page: number; has_more: boolean }>(`/api/posts?${q}`);
},
hotPosts: () => request<{ posts: PostItem[] }>('/api/posts/hot'),
tags: (limit = 40) => request<{ tags: TagCount[] }>(`/api/tags?limit=${limit}`),
post: (id: number, opts?: { skipView?: boolean }) => {
const q = opts?.skipView ? '?skip_view=1' : '';
@@ -51,6 +74,7 @@ export const api = {
return request<{ comments: Comment[]; total: number }>(`/api/posts/${id}/comments${q}`);
},
recentComments: () => request<{ comments: RecentComment[] }>('/api/comments/recent'),
recentUsers: () => request<{ users: RecentUser[] }>('/api/users/recent'),
favorites: () => request<{ favorites: unknown[]; total: number }>('/api/favorites'),
createBoard: (body: { name: string; description: string; sort_order: number; icon?: string; color_index?: number }) =>
request<{ board: Board }>('/api/admin/boards', { method: 'POST', body: JSON.stringify(body) }),
@@ -60,6 +84,59 @@ export const api = {
// 管理后台 API
adminDashboard: () => request<AdminDashboard>('/api/admin/dashboard'),
adminSettings: () => request<AdminSettings>('/api/admin/settings'),
adminUpdateCommunitySettings: (body: CommunityConfig) =>
request<{ message: string; community: CommunityConfig; heartbeat_error?: string }>('/api/admin/settings/community', {
method: 'PUT', body: JSON.stringify(body),
}),
adminMonitorSettings: () => request<MonitorConfig>('/api/admin/settings/monitor'),
adminUpdateMonitorSettings: (body: MonitorConfig) =>
request<{ message: string; monitor: MonitorConfig }>('/api/admin/settings/monitor', {
method: 'PUT', body: JSON.stringify(body),
}),
adminMonitorOverview: () => request<MonitorOverview>('/api/admin/monitor/overview'),
adminMonitorGeo: (range = '30d') =>
request<MonitorGeoResult>(`/api/admin/monitor/geo?range=${encodeURIComponent(range)}`),
adminMonitorStats: (dim: string, range = '30d') =>
request<{ dim: string; range: string; items: MonitorStatItem[] }>(
`/api/admin/monitor/stats?dim=${encodeURIComponent(dim)}&range=${encodeURIComponent(range)}`,
),
adminMonitorLogs: (params: { page?: number; size?: number; method?: string; path?: string; status?: string; ip?: string }) => {
const q = new URLSearchParams();
if (params.page) q.set('page', String(params.page));
if (params.size) q.set('size', String(params.size));
if (params.method) q.set('method', params.method);
if (params.path) q.set('path', params.path);
if (params.status) q.set('status', params.status);
if (params.ip) q.set('ip', params.ip);
const qs = q.toString();
return request<{ items: MonitorLogItem[]; total: number; page: number; size: number }>(
`/api/admin/monitor/logs${qs ? `?${qs}` : ''}`,
);
},
adminMonitorRealtime: () => request<MonitorRealtime>('/api/admin/monitor/realtime'),
adminCommunityInstances: () =>
request<{ hub_enabled: boolean; instances: CommunityInstance[] }>('/api/admin/community/instances'),
adminFeatureCommunityInstance: (instanceId: string, body: { featured: boolean; featured_note?: string }) =>
request<{ message: string; instance: CommunityInstance }>(
`/api/admin/community/instances/${encodeURIComponent(instanceId)}/feature`,
{ method: 'PUT', body: JSON.stringify(body) },
),
adminUpdateShowcaseEntry: (body: {
nav_show_showcase?: boolean;
footer_show_showcase?: boolean;
aside_show_showcase?: boolean;
}) =>
request<{
message: string;
nav_show_showcase: boolean;
footer_show_showcase: boolean;
aside_show_showcase: boolean;
}>('/api/admin/community/showcase-entry', {
method: 'PUT',
body: JSON.stringify(body),
}),
communityShowcase: () =>
request<{ items: CommunityShowcaseItem[] }>('/api/community/showcase'),
adminPosts: (params: { page?: number; keyword?: string; status?: string }) => {
const q = new URLSearchParams();
if (params.page) q.set('page', String(params.page));
@@ -285,6 +362,7 @@ export const api = {
check_in: CheckInStatus;
lottery: LotteryStatus;
}>(`/api/me/points?page=${page}`),
checkInStatus: () => request<{ check_in: CheckInStatus }>('/api/me/check-in'),
checkIn: () =>
request<{ message: string; check_in: CheckInStatus; points: number }>('/api/me/check-in', { method: 'POST' }),
lotteryStatus: () => request<{ lottery: LotteryStatus }>('/api/me/lottery'),
@@ -341,13 +419,27 @@ export const api = {
fd.append('image', file);
return request<{ url: string }>('/api/uploads/image', { method: 'POST', body: fd, headers: {} });
},
createPost: (data: { board_id: string; title: string; content: string; tags?: string; post_type?: string }) => {
/** 当前用户历史上传的帖子图片 */
myPostImages: (params?: { page?: number; size?: number }) => {
const q = new URLSearchParams();
if (params?.page) q.set('page', String(params.page));
if (params?.size) q.set('size', String(params.size));
const qs = q.toString();
return request<MediaListResult>(`/api/uploads/images${qs ? `?${qs}` : ''}`);
},
createPost: (data: {
board_id: string; title: string; content: string; tags?: string; post_type?: string;
poll_options?: string; bounty_points?: number; lottery_winner_count?: number;
}) => {
const fd = new FormData();
fd.append('board_id', data.board_id);
fd.append('title', data.title);
fd.append('content', data.content);
fd.append('tags', data.tags || '');
fd.append('post_type', data.post_type || 'normal');
if (data.poll_options) fd.append('poll_options', data.poll_options);
if (data.bounty_points != null) fd.append('bounty_points', String(data.bounty_points));
if (data.lottery_winner_count != null) fd.append('lottery_winner_count', String(data.lottery_winner_count));
return request<{ post_id: number; message?: string; status?: string }>('/api/posts', { method: 'POST', body: fd, headers: {} });
},
updatePost: (id: number, data: { title: string; content: string; tags?: string; board_id?: string | number; post_type?: string }) => {
@@ -372,6 +464,76 @@ export const api = {
headers: {},
});
},
pollVote: (id: number, optionIds: number[]) =>
request<{ message: string; poll: PollView }>(`/api/posts/${id}/poll/vote`, {
method: 'POST', body: JSON.stringify({ option_ids: optionIds }),
}),
pollClose: (id: number) =>
request<{ message: string; poll: PollView }>(`/api/posts/${id}/poll/close`, { method: 'POST', body: '{}' }),
bountyAward: (id: number, commentId: number) => {
const fd = new FormData();
fd.append('comment_id', String(commentId));
return request<{ message: string }>(`/api/posts/${id}/bounty/award`, { method: 'POST', body: fd, headers: {} });
},
bountyRefund: (id: number) =>
request<{ message: string }>(`/api/posts/${id}/bounty/refund`, { method: 'POST', body: '{}' }),
postLotteryDraw: (id: number) =>
request<{ message: string; lottery: PostLotteryView }>(`/api/posts/${id}/lottery/draw`, { method: 'POST', body: '{}' }),
adminPages: () => request<{ pages: SitePage[] }>('/api/admin/pages'),
adminPage: (id: number) => request<{ page: SitePage }>(`/api/admin/pages/${id}`),
adminCreatePage: (data: Partial<SitePage>) =>
request<{ message: string; page: SitePage }>('/api/admin/pages', { method: 'POST', body: JSON.stringify(data) }),
adminUpdatePage: (id: number, data: Partial<SitePage>) =>
request<{ message: string }>(`/api/admin/pages/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
adminSetPagePublished: (id: number, published: boolean) =>
request<{ message: string; published: boolean }>(`/api/admin/pages/${id}/published`, {
method: 'PUT',
body: JSON.stringify({ published }),
}),
adminDeletePage: (id: number) =>
request<{ message: string }>(`/api/admin/pages/${id}`, { method: 'DELETE' }),
adminFriendLinkApplies: (params?: { page?: number; size?: number; status?: string }) => {
const q = new URLSearchParams();
if (params?.page) q.set('page', String(params.page));
if (params?.size) q.set('size', String(params.size));
if (params?.status) q.set('status', params.status);
const qs = q.toString();
return request<{
applies: FriendLinkApply[];
total: number;
page: number;
pending_count: number;
reciprocal_check_enabled?: boolean;
}>(`/api/admin/friend-link-applies${qs ? `?${qs}` : ''}`);
},
adminUpdateFriendLinkSettings: (body: {
reciprocal_check_enabled?: boolean;
nav_show_friend_links?: boolean;
footer_show_friend_links?: boolean;
aside_show_friend_links?: boolean;
}) =>
request<{
message: string;
reciprocal_check_enabled: boolean;
nav_show_friend_links: boolean;
footer_show_friend_links: boolean;
aside_show_friend_links: boolean;
}>('/api/admin/friend-link-settings', {
method: 'PUT',
body: JSON.stringify(body),
}),
adminApproveFriendLinkApply: (id: number) =>
request<{ message: string; apply: FriendLinkApply }>(`/api/admin/friend-link-applies/${id}/approve`, {
method: 'POST', body: '{}',
}),
adminRejectFriendLinkApply: (id: number, body?: { note?: string }) =>
request<{ message: string; apply: FriendLinkApply }>(`/api/admin/friend-link-applies/${id}/reject`, {
method: 'POST', body: JSON.stringify(body ?? {}),
}),
adminRecheckFriendLinkApply: (id: number) =>
request<{ message: string; apply: FriendLinkApply }>(`/api/admin/friend-link-applies/${id}/recheck`, {
method: 'POST',
}),
deletePost: (id: number) => request<{ message: string }>(`/api/posts/${id}`, { method: 'DELETE' }),
login: (username: string, password: string) => {
const fd = new FormData();
@@ -425,6 +587,37 @@ export const api = {
like: (id: number) => request<{ liked: boolean; like_count: number }>(`/api/posts/${id}/like`, { method: 'POST' }),
likeComment: (id: number) => request<{ liked: boolean; like_count: number }>(`/api/comments/${id}/like`, { method: 'POST' }),
favorite: (id: number) => request<{ favorited: boolean }>(`/api/posts/${id}/favorite`, { method: 'POST' }),
applyFriendLink: (body: {
name: string;
url: string;
logo: string;
link_on_homepage: boolean;
reciprocal_page_url?: string;
}) =>
request<{ message: string; apply: FriendLinkApply; warning?: string }>('/api/friend-links/apply', {
method: 'POST', body: JSON.stringify(body),
}),
uploadFriendLinkLogo: (file: File) => {
const fd = new FormData();
fd.append('logo', file);
return request<{ message: string; url: string }>('/api/friend-links/logo', {
method: 'POST', body: fd, headers: {},
});
},
myFriendLinkApplies: () =>
request<{ applies: FriendLinkApply[] }>('/api/friend-links/my-applies'),
updateFriendLinkApply: (id: number, body: {
name: string;
url: string;
logo: string;
link_on_homepage: boolean;
reciprocal_page_url?: string;
}) =>
request<{ message: string; apply: FriendLinkApply; warning?: string }>(`/api/friend-links/applies/${id}`, {
method: 'PUT', body: JSON.stringify(body),
}),
cancelFriendLinkApply: (id: number) =>
request<{ message: string }>(`/api/friend-links/applies/${id}`, { method: 'DELETE' }),
reportPost: (id: number, body: { reason: ReportReason; detail?: string }) =>
request<{ message: string; report: PostReport }>(`/api/posts/${id}/report`, {
method: 'POST', body: JSON.stringify(body),
@@ -471,6 +664,8 @@ export const api = {
},
markNotificationsRead: () =>
request<{ message: string }>('/api/messages/notifications/read', { method: 'POST' }),
markMessageRead: (id: number) =>
request<{ message: string }>(`/api/messages/${id}/read`, { method: 'POST' }),
sendMessage: (body: { to_user_id: number; subject?: string; content: string }) =>
request<{ message: PrivateMessage }>('/api/messages', {
method: 'POST', body: JSON.stringify(body),

View File

@@ -69,6 +69,7 @@ export interface ForumStats {
users: number;
posts: number;
boards: number;
comments: number;
}
/** 标签云单项 */
@@ -84,10 +85,15 @@ export interface PostItem {
title: string;
content?: string;
tags: string;
/** normal=讨论 | question=问答 */
post_type?: 'normal' | 'question' | string;
/** normal=讨论 | question=问答 | poll=投票 | bounty=悬赏 | lottery=抽奖 */
post_type?: 'normal' | 'question' | 'poll' | 'bounty' | 'lottery' | string;
/** 仅问答帖有意义 */
question_resolved?: boolean;
bounty_points?: number;
bounty_status?: 'open' | 'awarded' | 'refunded' | string;
bounty_comment_id?: number;
lottery_winner_count?: number;
lottery_status?: 'open' | 'drawn' | string;
pinned: boolean;
/** 板块内置顶(仅板块列表抬升,首页不抬升) */
board_pinned?: boolean;
@@ -100,6 +106,10 @@ export interface PostItem {
view_count: number;
comment_count: number;
last_reply_at?: string;
/** 最后回复用户(登录用户);与 last_reply_guest_nick 二选一 */
last_reply_user?: User;
/** 最后回复游客昵称 */
last_reply_guest_nick?: string;
created_at: string;
updated_at?: string;
board?: Board;
@@ -131,12 +141,18 @@ export interface PostDetailResponse {
comment_count: number;
liked: boolean;
favorited: boolean;
/** 当前用户是否已在本帖发表过评论(含审核中) */
has_replied?: boolean;
can_edit?: boolean;
edit_block_reason?: string;
is_edited?: boolean;
post_edit_window_hours?: number;
poll?: PollView;
lottery?: PostLotteryView;
/** 悬赏进行中:当前用户是否可取消悬赏 */
bounty_can_refund?: boolean;
bounty_refund_block_reason?: string;
/** 他人已发布有效回复数 */
bounty_eligible_reply_count?: number;
}
export interface Comment {
@@ -163,6 +179,14 @@ export interface Comment {
reply_target?: Comment;
}
export interface AdminDashboardTraffic {
enabled: boolean;
today_pv: number;
today_uv: number;
yesterday_pv: number;
total_pv: number;
}
export interface AdminDashboard {
users: number;
posts: number;
@@ -171,9 +195,40 @@ export interface AdminDashboard {
pending_posts?: number;
pending_comments?: number;
pending_reports?: number;
pending_friend_links?: number;
recent_posts: PostItem[];
traffic?: AdminDashboardTraffic;
}
export type AsideWidgetId = 'tag_cloud' | 'recent_comments' | 'recent_users' | 'friend_links' | 'showcase';
export interface AsideWidget {
id: AsideWidgetId;
enabled: boolean;
}
export const DEFAULT_ASIDE_WIDGETS: AsideWidget[] = [
{ id: 'tag_cloud', enabled: false },
{ id: 'recent_comments', enabled: false },
{ id: 'recent_users', enabled: false },
{ id: 'friend_links', enabled: true },
{ id: 'showcase', enabled: false },
];
export type FeedSortId = 'reply' | 'latest' | 'hot';
export interface FeedSortTab {
id: FeedSortId;
label: string;
enabled: boolean;
}
export const DEFAULT_FEED_SORT_TABS: FeedSortTab[] = [
{ id: 'reply', label: '最新', enabled: true },
{ id: 'latest', label: '新帖子', enabled: true },
{ id: 'hot', label: '推荐帖', enabled: true },
];
export interface ForumLimits {
post_edit_window_hours: number;
comment_edit_window_minutes: number;
@@ -194,6 +249,28 @@ export interface ForumLimits {
signature_max: number;
open_posts_in_new_tab: boolean;
open_content_links_in_new_tab: boolean;
/** 右侧栏标签云 */
aside_show_tag_cloud: boolean;
/** 右侧栏最新评论 */
aside_show_recent_comments: boolean;
/** 右侧栏友情链接 */
aside_show_friend_links: boolean;
/** 右侧栏开源展柜 */
aside_show_showcase: boolean;
/** 右侧栏可选组件顺序与开关 */
aside_widgets: AsideWidget[];
/** 左侧栏「站点」展示友情链接入口 */
nav_show_friend_links: boolean;
/** 页脚展示友情链接入口 */
footer_show_friend_links: boolean;
/** 左侧栏「站点」展示开源展柜入口 */
nav_show_showcase: boolean;
/** 页脚展示开源展柜入口 */
footer_show_showcase: boolean;
/** 首页列表样式:title 仅标题 / thumbnail 缩略图 */
feed_list_style: 'title' | 'excerpt' | 'thumbnail';
/** 首页排序标签:名称、顺序、启停 */
feed_sort_tabs: FeedSortTab[];
/** 伪静态(固定链接)开关 */
permalink_enabled: boolean;
/** 伪静态后缀,不含点,如 html / htm */
@@ -214,19 +291,99 @@ export interface ForumLimitsPublic {
signature_max: number;
open_posts_in_new_tab: boolean;
open_content_links_in_new_tab: boolean;
aside_show_tag_cloud: boolean;
aside_show_recent_comments: boolean;
aside_show_friend_links: boolean;
aside_show_showcase: boolean;
aside_widgets: AsideWidget[];
nav_show_friend_links: boolean;
footer_show_friend_links: boolean;
nav_show_showcase: boolean;
footer_show_showcase: boolean;
feed_list_style: 'title' | 'excerpt' | 'thumbnail';
feed_sort_tabs: FeedSortTab[];
permalink_enabled: boolean;
permalink_ext: string;
/** 是否上报前台路由 pageview(与后台监控采集开关同步) */
monitor_pageview: boolean;
}
export interface FriendLink {
name: string;
url: string;
logo?: string;
}
export interface FriendLinkApply {
id: number;
user_id: number;
name: string;
url: string;
description?: string;
logo?: string;
reciprocal_page_url?: string;
link_on_homepage?: boolean;
reciprocal_verified?: boolean;
reciprocal_check_note?: string;
reciprocal_checked_at?: string;
status: 'pending' | 'approved' | 'rejected';
review_note?: string;
reviewed_at?: string;
created_at: string;
user?: User;
}
export interface SitePageSummary {
id: number;
title: string;
slug: string;
show_in_footer?: boolean;
show_in_nav?: boolean;
sort_order?: number;
}
export interface SitePage extends SitePageSummary {
content: string;
published: boolean;
created_at?: string;
updated_at?: string;
}
export interface PollOptionView {
id: number;
text: string;
vote_count: number;
percent?: number;
}
export interface PollView {
multi: boolean;
max_choices: number;
closed: boolean;
ends_at?: string;
options: PollOptionView[];
my_option_ids?: number[];
total_votes: number;
}
export interface PostLotteryWinnerView {
user_id: number;
username: string;
nickname: string;
comment_id: number;
}
export interface PostLotteryView {
winner_count: number;
status: string;
participant_count: number;
winners?: PostLotteryWinnerView[];
}
export interface SiteBranding {
name: string;
slogan: string;
/** 站点简介(首页可见 + SEO description) */
/** 站点简介(右侧栏顶部 + SEO description) */
description?: string;
/** SEO keywords,逗号分隔 */
keywords?: string;
@@ -241,6 +398,8 @@ export interface SiteBranding {
icp_beian_url?: string;
/** 页脚友情链接 */
friend_links?: FriendLink[];
/** 公开站点根 URL(API 动态填充) */
site_url?: string;
}
export interface AdminSettings {
@@ -255,10 +414,148 @@ export interface AdminSettings {
gitea?: GiteaSyncConfig;
storage?: StorageConfig;
branding?: SiteBranding;
community?: CommunityConfig;
filter_words: string;
filter_word_count: number;
}
/** 社区上报配置(hub_url / site_url 只读) */
export interface CommunityConfig {
report_enabled: boolean;
/** 只读:是否作为社区枢纽 */
hub_enabled: boolean;
/** 只读:固定为官方演示站 */
hub_url: string;
/** 只读:服务端自动推断的本站地址 */
site_url: string;
instance_id: string;
}
/** 网站监控设置 */
export interface MonitorConfig {
enabled: boolean;
retention_days: number;
access_log_retention_days: number;
exclude_rules: string[];
default_exclude_rules?: string[];
trust_proxy: boolean;
access_log_dir?: string;
ip2location_v4_path?: string;
ip2location_v6_path?: string;
ip2location_v4_available?: boolean;
ip2location_v6_available?: boolean;
geoip_available: boolean;
geoip_country_path?: string;
geoip_asn_path?: string;
geoip_country_available?: boolean;
geoip_asn_available?: boolean;
}
export interface MonitorOverview {
enabled: boolean;
pageviews: number;
visitors: number;
unique_ips: number;
traffic: number;
bots: number;
requests: number;
status_4xx: number;
status_5xx: number;
}
export interface MonitorGeoItem {
country: string;
count: number;
}
export interface MonitorRegionItem {
country: string;
region: string;
region_iso: string;
count: number;
}
export interface MonitorCityItem {
country: string;
region: string;
city: string;
count: number;
}
export interface MonitorASNItem {
asn: number;
as_org: string;
count: number;
}
export interface MonitorGeoResult {
range: string;
countries: MonitorGeoItem[];
regions: MonitorRegionItem[];
cities: MonitorCityItem[];
asns: MonitorASNItem[];
has_data: boolean;
}
export interface MonitorStatItem {
key: string;
count: number;
}
export interface MonitorRealtimePoint {
minute: string;
count: number;
bytes: number;
}
export interface MonitorRealtime {
enabled: boolean;
requests_1m: number;
traffic_1m: number;
hourly_series: MonitorRealtimePoint[];
}
export interface MonitorLogItem {
id: number;
created_at: string;
method: string;
path: string;
status: number;
bytes: number;
duration_ms: number;
ip: string;
ua: string;
referer: string;
country: string;
region?: string;
city?: string;
asn?: number;
as_org?: string;
is_bot: boolean;
}
export interface CommunityInstance {
instance_id: string;
site_url: string;
site_name: string;
version: string;
users: number;
posts: number;
first_seen_at: string;
last_seen_at: string;
online: boolean;
featured: boolean;
featured_note: string;
}
/** 公开展柜条目 */
export interface CommunityShowcaseItem {
site_url: string;
site_name: string;
version: string;
featured_note?: string;
}
export interface StorageConfig {
type: 'local' | 's3';
endpoint: string;
@@ -349,8 +646,21 @@ export interface GiteaProject {
full_name: string;
description: string;
html_url: string;
language?: string;
stars_count?: number;
forks_count?: number;
updated_at_remote?: string | null;
forum_user_id?: number;
owner?: {
id: number;
nickname: string;
avatar: string;
role: 'user' | 'admin';
verified?: boolean;
exp?: number;
level?: number;
badges?: UserBadge[];
};
synced_at: string;
}
@@ -392,6 +702,14 @@ export interface RecentComment {
created_at: string;
}
/** 右栏「最新注册」用户 */
export interface RecentUser {
id: number;
nickname: string;
avatar: string;
created_at: string;
}
/** 站内私信 */
export interface PrivateMessage {
id: number;
@@ -399,9 +717,13 @@ export interface PrivateMessage {
to_user_id: number;
subject: string;
content: string;
kind: 'user' | 'system' | 'reject' | 'report_result' | string;
kind: 'user' | 'system' | 'reject' | 'report_result' | 'reply' | 'mention' | 'moderation' | string;
related_post_id?: number;
related_report_id?: number;
related_comment_id?: number;
related_floor?: number;
/** 待审目标实时状态:pending|published|rejected|deleted */
related_status?: string;
is_read: boolean;
created_at: string;
from_user?: User;

View File

@@ -27,10 +27,10 @@ import {
cycleMarkdownHeading,
insertMarkdownMembersOnly,
insertMarkdownReplyOnly,
insertMarkdownPointsOnly,
insertMarkdownLink,
} from '../utils/markdownFormat';
import { countWords } from '../utils/text';
import { api } from '../api/client';
import { notify } from '@/lib/notify';
import { MembersOnly } from './editor/MembersOnlyExtension';
import { ReplyOnly } from './editor/ReplyOnlyExtension';
@@ -39,7 +39,8 @@ import { TabIndent } from './editor/TabIndentExtension';
import { ArticleImage, type ImageDisplay } from './editor/ArticleImageExtension';
import { ImageGroup, suggestImageGroupLayout } from './editor/ImageGroupExtension';
import { ClearFloatParagraph, ClearFloatSync } from './editor/ClearFloatParagraph';
import { ArticleLinkDialog } from './editor/ArticleLinkDialog';
import { ArticleLinkDialog, type ArticleLinkConfirm } from './editor/ArticleLinkDialog';
import { ArticleImagePickerDialog } from './editor/ArticleImagePickerDialog';
import { ArticleCodeBlockDialog } from './editor/ArticleCodeBlockDialog';
import { ArticleCodeBlock } from './editor/ArticleCodeBlockExtension';
import {
@@ -63,10 +64,16 @@ interface Props {
value: string;
onChange: (v: string) => void;
placeholder?: string;
/**
* 是否启用登录/回复/积分可见区块。
* 发帖默认 true;自定义单页等场景应关闭。
*/
enableContentGates?: boolean;
}
type EditorMode = 'rich' | 'markdown';
type LinkTarget = 'rich' | 'markdown';
type ImagePickerTarget = 'rich' | 'markdown';
type CodeBlockTarget = 'rich' | 'markdown';
type TableTarget = 'rich' | 'markdown';
@@ -161,34 +168,6 @@ function cycleHeading(editor: Editor) {
editor.chain().focus().toggleHeading({ level: 2 }).run();
}
/** 触发图片文件选择并上传(支持多选) */
async function uploadPostImageFiles(multiple = true): Promise<string[]> {
return new Promise(resolve => {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/jpeg,image/png,image/gif,image/webp';
input.multiple = multiple;
input.onchange = async () => {
const files = [...(input.files ?? [])];
if (!files.length) {
resolve([]);
return;
}
const urls: string[] = [];
for (const file of files) {
try {
const { url } = await api.uploadPostImage(file);
urls.push(url);
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '图片上传失败');
}
}
resolve(urls);
};
input.click();
});
}
/** 渲染工具栏按钮列表 */
function renderToolButtons(tools: ToolBtn[]) {
return tools.map((t, i) => (
@@ -211,7 +190,7 @@ function renderToolButtons(tools: ToolBtn[]) {
}
const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEditor(
{ value, onChange, placeholder = '在此撰写正文…' },
{ value, onChange, placeholder = '在此撰写正文…', enableContentGates = true },
ref,
) {
const isInternalUpdate = useRef(false);
@@ -222,7 +201,11 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
const [markdownSource, setMarkdownSource] = useState('');
const [linkDialogOpen, setLinkDialogOpen] = useState(false);
const [linkDialogUrl, setLinkDialogUrl] = useState('');
const [linkDialogText, setLinkDialogText] = useState('');
const [linkDialogEditing, setLinkDialogEditing] = useState(false);
const [linkTarget, setLinkTarget] = useState<LinkTarget>('rich');
const [imagePickerOpen, setImagePickerOpen] = useState(false);
const [imagePickerTarget, setImagePickerTarget] = useState<ImagePickerTarget>('rich');
const [codeBlockDialogOpen, setCodeBlockDialogOpen] = useState(false);
const [codeBlockTarget, setCodeBlockTarget] = useState<CodeBlockTarget>('rich');
const [codeBlockEditing, setCodeBlockEditing] = useState(false);
@@ -256,6 +239,11 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
openOnClick: false,
autolink: true,
defaultProtocol: 'https',
// 新标签由全站设置在展示层处理,编辑器不写 target/rel
HTMLAttributes: {
target: null,
rel: null,
},
}),
ArticleImage.configure({ inline: false, allowBase64: false }),
ImageGroup,
@@ -274,9 +262,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
},
includeChildren: true,
}),
MembersOnly,
ReplyOnly,
PointsOnly,
...(enableContentGates ? [MembersOnly, ReplyOnly, PointsOnly] : []),
TabIndent,
],
content: sanitizeHtml(value) || '',
@@ -389,14 +375,33 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
const openLinkDialog = useCallback((target: LinkTarget) => {
if (target === 'rich') {
if (!editor) return;
const prev = editor.getAttributes('link').href as string | undefined;
setLinkDialogUrl(prev ?? '');
const { from, to, empty } = editor.state.selection;
let text = empty ? '' : editor.state.doc.textBetween(from, to, '');
let href = '';
let editing = false;
if (editor.isActive('link')) {
const attrs = editor.getAttributes('link');
href = (attrs.href as string) || '';
editing = Boolean(href);
editor.chain().focus().extendMarkRange('link').run();
const sel = editor.state.selection;
text = editor.state.doc.textBetween(sel.from, sel.to, '') || text;
}
setLinkDialogUrl(href);
setLinkDialogText(text);
setLinkDialogEditing(editing);
} else {
const textarea = markdownRef.current;
const selected = textarea
? markdownSource.slice(textarea.selectionStart, textarea.selectionEnd)
: '';
setLinkDialogUrl('');
setLinkDialogText(selected);
setLinkDialogEditing(false);
}
setLinkTarget(target);
setLinkDialogOpen(true);
}, [editor]);
}, [editor, markdownSource]);
const openCodeBlockDialog = useCallback((target: CodeBlockTarget) => {
setCodeBlockTarget(target);
@@ -473,11 +478,12 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
}
}, [editor]);
const applyLink = useCallback((url: string) => {
const applyLink = useCallback((payload: ArticleLinkConfirm) => {
const { url, text } = payload;
if (linkTarget === 'markdown') {
const textarea = markdownRef.current;
if (!textarea || !url) return;
insertMarkdownLink(textarea, markdownSource, url, handleMarkdownChange);
insertMarkdownLink(textarea, markdownSource, url, handleMarkdownChange, { text });
return;
}
if (!editor) return;
@@ -485,7 +491,31 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
editor.chain().focus().extendMarkRange('link').unsetLink().run();
return;
}
editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
// 新标签行为由全站 open_content_links_in_new_tab 在展示层处理
const linkAttrs = { href: url };
const { empty } = editor.state.selection;
const hasLink = editor.isActive('link');
if (!empty || hasLink) {
editor.chain().focus().extendMarkRange('link').setLink(linkAttrs).run();
const { from, to } = editor.state.selection;
const current = editor.state.doc.textBetween(from, to, '');
if (text && current !== text) {
editor.chain().focus().insertContentAt(
{ from, to },
{
type: 'text',
text,
marks: [{ type: 'link', attrs: linkAttrs }],
},
).run();
}
return;
}
editor.chain().focus().insertContent({
type: 'text',
text: text || '链接文字',
marks: [{ type: 'link', attrs: linkAttrs }],
}).run();
}, [editor, linkTarget, markdownSource, handleMarkdownChange]);
const removeLink = useCallback(() => {
@@ -493,16 +523,33 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
editor.chain().focus().extendMarkRange('link').unsetLink().run();
}, [editor]);
const setImage = useCallback(async () => {
if (!editor) return;
const urls = await uploadPostImageFiles(true);
const openImagePicker = useCallback((target: ImagePickerTarget) => {
setImagePickerTarget(target);
setImagePickerOpen(true);
}, []);
const applyImageUrls = useCallback((urls: string[]) => {
if (!urls.length) return;
if (imagePickerTarget === 'markdown') {
const textarea = markdownRef.current;
if (!textarea) return;
if (urls.length === 1) {
insertAtCursor(textarea, markdownSource, `\n\n![图片](${urls[0]})\n\n`, handleMarkdownChange);
return;
}
const layout = suggestImageGroupLayout(urls.length);
const imgs = urls.map(u => `<img src="${u}" alt="">`).join('');
const block = `\n\n<div data-image-group data-layout="${layout}" class="image-group image-group--${layout}">${imgs}</div>\n\n`;
insertAtCursor(textarea, markdownSource, block, handleMarkdownChange);
return;
}
if (!editor) return;
if (urls.length === 1) {
editor.chain().focus().setImage({ src: urls[0] }).run();
return;
}
editor.chain().focus().insertImageGroup(urls, suggestImageGroupLayout(urls.length)).run();
}, [editor]);
}, [editor, imagePickerTarget, markdownSource, handleMarkdownChange]);
const setImageDisplay = useCallback((display: ImageDisplay) => {
if (!editor) return;
@@ -592,21 +639,6 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
fn(textarea, markdownSource, handleMarkdownChange);
}, [markdownSource, handleMarkdownChange]);
const insertMarkdownImage = useCallback(async () => {
const textarea = markdownRef.current;
if (!textarea) return;
const urls = await uploadPostImageFiles(true);
if (!urls.length) return;
if (urls.length === 1) {
insertAtCursor(textarea, markdownSource, `\n\n![图片](${urls[0]})\n\n`, handleMarkdownChange);
return;
}
const layout = suggestImageGroupLayout(urls.length);
const imgs = urls.map(u => `<img src="${u}" alt="">`).join('');
const block = `\n\n<div data-image-group data-layout="${layout}" class="image-group image-group--${layout}">${imgs}</div>\n\n`;
insertAtCursor(textarea, markdownSource, block, handleMarkdownChange);
}, [markdownSource, handleMarkdownChange]);
const markdownPreviewHtml = useMemo(
() => sanitizeHtml(markdownToHtml(markdownSource)),
[markdownSource],
@@ -633,9 +665,9 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
{ icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: () => openLinkDialog('rich') },
{
icon: <ImageIcon size={15} />,
title: '上传图片',
hint: '可多选;多张自动并排成图组',
action: setImage,
title: '图片',
hint: '上传、链接或从已上传中选择',
action: () => openImagePicker('rich'),
},
{
icon: <Columns2 size={15} />,
@@ -698,6 +730,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
);
}
if (enableContentGates) {
tools.push(
{
icon: <LockKeyhole size={15} />,
@@ -724,11 +757,13 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
action: wrapPointsOnly,
},
);
}
return tools;
}, [editor, openLinkDialog, openCodeBlockDialog, openTableDialog, setImage, wrapMembersOnly, wrapReplyOnly, wrapPointsOnly, wrapSelectedAsGroup, setImageDisplay]);
}, [editor, enableContentGates, openLinkDialog, openCodeBlockDialog, openTableDialog, openImagePicker, wrapMembersOnly, wrapReplyOnly, wrapPointsOnly, wrapSelectedAsGroup, setImageDisplay]);
const buildMarkdownTools = useCallback((): ToolBtn[] => [
const buildMarkdownTools = useCallback((): ToolBtn[] => {
const tools: ToolBtn[] = [
{ icon: <strong>H</strong>, title: '标题', hint: 'H2 → H6 循环', action: withMarkdown(cycleMarkdownHeading) },
{ icon: <Bold size={15} />, title: '加粗', action: withMarkdown((ta, v, ch) => wrapMarkdownSelection(ta, v, '**', '**', '加粗文字', ch)) },
{ icon: <Italic size={15} />, title: '斜体', action: withMarkdown((ta, v, ch) => wrapMarkdownSelection(ta, v, '*', '*', '斜体文字', ch)) },
@@ -741,7 +776,15 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
{ icon: <Code size={15} />, title: '代码块', hint: '语言、行号与折叠', action: () => openCodeBlockDialog('markdown') },
{ icon: <TableIcon size={15} />, title: '表格', hint: '插入 GFM 管道表', action: () => openTableDialog('markdown') },
{ icon: <LinkIcon size={15} />, title: '链接', action: () => openLinkDialog('markdown') },
{ icon: <ImageIcon size={15} />, title: '上传图片', action: insertMarkdownImage },
{
icon: <ImageIcon size={15} />,
title: '图片',
hint: '上传、链接或从已上传中选择',
action: () => openImagePicker('markdown'),
},
];
if (enableContentGates) {
tools.push(
{
icon: <LockKeyhole size={15} />,
title: '登录可见',
@@ -756,7 +799,17 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
className: 'article-tool-btn--reply',
action: withMarkdown(insertMarkdownReplyOnly),
},
], [withMarkdown, openLinkDialog, openCodeBlockDialog, openTableDialog, insertMarkdownImage]);
{
icon: <Coins size={15} />,
title: '积分可见',
hint: '插入 <points-only> 区块',
className: 'article-tool-btn--points',
action: withMarkdown(insertMarkdownPointsOnly),
},
);
}
return tools;
}, [enableContentGates, withMarkdown, openLinkDialog, openCodeBlockDialog, openTableDialog, openImagePicker]);
const tools = mode === 'rich' ? buildRichTools() : buildMarkdownTools();
const words = mode === 'markdown'
@@ -877,8 +930,15 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
open={linkDialogOpen}
onOpenChange={setLinkDialogOpen}
initialUrl={linkDialogUrl}
initialText={linkDialogText}
editing={linkDialogEditing}
onConfirm={applyLink}
onRemove={linkTarget === 'rich' && linkDialogUrl ? removeLink : undefined}
onRemove={linkTarget === 'rich' && linkDialogEditing ? removeLink : undefined}
/>
<ArticleImagePickerDialog
open={imagePickerOpen}
onOpenChange={setImagePickerOpen}
onInsert={applyImageUrls}
/>
<ArticleCodeBlockDialog
open={codeBlockDialogOpen}

View File

@@ -0,0 +1,106 @@
import { CalendarCheck, Check, Gift, Loader2 } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useCheckIn } from '../hooks/useCheckIn';
import { useAuth } from '../hooks/useAuth';
import { loginPath } from '../utils/authRedirect';
/** 右侧栏首块底部:每日签到 */
export default function AsideCheckInStrip() {
const nav = useNavigate();
const { user, loading: authLoading } = useAuth();
const { status, loading, busy, doCheckIn } = useCheckIn(!!user && !authLoading);
// 鉴权未完成且无种子:空白,避免访客签到卡闪一下再消失
// 有 SSR boot 时 loading 一开始就是 false
if (authLoading) {
return null;
}
if (!user) {
return (
<div className="widget-checkin">
<div className="widget-checkin-panel widget-checkin-panel--guest">
<div className="widget-checkin-main">
<div className="widget-checkin-icon" aria-hidden>
<CalendarCheck size={18} strokeWidth={2.25} />
</div>
<div className="widget-checkin-info">
<span className="widget-checkin-title">每日签到</span>
<span className="widget-checkin-meta">登录后每日可得 5–15 积分</span>
</div>
</div>
<button
type="button"
className="widget-checkin-action"
onClick={() => nav(loginPath())}
>
<Gift size={15} aria-hidden />
登录签到
</button>
</div>
</div>
);
}
// 登录用户:status 未到齐前不渲染最终态
if (loading || !status) {
return null;
}
const checkedIn = !!status.checked_in;
const streak = status.streak ?? 0;
const todayPoints = status.today_points ?? 5;
const meta = checkedIn
? (streak > 0 ? `连续 ${streak} 天 · 今日已获得 ${todayPoints} 积分` : `今日已获得 ${todayPoints} 积分`)
: (streak > 0 ? `连续 ${streak} 天 · 今日可得 ${todayPoints} 积分` : `今日签到可得 ${todayPoints} 积分`);
return (
<div className="widget-checkin">
<div
className={`widget-checkin-panel${checkedIn ? ' widget-checkin-panel--done' : ''}`}
>
<div className="widget-checkin-main">
<div className="widget-checkin-icon" aria-hidden>
{checkedIn ? (
<Check size={18} strokeWidth={2.5} />
) : (
<CalendarCheck size={18} strokeWidth={2.25} />
)}
</div>
<div className="widget-checkin-info">
<span className="widget-checkin-title">
{checkedIn ? '今日已签到' : '每日签到'}
</span>
<span className="widget-checkin-meta">{meta}</span>
</div>
{!checkedIn && (
<span className="widget-checkin-reward" aria-hidden>
{todayPoints}
</span>
)}
</div>
{!checkedIn && (
<button
type="button"
className="widget-checkin-action"
disabled={busy}
onClick={doCheckIn}
>
{busy ? (
<>
<Loader2 size={15} className="widget-checkin-action-spinner animate-spin" aria-hidden />
签到中…
</>
) : (
<>
<Gift size={15} aria-hidden />
立即签到
</>
)}
</button>
)}
</div>
</div>
);
}

View File

@@ -30,6 +30,7 @@ export default function CommentBox({ user, replyTo, inline, submitting, submitCo
const [content, setContent] = useState('');
const [isPrivate, setIsPrivate] = useState(false);
const editorRef = useRef<CommentEditorHandle>(null);
const prevSubmitCountRef = useRef<number>(submitCount);
useEffect(() => {
if (inline && replyTo) {
@@ -38,6 +39,9 @@ export default function CommentBox({ user, replyTo, inline, submitting, submitCo
}, [replyTo?.id, inline]);
useEffect(() => {
// 跳过首次挂载,仅在 submitCount 真正变化(评论成功提交)时清空并聚焦
if (prevSubmitCountRef.current === submitCount) return;
prevSubmitCountRef.current = submitCount;
setContent('');
setIsPrivate(false);
editorRef.current?.focus();

View File

@@ -8,15 +8,15 @@ import Placeholder from '@tiptap/extension-placeholder';
import Underline from '@tiptap/extension-underline';
import DOMPurify from 'dompurify';
import {
Bold, Italic, Underline as UnderlineIcon, Strikethrough, Quote,
Bold, Italic, Underline as UnderlineIcon, Strikethrough,
List, ListOrdered, Code, Link as LinkIcon, Image as ImageIcon,
} from 'lucide-react';
import { POST_CONTENT_PURIFY_CONFIG } from '../utils/postContent';
import { api } from '../api/client';
import { notify } from '@/lib/notify';
import { ArticleCodeBlock } from './editor/ArticleCodeBlockExtension';
import { ArticleCodeBlockDialog } from './editor/ArticleCodeBlockDialog';
import { ArticleImage } from './editor/ArticleImageExtension';
import { ArticleImagePickerDialog } from './editor/ArticleImagePickerDialog';
import { ArticleLinkDialog, type ArticleLinkConfirm } from './editor/ArticleLinkDialog';
import { TabIndent } from './editor/TabIndentExtension';
import type { CodeBlockInsertOptions } from '../utils/codeBlockOptions';
import { Tooltip } from './ui/Tooltip';
@@ -26,7 +26,7 @@ import type { Sticker } from '../data/stickers';
export interface CommentEditorHandle {
getHTML: () => string;
isEmpty: () => boolean;
focus: () => void;
focus: (options?: { preventScroll?: boolean }) => void;
}
interface Props {
@@ -49,28 +49,6 @@ function isEditorEmpty(editor: Editor): boolean {
return !hasImage;
}
/** 触发图片文件选择并上传 */
async function uploadImageFiles(): Promise<string[]> {
return new Promise(resolve => {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/jpeg,image/png,image/gif,image/webp';
input.multiple = false;
input.onchange = async () => {
const files = [...(input.files ?? [])];
if (!files.length) { resolve([]); return; }
try {
const { url } = await api.uploadPostImage(files[0]);
resolve([url]);
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '图片上传失败');
resolve([]);
}
};
input.click();
});
}
const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEditor(
{ value, onChange, placeholder = '说点什么吧…' },
ref,
@@ -79,6 +57,11 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
const lastValueRef = useRef(value);
const [, setTick] = useState(0);
const [showSticker, setShowSticker] = useState(false);
const [imagePickerOpen, setImagePickerOpen] = useState(false);
const [linkDialogOpen, setLinkDialogOpen] = useState(false);
const [linkDialogUrl, setLinkDialogUrl] = useState('');
const [linkDialogText, setLinkDialogText] = useState('');
const [linkDialogEditing, setLinkDialogEditing] = useState(false);
const [codeBlockDialogOpen, setCodeBlockDialogOpen] = useState(false);
const [codeBlockEditing, setCodeBlockEditing] = useState(false);
const [codeBlockInitial, setCodeBlockInitial] = useState<CodeBlockInsertOptions | null>(null);
@@ -99,6 +82,11 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
openOnClick: false,
autolink: true,
defaultProtocol: 'https',
// 新标签由全站设置在展示层处理,编辑器不写 target/rel
HTMLAttributes: {
target: null,
rel: null,
},
}),
ArticleImage.configure({ inline: true, allowBase64: true }),
Placeholder.configure({ placeholder }),
@@ -160,7 +148,7 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
useImperativeHandle(ref, () => ({
getHTML: () => editor ? sanitizeHtml(editor.getHTML()) : value,
isEmpty: () => editor ? isEditorEmpty(editor) : !value.trim(),
focus: () => { editor?.commands.focus(); },
focus: (options?: { preventScroll?: boolean }) => { editor?.commands.focus(options); },
}), [editor, value]);
const insertSticker = useCallback((sticker: Sticker) => {
@@ -179,11 +167,14 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
setShowSticker(false);
}, [editor]);
const setImage = useCallback(async () => {
if (!editor) return;
const urls = await uploadImageFiles();
if (!urls.length) return;
editor.chain().focus().setImage({ src: urls[0] }).run();
const applyImageUrls = useCallback((urls: string[]) => {
if (!editor || !urls.length) return;
// 评论为 inline 图,无图组:逐张插入并跟空格,便于光标落在右侧
const nodes = urls.flatMap(src => [
{ type: 'image' as const, attrs: { src } },
{ type: 'text' as const, text: ' ' },
]);
editor.chain().focus().insertContent(nodes).run();
}, [editor]);
const openCodeBlockDialog = useCallback(() => {
@@ -213,44 +204,85 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
}).run();
}, [editor]);
const setLink = useCallback(() => {
const openLinkDialog = useCallback(() => {
if (!editor) return;
const prev = editor.getAttributes('link').href as string | undefined;
const url = window.prompt('链接地址', prev ?? 'https://');
if (url === null) return;
const { from, to, empty } = editor.state.selection;
let text = empty ? '' : editor.state.doc.textBetween(from, to, '');
let href = '';
let editing = false;
if (editor.isActive('link')) {
const attrs = editor.getAttributes('link');
href = (attrs.href as string) || '';
editing = Boolean(href);
editor.chain().focus().extendMarkRange('link').run();
const sel = editor.state.selection;
text = editor.state.doc.textBetween(sel.from, sel.to, '') || text;
}
setLinkDialogUrl(href);
setLinkDialogText(text);
setLinkDialogEditing(editing);
setLinkDialogOpen(true);
}, [editor]);
const applyLink = useCallback((payload: ArticleLinkConfirm) => {
if (!editor) return;
const { url, text } = payload;
if (!url) {
editor.chain().focus().extendMarkRange('link').unsetLink().run();
return;
}
editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
// 新标签行为由全站 open_content_links_in_new_tab 在展示层处理
const linkAttrs = { href: url };
const { empty } = editor.state.selection;
const hasLink = editor.isActive('link');
if (!empty || hasLink) {
editor.chain().focus().extendMarkRange('link').setLink(linkAttrs).run();
const { from, to } = editor.state.selection;
const current = editor.state.doc.textBetween(from, to, '');
if (text && current !== text) {
editor.chain().focus().insertContentAt(
{ from, to },
{
type: 'text',
text,
marks: [{ type: 'link', attrs: linkAttrs }],
},
).run();
}
return;
}
editor.chain().focus().insertContent({
type: 'text',
text: text || '链接文字',
marks: [{ type: 'link', attrs: linkAttrs }],
}).run();
}, [editor]);
const removeLink = useCallback(() => {
if (!editor) return;
editor.chain().focus().extendMarkRange('link').unsetLink().run();
}, [editor]);
if (!editor) {
return <div className="comment-editor"><div className="article-editor-bar" /><div className="article-editor-body" /></div>;
}
const tools: { icon: React.ReactNode; title: string; active?: boolean; action: () => void }[] = [
{ icon: <strong>H</strong>, title: '标题', active: editor.isActive('heading'), action: () => {
for (let l = 2; l <= 4; l++) {
if (editor.isActive('heading', { level: l })) {
if (l === 4) editor.chain().focus().setParagraph().run();
else editor.chain().focus().toggleHeading({ level: (l + 1) as 2 | 3 | 4 }).run();
return;
}
}
editor.chain().focus().toggleHeading({ level: 2 }).run();
}},
const tools: { icon: React.ReactNode; title: string; hint?: string; active?: boolean; action: () => void; className?: string }[] = [
{ icon: <Bold size={15} />, title: '加粗', active: editor.isActive('bold'), action: () => editor.chain().focus().toggleBold().run() },
{ icon: <Italic size={15} />, title: '斜体', active: editor.isActive('italic'), action: () => editor.chain().focus().toggleItalic().run() },
{ icon: <UnderlineIcon size={15} />, title: '下划线', active: editor.isActive('underline'), action: () => editor.chain().focus().toggleUnderline().run() },
{ icon: <Strikethrough size={15} />, title: '删除线', active: editor.isActive('strike'), action: () => editor.chain().focus().toggleStrike().run() },
{ icon: <Quote size={15} />, title: '引用', active: editor.isActive('blockquote'), action: () => editor.chain().focus().toggleBlockquote().run() },
{ icon: <List size={15} />, title: '无序列表', active: editor.isActive('bulletList'), action: () => editor.chain().focus().toggleBulletList().run() },
{ icon: <ListOrdered size={15} />, title: '有序列表', active: editor.isActive('orderedList'), action: () => editor.chain().focus().toggleOrderedList().run() },
{ icon: <Code size={15} />, title: '代码块', active: editor.isActive('codeBlock'), action: openCodeBlockDialog },
{ icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: setLink },
{ icon: <ImageIcon size={15} />, title: '上传图片', action: setImage },
{ icon: <span className="article-tool-btn__owo">OwO</span>, title: '表情 OwO', active: showSticker, action: () => setShowSticker(v => !v) },
{ icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: openLinkDialog },
{
icon: <ImageIcon size={15} />,
title: '图片',
hint: '上传、链接或从已上传中选择',
action: () => setImagePickerOpen(true),
},
{ icon: <span className="article-tool-btn__owo">OwO</span>, title: '表情 OwO', active: showSticker, action: () => setShowSticker(v => !v), className: 'article-tool-btn--owo' },
];
return (
@@ -258,14 +290,14 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
<div className="article-editor-bar">
<div className="article-editor-tools">
{tools.map((t, i) => (
<Tooltip key={i} content={t.title} side="bottom">
<Tooltip key={i} content={t.title} hint={t.hint} side="bottom">
<button
ref={i === tools.length - 1 ? stickerBtnRef : undefined}
type="button"
className={`article-tool-btn${t.active ? ' active' : ''}`}
className={`article-tool-btn${t.active ? ' active' : ''}${t.className ? ` ${t.className}` : ''}`}
onMouseDown={e => e.preventDefault()}
onClick={t.action}
aria-label={t.title}
aria-label={t.hint ? `${t.title},${t.hint}` : t.title}
>
{t.icon}
</button>
@@ -279,6 +311,20 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
</div>
</div>
{showSticker && <StickerPicker onSelect={insertSticker} />}
<ArticleLinkDialog
open={linkDialogOpen}
onOpenChange={setLinkDialogOpen}
initialUrl={linkDialogUrl}
initialText={linkDialogText}
editing={linkDialogEditing}
onConfirm={applyLink}
onRemove={linkDialogEditing ? removeLink : undefined}
/>
<ArticleImagePickerDialog
open={imagePickerOpen}
onOpenChange={setImagePickerOpen}
onInsert={applyImageUrls}
/>
<ArticleCodeBlockDialog
open={codeBlockDialogOpen}
onOpenChange={setCodeBlockDialogOpen}

View File

@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react';
import {
Check, Clock, History, MessageSquare, X, Pencil, Trash2,
Check, Award, Clock, History, MessageSquare, X, Pencil, Trash2,
ThumbsUp, MoreHorizontal, Flag,
} from 'lucide-react';
import type { ReactNode } from 'react';
@@ -18,7 +18,6 @@ import {
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import {
Dialog,
@@ -32,6 +31,8 @@ import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Button } from '@/components/ui/button';
@@ -51,6 +52,7 @@ import { isHtmlEmpty } from '../utils/postContent';
import { Tooltip } from './ui/Tooltip';
import UserLink from './UserLink';
import { cn } from '@/lib/utils';
import { pinAwardedCommentTree } from '../utils/bounty';
function isCommentAuthor(c: Comment, user?: User | null): boolean {
return !!user && c.user_id > 0 && c.user_id === user.id;
@@ -83,6 +85,13 @@ interface ItemProps {
onRequireLogin?: (actionLabel: string) => void;
onLikeUpdate?: (commentId: number, liked: boolean, likeCount: number) => void;
renderReplyBox?: (comment: Comment) => ReactNode;
bountyAward?: {
open: boolean;
awardedCommentId?: number;
postAuthorId: number;
canAward: boolean;
onAward: (commentId: number) => void;
};
}
/** 单条评论(支持嵌套子回复 + 内联回复框 + 编辑/删除) */
@@ -103,12 +112,14 @@ function CommentItem({
onRequireLogin,
onLikeUpdate,
renderReplyBox,
bountyAward,
}: ItemProps) {
const { limits } = useForumLimits();
const c = node.comment;
const nick = commentNick(c);
const guest = isGuestComment(c);
const isHighlighted = highlightFloor === c.floor;
const isBountyAwarded = bountyAward?.awardedCommentId === c.id;
const hidden = !!c.content_hidden;
const isReplying = replyToId === c.id;
const isEditing = editingId === c.id;
@@ -134,6 +145,11 @@ function CommentItem({
&& !!onApprove;
const showEdited = !hidden && !!c.updated_at && isTimeDiffSignificant(c.created_at, c.updated_at);
const canReport = !hidden && !isEditing && !isCommentAuthor(c, currentUser);
const showHistory = isAdmin && showEdited;
const showManageMenu = !hidden && !isEditing && (
canApprove || canEdit || showHistory || canDelete || canReport
);
const showManageGroup = canApprove || canEdit || showHistory || canDelete;
const [editText, setEditText] = useState(c.content);
const [saving, setSaving] = useState(false);
const [deleting, setDeleting] = useState(false);
@@ -142,6 +158,7 @@ function CommentItem({
const [liked, setLiked] = useState(!!c.liked);
const [likeCount, setLikeCount] = useState(c.like_count ?? 0);
const [revOpen, setRevOpen] = useState(false);
const [deleteOpen, setDeleteOpen] = useState(false);
const [reportOpen, setReportOpen] = useState(false);
const [reportReason, setReportReason] = useState<ReportReason>('spam');
const [reportDetail, setReportDetail] = useState('');
@@ -215,14 +232,19 @@ function CommentItem({
return (
<div
id={`floor-${c.floor}`}
className={`waline-comment ${nested ? 'nested' : ''} ${isHighlighted ? 'highlight' : ''}`}
className={cn(
'waline-comment',
nested && 'nested',
isHighlighted && 'highlight',
isBountyAwarded && 'waline-comment--bounty-awarded',
)}
>
{!guest && c.user_id ? (
<UserLink
user={c.user ?? { id: c.user_id, nickname: nick }}
showAvatar={false}
showName={false}
className={`waline-comment-avatar user-link--avatar-only${!c.user?.avatar ? ' guest' : ''}`}
className="waline-comment-avatar user-link--avatar-only"
>
{c.user?.avatar ? (
<img src={c.user.avatar} alt="" loading="lazy" decoding="async" />
@@ -231,7 +253,7 @@ function CommentItem({
)}
</UserLink>
) : (
<div className={`waline-comment-avatar ${!c.user?.avatar ? 'guest' : ''}`}>
<div className={`waline-comment-avatar${!c.user?.avatar ? ' guest' : ''}`}>
{c.user?.avatar ? (
<img src={c.user.avatar} alt="" loading="lazy" decoding="async" />
) : (
@@ -255,6 +277,12 @@ function CommentItem({
) : (
<span className="waline-comment-author">{nick}</span>
)}
{isBountyAwarded && (
<span className="waline-comment-bounty-badge" title="悬赏已采纳">
<Check size={12} aria-hidden />
已采纳
</span>
)}
{!hidden && (
<button
type="button"
@@ -312,24 +340,6 @@ function CommentItem({
{c.reply_target && (
<span className="waline-reply-at">@{commentNick(c.reply_target)}</span>
)}
{!hidden && !isEditing && canApprove && (
<button
type="button"
className="waline-comment-reply-btn waline-comment-approve-btn"
disabled={approving}
onClick={async () => {
setApproving(true);
try {
await onApprove?.(c);
} finally {
setApproving(false);
}
}}
>
<Check size={14} />
{approving ? '通过中…' : '通过'}
</button>
)}
{!hidden && !isEditing && !!renderReplyBox && (
isReplying ? (
<button type="button" className="waline-comment-reply-btn cancel" onClick={onCancelReply}>
@@ -345,52 +355,18 @@ function CommentItem({
</Tooltip>
)
)}
{!hidden && !isEditing && canEdit && (
<button type="button" className="waline-comment-reply-btn" onClick={() => onStartEdit(c)}>
<Pencil size={14} />
编辑
</button>
)}
{!hidden && !isEditing && isAdmin && showEdited && (
<button type="button" className="waline-comment-reply-btn" onClick={() => setRevOpen(true)}>
<History size={14} />
编辑记录
</button>
)}
{!hidden && !isEditing && canDelete && (
<AlertDialog>
<AlertDialogTrigger asChild>
<button type="button" className="waline-comment-reply-btn cancel" disabled={deleting}>
<Trash2 size={14} />
删除
</button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>确定删除该评论?</AlertDialogTitle>
<AlertDialogDescription>
将同时移入回收站其下所有回复,可在后台恢复或永久删除。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>取消</AlertDialogCancel>
<AlertDialogAction
onClick={async () => {
setDeleting(true);
try {
await onDelete(c);
} finally {
setDeleting(false);
}
}}
{bountyAward?.open && bountyAward.canAward && c.user_id !== bountyAward.postAuthorId
&& c.status === 'published' && !hidden && (
<button
type="button"
className="bounty-award-btn"
onClick={() => bountyAward.onAward(c.id)}
>
删除
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Award size={14} aria-hidden />
采纳
</button>
)}
{canReport && (
{showManageMenu && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
@@ -401,19 +377,98 @@ function CommentItem({
<MoreHorizontal size={14} />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="center" className="report-more-menu">
<DropdownMenuContent align="end" className="comment-manage-menu">
{showManageGroup && (
<>
<DropdownMenuLabel>管理</DropdownMenuLabel>
{canApprove && (
<DropdownMenuItem
className="report-more-menu__item"
disabled={approving}
onSelect={() => {
void (async () => {
setApproving(true);
try {
await onApprove?.(c);
} finally {
setApproving(false);
}
})();
}}
>
<Check size={14} aria-hidden />
{approving ? '通过中…' : '通过审核'}
</DropdownMenuItem>
)}
{canEdit && (
<DropdownMenuItem onSelect={() => onStartEdit(c)}>
<Pencil size={14} aria-hidden />
编辑
</DropdownMenuItem>
)}
{showHistory && (
<DropdownMenuItem onSelect={() => setRevOpen(true)}>
<History size={14} aria-hidden />
编辑记录
</DropdownMenuItem>
)}
{canDelete && (
<DropdownMenuItem
className="text-destructive focus:text-destructive"
disabled={deleting}
onSelect={() => setDeleteOpen(true)}
>
<Trash2 size={14} aria-hidden />
删除
</DropdownMenuItem>
)}
{canReport && <DropdownMenuSeparator />}
</>
)}
{canReport && (
<DropdownMenuItem
className="text-destructive focus:text-destructive"
onSelect={openReport}
>
<Flag size={14} />
<Flag size={14} aria-hidden />
举报
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>确定删除该评论?</AlertDialogTitle>
<AlertDialogDescription>
将同时移入回收站其下所有回复,可在后台恢复或永久删除。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleting}>取消</AlertDialogCancel>
<AlertDialogAction
disabled={deleting}
onClick={(e) => {
e.preventDefault();
void (async () => {
setDeleting(true);
try {
await onDelete(c);
setDeleteOpen(false);
} finally {
setDeleting(false);
}
})();
}}
>
删除
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{isAdmin && (
<CommentRevisionDialog open={revOpen} onOpenChange={setRevOpen} comment={c} />
)}
@@ -481,6 +536,7 @@ function CommentItem({
onRequireLogin={onRequireLogin}
onLikeUpdate={onLikeUpdate}
renderReplyBox={renderReplyBox}
bountyAward={bountyAward}
/>
))}
</div>
@@ -506,6 +562,7 @@ interface Props {
onRequireLogin?: (actionLabel: string) => void;
onLikeUpdate?: (commentId: number, liked: boolean, likeCount: number) => void;
renderReplyBox?: (comment: Comment) => ReactNode;
bountyAward?: ItemProps['bountyAward'];
}
/** Waline 嵌套楼层评论列表 */
@@ -525,8 +582,12 @@ export default function CommentThreadList({
onRequireLogin,
onLikeUpdate,
renderReplyBox,
bountyAward,
}: Props) {
const tree = buildCommentTree(comments);
const tree = pinAwardedCommentTree(
buildCommentTree(comments),
bountyAward?.awardedCommentId,
);
return (
<div className="comment-thread-list">
@@ -548,6 +609,7 @@ export default function CommentThreadList({
onRequireLogin={onRequireLogin}
onLikeUpdate={onLikeUpdate}
renderReplyBox={renderReplyBox}
bountyAward={bountyAward}
/>
))}
</div>

View File

@@ -1,4 +1,4 @@
import { Sparkles } from 'lucide-react';
import { BadgeCheck } from 'lucide-react';
import { cn } from '@/lib/utils';
interface Props {
@@ -6,13 +6,13 @@ interface Props {
size?: number;
}
/** 精华帖标识 */
/** 推荐帖标识 */
export default function FeaturedIcon({ className, size = 16 }: Props) {
return (
<Sparkles
<BadgeCheck
className={cn('post-featured-icon', className)}
size={size}
aria-label="精华"
aria-label="推荐"
role="img"
/>
);

View File

@@ -1,94 +1,51 @@
import { Users, FileText, LayoutGrid } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import type { Board, ForumStats } from '../api/types';
import { navigateFeed } from '../utils/feedCache';
interface Props {
boardId: number;
keyword: string;
tag?: string;
author?: string;
titleOnly?: boolean;
boards: Board[];
stats: ForumStats | null;
postTotal: number;
/** 搜索页用 h1;首页/板块页中间栏不再展示标题 */
titleAs?: 'h1' | 'h2';
}
export default function FeedHeader({
boardId,
keyword,
tag = '',
author = '',
titleOnly = false,
boards,
stats,
postTotal,
titleAs = 'h1',
}: Props) {
const nav = useNavigate();
const board = boards.find(b => b.id === boardId);
const filtered = !!(keyword || tag || author);
const inBoard = !filtered && boardId > 0 && !!board;
/** 侧栏已有「全部帖子 / 板块名」,中间栏不再重复;仅搜索/标签保留标题 */
let title = '';
if (tag) title = `标签:${tag}`;
else if (keyword || author) {
const parts: string[] = [];
if (keyword) parts.push(titleOnly ? `标题含「${keyword}」` : `搜索:${keyword}`);
if (author) parts.push(`作者 ${author}`);
if (boardId && board) parts.push(`板块 ${board.name}`);
title = parts.join(' · ');
}
const isSearch = !!(keyword || author);
const isTag = !!tag;
const filtered = isSearch || isTag;
const TitleTag = titleAs;
let title = '';
if (isTag) title = `标签:${tag}`;
else if (isSearch) title = '搜索结果';
// 无标题且无操作时不占位
if (!filtered) return null;
return (
<div className={`feed-head${filtered ? ' feed-head--solo' : ' feed-head--stats-only'}`}>
<div className="feed-head feed-head--solo">
<div className="feed-head__title">
{title ? <TitleTag>{title}</TitleTag> : null}
{!filtered && inBoard && (
<div className="feed-head__stats">
<span className="feed-stat-chip">
<FileText aria-hidden />
本板块 <strong>{postTotal}</strong> 帖
</span>
{stats && (
<span className="feed-stat-chip feed-stat-chip--muted" title="全站统计">
全站 {stats.posts} 帖 · {stats.users} 会员
</span>
)}
<span className="feed-head__meta feed-head__meta--count">共 {postTotal} 条</span>
</div>
)}
{!filtered && !inBoard && stats && (
<div className="feed-head__stats">
<span className="feed-stat-chip">
<Users aria-hidden />
会员 <strong>{stats.users}</strong>
</span>
<span className="feed-stat-chip">
<FileText aria-hidden />
帖子 <strong>{stats.posts}</strong>
</span>
<span className="feed-stat-chip">
<LayoutGrid aria-hidden />
板块 <strong>{stats.boards}</strong>
</span>
</div>
)}
</div>
{filtered && (
{isTag && (
<button
type="button"
className="feed-head__clear"
onClick={() => nav('/')}
onClick={() => navigateFeed(nav, '/')}
>
{tag ? '清除标签' : '清除搜索'}
清除标签
</button>
)}
{filtered && (
<span className="feed-toolbar__count">共 {postTotal} 条</span>
)}
</div>
);
}

View File

@@ -1,35 +0,0 @@
import { Skeleton } from '@/components/ui/skeleton';
import PostListSkeleton from './PostListSkeleton';
/** 首页 Feed 初始骨架(标题区 + 排序栏 + 列表) */
export default function FeedPageSkeleton() {
return (
<div className="page-wrap page-wrap--feed" aria-busy="true" aria-label="内容加载中">
<div className="feed-panel">
<div className="feed-top">
<div className="feed-top__bar">
<div className="feed-head feed-head--stats-only">
<div className="feed-head__title">
<div className="feed-head__stats">
<Skeleton className="skeleton--stat-chip" />
<Skeleton className="skeleton--stat-chip" />
<Skeleton className="skeleton--stat-chip" />
</div>
</div>
</div>
<div className="feed-toolbar feed-toolbar--skeleton" aria-hidden>
<Skeleton className="skeleton--sort-tab" />
<Skeleton className="skeleton--sort-tab" />
<Skeleton className="skeleton--sort-tab" />
<span className="feed-toolbar__spacer" />
<Skeleton className="skeleton--count" />
</div>
</div>
</div>
<div className="post-list-scroll">
<PostListSkeleton />
</div>
</div>
</div>
);
}

View File

@@ -1,39 +1,57 @@
import { useRef } from 'react';
import { Clock, MessageCircle, Flame } from 'lucide-react';
import { useMemo, useRef } from 'react';
import { useParams, useSearchParams } from 'react-router-dom';
import { boardPath, parsePermalinkID, type PermalinkOpts } from '../utils/permalink';
import { getCachedForumLimits, useForumLimits } from '../hooks/useForumLimits';
import { Clock, MessageCircle, BadgeCheck, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { moveTabIndex } from '../hooks/useOverlayA11y';
import {
enabledFeedSortTabs,
getDefaultFeedSort,
normalizeFeedSortTabs,
} from '../utils/feedSortTabs';
import type { FeedSortTab } from '../api/types';
export type FeedSort = 'latest' | 'reply' | 'hot';
const SORT_OPTIONS: {
key: FeedSort;
label: string;
hint: string;
icon: typeof Clock;
}[] = [
{ key: 'latest', label: '最新发帖', hint: '按发布时间', icon: Clock },
{ key: 'reply', label: '最新回复', hint: '最近有人回复', icon: MessageCircle },
{ key: 'hot', label: '热门讨论', hint: '按互动热度', icon: Flame },
];
const SORT_META: Record<FeedSort, { hint: string; icon: typeof Clock }> = {
reply: { hint: '按最近活动(发帖或评论)', icon: MessageCircle },
latest: { hint: '按发帖时间', icon: Clock },
hot: { hint: '仅展示推荐帖', icon: BadgeCheck },
};
interface Props {
value: FeedSort;
onChange: (sort: FeedSort) => void;
postTotal?: number;
/** 正在加载、尚未提交到画面的目标排序 */
pendingValue?: FeedSort | null;
}
export function parseFeedSort(raw: string | null): FeedSort {
if (raw === 'reply' || raw === 'hot') return raw;
return 'latest';
/** 当前配置下的默认排序(读缓存,供非 hook 路径) */
export function getDefaultFeedSortFromCache(): FeedSort {
return getDefaultFeedSort(getCachedForumLimits().feed_sort_tabs);
}
/** 解析 URL sort;未启用或不合法时回落默认 */
export function parseFeedSort(raw: string | null, tabs?: FeedSortTab[] | null): FeedSort {
const list = tabs ?? getCachedForumLimits().feed_sort_tabs;
const def = getDefaultFeedSort(list);
if (raw === 'latest' || raw === 'hot' || raw === 'reply') {
const enabled = enabledFeedSortTabs(list).some(t => t.id === raw);
if (enabled) return raw;
}
return def;
}
export function buildHomeUrl(
boardId: number,
sort: FeedSort = 'latest',
opts?: { keyword?: string; tag?: string; author?: string; titleOnly?: boolean },
sort?: FeedSort,
opts?: { keyword?: string; tag?: string; author?: string; titleOnly?: boolean; permalink?: PermalinkOpts },
) {
const def = getDefaultFeedSortFromCache();
const effective = sort ?? def;
const p = new URLSearchParams();
if (boardId) p.set('board', String(boardId));
const tag = opts?.tag?.trim();
const keyword = opts?.keyword?.trim();
const author = opts?.author?.trim();
@@ -46,30 +64,76 @@ export function buildHomeUrl(
} else if (author) {
p.set('author', author);
}
if (sort !== 'latest') p.set('sort', sort);
// 默认排序不写进 URL
if (effective !== def) p.set('sort', effective);
const qs = p.toString();
if (boardId) {
const base = boardPath(boardId, opts?.permalink ?? getCachedForumLimits());
return qs ? `${base}?${qs}` : base;
}
return qs ? `/?${qs}` : '/';
}
export function feedSortLabel(sort: FeedSort): string {
return SORT_OPTIONS.find(o => o.key === sort)?.label ?? '帖子列表';
export function feedSortLabel(sort: FeedSort, tabs?: FeedSortTab[] | null): string {
const list = normalizeFeedSortTabs(tabs ?? getCachedForumLimits().feed_sort_tabs);
return list.find(t => t.id === sort)?.label ?? '帖子列表';
}
export default function FeedSortBar({ value, onChange, postTotal }: Props) {
export default function FeedSortBar({
value,
onChange,
postTotal,
pendingValue,
}: Props) {
const { limits } = useForumLimits();
const { id: boardRouteId } = useParams();
const [params] = useSearchParams();
// 与 SSR href / HomePage 一致:从路由与查询串解析板块与筛选
const boardId = boardRouteId
? (() => {
const id = parsePermalinkID(boardRouteId);
return Number.isFinite(id) && id > 0 ? id : 0;
})()
: (Number(params.get('board')) || 0);
const keyword = params.get('keyword') || '';
const tag = params.get('tag') || '';
const author = params.get('author') || '';
const titleOnly = params.get('title_only') === '1';
const options = useMemo(
() => enabledFeedSortTabs(limits.feed_sort_tabs).map(t => ({
key: t.id as FeedSort,
label: t.label,
hint: SORT_META[t.id]?.hint ?? '',
icon: SORT_META[t.id]?.icon ?? Clock,
href: buildHomeUrl(boardId, t.id as FeedSort, {
keyword,
tag,
author,
titleOnly,
permalink: limits,
}),
})),
[limits, boardId, keyword, tag, author, titleOnly],
);
const listRef = useRef<HTMLDivElement>(null);
const activeIndex = Math.max(0, SORT_OPTIONS.findIndex(o => o.key === value));
const activeIndex = Math.max(0, options.findIndex(o => o.key === value));
const onKeyDown = (e: React.KeyboardEvent) => {
const next = moveTabIndex(e.key, activeIndex, SORT_OPTIONS.length);
const next = moveTabIndex(e.key, activeIndex, options.length);
if (next == null) return;
e.preventDefault();
onChange(SORT_OPTIONS[next].key);
onChange(options[next].key);
requestAnimationFrame(() => {
const tabs = listRef.current?.querySelectorAll<HTMLElement>('[role="tab"]');
tabs?.[next]?.focus();
});
};
if (options.length === 0) return null;
return (
<div className="feed-toolbar">
<div
@@ -79,21 +143,30 @@ export default function FeedSortBar({ value, onChange, postTotal }: Props) {
aria-label="帖子排序"
onKeyDown={onKeyDown}
>
{SORT_OPTIONS.map(({ key, label, hint, icon: Icon }, i) => (
<button
{options.map(({ key, label, hint, icon: Icon, href }, i) => {
const pending = pendingValue === key;
return (
<a
key={key}
type="button"
href={href}
role="tab"
tabIndex={activeIndex === i ? 0 : -1}
aria-selected={value === key}
aria-busy={pending || undefined}
title={`${label} · ${hint}`}
className={cn('feed-sort-tab', value === key && 'active')}
onClick={() => onChange(key)}
className={cn('feed-sort-tab', value === key && 'active', pending && 'is-pending')}
onClick={(e) => {
e.preventDefault();
onChange(key);
}}
>
<Icon aria-hidden />
{pending
? <Loader2 className="feed-sort-tab__spin" aria-hidden />
: <Icon aria-hidden />}
<span className="feed-sort-tab__label">{label}</span>
</button>
))}
</a>
);
})}
</div>
{postTotal != null && (
<span className="feed-toolbar__count">共 {postTotal} 条</span>

View File

@@ -0,0 +1,284 @@
import { useEffect, useRef, useState } from 'react';
import { Link2, Upload } from 'lucide-react';
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/ui/spinner';
import { notify } from '@/lib/notify';
import { cn } from '@/lib/utils';
import { api } from '../api/client';
import type { FriendLinkApply } from '../api/types';
import { getCachedSiteBranding } from '../hooks/useSiteBranding';
import { resolveFriendLinkLogo } from '../utils/friendLink';
import FriendLinkSiteInfo from './FriendLinkSiteInfo';
type LinkPlacement = 'homepage' | 'custom';
interface Props {
open: boolean;
onOpenChange: (open: boolean) => void;
editApply?: FriendLinkApply | null;
onSubmitted?: () => void;
}
/** 友链申请 / 修改弹窗 */
export default function FriendLinkApplyDialog({ open, onOpenChange, editApply, onSubmitted }: Props) {
const [name, setName] = useState('');
const [url, setUrl] = useState('');
const [logo, setLogo] = useState('');
const [linkPlacement, setLinkPlacement] = useState<LinkPlacement>('homepage');
const [reciprocalPageURL, setReciprocalPageURL] = useState('');
const [submitting, setSubmitting] = useState(false);
const [uploadingLogo, setUploadingLogo] = useState(false);
const fileRef = useRef<HTMLInputElement>(null);
const isEdit = !!editApply?.id;
const reset = () => {
setName('');
setUrl('');
setLogo('');
setLinkPlacement('homepage');
setReciprocalPageURL('');
};
useEffect(() => {
if (!open) return;
if (editApply) {
setName(editApply.name ?? '');
setUrl(editApply.url ?? '');
setLogo(editApply.logo ?? '');
const onHomepage = editApply.link_on_homepage !== false;
setLinkPlacement(onHomepage ? 'homepage' : 'custom');
setReciprocalPageURL(onHomepage ? '' : (editApply.reciprocal_page_url ?? ''));
} else {
reset();
}
}, [open, editApply]);
const handleOpenChange = (next: boolean) => {
if (!next) reset();
onOpenChange(next);
};
const uploadLogo = async (file: File | undefined) => {
if (!file) return;
setUploadingLogo(true);
try {
const r = await api.uploadFriendLinkLogo(file);
setLogo(r.url);
notify.success('LOGO 已上传');
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '上传失败');
} finally {
setUploadingLogo(false);
if (fileRef.current) fileRef.current.value = '';
}
};
const submit = async () => {
const trimmedName = name.trim();
const trimmedURL = url.trim();
const trimmedLogo = logo.trim();
const trimmedReciprocal = reciprocalPageURL.trim();
if (!trimmedName || !trimmedURL) {
notify.warning('请填写网站名称与网站链接');
return;
}
if (!/^https?:\/\//i.test(trimmedURL)) {
notify.warning('网站链接需以 http:// 或 https:// 开头');
return;
}
if (!trimmedLogo) {
notify.warning('请填写或上传网站 LOGO');
return;
}
if (linkPlacement === 'custom') {
if (!trimmedReciprocal) {
notify.warning('请填写添加本站链接的页面地址');
return;
}
if (!/^https?:\/\//i.test(trimmedReciprocal)) {
notify.warning('回链页地址需以 http:// 或 https:// 开头');
return;
}
}
const linkOnHomepage = linkPlacement === 'homepage';
const body = {
name: trimmedName,
url: trimmedURL,
logo: trimmedLogo,
link_on_homepage: linkOnHomepage,
reciprocal_page_url: linkOnHomepage ? trimmedURL : trimmedReciprocal,
};
setSubmitting(true);
try {
if (isEdit) {
const r = await api.updateFriendLinkApply(editApply!.id, body);
notify.success(
editApply?.status === 'approved'
? `已更新并重新提交审核,友链已暂时从列表移除${r.message.includes('回链检测') ? ',回链检测将在后台进行' : ''}`
: r.message,
);
} else {
const r = await api.applyFriendLink(body);
notify.success(r.message);
}
onSubmitted?.();
handleOpenChange(false);
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '提交失败');
} finally {
setSubmitting(false);
}
};
const logoPreview = resolveFriendLinkLogo(logo.trim(), getCachedSiteBranding().site_url);
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="friend-link-apply-dialog sm:max-w-[560px]">
<DialogHeader className="friend-link-apply-dialog__header">
<DialogTitle>{isEdit ? '修改友链申请' : '申请本页友情链接'}</DialogTitle>
</DialogHeader>
<FriendLinkSiteInfo />
<div className="friend-link-apply-form">
<div className="friend-link-apply-field">
<Label htmlFor="friend-link-name">网站名称</Label>
<Input
id="friend-link-name"
value={name}
onChange={e => setName(e.target.value)}
placeholder="请输入您的网站名称"
maxLength={32}
/>
</div>
<div className="friend-link-apply-field">
<Label htmlFor="friend-link-url">网站链接</Label>
<Input
id="friend-link-url"
value={url}
onChange={e => setUrl(e.target.value)}
placeholder="请输入您的网站地址(以 http 开头)"
maxLength={512}
/>
</div>
<div className="friend-link-apply-field">
<Label>本站链接放置位置</Label>
<div className="friend-link-apply-placement" role="radiogroup" aria-label="本站链接放置位置">
<button
type="button"
role="radio"
aria-checked={linkPlacement === 'homepage'}
className={cn(
'friend-link-apply-placement__option',
linkPlacement === 'homepage' && 'friend-link-apply-placement__option--active',
)}
onClick={() => setLinkPlacement('homepage')}
>
友链在我的网站首页
</button>
<div
className={cn(
'friend-link-apply-placement__custom',
linkPlacement === 'custom' && 'friend-link-apply-placement__custom--open',
)}
>
<button
type="button"
role="radio"
aria-checked={linkPlacement === 'custom'}
className={cn(
'friend-link-apply-placement__option',
linkPlacement === 'custom' && 'friend-link-apply-placement__option--active',
)}
onClick={() => setLinkPlacement('custom')}
>
友链在其它页面
</button>
<div className="friend-link-apply-placement__custom-panel" aria-hidden={linkPlacement !== 'custom'}>
<div className="friend-link-apply-placement__custom-inner">
<Label htmlFor="friend-link-reciprocal">添加我方链接的页面地址</Label>
<Input
id="friend-link-reciprocal"
value={reciprocalPageURL}
onChange={e => setReciprocalPageURL(e.target.value)}
placeholder="如:https://您的域名/link.htm"
maxLength={512}
tabIndex={linkPlacement === 'custom' ? 0 : -1}
/>
<p className="friend-link-apply-field__hint">
请填写实际放置本站友链的页面,提交后将在后台检测该页面
</p>
</div>
</div>
</div>
</div>
</div>
<div className="friend-link-apply-field">
<Label htmlFor="friend-link-logo">填写或上传网站 LOGO</Label>
<div className="friend-link-apply-logo-row">
<div className="friend-link-apply-logo-preview" aria-label="LOGO 预览">
{logoPreview ? (
<img src={logoPreview} alt="" loading="lazy" decoding="async" />
) : (
<span>预览</span>
)}
</div>
<Input
id="friend-link-logo"
className="friend-link-apply-logo-input"
value={logo}
onChange={e => setLogo(e.target.value)}
placeholder="LOGO 图片地址"
maxLength={512}
/>
<input
ref={fileRef}
type="file"
accept="image/jpeg,image/png,image/gif,image/webp"
className="sr-only"
onChange={e => uploadLogo(e.target.files?.[0])}
/>
<Button
type="button"
variant="outline"
className="friend-link-apply-logo-upload"
disabled={uploadingLogo}
onClick={() => fileRef.current?.click()}
>
{uploadingLogo ? <Spinner size="sm" /> : <Upload size={15} aria-hidden />}
上传
</Button>
</div>
</div>
</div>
<DialogFooter className="friend-link-apply-dialog__footer">
<p className="friend-link-apply-dialog__note">
<Link2 size={14} aria-hidden />
提交后立即返回,回链检测在后台进行,结果供管理员参考
</p>
<div className="friend-link-apply-dialog__actions">
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)}>
取消
</Button>
<Button type="button" disabled={submitting || uploadingLogo} onClick={submit}>
{submitting ? '提交中…' : isEdit ? '保存并提交' : '提交申请'}
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,44 @@
import { useSiteBranding } from '../hooks/useSiteBranding';
function resolveSiteURL(siteURL?: string): string {
const fromApi = siteURL?.trim();
if (fromApi) return fromApi;
if (typeof window !== 'undefined') return window.location.origin;
return '';
}
function resolveSiteLogoURL(logo?: string, favicon?: string, siteURL?: string): string {
const raw = logo?.trim() || favicon?.trim() || '';
if (!raw) return '';
if (/^https?:\/\//i.test(raw)) return raw;
const base = resolveSiteURL(siteURL);
if (!base) return raw;
return raw.startsWith('/') ? `${base}${raw}` : `${base}/${raw}`;
}
/** 申请弹窗内:本站友链信息(名称 / 地址 / LOGO 链接) */
export default function FriendLinkSiteInfo() {
const { branding } = useSiteBranding();
const siteURL = resolveSiteURL(branding.site_url);
const siteLogoURL = resolveSiteLogoURL(branding.logo, branding.favicon, branding.site_url);
return (
<section className="friend-link-site-info" aria-label="本站友链信息">
<h3 className="friend-link-site-info__title">本站信息(请添加本站链接后再申请)</h3>
<dl className="friend-link-site-info__list">
<div className="friend-link-site-info__item">
<dt>名称</dt>
<dd>{branding.name}</dd>
</div>
<div className="friend-link-site-info__item">
<dt>地址</dt>
<dd>{siteURL || '—'}</dd>
</div>
<div className="friend-link-site-info__item">
<dt>LOGO</dt>
<dd>{siteLogoURL || '—'}</dd>
</div>
</dl>
</section>
);
}

View File

@@ -1,4 +1,4 @@
import { useEffect } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { X } from 'lucide-react';
import { createPortal } from 'react-dom';
@@ -9,8 +9,72 @@ interface Props {
onClose: () => void;
}
/** 帖子正文图片灯箱:展示原图,点击遮罩 / Esc / 关闭按钮退出 */
const MIN_SCALE = 1;
const MAX_SCALE = 4;
function touchDistance(a: Touch, b: Touch) {
const dx = a.clientX - b.clientX;
const dy = a.clientY - b.clientY;
return Math.hypot(dx, dy);
}
function touchMidpoint(a: Touch, b: Touch) {
return {
x: (a.clientX + b.clientX) / 2,
y: (a.clientY + b.clientY) / 2,
};
}
function clampScale(s: number) {
return Math.min(MAX_SCALE, Math.max(MIN_SCALE, s));
}
/** 帖子正文图片灯箱:展示原图,支持双指缩放 / 拖动,点击遮罩 / Esc / 关闭按钮退出 */
export default function ImageLightbox({ src, alt = '', open, onClose }: Props) {
const [scale, setScale] = useState(1);
const [tx, setTx] = useState(0);
const [ty, setTy] = useState(0);
const [settling, setSettling] = useState(false);
const scaleRef = useRef(1);
const txRef = useRef(0);
const tyRef = useRef(0);
const pinchRef = useRef<{
startDist: number;
startScale: number;
startTx: number;
startTy: number;
midX: number;
midY: number;
} | null>(null);
const panRef = useRef<{
startX: number;
startY: number;
startTx: number;
startTy: number;
} | null>(null);
const stageRef = useRef<HTMLDivElement>(null);
const applyTransform = useCallback((nextScale: number, nextTx: number, nextTy: number) => {
scaleRef.current = nextScale;
txRef.current = nextTx;
tyRef.current = nextTy;
setScale(nextScale);
setTx(nextTx);
setTy(nextTy);
}, []);
const resetTransform = useCallback((animate = false) => {
if (animate) setSettling(true);
applyTransform(1, 0, 0);
}, [applyTransform]);
useEffect(() => {
if (!open) return;
resetTransform(false);
setSettling(false);
}, [open, src, resetTransform]);
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
@@ -25,6 +89,111 @@ export default function ImageLightbox({ src, alt = '', open, onClose }: Props) {
};
}, [open, onClose]);
// 原生非 passive 监听,才能在 pinch/pan 时 preventDefault
useEffect(() => {
if (!open) return;
const el = stageRef.current;
if (!el) return;
const onTouchStart = (e: TouchEvent) => {
setSettling(false);
if (e.touches.length === 2) {
const a = e.touches[0];
const b = e.touches[1];
const mid = touchMidpoint(a, b);
pinchRef.current = {
startDist: touchDistance(a, b) || 1,
startScale: scaleRef.current,
startTx: txRef.current,
startTy: tyRef.current,
midX: mid.x,
midY: mid.y,
};
panRef.current = null;
return;
}
if (e.touches.length === 1 && scaleRef.current > 1.01) {
panRef.current = {
startX: e.touches[0].clientX,
startY: e.touches[0].clientY,
startTx: txRef.current,
startTy: tyRef.current,
};
}
};
const onTouchMove = (e: TouchEvent) => {
if (e.touches.length === 2 && pinchRef.current) {
if (e.cancelable) e.preventDefault();
const a = e.touches[0];
const b = e.touches[1];
const dist = touchDistance(a, b) || 1;
const nextScale = clampScale(
pinchRef.current.startScale * (dist / pinchRef.current.startDist),
);
const mid = touchMidpoint(a, b);
applyTransform(
nextScale,
pinchRef.current.startTx + (mid.x - pinchRef.current.midX),
pinchRef.current.startTy + (mid.y - pinchRef.current.midY),
);
return;
}
if (e.touches.length === 1 && panRef.current && scaleRef.current > 1.01) {
if (e.cancelable) e.preventDefault();
const dx = e.touches[0].clientX - panRef.current.startX;
const dy = e.touches[0].clientY - panRef.current.startY;
applyTransform(
scaleRef.current,
panRef.current.startTx + dx,
panRef.current.startTy + dy,
);
}
};
const onTouchEnd = (e: TouchEvent) => {
if (e.touches.length < 2) pinchRef.current = null;
if (e.touches.length === 0) {
panRef.current = null;
if (scaleRef.current <= 1.05) resetTransform(true);
}
};
const onWheel = (e: WheelEvent) => {
if (!(e.ctrlKey || e.metaKey)) return;
e.preventDefault();
setSettling(false);
const delta = -e.deltaY * 0.01;
const next = clampScale(scaleRef.current * (1 + delta));
if (next <= 1.01) {
resetTransform(true);
return;
}
applyTransform(next, txRef.current, tyRef.current);
};
el.addEventListener('touchstart', onTouchStart, { passive: false });
el.addEventListener('touchmove', onTouchMove, { passive: false });
el.addEventListener('touchend', onTouchEnd);
el.addEventListener('touchcancel', onTouchEnd);
el.addEventListener('wheel', onWheel, { passive: false });
return () => {
el.removeEventListener('touchstart', onTouchStart);
el.removeEventListener('touchmove', onTouchMove);
el.removeEventListener('touchend', onTouchEnd);
el.removeEventListener('touchcancel', onTouchEnd);
el.removeEventListener('wheel', onWheel);
};
}, [open, applyTransform, resetTransform]);
const handleBackdropClick = useCallback(() => {
if (scaleRef.current > 1.01) {
resetTransform(true);
return;
}
onClose();
}, [onClose, resetTransform]);
if (!open || !src) return null;
return createPortal(
@@ -33,7 +202,7 @@ export default function ImageLightbox({ src, alt = '', open, onClose }: Props) {
type="button"
className="image-lightbox-backdrop"
aria-label="关闭"
onClick={onClose}
onClick={handleBackdropClick}
/>
<button
type="button"
@@ -43,15 +212,20 @@ export default function ImageLightbox({ src, alt = '', open, onClose }: Props) {
>
<X size={20} aria-hidden />
</button>
<div className="image-lightbox-stage">
<div ref={stageRef} className="image-lightbox-stage">
<img
src={src}
alt={alt || '原图'}
className="image-lightbox-img"
className={`image-lightbox-img${settling ? ' image-lightbox-img--settling' : ''}`}
decoding="async"
draggable={false}
style={{ transform: `translate3d(${tx}px, ${ty}px, 0) scale(${scale})` }}
onTransitionEnd={() => setSettling(false)}
onClick={e => e.stopPropagation()}
/>
</div>
<p className="image-lightbox-hint">点击空白处关闭</p>
<p className="image-lightbox-hint image-lightbox-hint--desktop">点击空白处关闭</p>
<p className="image-lightbox-hint image-lightbox-hint--mobile">双指缩放 · 点击空白关闭</p>
</div>,
document.body,
);

View File

@@ -6,7 +6,7 @@ type PageLoaderProps = {
fullScreen?: boolean;
};
/** 通用路由懒加载占位;首页请用 FeedPageSkeleton,避免非 Feed 页闪出鱼骨骨架 */
/** 通用路由懒加载占位(后台 / 全屏独立页);前台 MainLayout 用顶栏进度条 + 空白 */
export default function PageLoader({ fullScreen = false }: PageLoaderProps) {
return (
<div

View File

@@ -9,7 +9,6 @@ import { useAuth } from '../hooks/useAuth';
import { loginPath } from '../utils/authRedirect';
import { formatTime } from '../utils/content';
import { userPath } from '../utils/userPath';
import ComposeMessageDialog from './ComposeMessageDialog';
import UserLink from './UserLink';
interface Props {
@@ -28,7 +27,6 @@ export default function PostAuthorCard({
const { user: me } = useAuth();
const [profile, setProfile] = useState<UserPublic | null>(null);
const [stats, setStats] = useState<UserActivityStats | null>(null);
const [msgOpen, setMsgOpen] = useState(false);
useEffect(() => {
if (!author?.id) {
@@ -78,7 +76,7 @@ export default function PostAuthorCard({
nav(loginPath(profileHref));
return;
}
setMsgOpen(true);
nav(`/messages?peer=${author.id}`);
};
return (
@@ -159,16 +157,6 @@ export default function PostAuthorCard({
</Button>
</div>
</div>
{!isSelf && (
<ComposeMessageDialog
open={msgOpen}
onOpenChange={setMsgOpen}
toUserId={author.id}
toNickname={nick}
onSent={() => nav(`/messages?peer=${author.id}`)}
/>
)}
</div>
);
}

View File

@@ -0,0 +1,182 @@
import { useState } from 'react';
import { CheckCircle2, Coins } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { notify } from '@/lib/notify';
import { api } from '../api/client';
import type { PostItem } from '../api/types';
interface Props {
post: PostItem;
isOwnerOrAdmin: boolean;
isAdmin?: boolean;
/** 是否可取消悬赏(楼主有他人回复时为 false;管理员为 true) */
canRefund?: boolean;
refundBlockReason?: string;
eligibleReplyCount?: number;
onUpdate?: () => void;
/** 跳转到被采纳的评论楼层 */
onJumpToAwarded?: () => void;
/** 被采纳评论是否仍在当前评论列表中 */
canJumpToAwarded?: boolean;
}
/** 悬赏帖状态卡 */
export default function PostBountyBanner({
post,
isOwnerOrAdmin,
isAdmin = false,
canRefund = true,
refundBlockReason,
eligibleReplyCount = 0,
onUpdate,
onJumpToAwarded,
canJumpToAwarded,
}: Props) {
const [refundOpen, setRefundOpen] = useState(false);
const [refunding, setRefunding] = useState(false);
if (post.post_type !== 'bounty') return null;
const points = post.bounty_points ?? 0;
const open = post.bounty_status === 'open' && points > 0;
const awarded = post.bounty_status === 'awarded';
const refunded = post.bounty_status === 'refunded';
if (refunded && !isOwnerOrAdmin) return null;
const showRefundButton = isOwnerOrAdmin && canRefund;
const ownerRefundBlocked = isOwnerOrAdmin && !isAdmin && !canRefund;
const confirmRefund = async () => {
setRefunding(true);
try {
await api.bountyRefund(post.id);
notify.success('悬赏已退回');
setRefundOpen(false);
onUpdate?.();
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '操作失败');
} finally {
setRefunding(false);
}
};
const refundDialogDescription = isAdmin && eligibleReplyCount > 0
? `将强制取消悬赏并把 ${points} 积分退回楼主账户。当前已有 ${eligibleReplyCount} 条他人回复,请确认已审慎处理。`
: `确定取消悬赏并将 ${points} 积分退回你的账户?取消后他人将无法再参与本帖悬赏。`;
if (open) {
let ownerHint = '在评论上点击「采纳」发放积分';
if (ownerRefundBlocked) {
ownerHint = refundBlockReason || '已有用户回复,请从评论中采纳发放积分';
}
return (
<>
<section className="post-bounty post-bounty--open" aria-label="悬赏">
<div className="post-bounty__head">
<div className="post-bounty__lead">
<Coins size={18} className="post-bounty__icon" aria-hidden />
<div className="post-bounty__titles">
<strong className="post-bounty__title">悬赏进行中</strong>
<span className="post-bounty__points">{points} 积分</span>
</div>
</div>
{showRefundButton && (
<div className="post-bounty__actions">
<Button type="button" variant="outline" size="sm" onClick={() => setRefundOpen(true)}>
取消悬赏
</Button>
</div>
)}
</div>
<p className="post-bounty__hint">
{isOwnerOrAdmin
? ownerHint
: `回复本帖,优质回答可获得这 ${points} 积分`}
</p>
</section>
{showRefundButton && (
<AlertDialog
open={refundOpen}
onOpenChange={(next) => { if (!next && !refunding) setRefundOpen(false); }}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{isAdmin && eligibleReplyCount > 0 ? '强制取消悬赏?' : '取消悬赏?'}</AlertDialogTitle>
<AlertDialogDescription>
{refundDialogDescription}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={refunding}>返回</AlertDialogCancel>
<AlertDialogAction
disabled={refunding}
onClick={(e) => {
e.preventDefault();
void confirmRefund();
}}
>
{refunding ? '退回中…' : '确认取消'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)}
</>
);
}
if (awarded) {
return (
<section className="post-bounty post-bounty--awarded" aria-label="悬赏已采纳">
<div className="post-bounty__head">
<div className="post-bounty__lead">
<CheckCircle2 size={18} className="post-bounty__icon" aria-hidden />
<div className="post-bounty__titles">
<strong className="post-bounty__title">已采纳</strong>
<span className="post-bounty__subtitle">
{points} 积分已发放给被采纳的回复
</span>
</div>
</div>
</div>
{canJumpToAwarded && onJumpToAwarded && (
<div className="post-bounty__actions post-bounty__actions--inline">
<button type="button" className="post-bounty__jump" onClick={onJumpToAwarded}>
查看被采纳的回复
</button>
</div>
)}
</section>
);
}
if (refunded) {
return (
<section className="post-bounty post-bounty--refunded" aria-label="悬赏已退回">
<div className="post-bounty__head">
<div className="post-bounty__lead">
<Coins size={18} className="post-bounty__icon" aria-hidden />
<div className="post-bounty__titles">
<strong className="post-bounty__title">悬赏已取消</strong>
<span className="post-bounty__subtitle">积分已退回</span>
</div>
</div>
</div>
</section>
);
}
return null;
}

View File

@@ -1,7 +1,6 @@
import { useMemo, useCallback, useEffect, useState } from 'react';
import { useMemo, useCallback, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { renderPostContentHtml } from '../utils/postContent';
import { extractHeadingsFromHtml, type PostHeading } from '../utils/postHeadings';
import { loginPath, registerPath } from '../utils/authRedirect';
import { useForumLimits } from '../hooks/useForumLimits';
import { notify } from '@/lib/notify';
@@ -12,8 +11,6 @@ interface Props {
html: string;
isLoggedIn: boolean;
className?: string;
/** 正文标题树变化时回调(用于侧栏目录) */
onHeadingsChange?: (headings: PostHeading[]) => void;
/** 点击「回复可见」门控的「去回复」 */
onRequestReply?: () => void;
/** 积分解锁成功后刷新正文 */
@@ -26,7 +23,6 @@ export default function PostContent({
html,
isLoggedIn,
className = 'post-detail-content',
onHeadingsChange,
onRequestReply,
onUnlocked,
postId: postIdProp,
@@ -39,19 +35,12 @@ export default function PostContent({
const [lightboxAlt, setLightboxAlt] = useState('');
const [unlocking, setUnlocking] = useState(false);
const prepared = useMemo(() => {
const rendered = renderPostContentHtml(html, isLoggedIn, {
const preparedHtml = useMemo(
() => renderPostContentHtml(html, isLoggedIn, {
openLinksInNewTab: limits.open_content_links_in_new_tab,
});
return {
html: rendered,
headings: extractHeadingsFromHtml(rendered),
};
}, [html, isLoggedIn, limits.open_content_links_in_new_tab]);
useEffect(() => {
onHeadingsChange?.(prepared.headings);
}, [prepared.headings, onHeadingsChange]);
}),
[html, isLoggedIn, limits.open_content_links_in_new_tab],
);
const openLightbox = useCallback((img: HTMLImageElement) => {
const full = img.getAttribute('data-full') || img.currentSrc || img.src;
@@ -167,7 +156,7 @@ export default function PostContent({
className={className}
onClick={handleClick}
onKeyDown={handleKeyDown}
dangerouslySetInnerHTML={{ __html: prepared.html }}
dangerouslySetInnerHTML={{ __html: preparedHtml }}
/>
<ImageLightbox
src={lightboxSrc}

View File

@@ -1,37 +1,48 @@
import { memo } from 'react';
import { useNavigate } from 'react-router-dom';
import { Eye, Image as ImageIcon, MessageCircle, ThumbsUp } from 'lucide-react';
import { MessageCircle } from 'lucide-react';
import BoardBadge from '@/components/BoardBadge';
import FeaturedIcon from '@/components/FeaturedIcon';
import UserLink from '@/components/UserLink';
import type { PostItem } from '../api/types';
import type { FeedSort } from './FeedSortBar';
import { useForumLimits } from '../hooks/useForumLimits';
import { formatTime } from '../utils/content';
import { postPath } from '../utils/permalink';
import { boardPath, postPath } from '../utils/permalink';
import { toPostImageThumbSrc } from '../utils/postContent';
import { excerptFromHTML, firstImageFromHTML } from '../utils/seoText';
import { parseTags } from './TagInput';
interface Props {
post: PostItem;
sort?: FeedSort;
/** 当前板块 id,>0 时隐藏行内板块色标(避免板块页重复) */
boardId?: number;
onSelect: (id: number) => void;
}
function PostListItem({ post, sort = 'latest', onSelect }: Props) {
function PostListItem({ post, sort = 'latest', boardId = 0, onSelect }: Props) {
const nav = useNavigate();
const { limits } = useForumLimits();
const feedStyle = limits.feed_list_style ?? 'title';
const showExcerpt = feedStyle === 'excerpt' || feedStyle === 'thumbnail';
const showThumb = feedStyle === 'thumbnail';
const titleOnly = feedStyle === 'title';
const initial = post.user?.nickname?.[0] || '?';
const timeLabel = sort === 'reply'
? (post.last_reply_at
? `${formatTime(post.last_reply_at)} 回复`
: '暂无回复')
const timeLabel = sort === 'reply' && !post.last_reply_at
? '暂无回复'
: formatTime(post.created_at);
const lastReplyName = post.last_reply_user?.nickname?.trim()
|| post.last_reply_user?.username?.trim()
|| post.last_reply_guest_nick?.trim()
|| '';
const showLastReply = !!post.last_reply_at && (!!post.last_reply_user || !!lastReplyName);
const commentCount = post.comment_count ?? 0;
const likeCount = post.like_count ?? 0;
const viewCount = post.view_count ?? 0;
const href = postPath(post.id);
const excerpt = excerptFromHTML(post.content || '', 72);
const hasImage = !!firstImageFromHTML(post.content || '');
const tagList = parseTags(post.tags || '').slice(0, 3);
const firstImage = firstImageFromHTML(post.content || '');
const thumbSrc = showThumb && firstImage ? toPostImageThumbSrc(firstImage) : null;
const excerpt = showExcerpt ? excerptFromHTML(post.content || '', 60) : '';
const showBoardBadge = !!post.board && boardId !== post.board.id;
const openPost = () => onSelect(post.id);
const onKeyDown = (e: React.KeyboardEvent) => {
@@ -41,7 +52,6 @@ function PostListItem({ post, sort = 'latest', onSelect }: Props) {
}
};
const onTitleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
// 修饰键 / 非左键:交给浏览器(新标签等)
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
e.stopPropagation();
return;
@@ -51,9 +61,116 @@ function PostListItem({ post, sort = 'latest', onSelect }: Props) {
openPost();
};
const hasTypeBadge = post.post_type === 'question'
|| post.post_type === 'poll'
|| post.post_type === 'lottery'
|| (post.post_type === 'bounty' && (
(post.bounty_status === 'open' && (post.bounty_points ?? 0) > 0)
|| post.bounty_status === 'awarded'
));
const titleRow = (
<div className="post-title-row">
{post.pinned && (
<span className="post-pin-badge" title="全局置顶">全局置顶</span>
)}
{post.board_pinned && (
<span className="post-pin-badge post-pin-badge--board" title="板块置顶">板块置顶</span>
)}
{post.featured && (
<span className="post-feature-badge" title="推荐">
<FeaturedIcon size={12} />
推荐
</span>
)}
{post.status === 'pending' && (
<span className="post-status-badge post-status-badge--pending" title="审核中">审核中</span>
)}
{post.status === 'rejected' && (
<span className="post-status-badge post-status-badge--rejected" title="未通过">未通过</span>
)}
<a href={href} className="post-title" onClick={onTitleClick}>
{post.title}
</a>
{/* 类型徽章放标题后:flex 自动扣宽,长标题省略号紧挨徽章左侧 */}
{hasTypeBadge && (
<span className="post-title-type-badges">
{post.post_type === 'question' && (
<span
className={`post-qa-badge${post.question_resolved ? ' post-qa-badge--resolved' : ' post-qa-badge--open'}`}
title={post.question_resolved ? '已解决' : '未解决'}
>
{post.question_resolved ? '已解决' : '未解决'}
</span>
)}
{post.post_type === 'poll' && (
<span className="post-type-badge post-type-badge--poll" title="投票">投票</span>
)}
{post.post_type === 'bounty' && post.bounty_status === 'open' && (post.bounty_points ?? 0) > 0 && (
<span className="post-bounty-badge post-bounty-badge--open" title="悬赏">悬赏 {post.bounty_points}</span>
)}
{post.post_type === 'bounty' && post.bounty_status === 'awarded' && (
<span className="post-bounty-badge post-bounty-badge--awarded" title="已采纳">已采纳</span>
)}
{post.post_type === 'lottery' && (
<span className="post-type-badge post-type-badge--lottery" title="抽奖">
{post.lottery_status === 'drawn' ? '已开奖' : '抽奖'}
</span>
)}
</span>
)}
</div>
);
const metaLeft = (
<div className="post-meta-left">
{showBoardBadge && post.board && (
<button
type="button"
className="post-list-board-btn"
title={`进入板块:${post.board.name}`}
onClick={(e) => {
e.stopPropagation();
nav(boardPath(post.board!.id, limits));
}}
>
<BoardBadge board={post.board} className="post-list-board-badge" />
</button>
)}
<UserLink user={post.user} stopPropagation className="post-meta-author" showBadges={false} />
<span className="post-meta-sep post-meta-sep--before-time" aria-hidden>·</span>
<span className="post-meta-time post-meta-time--created">{timeLabel}</span>
{showLastReply && (
<span className="post-meta-last-reply">
<span className="post-meta-last-reply-arrow" aria-hidden>←</span>
{post.last_reply_user ? (
<UserLink
user={post.last_reply_user}
stopPropagation
className="post-meta-last-reply-user"
showBadges={false}
/>
) : (
<span className="post-meta-last-reply-user">{lastReplyName}</span>
)}
<span className="post-meta-last-reply-time">{formatTime(post.last_reply_at!)}</span>
</span>
)}
</div>
);
const stats = (
<div className="post-stats">
<span className={`post-stat${commentCount === 0 ? ' post-stat--zero' : ''}`} title="评论">
<MessageCircle aria-hidden />
{commentCount}
</span>
</div>
);
return (
<div
className="post-row"
className={`post-row post-row--v2${titleOnly ? ' post-row--title-only' : ''}${thumbSrc ? ' post-row--has-thumb' : ''}`}
role="link"
tabIndex={0}
onClick={openPost}
@@ -71,88 +188,32 @@ function PostListItem({ post, sort = 'latest', onSelect }: Props) {
: initial}
</UserLink>
<div className="post-body">
<div className="post-head">
<div className="post-head-meta">
<UserLink user={post.user} stopPropagation className="post-author" showBadges />
<span className="post-head-dot" aria-hidden>·</span>
<span className="post-time">{timeLabel}</span>
</div>
</div>
<div className="post-title-row">
{post.pinned && (
<span className="post-pin-badge" title="全局置顶">全局置顶</span>
)}
{post.board_pinned && (
<span className="post-pin-badge post-pin-badge--board" title="板块置顶">板块置顶</span>
)}
{post.featured && (
<span className="post-feature-badge" title="精华">
<FeaturedIcon size={12} />
精华
</span>
)}
{post.status === 'pending' && (
<span className="post-status-badge post-status-badge--pending" title="审核中">审核中</span>
)}
{post.status === 'rejected' && (
<span className="post-status-badge post-status-badge--rejected" title="未通过">未通过</span>
)}
{post.post_type === 'question' && (
<span
className={`post-qa-badge${post.question_resolved ? ' post-qa-badge--resolved' : ' post-qa-badge--open'}`}
title={post.question_resolved ? '已解决' : '未解决'}
>
{post.question_resolved ? '已解决' : '未解决'}
</span>
)}
<a href={href} className="post-title" onClick={onTitleClick}>
{post.title}
</a>
</div>
{thumbSrc ? (
<div className="post-main post-main--with-thumb">
<div className="post-content">
{titleRow}
{excerpt && <p className="post-excerpt">{excerpt}</p>}
<div className="post-foot">
<div className="post-foot-left">
{post.board && <BoardBadge board={post.board} />}
{tagList.map(t => (
<button
key={t}
type="button"
className="post-list-tag"
title={`筛选标签:${t}`}
onClick={(e) => {
e.stopPropagation();
nav(`/?tag=${encodeURIComponent(t)}`);
}}
>
{t}
</button>
))}
<div className="post-meta post-meta--inline">{metaLeft}</div>
</div>
<div className="post-aside">
<div className="post-thumb" aria-hidden>
<img src={thumbSrc} alt="" loading="lazy" decoding="async" />
</div>
{stats}
</div>
</div>
) : (
<div className="post-main">
<div className="post-text">
{titleRow}
{excerpt && <p className="post-excerpt">{excerpt}</p>}
</div>
<div className="post-meta">
{metaLeft}
{stats}
</div>
</div>
<div className="post-stats">
{hasImage && (
<span className="post-stat post-stat--media" title="含图片">
<ImageIcon aria-hidden />
</span>
)}
<span className={`post-stat${commentCount === 0 ? ' post-stat--zero' : ''}`} title="评论">
<MessageCircle aria-hidden />
{commentCount}
</span>
<span className={`post-stat${likeCount === 0 ? ' post-stat--zero' : ''}`} title="点赞">
<ThumbsUp aria-hidden />
{likeCount}
</span>
<span className={`post-stat${viewCount === 0 ? ' post-stat--zero' : ''}`} title="浏览">
<Eye aria-hidden />
{viewCount}
</span>
</div>
</div>
</div>
</div>
);
}

View File

@@ -1,37 +1,12 @@
import { Skeleton } from '@/components/ui/skeleton';
import type { ForumLimitsPublic } from '../api/types';
interface Props {
count?: number;
}
export type FeedListStyle = ForumLimitsPublic['feed_list_style'];
/** 帖子列表加载骨架屏(对齐卡片式列表) */
export default function PostListSkeleton({ count = 8 }: Props) {
return (
<div className="post-list-skeleton" aria-busy="true" aria-label="加载中">
{Array.from({ length: count }, (_, i) => (
<div key={i} className="post-row post-row--skeleton">
<Skeleton className="skeleton--avatar" />
<div className="post-body">
<div className="post-head">
<div className="skeleton-meta-row">
<Skeleton className="skeleton--meta" />
<Skeleton className="skeleton--meta skeleton--meta-short" />
</div>
{i % 4 === 0 && <Skeleton className="skeleton--badge" />}
</div>
<Skeleton className="skeleton--title" style={{ width: `${58 + (i % 4) * 9}%` }} />
<Skeleton className="skeleton--excerpt" style={{ width: `${72 + (i % 3) * 8}%` }} />
<div className="post-foot">
<Skeleton className="skeleton--badge" />
<div className="post-stats">
<Skeleton className="skeleton--stat" />
<Skeleton className="skeleton--stat" />
<Skeleton className="skeleton--stat" />
</div>
</div>
</div>
</div>
))}
</div>
);
/** 虚拟列表行高预估值 */
export function feedListRowEstimate(style: FeedListStyle): number {
switch (style) {
case 'excerpt': return 68;
case 'thumbnail': return 72;
default: return 64;
}
}

View File

@@ -0,0 +1,98 @@
import { useState } from 'react';
import { Gift } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { notify } from '@/lib/notify';
import { api } from '../api/client';
import type { PostLotteryView } from '../api/types';
import { userPath } from '../utils/userPath';
interface Props {
postId: number;
lottery: PostLotteryView;
isOwnerOrAdmin: boolean;
onUpdate: (lottery: PostLotteryView) => void;
}
/** 抽奖帖信息卡 */
export default function PostLotteryCard({ postId, lottery, isOwnerOrAdmin, onUpdate }: Props) {
const [drawOpen, setDrawOpen] = useState(false);
const [drawing, setDrawing] = useState(false);
const drawn = lottery.status === 'drawn';
const canDraw = !drawn && isOwnerOrAdmin && lottery.participant_count >= lottery.winner_count;
const confirmDraw = async () => {
setDrawing(true);
try {
const r = await api.postLotteryDraw(postId);
onUpdate(r.lottery);
notify.success('开奖完成');
setDrawOpen(false);
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '开奖失败');
} finally {
setDrawing(false);
}
};
return (
<>
<section className="post-lottery" aria-label="抽奖">
<div className="post-lottery__head">
<Gift size={18} aria-hidden />
<strong>{drawn ? '已开奖' : '抽奖进行中'}</strong>
<span>抽取 {lottery.winner_count} 人 · 当前 {lottery.participant_count} 人参与</span>
</div>
{!drawn && (
<p className="post-lottery__hint">回帖即可参与(楼主除外),由作者或管理员手动开奖</p>
)}
{drawn && lottery.winners && lottery.winners.length > 0 && (
<ul className="post-lottery__winners">
{lottery.winners.map(w => (
<li key={`${w.user_id}-${w.comment_id}`}>
<a href={userPath(w.user_id)}>{w.nickname || w.username}</a>
</li>
))}
</ul>
)}
{canDraw && (
<Button type="button" size="sm" onClick={() => setDrawOpen(true)}>立即开奖</Button>
)}
</section>
<AlertDialog
open={drawOpen}
onOpenChange={(next) => { if (!next && !drawing) setDrawOpen(false); }}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>立即开奖?</AlertDialogTitle>
<AlertDialogDescription>
将从 {lottery.participant_count} 位参与者中抽取 {lottery.winner_count} 名中奖者。此操作不可撤销。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={drawing}>取消</AlertDialogCancel>
<AlertDialogAction
disabled={drawing}
onClick={(e) => {
e.preventDefault();
void confirmDraw();
}}
>
{drawing ? '开奖中…' : '确认开奖'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}

View File

@@ -0,0 +1,189 @@
import {
Ban,
CircleCheck,
CircleHelp,
EllipsisVertical,
History,
Lock,
LockOpen,
MessageSquareOff,
Pencil,
Pin,
Sparkles,
Trash2,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import type { PostItem } from '../api/types';
export interface PostManageMenuProps {
post: PostItem;
isAdmin: boolean;
isOwnerOrAdmin: boolean;
canEdit: boolean;
isEdited: boolean;
isMobile?: boolean;
editRemaining?: string;
editBlockReason?: string;
deleting?: boolean;
onEdit: () => void;
onShowRevisions: () => void;
onToggleResolved: () => void;
onApprove: () => void;
onReject: () => void;
onFeature: () => void;
onPin: () => void;
onBoardPin: () => void;
onLock: () => void;
onCommentsLock: () => void;
onDelete: () => void;
}
/** 帖子右上角管理菜单:编辑、审核、置顶、锁定、删除等 */
export default function PostManageMenu({
post,
isAdmin,
isOwnerOrAdmin,
canEdit,
isEdited,
isMobile,
editRemaining,
editBlockReason,
deleting,
onEdit,
onShowRevisions,
onToggleResolved,
onApprove,
onReject,
onFeature,
onPin,
onBoardPin,
onLock,
onCommentsLock,
onDelete,
}: PostManageMenuProps) {
const showContent =
canEdit
|| (isOwnerOrAdmin && isEdited)
|| (isOwnerOrAdmin && post.post_type === 'question');
const hint = editRemaining || (!canEdit && isOwnerOrAdmin ? editBlockReason : '') || '';
if (!showContent && !isAdmin && !hint) return null;
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="post-manage-menu-trigger"
aria-label="管理帖子"
>
{!isMobile && <span>管理</span>}
<EllipsisVertical size={16} aria-hidden />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="post-manage-menu">
{hint && (
<>
<DropdownMenuLabel className="post-manage-menu-hint">
{hint}
</DropdownMenuLabel>
<DropdownMenuSeparator />
</>
)}
{showContent && (
<>
<DropdownMenuLabel>内容</DropdownMenuLabel>
{canEdit && (
<DropdownMenuItem onSelect={onEdit}>
<Pencil size={14} aria-hidden />
编辑
</DropdownMenuItem>
)}
{isOwnerOrAdmin && isEdited && (
<DropdownMenuItem onSelect={onShowRevisions}>
<History size={14} aria-hidden />
编辑历史
</DropdownMenuItem>
)}
{isOwnerOrAdmin && post.post_type === 'question' && (
<DropdownMenuItem onSelect={onToggleResolved}>
{post.question_resolved
? <CircleHelp size={14} aria-hidden />
: <CircleCheck size={14} aria-hidden />}
{post.question_resolved ? '标为未解决' : '标为已解决'}
</DropdownMenuItem>
)}
{isAdmin && <DropdownMenuSeparator />}
</>
)}
{isAdmin && (
<>
<DropdownMenuLabel>审核</DropdownMenuLabel>
{(post.status === 'pending' || post.status === 'rejected') && (
<DropdownMenuItem onSelect={onApprove}>
<CircleCheck size={14} aria-hidden />
通过审核
</DropdownMenuItem>
)}
{post.status !== 'rejected' && (
<DropdownMenuItem onSelect={onReject}>
<Ban size={14} aria-hidden />
拒绝并通知
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
<DropdownMenuLabel>展示</DropdownMenuLabel>
<DropdownMenuItem onSelect={onFeature}>
<Sparkles size={14} aria-hidden />
{post.featured ? '取消推荐' : '设为推荐'}
</DropdownMenuItem>
<DropdownMenuItem onSelect={onPin}>
<Pin size={14} aria-hidden />
{post.pinned ? '取消全局置顶' : '全局置顶'}
</DropdownMenuItem>
<DropdownMenuItem onSelect={onBoardPin}>
<Pin size={14} aria-hidden />
{post.board_pinned ? '取消板块置顶' : '板块置顶'}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuLabel>讨论</DropdownMenuLabel>
<DropdownMenuItem onSelect={onLock}>
<Lock size={14} aria-hidden />
{post.edit_locked ? '解锁编辑' : '锁定编辑'}
</DropdownMenuItem>
<DropdownMenuItem onSelect={onCommentsLock}>
{post.comments_locked
? <LockOpen size={14} aria-hidden />
: <MessageSquareOff size={14} aria-hidden />}
{post.comments_locked ? '开放讨论' : '锁定讨论'}
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuLabel>危险</DropdownMenuLabel>
<DropdownMenuItem
className="text-destructive focus:text-destructive"
disabled={deleting}
onSelect={onDelete}
>
<Trash2 size={14} aria-hidden />
删除
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@@ -0,0 +1,175 @@
import { useState } from 'react';
import { BarChart3 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { notify } from '@/lib/notify';
import { api } from '../api/client';
import type { PollView } from '../api/types';
import { useAuth } from '../hooks/useAuth';
import { formatDateTime } from '../utils/content';
interface Props {
postId: number;
poll: PollView;
isOwnerOrAdmin: boolean;
onUpdate: (poll: PollView) => void;
}
/** 投票帖投票卡 */
export default function PostPollCard({ postId, poll, isOwnerOrAdmin, onUpdate }: Props) {
const { user } = useAuth();
const [selected, setSelected] = useState<number[]>(poll.my_option_ids ?? []);
const [busy, setBusy] = useState(false);
const voted = (poll.my_option_ids?.length ?? 0) > 0;
const showResults = poll.closed || voted;
const canVote = !voted && !poll.closed;
const headTitle = poll.closed
? '投票已结束'
: poll.multi
? `多选(最多 ${poll.max_choices} 项)`
: '单选投票';
const endsAtMs = poll.ends_at ? new Date(poll.ends_at).getTime() : NaN;
const expiredByDeadline = poll.closed && poll.ends_at && !Number.isNaN(endsAtMs) && endsAtMs <= Date.now();
const deadlineHint = poll.ends_at && !Number.isNaN(endsAtMs)
? poll.closed
? (expiredByDeadline ? `已于 ${formatDateTime(poll.ends_at)} 截止` : undefined)
: `截止于 ${formatDateTime(poll.ends_at)}`
: undefined;
const toggle = (id: number) => {
if (!canVote) return;
if (!user) {
notify.warning('请先登录');
return;
}
if (poll.multi) {
setSelected(prev => (
prev.includes(id)
? prev.filter(x => x !== id)
: [...prev, id].slice(0, poll.max_choices)
));
} else {
setSelected([id]);
}
};
const submit = async () => {
if (!user) {
notify.warning('请先登录');
return;
}
if (selected.length === 0) {
notify.warning('请选择选项');
return;
}
setBusy(true);
try {
const r = await api.pollVote(postId, selected);
onUpdate(r.poll);
notify.success('投票成功');
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '投票失败');
} finally {
setBusy(false);
}
};
const closePoll = async () => {
setBusy(true);
try {
const r = await api.pollClose(postId);
onUpdate(r.poll);
notify.success('投票已结束');
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '操作失败');
} finally {
setBusy(false);
}
};
return (
<section className="post-poll" aria-label="投票">
<div className="post-poll__head">
<BarChart3 size={18} aria-hidden />
<strong>{headTitle}</strong>
{deadlineHint && (
<span className="post-poll__deadline">{deadlineHint}</span>
)}
<span className="post-poll__meta">{poll.total_votes} 票</span>
</div>
<ul
className="post-poll__options"
role={poll.multi ? 'group' : 'radiogroup'}
aria-label="投票选项"
>
{poll.options.map(opt => {
const isActive = selected.includes(opt.id);
const isMine = poll.my_option_ids?.includes(opt.id);
return (
<li key={opt.id}>
<button
type="button"
className={[
'post-poll__option',
poll.multi ? 'post-poll__option--multi' : 'post-poll__option--single',
isActive ? 'active' : '',
showResults ? 'results' : '',
isMine ? 'mine' : '',
].filter(Boolean).join(' ')}
disabled={!canVote}
onClick={() => toggle(opt.id)}
role={poll.multi ? 'checkbox' : 'radio'}
aria-checked={isActive}
>
<span className="post-poll__option-main">
<span className="post-poll__option-indicator" aria-hidden />
<span className="post-poll__option-text">{opt.text}</span>
{showResults && (
<span className="post-poll__option-stat">
{opt.percent ?? 0}% · {opt.vote_count} 票
</span>
)}
</span>
{showResults && (
<span className="post-poll__option-bar" aria-hidden>
<span
className="post-poll__option-fill"
style={{ width: `${opt.percent ?? 0}%` }}
/>
</span>
)}
</button>
</li>
);
})}
</ul>
<div className="post-poll__actions">
{canVote && user && (
<Button
type="button"
size="sm"
disabled={busy || selected.length === 0}
onClick={submit}
>
提交投票
</Button>
)}
{canVote && user && selected.length === 0 && (
<p className="post-poll__select-hint">
{poll.multi ? '请选择后提交' : '请选择一项后提交'}
</p>
)}
{!user && canVote && (
<p className="post-poll__login-hint">登录后可参与投票</p>
)}
{isOwnerOrAdmin && !poll.closed && (
<Button type="button" variant="outline" size="sm" disabled={busy} onClick={closePoll}>
结束投票
</Button>
)}
</div>
</section>
);
}

View File

@@ -0,0 +1,121 @@
import { memo } from 'react';
import { GitFork, Star } from 'lucide-react';
import UserBadges from './UserBadges';
import UserLink from './UserLink';
import type { GiteaProject } from '../api/types';
import { formatTime } from '../utils/content';
interface Props {
project: GiteaProject;
}
/** 开源码桶列表行:结构对齐帖子列表;作者一律用论坛用户,不展示 Gitea login */
function ProjectListItem({ project }: Props) {
const owner = project.owner;
// 未绑定论坛用户的仓库不应出现在列表;兜底不渲染
if (!owner?.id) return null;
const title = project.name || project.full_name;
const initial = owner.nickname?.[0] || '?';
const remoteIso = project.updated_at_remote ?? undefined;
const timeLabel = remoteIso ? formatTime(remoteIso) : '';
const stars = project.stars_count ?? 0;
const forks = project.forks_count ?? 0;
const open = () => {
if (!project.html_url) return;
window.open(project.html_url, '_blank', 'noopener,noreferrer');
};
const onKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
open();
}
};
const onTitleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
e.stopPropagation();
return;
}
e.preventDefault();
e.stopPropagation();
open();
};
return (
<div
className="post-row post-row--v2 project-list-item"
role="link"
tabIndex={0}
onClick={open}
onKeyDown={onKeyDown}
>
<UserLink
user={owner}
showAvatar={false}
showName={false}
stopPropagation
className="post-avatar user-link--avatar-only"
>
{owner.avatar
? <img src={owner.avatar} alt="" loading="lazy" decoding="async" />
: initial}
</UserLink>
<div className="post-main">
<div className="post-text">
<div className="post-title-row">
{project.language ? (
<span className="project-lang-badge" title="主要语言">{project.language}</span>
) : null}
<a
href={project.html_url}
className="post-title"
target="_blank"
rel="noopener noreferrer"
onClick={onTitleClick}
>
{title}
</a>
</div>
{project.description ? (
<p className="post-excerpt">{project.description}</p>
) : null}
</div>
<div className="post-meta">
<div className="post-meta-left">
<UserLink
user={owner}
stopPropagation
className="post-meta-author"
showBadges={false}
/>
<UserBadges user={owner} compact maxAchievement={3} className="project-list-badges" />
{timeLabel ? (
<>
<span className="post-meta-sep post-meta-sep--before-time" aria-hidden>·</span>
<span className="post-meta-time post-meta-time--created" title={remoteIso}>
{timeLabel}
</span>
</>
) : null}
</div>
<div className="post-stats">
<span className={`post-stat${stars === 0 ? ' post-stat--zero' : ''}`} title="Stars">
<Star aria-hidden />
{stars}
</span>
<span className={`post-stat${forks === 0 ? ' post-stat--zero' : ''}`} title="Forks">
<GitFork aria-hidden />
{forks}
</span>
</div>
</div>
</div>
</div>
);
}
export default memo(ProjectListItem);

View File

@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from 'react';
import { Loader2, ArrowDown } from 'lucide-react';
import { softRefreshCurrentPage } from '../utils/softRefresh';
/** 触发刷新的下拉距离(px) */
const REFRESH_THRESHOLD = 68;
@@ -30,6 +31,9 @@ function pickScrollEl(): HTMLElement | null {
const page = document.querySelector<HTMLElement>('.page-wrap:not(.page-wrap--feed)');
if (page) return page;
const showcase = document.querySelector<HTMLElement>('.showcase-panel');
if (showcase) return showcase.closest<HTMLElement>('.main-content') ?? showcase;
const admin = document.querySelector<HTMLElement>('.admin-main');
if (admin) return admin;
@@ -76,7 +80,7 @@ function isNestedScrollBlocking(target: EventTarget | null, bound: HTMLElement):
}
/**
* 手机端下拉刷新:在内部滚动容器顶部下拉后整页重载。
* 手机端下拉刷新:在内部滚动容器顶部下拉后强制刷新当前页。
* (浏览器原生 PTR 依赖 document 滚动,与本站 app-shell 布局不兼容。)
*
* 挂在 Router 外,故用 MutationObserver 在路由切换后重绑滚动容器。
@@ -167,7 +171,22 @@ export default function PullToRefresh() {
setSettling(true);
setPull(REFRESH_THRESHOLD * 0.7);
window.setTimeout(() => {
// 后台 / 登录页:整页 reload;前台:静默软刷新(无进度条,齐套后一次覆盖)
const isAdminOrAuth = !!(
document.querySelector('.admin-main')
|| document.querySelector('.auth-page')
);
if (isAdminOrAuth) {
window.location.reload();
return;
}
void softRefreshCurrentPage()
.catch(() => undefined)
.finally(() => {
setRefreshing(false);
setSettling(true);
setPull(0);
});
}, 180);
return;
}

View File

@@ -1,14 +1,17 @@
import { ListTree, MessageCircle, MessagesSquare, Tags, Sparkles } from 'lucide-react';
import { useLocation, useSearchParams } from 'react-router-dom';
import { Skeleton } from '@/components/ui/skeleton';
import type { PostItem, RecentComment, TagCount, User } from '../api/types';
import { useMemo } from 'react';
import { ListTree, MessageCircle, Tags, Link2, UserPlus } from 'lucide-react';
import { useLocation, useSearchParams, useNavigate } from 'react-router-dom';
import type { AsideWidget, RecentComment, RecentUser, TagCount, User, ForumStats, FriendLink } from '../api/types';
import type { PostHeading } from '../utils/postHeadings';
import { useSiteBranding } from '../hooks/useSiteBranding';
import { formatShortDateTime, formatTime } from '../utils/content';
import { resolveAsideWidgets } from '../utils/asideWidgets';
import TagCloud from './TagCloud';
import UserLink from './UserLink';
import ArticleOutline from './ArticleOutline';
import PostAuthorCard from './PostAuthorCard';
import AsideCheckInStrip from './AsideCheckInStrip';
import ShowcaseAsideWidget from './ShowcaseAsideWidget';
export type PostDetailAside = {
author?: User | null;
@@ -20,60 +23,41 @@ export type PostDetailAside = {
};
interface Props {
hot: PostItem[];
recentComments: RecentComment[];
recentUsers: RecentUser[];
tags?: TagCount[];
tagsLoading?: boolean;
stats?: ForumStats | null;
onPostClick: (id: number, opts?: { floor?: number }) => void;
/** 首次拉取中,显示骨架避免空态闪烁 */
/** 首次拉取中:不渲染该块内容(由冷启动门闩保证首屏已齐或空白) */
loading?: boolean;
/** 右侧栏可选组件顺序与开关 */
asideWidgets: AsideWidget[];
/** 帖子详情:右侧顶部展示作者与目录 */
postDetail?: PostDetailAside | null;
}
function ActiveSkeleton() {
return (
<div className="widget-skeleton" aria-busy="true" aria-label="正在聊加载中">
{Array.from({ length: 6 }, (_, i) => (
<div key={i} className="widget-item widget-item--active widget-item--skeleton">
<Skeleton className="skeleton--widget-title" style={{ width: `${62 + (i % 4) * 8}%` }} />
<Skeleton className="skeleton--widget-time" />
</div>
))}
</div>
);
}
function CommentSkeleton() {
return (
<div className="widget-skeleton" aria-busy="true" aria-label="评论加载中">
{Array.from({ length: 5 }, (_, i) => (
<div key={i} className="widget-item widget-item--comment widget-item--skeleton">
<Skeleton className="skeleton--widget-avatar" />
<Skeleton className="skeleton--widget-title" style={{ width: `${55 + (i % 3) * 12}%` }} />
<Skeleton className="skeleton--widget-time" />
</div>
))}
</div>
);
}
export default function RightPanel({
hot,
recentComments,
recentUsers,
tags = [],
tagsLoading = false,
stats = null,
onPostClick,
loading = false,
asideWidgets,
postDetail = null,
}: Props) {
const { branding } = useSiteBranding();
const nav = useNavigate();
const loc = useLocation();
const [params] = useSearchParams();
const activeTag = params.get('tag') || '';
const hotList = hot?.slice(0, 8) ?? [];
const commentList = recentComments?.slice(0, 6) ?? [];
// 站点首页:右侧品牌块承担唯一 h1;板块/搜索等页面由 Feed 标题作 h1
const userList = recentUsers?.slice(0, 8) ?? [];
const friendLinks = (branding.friend_links ?? []).filter(
(l: FriendLink) => l.name?.trim() && l.url?.trim(),
);
const isSiteHome = loc.pathname === '/'
&& !params.get('board')
&& !params.get('keyword')
@@ -81,94 +65,64 @@ export default function RightPanel({
&& !params.get('author');
const description = branding.description?.trim() || '';
const slogan = branding.slogan?.trim() || '';
// 有独立简介时展示简介;否则用欢迎语,避免与页脚 slogan 三连重复
const aboutText = description || '欢迎参与讨论,发帖、评论,一起把小圈子聊热。';
// 有近期讨论则展示「正在聊」;否则显示欢迎引导
const showActive = loading || hotList.length > 0;
const showWelcome = !loading && hotList.length === 0;
const introText = description || slogan;
const isPostDetail = !!postDetail;
const enabledWidgets = useMemo(
() => resolveAsideWidgets({
aside_widgets: asideWidgets,
aside_show_tag_cloud: false,
aside_show_recent_comments: false,
aside_show_friend_links: false,
}).filter(w => w.enabled),
[asideWidgets],
);
const renderWidget = (widget: AsideWidget) => {
switch (widget.id) {
case 'showcase':
return <ShowcaseAsideWidget key="showcase" />;
case 'friend_links':
return (
<div className={`aside-panel-inner${isPostDetail ? ' aside-panel-inner--post-detail' : ''}`}>
{isPostDetail && (
<div key="friend_links" className="widget-card widget-card--friend-links">
<div className="widget-card-head widget-card-head--split">
<span className="widget-card-head-main">
<Link2 className="widget-card-icon widget-card-icon--links" aria-hidden />
<button type="button" className="widget-friend-links-title" onClick={() => nav('/links')}>
友情链接
</button>
</span>
<a href="/links?apply=1" className="widget-friend-links-apply">
申请
</a>
</div>
<div className="widget-card-body widget-card-body--friend-links">
{friendLinks.length === 0 ? (
<div className="widget-empty">暂无友情链接</div>
) : (
<>
<PostAuthorCard
author={postDetail.author}
publishedAt={postDetail.publishedAt}
viewCount={postDetail.viewCount}
/>
<div className="widget-card widget-card--outline">
<div className="widget-card-head">
<ListTree className="widget-card-icon widget-card-icon--outline" aria-hidden />
{postDetail.outlineTitle || '文章目录'}
</div>
<div className="widget-card-body widget-outline-body">
<ArticleOutline
headings={postDetail.headings}
scrollRoot={postDetail.scrollRoot}
title={postDetail.outlineTitle || '文章目录'}
className="article-outline--aside"
/>
</div>
</div>
<ul className="widget-friend-links-list">
{friendLinks.slice(0, 8).map((link: FriendLink) => (
<li key={`${link.name}-${link.url}`}>
<a href={link.url} target="_blank" rel="noopener noreferrer" title={link.name}>
{link.name}
</a>
</li>
))}
</ul>
{friendLinks.length > 8 && (
<button type="button" className="widget-friend-links-more" onClick={() => nav('/links')}>
查看全部 {friendLinks.length} 个
</button>
)}
</>
)}
{!isPostDetail && showWelcome && (
<div className="widget-card widget-card--welcome">
<div className="widget-card-head">
<Sparkles className="widget-card-icon widget-card-icon--welcome" aria-hidden />
加入讨论
</div>
<div className="widget-card-body widget-welcome-body">
<p>社区还在起步,每条回复都很珍贵。</p>
<ul>
<li>逛逛板块,找到感兴趣的话题</li>
<li>游客也能评论,登录可点赞收藏</li>
<li>发一篇帖,留下你的痕迹</li>
</ul>
</div>
</div>
)}
{!isPostDetail && showActive && (
<div className="widget-card">
<div className="widget-card-head">
<MessagesSquare className="widget-card-icon widget-card-icon--hot" aria-hidden />
正在聊
</div>
<div className="widget-card-body">
{loading && hotList.length === 0 ? (
<ActiveSkeleton />
) : hotList.length === 0 ? (
<div className="widget-empty">近 7 日暂无新回复</div>
) : hotList.map((item) => {
const replyLabel = item.last_reply_at
? `${formatTime(item.last_reply_at)}有人回`
: '近期有讨论';
const count = item.comment_count ?? 0;
return (
<button
key={item.id}
type="button"
className="widget-item widget-item--active"
onClick={() => onPostClick(item.id)}
title={item.title}
>
<span className="widget-item-title">{item.title}</span>
<span className="widget-item-meta">
<span className="widget-item-time">{replyLabel}</span>
{count > 0 && <span className="widget-item-count">{count} 评</span>}
</span>
</button>
);
})}
</div>
</div>
)}
{!isPostDetail && (
<div className="widget-card widget-card--tags">
case 'tag_cloud':
return (
<div key="tag_cloud" className="widget-card widget-card--tags">
<div className="widget-card-head">
<Tags className="widget-card-icon widget-card-icon--tags" aria-hidden />
标签云
@@ -177,18 +131,16 @@ export default function RightPanel({
<TagCloud tags={tags} loading={tagsLoading} activeTag={activeTag} />
</div>
</div>
)}
{!isPostDetail && (
<div className="widget-card">
);
case 'recent_comments':
return (
<div key="recent_comments" className="widget-card">
<div className="widget-card-head">
<MessageCircle className="widget-card-icon widget-card-icon--notice" aria-hidden />
最新评论
</div>
<div className="widget-card-body">
{loading && commentList.length === 0 ? (
<CommentSkeleton />
) : commentList.length === 0 ? (
{loading && commentList.length === 0 ? null : commentList.length === 0 ? (
<div className="widget-empty">暂无评论</div>
) : commentList.map(item => (
<div
@@ -221,12 +173,87 @@ export default function RightPanel({
onClick={() => onPostClick(item.post_id, item.floor > 0 ? { floor: item.floor } : undefined)}
>
<span className="widget-item-title">{item.excerpt}</span>
<span className="widget-item-time">{formatShortDateTime(item.created_at)}</span>
<span className="widget-item-meta">
<span
className="widget-item-time"
title={formatShortDateTime(item.created_at)}
>
{formatTime(item.created_at)}
</span>
{item.post_title && (
<span className="widget-item-post-title">{item.post_title}</span>
)}
</span>
</button>
</div>
))}
</div>
</div>
);
case 'recent_users':
return (
<div key="recent_users" className="widget-card widget-card--users">
<div className="widget-card-head">
<UserPlus className="widget-card-icon widget-card-icon--users" aria-hidden />
最新注册
</div>
<div className="widget-card-body widget-card-body--users">
{loading && userList.length === 0 ? null : userList.length === 0 ? (
<div className="widget-empty">暂无用户</div>
) : (
<div className="widget-recent-users-grid">
{userList.map(item => (
<UserLink
key={item.id}
user={{ id: item.id, nickname: item.nickname, avatar: item.avatar }}
className="widget-recent-user-cell"
showBadges={false}
title={item.nickname}
>
<span className="widget-recent-user-avatar" aria-hidden>
{item.avatar
? <img src={item.avatar} alt="" loading="lazy" decoding="async" />
: (item.nickname?.[0] || '?')}
</span>
<span className="widget-recent-user-name">{item.nickname}</span>
</UserLink>
))}
</div>
)}
</div>
</div>
);
default:
return null;
}
};
return (
<div className={`aside-panel-inner${isPostDetail ? ' aside-panel-inner--post-detail' : ''}`}>
{isPostDetail && (
<>
{postDetail.author?.id ? (
<PostAuthorCard
author={postDetail.author}
publishedAt={postDetail.publishedAt}
viewCount={postDetail.viewCount}
/>
) : null}
<div className="widget-card widget-card--outline">
<div className="widget-card-head">
<ListTree className="widget-card-icon widget-card-icon--outline" aria-hidden />
{postDetail.outlineTitle || '文章目录'}
</div>
<div className="widget-card-body widget-outline-body">
<ArticleOutline
headings={postDetail.headings}
scrollRoot={postDetail.scrollRoot}
title={postDetail.outlineTitle || '文章目录'}
className="article-outline--aside"
/>
</div>
</div>
</>
)}
{!isPostDetail && (
@@ -238,14 +265,32 @@ export default function RightPanel({
) : (
<p className="widget-about-title">{branding.name}</p>
)}
<p className="widget-about-desc">{aboutText}</p>
{description && slogan && slogan !== description && (
<p className="widget-about-slogan">{slogan}</p>
{introText && (
<p className="widget-about-desc">{introText}</p>
)}
</div>
{stats && (
<div className="widget-stats" aria-label="论坛统计">
<div className="widget-stat">
<span className="widget-stat-value">{stats.posts}</span>
<span className="widget-stat-label">帖子</span>
</div>
<div className="widget-stat">
<span className="widget-stat-value">{stats.comments}</span>
<span className="widget-stat-label">回复</span>
</div>
<div className="widget-stat">
<span className="widget-stat-value">{stats.users}</span>
<span className="widget-stat-label">用户</span>
</div>
</div>
)}
<AsideCheckInStrip />
</div>
</div>
)}
{!isPostDetail && enabledWidgets.map(renderWidget)}
</div>
);
}

View File

@@ -0,0 +1,124 @@
import { useEffect, useState } from 'react';
import { Globe2 } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { api } from '../api/client';
import type { CommunityShowcaseItem } from '../api/types';
import { getSessionSnapshot, setSessionSnapshot } from '../utils/sessionPageCache';
import { PAGE_FORCE_REFRESH_EVENT } from '../utils/feedCache';
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
const SHOWCASE_KEY = 'showcase';
/** 右侧栏:开源展柜精简列表 */
export default function ShowcaseAsideWidget() {
const nav = useNavigate();
const cached = getSessionSnapshot<CommunityShowcaseItem[]>(SHOWCASE_KEY);
const [items, setItems] = useState<CommunityShowcaseItem[]>(() => cached ?? []);
const [loading, setLoading] = useState(() => cached === undefined);
useEffect(() => {
let cancelled = false;
const hit = getSessionSnapshot<CommunityShowcaseItem[]>(SHOWCASE_KEY);
// 非空快照直接用;空数组可能是启动竞态假空,仍再拉
if (hit !== undefined && hit.length > 0) {
setItems(hit);
setLoading(false);
return;
}
if (hit !== undefined) setItems(hit);
setLoading(hit === undefined);
api.communityShowcase()
.then((r) => {
if (cancelled) return;
const next = Array.isArray(r.items) ? r.items : [];
setSessionSnapshot(SHOWCASE_KEY, next);
setItems(next);
})
.catch(() => {
// 失败不写空快照,避免假空粘死
if (!cancelled && hit === undefined) setItems([]);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => { cancelled = true; };
}, []);
useEffect(() => {
const fetchShowcase = (opts: { showLoading: boolean }) => {
if (opts.showLoading) setLoading(true);
api.communityShowcase()
.then((r) => {
const next = Array.isArray(r.items) ? r.items : [];
setSessionSnapshot(SHOWCASE_KEY, next);
setItems(next);
})
.catch(() => {
// 软刷新 / 强刷失败:保持旧 UI,不写空快照
})
.finally(() => setLoading(false));
};
const applyHitOrReload = (showLoading: boolean) => {
const hit = getSessionSnapshot<CommunityShowcaseItem[]>(SHOWCASE_KEY);
if (hit !== undefined && hit.length > 0) {
setItems(hit);
setLoading(false);
return;
}
fetchShowcase({ showLoading });
};
const onForce = () => applyHitOrReload(true);
const onCommit = () => applyHitOrReload(false);
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
return () => {
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
};
}, []);
return (
<div className="widget-card widget-card--showcase">
<div className="widget-card-head widget-card-head--split">
<span className="widget-card-head-main">
<Globe2 className="widget-card-icon widget-card-icon--showcase" aria-hidden />
<button type="button" className="widget-friend-links-title" onClick={() => nav('/showcase')}>
开源展柜
</button>
</span>
<button type="button" className="widget-friend-links-more" onClick={() => nav('/showcase')}>
全部
</button>
</div>
<div className="widget-card-body widget-card-body--friend-links">
{loading ? (
<div className="widget-empty">加载中…</div>
) : items.length === 0 ? (
<div className="widget-empty">
暂无精选实例
<button type="button" className="widget-friend-links-more" onClick={() => nav('/showcase')}>
查看展柜
</button>
</div>
) : (
<>
<ul className="widget-friend-links-list">
{items.slice(0, 8).map((item) => (
<li key={item.site_url}>
<a href={item.site_url} target="_blank" rel="noopener noreferrer" title={item.site_name || item.site_url}>
{item.site_name || '未命名站点'}
</a>
</li>
))}
</ul>
{items.length > 8 && (
<button type="button" className="widget-friend-links-more" onClick={() => nav('/showcase')}>
查看全部 {items.length} 个
</button>
)}
</>
)}
</div>
</div>
);
}

View File

@@ -1,20 +1,23 @@
import {
Home, Star, LayoutDashboard, FolderGit2, FolderKanban, ArrowLeft,
Home, Star, LayoutDashboard, FolderGit2, FolderKanban, ArrowLeft, FileText, Link2, Globe2,
} from 'lucide-react';
import { useNavigate, useLocation, useSearchParams } from 'react-router-dom';
import { useNavigate, useLocation, useSearchParams, Link } from 'react-router-dom';
import type { Board } from '../api/types';
import type { PostHeading } from '../utils/postHeadings';
import { useAuth } from '../hooks/useAuth';
import { cn } from '@/lib/utils';
import { Skeleton } from '@/components/ui/skeleton';
import { buildHomeUrl, parseFeedSort } from './FeedSortBar';
import { navigateFeed } from '../utils/feedCache';
import { transitionTo } from '../utils/spaTransition';
import BoardIconDisplay from './BoardIconDisplay';
import { getBoardThemeIndex } from '../utils/boardTheme';
import ArticleOutline from './ArticleOutline';
import { useSitePages } from '../hooks/useSitePages';
import { pagePath } from '../utils/permalink';
import { useForumLimits } from '../hooks/useForumLimits';
// 内容页不参与左侧栏高亮(非 feed 浏览上下文)
const NEUTRAL_SIDEBAR_PREFIXES = ['/post/', '/profile', '/user/'];
const NEUTRAL_SIDEBAR_PREFIXES = ['/post/', '/profile', '/user/', '/page/'];
export function isNeutralSidebarRoute(pathname: string): boolean {
return NEUTRAL_SIDEBAR_PREFIXES.some(prefix => pathname.startsWith(prefix));
@@ -26,6 +29,9 @@ function resolveMenuKey(pathname: string, activeBoard: number, keyword = ''): st
if (keyword.trim()) return null;
if (pathname.startsWith('/favorites')) return 'favorites';
if (pathname.startsWith('/projects')) return 'projects';
if (pathname.startsWith('/links')) return 'links';
if (pathname.startsWith('/showcase')) return 'showcase';
if (pathname.startsWith('/page/')) return 'pages';
if (pathname.startsWith('/admin')) return 'admin';
return activeBoard === 0 ? 'all' : String(activeBoard);
}
@@ -56,12 +62,43 @@ export default function Sidebar({
const nav = useNavigate();
const loc = useLocation();
const [params] = useSearchParams();
const sort = parseFeedSort(params.get('sort'));
const { user } = useAuth();
const isAdmin = user?.role === 'admin';
const { navPages } = useSitePages();
const { limits } = useForumLimits();
const sort = parseFeedSort(params.get('sort'), limits.feed_sort_tabs);
const showFriendLinksNav = limits.nav_show_friend_links !== false;
const showShowcaseNav = !!limits.nav_show_showcase;
const showSiteSection = navPages.length > 0 || showFriendLinksNav || showShowcaseNav;
const keyword = params.get('keyword') || '';
const menuKey = resolveMenuKey(loc.pathname, activeBoard, keyword);
const permalinkOpts = { permalink: limits };
const feedNavLink = (
key: string,
to: string,
label: React.ReactNode,
icon: React.ReactNode,
selectId: number,
className?: string,
trailing?: React.ReactNode,
) => (
<Link
key={key}
to={to}
className={cn('sidebar-nav-item', className, menuKey != null && menuKey === key && 'active')}
onClick={(e) => {
e.preventDefault();
onSelectBoard(selectId);
navigateFeed(nav, to);
}}
>
{icon}
<span className="flex-1 truncate">{label}</span>
{trailing}
</Link>
);
const navItem = (key: string, label: React.ReactNode, icon?: React.ReactNode, onClick?: () => void) => (
<button
@@ -99,23 +136,13 @@ export default function Sidebar({
<aside className="sidebar">
<div className="sidebar-section">浏览</div>
<nav className="sidebar-nav">
{navItem('all', '全部帖子', <Home aria-hidden />, () => { onSelectBoard(0); navigateFeed(nav, buildHomeUrl(0, sort)); })}
{user && navItem('favorites', '我的收藏', <Star aria-hidden />, () => nav('/favorites'))}
{navItem('projects', '开源码桶', <FolderGit2 aria-hidden />, () => nav('/projects'))}
{feedNavLink('all', buildHomeUrl(0, sort, permalinkOpts), '全部帖子', <Home aria-hidden />, 0)}
{user && navItem('favorites', '我的收藏', <Star aria-hidden />, () => void transitionTo(nav, '/favorites'))}
{navItem('projects', '开源码桶', <FolderGit2 aria-hidden />, () => void transitionTo(nav, '/projects'))}
</nav>
{(boardsLoading && boards.length === 0) ? (
<>
<div className="sidebar-section sidebar-section--boards">板块</div>
<nav className="sidebar-nav sidebar-nav--skeleton" aria-busy="true" aria-label="板块加载中">
{Array.from({ length: 4 }, (_, i) => (
<div key={i} className="sidebar-nav-item sidebar-nav-item--skeleton">
<Skeleton className="skeleton--sidebar-icon" />
<Skeleton className="skeleton--sidebar-label" style={{ width: `${58 + (i % 3) * 12}%` }} />
</div>
))}
</nav>
</>
) : boards.length > 0 ? (
<>
<div className="sidebar-section sidebar-section--boards">板块</div>
@@ -123,29 +150,27 @@ export default function Sidebar({
{boards.map(b => {
const isActive = menuKey != null && menuKey === String(b.id);
const themeIdx = getBoardThemeIndex(b);
return (
<button
type="button"
key={b.id}
className={cn(
'sidebar-nav-item',
'sidebar-nav-item--board',
isActive && 'active',
isActive && `sidebar-nav-item--board-${themeIdx}`,
)}
onClick={() => { onSelectBoard(b.id); navigateFeed(nav, buildHomeUrl(b.id, sort)); }}
>
<BoardIconDisplay
board={b}
className={cn('sidebar-board-icon', `sidebar-board-icon--${themeIdx}`)}
/>
<span className="flex-1 truncate">{b.name}</span>
{(b.post_count ?? 0) > 0 && (
const boardUrl = buildHomeUrl(b.id, sort, permalinkOpts);
const postMeta = (b.post_count ?? 0) > 0 ? (
<span className="sidebar-nav-item__meta" title={`${b.post_count} 篇帖子`}>
{b.post_count} 帖
</span>
)}
</button>
) : null;
return feedNavLink(
String(b.id),
boardUrl,
b.name,
<BoardIconDisplay
board={b}
className={cn('sidebar-board-icon', `sidebar-board-icon--${themeIdx}`)}
/>,
b.id,
cn(
'sidebar-nav-item--board',
isActive && 'active',
isActive && `sidebar-nav-item--board-${themeIdx}`,
),
postMeta,
);
})}
</nav>
@@ -159,6 +184,19 @@ export default function Sidebar({
</>
) : null}
{showSiteSection && (
<>
<div className="sidebar-section sidebar-section--spaced">站点</div>
<nav className="sidebar-nav">
{showFriendLinksNav && navItem('links', '友情链接', <Link2 aria-hidden />, () => void transitionTo(nav, '/links'))}
{showShowcaseNav && navItem('showcase', '开源展柜', <Globe2 aria-hidden />, () => void transitionTo(nav, '/showcase'))}
{navPages.map(p => (
navItem(`page-${p.slug}`, p.title, <FileText aria-hidden />, () => void transitionTo(nav, pagePath(p.slug, limits)))
))}
</nav>
</>
)}
{isAdmin && (
<>
<div className="sidebar-section sidebar-section--spaced">管理</div>

View File

@@ -1,18 +1,60 @@
import { useSiteBranding } from '../hooks/useSiteBranding';
import { useMediaQuery } from '../hooks/useTheme';
import type { FriendLink } from '../api/types';
import { Link } from 'react-router-dom';
import { useSitePages } from '../hooks/useSitePages';
import { pagePath } from '../utils/permalink';
import { useForumLimits } from '../hooks/useForumLimits';
function FooterSep() {
return <span className="site-footer__sep" aria-hidden>·</span>;
}
/** 站点页脚:版权、Sitemap、友链、备案号 */
/** 站点页脚:版权、友链/展柜入口、单页、备案号(结构与 Go writeSSRFooter 对齐) */
export default function SiteFooter() {
const { branding } = useSiteBranding();
const { footerPages } = useSitePages();
const { limits } = useForumLimits();
const year = new Date().getFullYear();
const links = Array.isArray(branding.friend_links) ? branding.friend_links : [];
const icp = branding.icp_beian?.trim() || '';
const icpURL = branding.icp_beian_url?.trim() || 'https://beian.miit.gov.cn/';
const showFriendLinks = limits.footer_show_friend_links !== false;
const showShowcase = !!limits.footer_show_showcase;
const navItems: React.ReactNode[] = [];
if (showFriendLinks) {
navItems.push(
<span key="links" className="site-footer__friend">
<Link to="/links">友情链接</Link>
</span>,
);
}
if (showShowcase) {
navItems.push(
<span key="showcase" className="site-footer__friend">
<Link to="/showcase">开源展柜</Link>
</span>,
);
}
for (const p of footerPages) {
navItems.push(
<span key={p.slug} className="site-footer__friend">
<Link to={pagePath(p.slug, limits)}>{p.title}</Link>
</span>,
);
}
if (icp) {
navItems.push(
<a
key="icp"
href={icpURL}
target="_blank"
rel="noopener noreferrer"
className="site-footer__icp"
>
{icp}
</a>,
);
}
return (
<footer className="site-footer">
@@ -29,31 +71,11 @@ export default function SiteFooter() {
)}
</div>
{(links.length > 0 || icp) && (
<nav className="site-footer__nav" aria-label="站点链接">
{links.map((link: FriendLink, i) => (
<span key={`${link.name}-${link.url}`} className="site-footer__friend">
{i > 0 && <FooterSep />}
<a href={link.url} target="_blank" rel="noopener noreferrer">
{link.name}
</a>
</span>
))}
{icp && (
<>
{links.length > 0 && <FooterSep />}
<a
href={icpURL}
target="_blank"
rel="noopener noreferrer"
className="site-footer__icp"
>
{icp}
</a>
</>
{navItems.flatMap((node, i) =>
i === 0 ? [node] : [<FooterSep key={`sep-${i}`} />, node],
)}
</nav>
)}
</div>
</footer>
);

View File

@@ -0,0 +1,227 @@
import type { PostItem } from '../api/types';
import type { FeedSort } from './FeedSortBar';
import { getBoardThemeIndex } from '../utils/boardTheme';
import { postPath } from '../utils/permalink';
import { useForumLimits } from '../hooks/useForumLimits';
import { formatTime } from '../utils/content';
import { MessageCircle } from 'lucide-react';
/** 与 Go formatSSRRelativeTime / 前端 formatTime 对齐的列表时间 */
function stripHtmlPlain(html: string): string {
if (!html) return '';
const t = html
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
.replace(/<[^>]+>/g, ' ')
.replace(/&nbsp;/gi, ' ')
.replace(/\s+/g, ' ')
.trim();
return t;
}
function truncateRunes(s: string, max: number): string {
const chars = Array.from(s);
if (chars.length <= max) return s;
return chars.slice(0, max).join('');
}
function firstImageSrc(html: string): string {
const m = html.match(/<img[^>]+src=["']([^"']+)["']/i);
const src = m?.[1]?.trim() || '';
if (!src || src.startsWith('data:')) return '';
return src;
}
function displayName(post: PostItem): string {
const n = post.user?.nickname?.trim() || post.user?.username?.trim();
return n || '用户';
}
type Props = {
posts: PostItem[];
sort: FeedSort;
boardId: number;
};
/** 与 Go writeSSRPostRow 同构的静态列表(hydrate 首帧专用) */
export default function StaticFeedList({ posts, sort, boardId }: Props) {
const { limits } = useForumLimits();
const style = limits.feed_list_style ?? 'title';
const titleOnly = style === 'title';
const needExcerpt = style === 'excerpt' || style === 'thumbnail';
const needThumb = style === 'thumbnail';
return (
<div className="post-list-scroll post-list-scroll--ssr">
<div className="content-surface content-surface--ssr">
{posts.length === 0 ? (
<div className="feed-empty">暂无帖子</div>
) : (
posts.map((post) => {
const href = postPath(post.id, limits);
const author = displayName(post);
const initial = Array.from(author)[0] || '?';
let excerpt = '';
let thumb = '';
if (needExcerpt || needThumb) {
excerpt = truncateRunes(stripHtmlPlain(post.content || ''), 120);
}
if (needThumb) thumb = firstImageSrc(post.content || '');
const rowClass = [
'post-row',
'post-row--v2',
titleOnly ? 'post-row--title-only' : '',
thumb ? 'post-row--has-thumb' : '',
].filter(Boolean).join(' ');
let timeLabel = formatTime(post.created_at);
if (sort === 'reply' && !post.last_reply_at) {
timeLabel = '暂无回复';
}
const lastReplyName = post.last_reply_user?.nickname?.trim()
|| post.last_reply_user?.username?.trim()
|| post.last_reply_guest_nick?.trim()
|| '';
const showLastReply = !!post.last_reply_at && (!!post.last_reply_user || !!lastReplyName);
const commentCount = post.comment_count ?? 0;
const hasTypeBadge = post.post_type === 'question'
|| post.post_type === 'poll'
|| post.post_type === 'lottery'
|| (post.post_type === 'bounty' && (
(post.bounty_status === 'open' && (post.bounty_points ?? 0) > 0)
|| post.bounty_status === 'awarded'
));
const titleRow = (
<div className="post-title-row">
{post.pinned ? (
<span className="post-pin-badge" title="全局置顶">全局置顶</span>
) : null}
{post.board_pinned ? (
<span className="post-pin-badge post-pin-badge--board" title="板块置顶">板块置顶</span>
) : null}
{post.featured ? <span className="post-feature-badge" title="推荐">推荐</span> : null}
{post.status === 'pending' ? (
<span className="post-status-badge post-status-badge--pending" title="审核中">审核中</span>
) : null}
{post.status === 'rejected' ? (
<span className="post-status-badge post-status-badge--rejected" title="未通过">未通过</span>
) : null}
<span className="post-title">{post.title}</span>
{hasTypeBadge ? (
<span className="post-title-type-badges">
{post.post_type === 'question' ? (
<span
className={`post-qa-badge${post.question_resolved ? ' post-qa-badge--resolved' : ' post-qa-badge--open'}`}
title={post.question_resolved ? '已解决' : '未解决'}
>
{post.question_resolved ? '已解决' : '未解决'}
</span>
) : null}
{post.post_type === 'poll' ? (
<span className="post-type-badge post-type-badge--poll" title="投票">投票</span>
) : null}
{post.post_type === 'bounty' && post.bounty_status === 'open' && (post.bounty_points ?? 0) > 0 ? (
<span className="post-bounty-badge post-bounty-badge--open" title="悬赏">
悬赏 {post.bounty_points}
</span>
) : null}
{post.post_type === 'bounty' && post.bounty_status === 'awarded' ? (
<span className="post-bounty-badge post-bounty-badge--awarded" title="已采纳">已采纳</span>
) : null}
{post.post_type === 'lottery' ? (
<span className="post-type-badge post-type-badge--lottery" title="抽奖">
{post.lottery_status === 'drawn' ? '已开奖' : '抽奖'}
</span>
) : null}
</span>
) : null}
</div>
);
const metaLeft = (
<div className="post-meta-left">
{boardId === 0 && post.board?.id ? (
<span className="post-list-board-btn">
<span
className={`post-list-board-badge board-badge board-badge--${getBoardThemeIndex(post.board)}`}
>
{post.board.name}
</span>
</span>
) : null}
<span className="post-meta-author">{author}</span>
<span className="post-meta-sep post-meta-sep--before-time" aria-hidden>·</span>
<span className="post-meta-time post-meta-time--created">{timeLabel}</span>
{showLastReply ? (
<span className="post-meta-last-reply">
<span className="post-meta-last-reply-arrow" aria-hidden>←</span>
{/* 外层是 <a class="post-row">,禁止嵌套 a */}
<span className="post-meta-last-reply-user">{lastReplyName}</span>
<span className="post-meta-last-reply-time">{formatTime(post.last_reply_at!)}</span>
</span>
) : null}
</div>
);
const stats = (
<div className="post-stats">
<span
className={`post-stat${commentCount === 0 ? ' post-stat--zero' : ''}`}
title="评论"
>
<MessageCircle aria-hidden />
{commentCount}
</span>
</div>
);
return (
<a key={post.id} className={rowClass} href={href}>
{post.user?.avatar ? (
<span className="post-avatar user-link--avatar-only">
<img src={post.user.avatar} alt="" loading="lazy" decoding="async" />
</span>
) : (
<span className="post-avatar user-link--avatar-only">{initial}</span>
)}
{thumb ? (
<div className="post-main post-main--with-thumb">
<div className="post-content">
{titleRow}
{excerpt ? <p className="post-excerpt">{excerpt}</p> : null}
<div className="post-meta post-meta--inline">
{metaLeft}
{stats}
</div>
</div>
<div className="post-aside">
<div className="post-thumb" aria-hidden>
<img src={thumb} alt="" loading="lazy" decoding="async" />
</div>
</div>
</div>
) : (
<div className="post-main">
<div className="post-text">
{titleRow}
{excerpt ? <p className="post-excerpt">{excerpt}</p> : null}
</div>
<div className="post-meta">
{metaLeft}
{stats}
</div>
</div>
)}
</a>
);
})
)}
</div>
</div>
);
}

View File

@@ -1,7 +1,6 @@
import { useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import type { TagCount } from '../api/types';
import { Skeleton } from '@/components/ui/skeleton';
import { cn } from '@/lib/utils';
interface Props {
@@ -63,20 +62,7 @@ export default function TagCloud({ tags, loading = false, activeTag = '' }: Prop
}, [tags]);
if (loading && tags.length === 0) {
return (
<div className="tag-cloud tag-cloud--skeleton" aria-busy="true" aria-label="标签加载中">
{Array.from({ length: 10 }, (_, i) => (
<Skeleton
key={i}
className="skeleton--tag-cloud"
style={{
width: `${42 + (i % 5) * 16}px`,
height: `${20 + (i % 3) * 4}px`,
}}
/>
))}
</div>
);
return null;
}
if (items.length === 0) {

View File

@@ -0,0 +1,75 @@
import { useEffect, useRef, useState } from 'react';
import { subscribeSpaTransition } from '../utils/spaTransition';
/**
* 视口顶部 2px 细进度条(类 Next.js / YouTube)。
* 由 spaTransition start/done 驱动,假进度爬升至约 80%,结束冲到 100%。
*/
export default function TopProgressBar() {
const [visible, setVisible] = useState(false);
const [width, setWidth] = useState(0);
const [fading, setFading] = useState(false);
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const fadeRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const activeRef = useRef(false);
useEffect(() => {
const clearTick = () => {
if (timerRef.current) {
clearInterval(timerRef.current);
timerRef.current = null;
}
};
const clearFade = () => {
if (fadeRef.current) {
clearTimeout(fadeRef.current);
fadeRef.current = null;
}
};
return subscribeSpaTransition((active) => {
if (active) {
activeRef.current = true;
clearFade();
setFading(false);
setVisible(true);
setWidth(12);
clearTick();
timerRef.current = setInterval(() => {
setWidth((w) => {
if (w >= 80) return w;
// 越接近 80 越慢
const step = Math.max(0.4, (80 - w) * 0.045);
return Math.min(80, w + step);
});
}, 120);
return;
}
if (!activeRef.current) return;
activeRef.current = false;
clearTick();
setWidth(100);
setFading(true);
clearFade();
fadeRef.current = setTimeout(() => {
setVisible(false);
setFading(false);
setWidth(0);
}, 220);
});
}, []);
if (!visible && width <= 0) return null;
return (
<div
className={[
'top-progress',
fading ? 'top-progress--done' : '',
].filter(Boolean).join(' ')}
style={{ width: `${width}%` }}
aria-hidden
/>
);
}

View File

@@ -4,14 +4,17 @@ import { useVirtualizer } from '@tanstack/react-virtual';
import { Inbox, SearchX } from 'lucide-react';
import { Button } from '@/components/ui/button';
import PostListItem from './PostListItem';
import PostListSkeleton from './PostListSkeleton';
import { feedListRowEstimate } from './PostListSkeleton';
import FeedPagination from './FeedPagination';
import { InFlowSiteFooter } from './SiteFooter';
import { useAuth } from '../hooks/useAuth';
import { useForumLimits } from '../hooks/useForumLimits';
import { useMediaQuery } from '../hooks/useTheme';
import { loginPath } from '../utils/authRedirect';
import { dispatchOpenPostSearch } from '../hooks/usePostSearch';
import type { PostItem } from '../api/types';
import type { FeedSort } from './FeedSortBar';
import { getDefaultFeedSortFromCache } from './FeedSortBar';
interface Props {
posts: PostItem[];
@@ -32,6 +35,13 @@ interface Props {
onScrollRestored?: () => void;
/** 搜索关键词(用于空态文案) */
keyword?: string;
/** 是否为帖子搜索(区别于标签筛选) */
isSearchMode?: boolean;
searchKeyword?: string;
searchAuthor?: string;
searchTitleOnly?: boolean;
searchScopeBoardId?: number;
onClearSearch?: () => void;
/** 当前板块 id,0 表示全部 */
boardId?: number;
/** 当前板块名 */
@@ -47,7 +57,7 @@ function getMobileFeedScrollEl(): HTMLElement | null {
export default function VirtualPostList({
posts,
sort = 'latest',
sort = getDefaultFeedSortFromCache(),
loading,
hasMore,
showPagination,
@@ -61,13 +71,22 @@ export default function VirtualPostList({
onScrollTopChange,
onScrollRestored,
keyword = '',
isSearchMode = false,
searchKeyword = '',
searchAuthor = '',
searchTitleOnly = false,
searchScopeBoardId = 0,
onClearSearch,
boardId = 0,
boardName = '',
noBoards = false,
}: Props) {
const nav = useNavigate();
const { user } = useAuth();
const { limits } = useForumLimits();
const isMobile = useMediaQuery('(max-width: 768px)');
const feedStyle = limits.feed_list_style ?? 'title';
const rowEstimate = feedListRowEstimate(feedStyle);
const parentRef = useRef<HTMLDivElement>(null);
const restoredRef = useRef(false);
const onScrollTopChangeRef = useRef(onScrollTopChange);
@@ -116,7 +135,7 @@ export default function VirtualPostList({
const virtualizer = useVirtualizer({
count: posts.length,
getScrollElement,
estimateSize: () => 108,
estimateSize: () => rowEstimate,
overscan: 8,
scrollMargin: isMobile ? scrollMargin : 0,
measureElement:
@@ -128,7 +147,7 @@ export default function VirtualPostList({
const showEnd = !hasMore && !showPagination && posts.length > 0 && !loading;
const isInitialLoad = loading && posts.length === 0;
const isEmpty = !loading && posts.length === 0;
const isSearchEmpty = isEmpty && !!keyword.trim();
const isSearchEmpty = isEmpty && (isSearchMode || !!keyword.trim());
const composeTarget = boardId > 0 ? `/compose?board=${boardId}` : '/compose';
const isAdmin = user?.role === 'admin';
@@ -143,6 +162,12 @@ export default function VirtualPostList({
onScrollTopChangeRef.current?.(0);
}, [resetScrollKey, virtualizer, getScrollElement]);
useLayoutEffect(() => {
// 收到新的恢复目标时允许再次 restore;null 表示已消费,勿动标记
if (restoreScrollTop == null) return;
restoredRef.current = false;
}, [restoreScrollTop]);
useLayoutEffect(() => {
if (restoreScrollTop == null || restoredRef.current || posts.length === 0) return;
const el = getScrollElement();
@@ -155,10 +180,6 @@ export default function VirtualPostList({
onScrollRestoredRef.current?.();
}, [restoreScrollTop, posts.length, virtualizer, getScrollElement]);
useEffect(() => {
restoredRef.current = false;
}, [restoreScrollTop]);
useEffect(() => {
const el = getScrollElement();
if (!el) return;
@@ -169,6 +190,12 @@ export default function VirtualPostList({
return () => el.removeEventListener('scroll', onScroll);
}, [getScrollElement, isMobile]);
const searchSummaryParts: string[] = [];
if (searchKeyword.trim()) searchSummaryParts.push(`关键词「${searchKeyword.trim()}」`);
if (searchAuthor.trim()) searchSummaryParts.push(`作者 ${searchAuthor.trim()}`);
if (searchTitleOnly && searchKeyword.trim()) searchSummaryParts.push('仅标题');
if (searchScopeBoardId > 0 && boardName) searchSummaryParts.push(`板块 ${boardName}`);
const emptyActions = (
<div className="empty-feed-actions">
{noBoards ? (
@@ -183,12 +210,15 @@ export default function VirtualPostList({
)
) : isSearchEmpty ? (
<>
<Button type="button" size="sm" variant="outline" onClick={dispatchOpenPostSearch}>
修改搜索
</Button>
<Button type="button" size="sm" variant="outline" onClick={() => (onClearSearch ? onClearSearch() : nav('/'))}>
清除筛选
</Button>
<Button type="button" size="sm" variant="outline" onClick={() => nav('/')}>
返回全部帖子
</Button>
<Button type="button" size="sm" onClick={() => nav(user ? composeTarget : loginPath(composeTarget))}>
{user ? '发帖' : '登录后发帖'}
</Button>
</>
) : (
<>
@@ -213,9 +243,7 @@ export default function VirtualPostList({
return (
<div className="post-list-scroll" ref={parentRef}>
{isInitialLoad ? (
<PostListSkeleton />
) : isEmpty ? (
{isInitialLoad ? null : isEmpty ? (
<div className="empty-feed" role="status">
{isSearchEmpty
? <SearchX className="empty-feed-icon" aria-hidden size={36} strokeWidth={1.5} />
@@ -231,7 +259,9 @@ export default function VirtualPostList({
{noBoards
? (isAdmin ? '创建第一个板块后即可开始发帖' : '管理员创建板块后即可参与讨论')
: isSearchEmpty
? '试试更短的关键词,或浏览标签云 / 板块'
? (searchSummaryParts.length > 0
? `当前筛选:${searchSummaryParts.join(' · ')}。试试更短的关键词或放宽条件。`
: '试试更短的关键词,或浏览标签云 / 板块')
: boardName
? `「${boardName}」还没有内容,来发第一篇吧`
: '换个板块看看,或发第一篇内容'}
@@ -259,7 +289,7 @@ export default function VirtualPostList({
transform: `translateY(${offsetY}px)`,
}}
>
<PostListItem post={post} sort={sort} onSelect={onSelect} />
<PostListItem post={post} sort={sort} boardId={boardId} onSelect={onSelect} />
</div>
);
})}

View File

@@ -0,0 +1,215 @@
import {
type CSSProperties,
type ElementType,
type HTMLAttributes,
type ReactNode,
} from 'react';
import {
DndContext,
closestCenter,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
type DragEndEvent,
} from '@dnd-kit/core';
import {
SortableContext,
rectSortingStrategy,
sortableKeyboardCoordinates,
useSortable,
verticalListSortingStrategy,
type SortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { ArrowDown, ArrowUp, GripVertical } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { reorderItems, shouldShowSortableMoveButtons } from '../../utils/sortOrder';
export type SortableItemControls = {
setNodeRef: (node: HTMLElement | null) => void;
style: CSSProperties;
isDragging: boolean;
dragHandleProps: HTMLAttributes<HTMLButtonElement>;
moveUp: () => void;
moveDown: () => void;
canMoveUp: boolean;
canMoveDown: boolean;
};
type AdminSortableListProps<T> = {
items: T[];
getId: (item: T) => string | number;
onReorder: (items: T[]) => void;
renderItem: (item: T, index: number, controls: SortableItemControls) => ReactNode;
showMoveButtons?: boolean | 'auto';
strategy?: 'vertical' | 'grid';
as?: ElementType;
className?: string;
ariaLabel?: string;
};
function resolveStrategy(mode: 'vertical' | 'grid'): SortingStrategy {
return mode === 'grid' ? rectSortingStrategy : verticalListSortingStrategy;
}
function SortableItem<T>({
item,
index,
items,
getId,
onReorder,
showMoveButtons,
renderItem,
}: {
item: T;
index: number;
items: T[];
getId: (item: T) => string | number;
onReorder: (items: T[]) => void;
showMoveButtons: boolean;
renderItem: AdminSortableListProps<T>['renderItem'];
}) {
const id = getId(item);
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id });
const style: CSSProperties = {
transform: CSS.Transform.toString(transform),
transition,
};
const moveUp = () => {
if (index > 0) onReorder(reorderItems(items, index, index - 1));
};
const moveDown = () => {
if (index < items.length - 1) onReorder(reorderItems(items, index, index + 1));
};
const controls: SortableItemControls = {
setNodeRef,
style,
isDragging,
dragHandleProps: { ...attributes, ...listeners },
moveUp,
moveDown,
canMoveUp: index > 0,
canMoveDown: index < items.length - 1,
};
return (
<>
{renderItem(item, index, controls)}
{showMoveButtons && (
<span className="sr-only" aria-live="polite">
{controls.canMoveUp ? '可上移' : ''}{controls.canMoveDown ? '可下移' : ''}
</span>
)}
</>
);
}
export function SortableDragHandle({
label = '拖拽调整顺序',
className = 'admin-sortable-row__handle',
...props
}: HTMLAttributes<HTMLButtonElement> & { label?: string }) {
return (
<button
type="button"
className={className}
aria-label={label}
{...props}
>
<GripVertical size={16} aria-hidden />
</button>
);
}
export function SortableMoveButtons({
controls,
className = 'admin-sortable-row__order',
}: {
controls: Pick<SortableItemControls, 'moveUp' | 'moveDown' | 'canMoveUp' | 'canMoveDown'>;
className?: string;
}) {
return (
<div className={className}>
<Button
type="button"
variant="ghost"
size="icon"
disabled={!controls.canMoveUp}
onClick={controls.moveUp}
aria-label="上移"
>
<ArrowUp size={14} />
</Button>
<Button
type="button"
variant="ghost"
size="icon"
disabled={!controls.canMoveDown}
onClick={controls.moveDown}
aria-label="下移"
>
<ArrowDown size={14} />
</Button>
</div>
);
}
export default function AdminSortableList<T>({
items,
getId,
onReorder,
renderItem,
showMoveButtons = 'auto',
strategy = 'vertical',
as: Wrapper = 'div',
className,
ariaLabel,
}: AdminSortableListProps<T>) {
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
);
const moveButtons = shouldShowSortableMoveButtons(items.length, showMoveButtons);
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (!over || active.id === over.id) return;
const oldIndex = items.findIndex(item => getId(item) === active.id);
const newIndex = items.findIndex(item => getId(item) === over.id);
if (oldIndex < 0 || newIndex < 0) return;
onReorder(reorderItems(items, oldIndex, newIndex));
};
return (
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={items.map(getId)} strategy={resolveStrategy(strategy)}>
<Wrapper className={className} role={ariaLabel ? 'group' : undefined} aria-label={ariaLabel}>
{items.map((item, index) => (
<SortableItem
key={String(getId(item))}
item={item}
index={index}
items={items}
getId={getId}
onReorder={onReorder}
showMoveButtons={moveButtons}
renderItem={renderItem}
/>
))}
</Wrapper>
</SortableContext>
</DndContext>
);
}

View File

@@ -0,0 +1,79 @@
import AdminSortableList, { SortableDragHandle } from './AdminSortableList';
import type { AsideWidget, AsideWidgetId } from '../../api/types';
const WIDGET_META: Record<AsideWidgetId, { label: string; hint: string }> = {
tag_cloud: {
label: '标签云',
hint: '在右侧栏展示热门标签',
},
recent_comments: {
label: '最新评论',
hint: '在右侧栏展示最近回复',
},
recent_users: {
label: '最新注册',
hint: '在右侧栏展示最近注册的用户',
},
friend_links: {
label: '友情链接',
hint: '关闭后不在右侧栏展示,友链仍可在「友情链接」页面查看与申请',
},
showcase: {
label: '开源展柜',
hint: '展示精选公网部署;关闭后仍可直接访问 /showcase',
},
};
type Props = {
widgets: AsideWidget[];
onChange: (next: AsideWidget[]) => void;
};
export default function AsideWidgetList({ widgets, onChange }: Props) {
const handleToggle = (id: AsideWidgetId, enabled: boolean) => {
onChange(widgets.map(w => (w.id === id ? { ...w, enabled } : w)));
};
return (
<AdminSortableList
items={widgets}
getId={widget => widget.id}
onReorder={onChange}
showMoveButtons={false}
className="admin-sortable-list admin-sortable-list--boxed"
ariaLabel="右侧栏组件"
renderItem={(widget, _index, controls) => {
const meta = WIDGET_META[widget.id];
return (
<div
ref={controls.setNodeRef}
style={controls.style}
className={`admin-sortable-row admin-sortable-row--widget${controls.isDragging ? ' is-dragging' : ''}`}
>
<SortableDragHandle
label={`拖拽调整「${meta.label}」顺序`}
{...controls.dragHandleProps}
/>
<div className="admin-sortable-row__main">
<span className="admin-sortable-row__label" id={`aside-widget-label-${widget.id}`}>
{meta.label}
</span>
<span className="admin-sortable-row__hint">{meta.hint}</span>
</div>
<button
type="button"
id={`aside-widget-${widget.id}`}
role="switch"
aria-checked={widget.enabled}
aria-labelledby={`aside-widget-label-${widget.id}`}
className={`admin-settings-switch${widget.enabled ? ' is-on' : ''}`}
onClick={() => handleToggle(widget.id, !widget.enabled)}
>
<span className="admin-settings-switch-ui" aria-hidden />
</button>
</div>
);
}}
/>
);
}

View File

@@ -0,0 +1,90 @@
import { useEffect, useState } from 'react';
import { Heart } from 'lucide-react';
import { notify } from '@/lib/notify';
import { api } from '../../api/client';
import type { CommunityConfig } from '../../api/types';
const EMPTY_COMMUNITY: CommunityConfig = {
report_enabled: false,
hub_enabled: false,
hub_url: 'https://bbs.iioio.com',
site_url: '',
instance_id: '',
};
/** 仪表盘页脚:自愿社区上报开关(默认关,即时保存;枢纽站不显示) */
export default function CommunitySupportStrip() {
const [community, setCommunity] = useState<CommunityConfig>(EMPTY_COMMUNITY);
const [saving, setSaving] = useState(false);
const [ready, setReady] = useState(false);
useEffect(() => {
let cancelled = false;
api.adminSettings()
.then((s) => {
if (!cancelled) {
setCommunity({ ...EMPTY_COMMUNITY, ...(s.community ?? {}) });
setReady(true);
}
})
.catch(() => {
if (!cancelled) setReady(true);
});
return () => { cancelled = true; };
}, []);
const handleToggle = async () => {
if (saving || !ready) return;
const next = !community.report_enabled;
const prev = community;
setCommunity((c) => ({ ...c, report_enabled: next }));
setSaving(true);
try {
const r = await api.adminUpdateCommunitySettings({
...EMPTY_COMMUNITY,
report_enabled: next,
});
setCommunity({ ...EMPTY_COMMUNITY, ...r.community });
if (r.heartbeat_error) {
notify.warning(`${r.message}:${r.heartbeat_error}`);
} else {
notify.success(next ? '已开启社区上报' : '已关闭社区上报');
}
} catch (e: unknown) {
setCommunity(prev);
notify.error(e instanceof Error ? e.message : '保存失败');
} finally {
setSaving(false);
}
};
// 官网 / 枢纽站本身就是收报方,无需「支持开源」上报条
if (!ready || community.hub_enabled) {
return null;
}
return (
<div className="admin-community-support-strip" role="group" aria-label="支持姜十三开源">
<div className="admin-community-support-strip-main">
<Heart size={16} className="admin-community-support-strip-icon" aria-hidden />
<div className="admin-community-support-strip-copy">
<strong>支持姜十三开源</strong>
<span>
匿名向 bbs.iioio.com 上报站点地址、版本与规模;开启后有机会获官方演示站展示与推荐,可随时关闭
</span>
</div>
</div>
<button
type="button"
role="switch"
aria-checked={community.report_enabled}
aria-busy={saving}
disabled={saving || !ready}
className={`admin-settings-switch${community.report_enabled ? ' is-on' : ''}`}
onClick={() => void handleToggle()}
>
<span className="admin-settings-switch-ui" aria-hidden />
</button>
</div>
);
}

View File

@@ -0,0 +1,89 @@
import { Pencil } from 'lucide-react';
import { Input } from '@/components/ui/input';
import AdminSortableList, { SortableDragHandle } from './AdminSortableList';
import type { FeedSortId, FeedSortTab } from '../../api/types';
import { normalizeFeedSortTabs } from '../../utils/feedSortTabs';
const TAB_META: Record<FeedSortId, { hint: string; placeholder: string }> = {
reply: { hint: '按最近活动(发帖或评论)', placeholder: '最新' },
latest: { hint: '按发帖时间', placeholder: '新帖子' },
hot: { hint: '仅展示推荐帖', placeholder: '推荐帖' },
};
type Props = {
tabs: FeedSortTab[];
onChange: (next: FeedSortTab[]) => void;
};
export default function FeedSortTabList({ tabs, onChange }: Props) {
const items = normalizeFeedSortTabs(tabs);
const handleToggle = (id: FeedSortId, enabled: boolean) => {
const next = items.map(t => (t.id === id ? { ...t, enabled } : t));
// 不允许全部关闭:关掉最后一项时忽略
if (!enabled && !next.some(t => t.enabled)) return;
onChange(normalizeFeedSortTabs(next));
};
const handleLabel = (id: FeedSortId, label: string) => {
onChange(normalizeFeedSortTabs(items.map(t => (t.id === id ? { ...t, label } : t))));
};
return (
<AdminSortableList
items={items}
getId={tab => tab.id}
onReorder={next => onChange(normalizeFeedSortTabs(next))}
showMoveButtons={false}
className="admin-sortable-list admin-sortable-list--boxed"
ariaLabel="首页排序标签"
renderItem={(tab, _index, controls) => {
const meta = TAB_META[tab.id];
return (
<div
ref={controls.setNodeRef}
style={controls.style}
className={`admin-sortable-row admin-sortable-row--widget${controls.isDragging ? ' is-dragging' : ''}`}
>
<SortableDragHandle
label={`拖拽调整「${tab.label || meta.placeholder}」顺序`}
{...controls.dragHandleProps}
/>
<div className="admin-sortable-row__main">
<label className="admin-sortable-row__field" htmlFor={`feed-sort-label-${tab.id}`}>
<span className="admin-sortable-row__field-name">显示名称</span>
<span className="admin-sortable-row__name-wrap">
<Input
id={`feed-sort-label-${tab.id}`}
type="text"
className="admin-sortable-row__name-input"
value={tab.label}
maxLength={16}
placeholder={meta.placeholder}
onChange={e => handleLabel(tab.id, e.target.value)}
aria-describedby={`feed-sort-hint-${tab.id}`}
/>
<Pencil className="admin-sortable-row__name-icon" size={14} aria-hidden />
</span>
</label>
<span className="admin-sortable-row__hint" id={`feed-sort-hint-${tab.id}`}>
{meta.hint}
</span>
</div>
<button
type="button"
id={`feed-sort-${tab.id}`}
role="switch"
aria-checked={tab.enabled}
aria-label={`启用「${tab.label || meta.placeholder}」`}
className={`admin-settings-switch${tab.enabled ? ' is-on' : ''}`}
onClick={() => handleToggle(tab.id, !tab.enabled)}
>
<span className="admin-settings-switch-ui" aria-hidden />
</button>
</div>
);
}}
/>
);
}

View File

@@ -0,0 +1,91 @@
import { useMemo, useState } from 'react';
import china from '@svg-maps/china';
import { cn } from '@/lib/utils';
import { buildChinaRegionCountMap, heatFill } from './monitorMapUtils';
type Loc = { id: string; name: string; path: string };
type RegionStat = {
country: string;
region?: string;
region_iso?: string;
count: number;
};
type Props = {
regions: RegionStat[];
className?: string;
/** 近 30 日是否已有国家级浏览量 */
hasCountryHits?: boolean;
/** 近 30 日是否已有省级浏览量 */
hasRegionHits?: boolean;
};
/** 中国省区地图:按 BIN 解析出的省/区填色 */
export default function MonitorChinaMap({
regions,
className,
hasCountryHits = false,
hasRegionHits = false,
}: Props) {
const [hover, setHover] = useState<{ name: string; count: number } | null>(null);
const counts = useMemo(() => buildChinaRegionCountMap(regions), [regions]);
const max = useMemo(() => Math.max(0, ...Object.values(counts)), [counts]);
const hasData = max > 0;
const locations = (china as { locations: Loc[]; viewBox: string }).locations;
const viewBox = (china as { viewBox: string }).viewBox;
let emptyTitle = '暂无省级访问数据';
let emptyHint = '放置 IP2LOCATION-LITE-DB3.BIN 后按省/区填色';
if (hasCountryHits && !hasRegionHits) {
emptyTitle = '有国家浏览量,尚无省级数据';
emptyHint = '需前台路由产生带省字段的浏览量;仅请求日志不会点亮中国地图。请确认已放置 IP2Location DB3 BIN。';
} else if (!hasCountryHits) {
emptyTitle = '暂无浏览量地理数据';
emptyHint = '需前台路由产生浏览量后才会按省填色;仅请求日志不会点亮此处。';
}
return (
<div className={cn('admin-monitor-svg-wrap', className)}>
<svg
className="admin-monitor-svg-map"
viewBox={viewBox}
role="img"
aria-label="中国访客地图"
>
{locations.map((loc) => {
const count = counts[loc.id] || 0;
return (
<path
key={loc.id}
d={loc.path}
fill={heatFill(count, max, hasData)}
stroke="hsl(var(--background, 0 0% 100%))"
strokeWidth={0.6}
className={cn('admin-monitor-svg-path', count > 0 && 'has-data')}
onMouseEnter={() => setHover({ name: loc.name, count })}
onMouseLeave={() => setHover(null)}
>
<title>
{loc.name}
{count > 0 ? ` · ${count}` : ''}
</title>
</path>
);
})}
</svg>
{hover && (
<div className="admin-monitor-map-tip" role="status">
<strong>{hover.name}</strong>
<span>{hover.count > 0 ? hover.count : '—'}</span>
</div>
)}
{!hasData && (
<div className="admin-monitor-map-empty-overlay">
<p>{emptyTitle}</p>
<p>{emptyHint}</p>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,121 @@
import { useMemo, useState } from 'react';
import world from '@svg-maps/world';
import { cn } from '@/lib/utils';
import {
buildCountMap,
countryLabelZh,
emptyFill,
heatFill,
type GeoCountMap,
} from './monitorMapUtils';
type Loc = { id: string; name: string; path: string };
type Props = {
items: { country: string; count: number }[];
className?: string;
/** 裁切到东亚(中国模式) */
focusChina?: boolean;
};
const CHINA_VIEWBOX = '680 260 220 200';
export default function MonitorWorldMap({ items, className, focusChina }: Props) {
const [hover, setHover] = useState<{ code: string; name: string; count: number } | null>(null);
const counts = useMemo(() => buildCountMap(items), [items]);
const max = useMemo(() => Math.max(0, ...Object.values(counts)), [counts]);
const hasData = max > 0;
const locations = (world as { locations: Loc[]; viewBox: string }).locations;
const viewBox = focusChina ? CHINA_VIEWBOX : (world as { viewBox: string }).viewBox;
const filteredCounts: GeoCountMap = useMemo(() => {
if (!focusChina) return counts;
const allow = new Set(['CN', 'HK', 'MO', 'TW']);
const m: GeoCountMap = {};
for (const [k, v] of Object.entries(counts)) {
if (allow.has(k)) m[k] = v;
}
return m;
}, [counts, focusChina]);
const focusMax = useMemo(
() => Math.max(0, ...Object.values(filteredCounts)),
[filteredCounts],
);
const focusHas = focusMax > 0;
return (
<div className={cn('admin-monitor-svg-wrap', className)}>
<svg
className="admin-monitor-svg-map"
viewBox={viewBox}
role="img"
aria-label={focusChina ? '中国及周边访客地图' : '世界访客地图'}
>
{locations.map((loc) => {
const code = loc.id.toUpperCase();
if (focusChina) {
// 中国模式下非本区域保持极淡灰,本区域按数据着色
const inRegion = code === 'CN' || code === 'HK' || code === 'MO' || code === 'TW'
|| code === 'JP' || code === 'KR' || code === 'MN' || code === 'KP'
|| code === 'RU' || code === 'IN' || code === 'VN' || code === 'LA'
|| code === 'MM' || code === 'BT' || code === 'NP' || code === 'KZ'
|| code === 'KG' || code === 'TJ' || code === 'UZ' || code === 'AF'
|| code === 'PK' || code === 'PH' || code === 'MY' || code === 'TH'
|| code === 'KH' || code === 'BD' || code === 'LK';
if (!inRegion) return null;
}
const count = filteredCounts[code] || (focusChina ? 0 : counts[code]) || 0;
const useMax = focusChina ? focusMax : max;
const useHas = focusChina ? focusHas : hasData;
const isCore = !focusChina || code === 'CN' || code === 'HK' || code === 'MO' || code === 'TW';
const fill = isCore
? heatFill(count, useMax, useHas)
: emptyFill(useHas);
return (
<path
key={loc.id}
d={loc.path}
data-code={code}
fill={fill}
stroke="hsl(var(--background, 0 0% 100%))"
strokeWidth={focusChina ? 0.35 : 0.4}
className={cn('admin-monitor-svg-path', count > 0 && 'has-data')}
onMouseEnter={() => setHover({
code,
name: countryLabelZh(code, loc.name),
count: focusChina && !isCore ? 0 : count,
})}
onMouseLeave={() => setHover(null)}
>
<title>
{countryLabelZh(code, loc.name)}
{count > 0 ? ` · ${count}` : ''}
</title>
</path>
);
})}
</svg>
{hover && (
<div className="admin-monitor-map-tip" role="status">
<strong>{hover.name}</strong>
<span>{hover.count > 0 ? hover.count : '—'}</span>
</div>
)}
{!hasData && !focusChina && (
<div className="admin-monitor-map-empty-overlay">
<p>暂无国家数据</p>
<p>配置 GeoIP 或 CDN 国家头后可见</p>
</div>
)}
{focusChina && !focusHas && (
<div className="admin-monitor-map-empty-overlay">
<p>暂无中国地区访问数据</p>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,130 @@
/** 监控地图共用:国家码 → 数量色阶(本站绿色) */
export type GeoCountMap = Record<string, number>;
const EMPTY = 'var(--j13-border, #e5e7eb)';
const BASE = 'hsl(var(--muted, 210 20% 94%))';
/** 由浅到深的绿色阶 */
const GREEN_STEPS = [
'color-mix(in srgb, var(--j13-green) 28%, hsl(var(--card)))',
'color-mix(in srgb, var(--j13-green) 45%, hsl(var(--card)))',
'color-mix(in srgb, var(--j13-green) 62%, hsl(var(--card)))',
'color-mix(in srgb, var(--j13-green) 80%, hsl(var(--card)))',
'var(--j13-green)',
];
export function buildCountMap(items: { country: string; count: number }[]): GeoCountMap {
const m: GeoCountMap = {};
for (const it of items) {
const code = (it.country || '').toUpperCase();
if (!code) continue;
m[code] = (m[code] || 0) + it.count;
}
return m;
}
/** MaxMind region_iso / 中英文省名 → @svg-maps/china 的 location id */
const CN_ISO_TO_SVG: Record<string, string> = {
AH: 'anhui', BJ: 'beijing', CQ: 'chongqing', FJ: 'fujian', GS: 'gansu',
GD: 'guangdong', GX: 'guangxi-zhuang', GZ: 'guizhou', HI: 'hainan', HE: 'hebei',
HL: 'heilongjiang', HA: 'henan', HB: 'hubei', HN: 'hunan', JS: 'jiangsu',
JX: 'jiangxi', JL: 'jilin', LN: 'liaoning', NM: 'nei-mongol', NX: 'ningxia-hui',
QH: 'quinghai', SN: 'shaanxi', SD: 'shandong', SH: 'shanghai', SX: 'shanxi',
SC: 'sichuan', TJ: 'tianjin', XJ: 'xinjiang-uygur', XZ: 'xizang', YN: 'yunnan',
ZJ: 'zhejiang', HK: 'hong-kong', MO: 'macau',
};
const CN_NAME_TO_SVG: Record<string, string> = {
安徽: 'anhui', anhui: 'anhui',
北京: 'beijing', beijing: 'beijing',
重庆: 'chongqing', chongqing: 'chongqing',
福建: 'fujian', fujian: 'fujian',
甘肃: 'gansu', gansu: 'gansu',
广东: 'guangdong', guangdong: 'guangdong',
广西: 'guangxi-zhuang', '广西壮族自治区': 'guangxi-zhuang', 'guangxi zhuang': 'guangxi-zhuang', guangxi: 'guangxi-zhuang',
贵州: 'guizhou', guizhou: 'guizhou',
海南: 'hainan', hainan: 'hainan',
河北: 'hebei', hebei: 'hebei',
黑龙江: 'heilongjiang', heilongjiang: 'heilongjiang',
河南: 'henan', henan: 'henan',
湖北: 'hubei', hubei: 'hubei',
湖南: 'hunan', hunan: 'hunan',
江苏: 'jiangsu', jiangsu: 'jiangsu',
江西: 'jiangxi', jiangxi: 'jiangxi',
吉林: 'jilin', jilin: 'jilin',
辽宁: 'liaoning', liaoning: 'liaoning',
内蒙古: 'nei-mongol', '内蒙古自治区': 'nei-mongol', 'nei mongol': 'nei-mongol', 'inner mongolia': 'nei-mongol',
宁夏: 'ningxia-hui', '宁夏回族自治区': 'ningxia-hui', 'ningxia hui': 'ningxia-hui', ningxia: 'ningxia-hui',
青海: 'quinghai', qinghai: 'quinghai', quinghai: 'quinghai',
陕西: 'shaanxi', shaanxi: 'shaanxi',
山东: 'shandong', shandong: 'shandong',
上海: 'shanghai', shanghai: 'shanghai',
山西: 'shanxi', shanxi: 'shanxi',
四川: 'sichuan', sichuan: 'sichuan',
天津: 'tianjin', tianjin: 'tianjin',
新疆: 'xinjiang-uygur', '新疆维吾尔自治区': 'xinjiang-uygur', 'xinjiang uygur': 'xinjiang-uygur', xinjiang: 'xinjiang-uygur',
西藏: 'xizang', '西藏自治区': 'xizang', xizang: 'xizang', tibet: 'xizang',
云南: 'yunnan', yunnan: 'yunnan',
浙江: 'zhejiang', zhejiang: 'zhejiang',
香港: 'hong-kong', 'hong kong': 'hong-kong',
澳门: 'macau', macau: 'macau', macao: 'macau',
};
export function chinaRegionToSvgId(regionISO?: string, regionName?: string): string | null {
const iso = (regionISO || '').trim().toUpperCase().replace(/^CN-/, '');
if (iso && CN_ISO_TO_SVG[iso]) return CN_ISO_TO_SVG[iso];
const name = (regionName || '').trim().toLowerCase();
if (!name) return null;
if (CN_NAME_TO_SVG[name]) return CN_NAME_TO_SVG[name];
// 尝试去掉「省/市/自治区」后缀后再匹配中文键
const zh = (regionName || '').trim()
.replace(/(壮族|回族|维吾尔)?自治区$/, '')
.replace(/(省|市)$/, '');
if (CN_NAME_TO_SVG[zh]) return CN_NAME_TO_SVG[zh];
return null;
}
/** 将省级统计聚合为 svg-maps/china 的 id → count */
export function buildChinaRegionCountMap(
regions: { country: string; region?: string; region_iso?: string; count: number }[],
): GeoCountMap {
const m: GeoCountMap = {};
for (const it of regions) {
const c = (it.country || '').toUpperCase();
if (c && c !== 'CN' && c !== 'HK' && c !== 'MO' && c !== 'TW') continue;
const id = chinaRegionToSvgId(it.region_iso, it.region);
if (!id) continue;
m[id] = (m[id] || 0) + it.count;
}
return m;
}
export function heatFill(count: number, max: number, hasAnyData: boolean): string {
if (!hasAnyData) return BASE;
if (!count || max <= 0) return BASE;
const t = Math.log1p(count) / Math.log1p(max);
const idx = Math.min(GREEN_STEPS.length - 1, Math.floor(t * GREEN_STEPS.length));
return GREEN_STEPS[Math.max(0, idx)];
}
export function emptyFill(hasAnyData: boolean): string {
return hasAnyData ? BASE : EMPTY;
}
export const COUNTRY_NAMES_ZH: Record<string, string> = {
CN: '中国', US: '美国', JP: '日本', KR: '韩国', HK: '中国香港', TW: '中国台湾', MO: '中国澳门',
SG: '新加坡', DE: '德国', GB: '英国', FR: '法国', RU: '俄罗斯', AU: '澳大利亚',
CA: '加拿大', IN: '印度', BR: '巴西', NL: '荷兰', IT: '意大利', ES: '西班牙',
MY: '马来西亚', TH: '泰国', VN: '越南', ID: '印尼', PH: '菲律宾', MX: '墨西哥',
TR: '土耳其', SA: '沙特', AE: '阿联酋', ZA: '南非', NZ: '新西兰', SE: '瑞典',
NO: '挪威', FI: '芬兰', DK: '丹麦', PL: '波兰', CH: '瑞士', AT: '奥地利',
BE: '比利时', IE: '爱尔兰', PT: '葡萄牙', AR: '阿根廷', CL: '智利', CO: '哥伦比亚',
PK: '巴基斯坦', BD: '孟加拉', EG: '埃及', NG: '尼日利亚', KE: '肯尼亚',
UA: '乌克兰', CZ: '捷克', RO: '罗马尼亚', HU: '匈牙利', GR: '希腊', IL: '以色列',
};
export function countryLabelZh(code: string, fallbackName?: string) {
const c = code.toUpperCase();
return COUNTRY_NAMES_ZH[c] || fallbackName || c;
}

View File

@@ -3,7 +3,13 @@ import BoardIconDisplay from '../BoardIconDisplay';
import { getBoardThemeIndex } from '../../utils/boardTheme';
import type { Board, ForumLimitsPublic } from '../../api/types';
export type PostType = 'normal' | 'question';
export type PostType = 'normal' | 'question' | 'poll' | 'bounty' | 'lottery';
const SPECIAL_TYPE_LABELS: Record<'poll' | 'bounty' | 'lottery', string> = {
poll: '投票',
bounty: '悬赏',
lottery: '抽奖',
};
interface Props {
isEdit: boolean;
@@ -32,12 +38,26 @@ export default function ComposeContextBar({
onTagsChange,
limits,
}: Props) {
const isSpecialEdit = isEdit && (postType === 'poll' || postType === 'bounty' || postType === 'lottery');
return (
<section className="compose-context" aria-label="发布设置">
<div className="compose-context-row">
<span className="compose-context-label">类型</span>
<div className="compose-type-field">
<div className="compose-type-pills" role="radiogroup" aria-label="帖子类型">
{isSpecialEdit ? (
<button
type="button"
role="radio"
aria-checked
className="compose-type-pill active"
disabled
>
{SPECIAL_TYPE_LABELS[postType]}
</button>
) : (
<>
<button
type="button"
role="radio"
@@ -53,13 +73,58 @@ export default function ComposeContextBar({
aria-checked={postType === 'question'}
className={`compose-type-pill${postType === 'question' ? ' active' : ''}`}
onClick={() => onPostTypeChange('question')}
disabled={isEdit}
>
问答
</button>
{!isEdit && (
<>
<button
type="button"
role="radio"
aria-checked={postType === 'poll'}
className={`compose-type-pill${postType === 'poll' ? ' active' : ''}`}
onClick={() => onPostTypeChange('poll')}
>
投票
</button>
<button
type="button"
role="radio"
aria-checked={postType === 'bounty'}
className={`compose-type-pill${postType === 'bounty' ? ' active' : ''}`}
onClick={() => onPostTypeChange('bounty')}
>
悬赏
</button>
<button
type="button"
role="radio"
aria-checked={postType === 'lottery'}
className={`compose-type-pill${postType === 'lottery' ? ' active' : ''}`}
onClick={() => onPostTypeChange('lottery')}
>
抽奖
</button>
</>
)}
</>
)}
</div>
{postType === 'question' && (
<span className="compose-type-hint">问答可标记解决状态</span>
)}
{postType === 'poll' && (
<span className="compose-type-hint">
{isEdit ? '投票选项发布后不可修改' : '发布后选项不可修改'}
</span>
)}
{postType === 'bounty' && (
<span className="compose-type-hint">发布成功即扣除积分;有人回复后不可自行取消,需采纳或联系管理员</span>
)}
{postType === 'lottery' && (
<span className="compose-type-hint">回帖参与,手动开奖</span>
)}
</div>
</div>
<div className="compose-context-row">

View File

@@ -0,0 +1,259 @@
import { Plus, Trash2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import type { PostType } from './ComposeContextBar';
interface Props {
postType: PostType;
pollOptions: string[];
onPollOptionsChange: (opts: string[]) => void;
pollMulti: boolean;
onPollMultiChange: (v: boolean) => void;
pollMaxChoices: number;
onPollMaxChoicesChange: (v: number) => void;
pollEndsAt: string;
onPollEndsAtChange: (v: string) => void;
pollNoEndTime: boolean;
onPollNoEndTimeChange: (v: boolean) => void;
bountyPoints: number;
onBountyPointsChange: (v: number) => void;
userPointsBalance?: number;
lotteryWinners: number;
onLotteryWinnersChange: (v: number) => void;
disabled?: boolean;
}
/** 默认截止时间:7 天后,分钟进位到下一整点 */
export function defaultPollEndsAtLocal(): string {
const d = new Date(Date.now() + 7 * 24 * 3600_000);
d.setMinutes(0, 0, 0);
if (d.getTime() <= Date.now()) {
d.setHours(d.getHours() + 1);
}
const pad = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
/** datetime-local → ISO8601(UTC) */
export function pollEndsAtLocalToISO(local: string): string | undefined {
const trimmed = local.trim();
if (!trimmed) return undefined;
const d = new Date(trimmed);
if (Number.isNaN(d.getTime())) return undefined;
return d.toISOString();
}
/** ISO8601 → datetime-local */
export function pollEndsAtISOToLocal(iso: string): string {
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return '';
const pad = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
/** 特殊帖类型附加字段(投票/悬赏/抽奖) */
export default function ComposeSpecialFields({
postType,
pollOptions,
onPollOptionsChange,
pollMulti,
onPollMultiChange,
pollMaxChoices,
onPollMaxChoicesChange,
pollEndsAt,
onPollEndsAtChange,
pollNoEndTime,
onPollNoEndTimeChange,
bountyPoints,
onBountyPointsChange,
userPointsBalance,
lotteryWinners,
onLotteryWinnersChange,
disabled,
}: Props) {
if (postType === 'normal' || postType === 'question') return null;
if (postType === 'poll') {
return (
<section className="compose-special" aria-label="投票设置">
<Label>投票选项(2-10 项)</Label>
<div className="compose-special__poll-mode">
<Switch checked={pollMulti} onCheckedChange={onPollMultiChange} disabled={disabled} id="poll-multi" />
<label htmlFor="poll-multi">允许多选</label>
{pollMulti && (
<>
<span className="compose-special__max-choices-label">最多可选</span>
<Input
type="number"
min={1}
max={pollOptions.length || 10}
value={pollMaxChoices}
onChange={e => onPollMaxChoicesChange(Number(e.target.value) || 1)}
disabled={disabled}
className="compose-special__max-choices"
aria-label="最多可选"
/>
<span className="compose-special__max-choices-suffix">项</span>
</>
)}
</div>
<div className="compose-special__poll-deadline">
<div className="compose-special__poll-deadline-toggle">
<Switch
checked={pollNoEndTime}
onCheckedChange={onPollNoEndTimeChange}
disabled={disabled}
id="poll-no-end-time"
/>
<label htmlFor="poll-no-end-time">不限时</label>
</div>
{!pollNoEndTime && (
<div className="compose-special__poll-deadline-field">
<Label htmlFor="poll-ends-at" className="compose-special__poll-deadline-label">投票截止时间</Label>
<Input
id="poll-ends-at"
type="datetime-local"
value={pollEndsAt}
onChange={e => onPollEndsAtChange(e.target.value)}
disabled={disabled}
className="compose-special__poll-deadline-input w-auto"
/>
</div>
)}
</div>
<div className="compose-special__options">
{pollOptions.map((opt, i) => (
<div key={i} className="compose-special__option-row">
<Input
value={opt}
placeholder={`选项 ${i + 1}`}
maxLength={64}
disabled={disabled}
onChange={e => {
const next = [...pollOptions];
next[i] = e.target.value;
onPollOptionsChange(next);
}}
/>
<Button
type="button"
variant="ghost"
size="icon"
disabled={disabled || pollOptions.length <= 2}
onClick={() => onPollOptionsChange(pollOptions.filter((_, j) => j !== i))}
aria-label="删除选项"
>
<Trash2 size={16} />
</Button>
</div>
))}
</div>
{pollOptions.length < 10 && (
<Button
type="button"
variant="outline"
size="sm"
disabled={disabled}
onClick={() => onPollOptionsChange([...pollOptions, ''])}
>
<Plus size={14} /> 添加选项
</Button>
)}
</section>
);
}
if (postType === 'bounty') {
const showBalance = !disabled && typeof userPointsBalance === 'number';
const balance = userPointsBalance ?? 0;
const overBudget = showBalance && bountyPoints > balance;
const remaining = showBalance && bountyPoints > 0 && !overBudget
? balance - bountyPoints
: null;
return (
<section className="compose-special" aria-label="悬赏设置">
<Label htmlFor="bounty-points">悬赏积分(发布即扣除)</Label>
<div className="compose-special__bounty-row">
<Input
id="bounty-points"
type="number"
min={1}
value={bountyPoints || ''}
disabled={disabled}
onChange={e => onBountyPointsChange(Math.max(0, Number(e.target.value) || 0))}
/>
{showBalance && (
<p className={cn(
'compose-special__balance',
overBudget && 'compose-special__balance--over',
)}
>
{overBudget
? '积分不足'
: remaining != null
? `当前余额 ${balance} · 发布后剩余 ${remaining}`
: `当前余额 ${balance}`}
</p>
)}
</div>
</section>
);
}
if (postType === 'lottery') {
return (
<section className="compose-special" aria-label="抽奖设置">
<Label htmlFor="lottery-winners">中奖人数(1-20)</Label>
<Input
id="lottery-winners"
type="number"
min={1}
max={20}
value={lotteryWinners || 1}
disabled={disabled}
onChange={e => onLotteryWinnersChange(Math.min(20, Math.max(1, Number(e.target.value) || 1)))}
/>
<p className="compose-special__hint">参与者为已回帖用户(不含楼主),由作者或管理员开奖</p>
</section>
);
}
return null;
}
export function buildPollOptionsPayload(
options: string[],
multi: boolean,
maxChoices: number,
endsAtISO?: string | null,
): string {
const payload: Record<string, unknown> = {
multi,
max_choices: maxChoices,
options: options.filter(o => o.trim()).map(text => ({ text: text.trim() })),
};
if (endsAtISO) payload.ends_at = endsAtISO;
return JSON.stringify(payload);
}
/** 统计有效(非空)投票选项数量 */
export function countValidPollOptions(options: string[]): number {
return options.filter(o => o.trim()).length;
}
/** 前端校验投票截止时间(非不限时时) */
export function validatePollEndsAtLocal(local: string): string | null {
const iso = pollEndsAtLocalToISO(local);
if (!iso) return '请选择有效的投票截止时间';
if (new Date(iso).getTime() <= Date.now() + 5 * 60_000) {
return '投票截止时间须晚于当前时间至少 5 分钟';
}
if (new Date(iso).getTime() > Date.now() + 365 * 24 * 3600_000) {
return '投票截止时间不能超过 365 天';
}
return null;
}

View File

@@ -0,0 +1,351 @@
import { useCallback, useEffect, useRef, useState, type DragEvent } from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { notify } from '@/lib/notify';
import { api } from '@/api/client';
import type { MediaItem } from '@/api/types';
import { toPostImageThumbSrc } from '@/utils/postContent';
import { Upload, Link2, Images, Loader2 } from 'lucide-react';
export type ImagePickerTarget = 'rich' | 'markdown';
type PickerTab = 'upload' | 'link' | 'gallery';
interface Props {
open: boolean;
onOpenChange: (open: boolean) => void;
/** 上传或选中后插入一张或多张图片 URL */
onInsert: (urls: string[]) => void;
}
/** 校验可插入的图片地址:外链或站内绝对路径 */
export function isValidImageSrc(url: string): boolean {
const u = url.trim();
if (!u) return false;
if (u.startsWith('/') && !u.startsWith('//')) return true;
try {
const parsed = new URL(u);
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
} catch {
return false;
}
}
const ACCEPT = 'image/jpeg,image/png,image/gif,image/webp';
const PAGE_SIZE = 24;
/** 文章编辑器:统一图片插入(上传 / 链接 / 我的图片) */
export function ArticleImagePickerDialog({
open,
onOpenChange,
onInsert,
}: Props) {
const [tab, setTab] = useState<PickerTab>('upload');
const [url, setUrl] = useState('');
const [uploading, setUploading] = useState(false);
const [dragOver, setDragOver] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const [gallery, setGallery] = useState<MediaItem[]>([]);
const [galleryPage, setGalleryPage] = useState(1);
const [galleryTotalPages, setGalleryTotalPages] = useState(1);
const [galleryLoading, setGalleryLoading] = useState(false);
const [galleryLoaded, setGalleryLoaded] = useState(false);
const [selected, setSelected] = useState<Set<string>>(new Set());
const resetState = useCallback(() => {
setTab('upload');
setUrl('');
setUploading(false);
setDragOver(false);
setGallery([]);
setGalleryPage(1);
setGalleryTotalPages(1);
setGalleryLoading(false);
setGalleryLoaded(false);
setSelected(new Set());
}, []);
useEffect(() => {
if (open) resetState();
}, [open, resetState]);
const handleOpenChange = (next: boolean) => {
if (!next) resetState();
onOpenChange(next);
};
const finishInsert = (urls: string[]) => {
if (!urls.length) return;
onInsert(urls);
handleOpenChange(false);
};
const uploadFiles = async (files: File[]) => {
const images = files.filter(f => f.type.startsWith('image/'));
if (!images.length) {
notify.warning('请选择图片文件(jpeg / png / gif / webp)');
return;
}
setUploading(true);
const urls: string[] = [];
try {
for (const file of images) {
try {
const { url: uploaded } = await api.uploadPostImage(file);
urls.push(uploaded);
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '图片上传失败');
}
}
if (urls.length) finishInsert(urls);
} finally {
setUploading(false);
}
};
const onFileChange = (list: FileList | null) => {
if (!list?.length) return;
void uploadFiles([...list]);
};
const onDrop = (e: DragEvent) => {
e.preventDefault();
setDragOver(false);
if (uploading) return;
void uploadFiles([...e.dataTransfer.files]);
};
const handleLinkInsert = () => {
const next = url.trim();
if (!next) {
notify.warning('请输入图片地址');
return;
}
if (!isValidImageSrc(next)) {
notify.warning('请使用 http(s) 外链或本站以 / 开头的路径');
return;
}
finishInsert([next]);
};
const loadGallery = useCallback(async (page: number, append: boolean) => {
setGalleryLoading(true);
try {
const res = await api.myPostImages({ page, size: PAGE_SIZE });
setGallery(prev => (append ? [...prev, ...res.files] : res.files));
setGalleryPage(res.page);
setGalleryTotalPages(res.total_pages);
setGalleryLoaded(true);
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '加载图片失败');
setGalleryLoaded(true);
} finally {
setGalleryLoading(false);
}
}, []);
useEffect(() => {
if (open && tab === 'gallery' && !galleryLoaded && !galleryLoading) {
void loadGallery(1, false);
}
}, [open, tab, galleryLoaded, galleryLoading, loadGallery]);
const toggleSelect = (itemUrl: string) => {
setSelected(prev => {
const next = new Set(prev);
if (next.has(itemUrl)) next.delete(itemUrl);
else next.add(itemUrl);
return next;
});
};
const handleGalleryInsert = () => {
if (!selected.size) {
notify.warning('请先选择图片');
return;
}
// 保持网格出现顺序
const urls = gallery.filter(f => selected.has(f.url)).map(f => f.url);
finishInsert(urls);
};
const tabs: { id: PickerTab; label: string; icon: typeof Upload }[] = [
{ id: 'upload', label: '上传', icon: Upload },
{ id: 'link', label: '链接', icon: Link2 },
{ id: 'gallery', label: '我的图片', icon: Images },
];
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="article-image-picker">
<DialogHeader>
<DialogTitle>插入图片</DialogTitle>
<DialogDescription>
上传本地文件、粘贴链接,或从已上传图库中选择。
</DialogDescription>
</DialogHeader>
<div className="article-image-picker__tabs" role="tablist">
{tabs.map(t => {
const Icon = t.icon;
return (
<button
key={t.id}
type="button"
role="tab"
aria-selected={tab === t.id}
className={`article-image-picker__tab${tab === t.id ? ' is-active' : ''}`}
onClick={() => setTab(t.id)}
disabled={uploading}
>
<Icon size={14} aria-hidden />
{t.label}
</button>
);
})}
</div>
{tab === 'upload' && (
<div className="article-image-picker__panel">
<div
className={`article-image-picker__drop${dragOver ? ' is-dragover' : ''}${uploading ? ' is-busy' : ''}`}
onDragOver={e => {
e.preventDefault();
if (!uploading) setDragOver(true);
}}
onDragLeave={() => setDragOver(false)}
onDrop={onDrop}
onClick={() => !uploading && fileInputRef.current?.click()}
role="button"
tabIndex={0}
onKeyDown={e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
fileInputRef.current?.click();
}
}}
>
{uploading ? (
<>
<Loader2 size={28} className="article-image-picker__spin" />
<p>正在上传…</p>
</>
) : (
<>
<Upload size={28} />
<p>拖拽图片到此处,或点击选择文件</p>
<span>支持 jpeg / png / gif / webp;多选将并排成图组</span>
</>
)}
</div>
<input
ref={fileInputRef}
type="file"
accept={ACCEPT}
multiple
className="sr-only"
onChange={e => {
onFileChange(e.target.files);
e.target.value = '';
}}
/>
</div>
)}
{tab === 'link' && (
<div className="article-image-picker__panel">
<Input
type="url"
value={url}
placeholder="https://… 或 /uploads/posts/…"
onChange={e => setUrl(e.target.value)}
onKeyDown={e => {
if (e.key === 'Enter') {
e.preventDefault();
handleLinkInsert();
}
}}
autoFocus
/>
<p className="article-image-picker__hint">
粘贴外链或本站已上传地址,无需重复上传。
</p>
<DialogFooter className="article-image-picker__footer">
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)}>
取消
</Button>
<Button type="button" onClick={handleLinkInsert}>
插入
</Button>
</DialogFooter>
</div>
)}
{tab === 'gallery' && (
<div className="article-image-picker__panel">
{galleryLoading && !gallery.length ? (
<div className="article-image-picker__empty">
<Loader2 size={22} className="article-image-picker__spin" />
<span>加载中…</span>
</div>
) : !gallery.length ? (
<div className="article-image-picker__empty">暂无上传记录</div>
) : (
<>
<div className="article-image-picker__grid">
{gallery.map(item => {
const thumb = toPostImageThumbSrc(item.url) || item.url;
const isSel = selected.has(item.url);
return (
<button
key={item.url}
type="button"
className={`article-image-picker__thumb${isSel ? ' is-selected' : ''}`}
title={item.name}
onClick={() => toggleSelect(item.url)}
>
<img src={thumb} alt={item.name} loading="lazy" />
</button>
);
})}
</div>
{galleryPage < galleryTotalPages && (
<div className="article-image-picker__more">
<Button
type="button"
variant="outline"
size="sm"
disabled={galleryLoading}
onClick={() => void loadGallery(galleryPage + 1, true)}
>
{galleryLoading ? '加载中…' : '加载更多'}
</Button>
</div>
)}
</>
)}
<DialogFooter className="article-image-picker__footer">
<span className="article-image-picker__selected-count">
已选 {selected.size}
</span>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)}>
取消
</Button>
<Button type="button" disabled={!selected.size} onClick={handleGalleryInsert}>
插入选中
</Button>
</DialogFooter>
</div>
)}
</DialogContent>
</Dialog>
);
}

View File

@@ -1,39 +1,172 @@
import { useEffect, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { notify } from '@/lib/notify';
import { api } from '@/api/client';
import type { PostItem, SitePageSummary } from '@/api/types';
import { pagePath, postPath } from '@/utils/permalink';
import { useForumLimits } from '@/hooks/useForumLimits';
import { ChevronDown, Loader2 } from 'lucide-react';
export interface ArticleLinkConfirm {
url: string;
text: string;
}
interface Props {
open: boolean;
onOpenChange: (open: boolean) => void;
initialUrl?: string;
onConfirm: (url: string) => void;
initialText?: string;
/** 是否正在编辑已有链接 */
editing?: boolean;
onConfirm: (payload: ArticleLinkConfirm) => void;
onRemove?: () => void;
}
/** 文章编辑器链接输入弹窗 */
type SiteHit = {
key: string;
title: string;
url: string;
kind: 'post' | 'page';
};
/** 校验可插入的链接地址:外链或站内绝对路径 */
export function isValidLinkHref(url: string): boolean {
const u = url.trim();
if (!u) return false;
if (u.startsWith('/') && !u.startsWith('//')) return true;
if (u.startsWith('#') && u.length > 1) return true;
try {
const parsed = new URL(u);
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
} catch {
return false;
}
}
const SEARCH_DEBOUNCE_MS = 300;
const POST_PAGE_SIZE = 12;
/** 文章/评论编辑器:插入或编辑链接(含站内内容搜索) */
export function ArticleLinkDialog({
open,
onOpenChange,
initialUrl = '',
initialText = '',
editing = false,
onConfirm,
onRemove,
}: Props) {
const [url, setUrl] = useState(initialUrl);
const { limits } = useForumLimits();
const [url, setUrl] = useState('');
const [text, setText] = useState('');
const [advancedOpen, setAdvancedOpen] = useState(false);
const [query, setQuery] = useState('');
const [debouncedQuery, setDebouncedQuery] = useState('');
const [posts, setPosts] = useState<PostItem[]>([]);
const [pages, setPages] = useState<SitePageSummary[]>([]);
const [loading, setLoading] = useState(false);
const [loaded, setLoaded] = useState(false);
useEffect(() => {
if (open) setUrl(initialUrl || 'https://');
}, [open, initialUrl]);
if (!open) return;
setUrl(initialUrl || '');
setText(initialText || '');
setAdvancedOpen(false);
setQuery('');
setDebouncedQuery('');
setPosts([]);
setPages([]);
setLoaded(false);
}, [open, initialUrl, initialText]);
useEffect(() => {
if (!open || !advancedOpen) return;
const t = window.setTimeout(() => setDebouncedQuery(query.trim()), SEARCH_DEBOUNCE_MS);
return () => window.clearTimeout(t);
}, [query, open, advancedOpen]);
const loadSiteHits = useCallback(async (keyword: string) => {
setLoading(true);
try {
const [postsRes, pagesRes] = await Promise.all([
api.posts({
page: 1,
size: POST_PAGE_SIZE,
sort: 'new',
...(keyword ? { keyword, title_only: '1' } : {}),
}),
api.pages(),
]);
setPosts(postsRes.posts || []);
let nextPages = pagesRes.pages || [];
if (keyword) {
const q = keyword.toLowerCase();
nextPages = nextPages.filter(
p => p.title.toLowerCase().includes(q) || p.slug.toLowerCase().includes(q),
);
}
setPages(nextPages.slice(0, POST_PAGE_SIZE));
setLoaded(true);
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '加载站内内容失败');
setLoaded(true);
} finally {
setLoading(false);
}
}, []);
// 仅展开高级选项时再请求站内内容,避免默认打开就打接口
useEffect(() => {
if (!open || !advancedOpen) return;
void loadSiteHits(debouncedQuery);
}, [open, advancedOpen, debouncedQuery, loadSiteHits]);
const hits: SiteHit[] = useMemo(() => {
const postHits: SiteHit[] = posts.map(p => ({
key: `post-${p.id}`,
title: p.title,
url: postPath(p.id, limits),
kind: 'post',
}));
const pageHits: SiteHit[] = pages.map(p => ({
key: `page-${p.slug}`,
title: p.title,
url: pagePath(p.slug, limits),
kind: 'page',
}));
return [...postHits, ...pageHits];
}, [posts, pages, limits]);
const pickHit = (hit: SiteHit) => {
setUrl(hit.url);
// 选站内内容时同步用标题作为链接文字
setText(hit.title);
};
const handleConfirm = () => {
onConfirm(url.trim());
const nextUrl = url.trim();
if (!nextUrl) {
notify.warning('请输入网址');
return;
}
if (!isValidLinkHref(nextUrl)) {
notify.warning('请使用 http(s) 外链或本站以 / 开头的路径');
return;
}
onConfirm({
url: nextUrl,
text: text.trim() || '链接文字',
});
onOpenChange(false);
};
@@ -41,13 +174,17 @@ export function ArticleLinkDialog({
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="article-link-dialog">
<DialogHeader>
<DialogTitle>插入链接</DialogTitle>
<DialogDescription>输入完整 URL,留空并确认可移除已有链接。</DialogDescription>
<DialogTitle>插入或编辑链接</DialogTitle>
</DialogHeader>
<section className="article-link-dialog__section">
<div className="article-link-dialog__field">
<Label htmlFor="article-link-url">网址</Label>
<Input
id="article-link-url"
type="url"
value={url}
placeholder="https://"
placeholder="https://… 或 /post/123"
onChange={e => setUrl(e.target.value)}
onKeyDown={e => {
if (e.key === 'Enter') {
@@ -57,9 +194,99 @@ export function ArticleLinkDialog({
}}
autoFocus
/>
</div>
<div className="article-link-dialog__field">
<Label htmlFor="article-link-text">链接文字</Label>
<Input
id="article-link-text"
value={text}
placeholder="显示在正文中的文字"
onChange={e => setText(e.target.value)}
onKeyDown={e => {
if (e.key === 'Enter') {
e.preventDefault();
handleConfirm();
}
}}
/>
</div>
</section>
<section className="article-link-dialog__section article-link-dialog__advanced">
<button
type="button"
className={`article-link-dialog__advanced-toggle${advancedOpen ? ' is-open' : ''}`}
aria-expanded={advancedOpen}
onClick={() => setAdvancedOpen(v => !v)}
>
<span>高级选项</span>
<ChevronDown size={16} aria-hidden className="article-link-dialog__advanced-chevron" />
</button>
{advancedOpen ? (
<div className="article-link-dialog__advanced-body">
<h3 className="article-link-dialog__section-title">链接到站点中的内容</h3>
<div className="article-link-dialog__field">
<Label htmlFor="article-link-search">搜索</Label>
<Input
id="article-link-search"
type="search"
value={query}
placeholder="搜索帖子或单页…"
onChange={e => setQuery(e.target.value)}
/>
</div>
<div className="article-link-dialog__hits">
<p className="article-link-dialog__hits-hint">
{debouncedQuery
? `搜索「${debouncedQuery}」`
: '未指定搜索条件。自动显示最近发布条目。'}
</p>
{loading && !loaded ? (
<div className="article-link-dialog__hits-empty">
<Loader2 size={18} className="article-link-dialog__spin" />
<span>加载中…</span>
</div>
) : !hits.length ? (
<div className="article-link-dialog__hits-empty">暂无匹配内容</div>
) : (
<ul className="article-link-dialog__hit-list">
{hits.map(hit => (
<li key={hit.key}>
<button
type="button"
className={`article-link-dialog__hit${url === hit.url ? ' is-selected' : ''}`}
onClick={() => pickHit(hit)}
>
<span className="article-link-dialog__hit-title">{hit.title}</span>
<span className="article-link-dialog__hit-kind">
{hit.kind === 'post' ? '帖子' : '单页'}
</span>
</button>
</li>
))}
</ul>
)}
{loading && loaded ? (
<div className="article-link-dialog__hits-loading">
<Loader2 size={14} className="article-link-dialog__spin" />
</div>
) : null}
</div>
</div>
) : null}
</section>
<DialogFooter className="article-link-dialog__footer">
{onRemove && initialUrl ? (
<Button type="button" variant="outline" onClick={() => { onRemove(); onOpenChange(false); }}>
{editing && onRemove ? (
<Button
type="button"
variant="outline"
className="article-link-dialog__remove"
onClick={() => {
onRemove();
onOpenChange(false);
}}
>
移除链接
</Button>
) : null}
@@ -67,7 +294,7 @@ export function ArticleLinkDialog({
取消
</Button>
<Button type="button" onClick={handleConfirm}>
确定
{editing ? '更新链接' : '添加链接'}
</Button>
</DialogFooter>
</DialogContent>

View File

@@ -0,0 +1,87 @@
import { X } from 'lucide-react';
import type { Board } from '../../api/types';
import type { PostSearchState, SearchFilterKey } from '../../hooks/usePostSearch';
import { dispatchOpenPostSearch } from '../../hooks/usePostSearch';
interface Props {
filters: PostSearchState;
boards: Board[];
onRemove: (key: SearchFilterKey) => void;
onClear: () => void;
}
export default function FeedSearchFilters({ filters, boards, onRemove, onClear }: Props) {
const { keyword, author, titleOnly, scopeBoardId } = filters;
if (!keyword && !author) return null;
const boardName = scopeBoardId > 0
? boards.find((b) => b.id === scopeBoardId)?.name || '当前板块'
: '';
return (
<div className="search-filter-bar">
<div className="search-filter-bar__chips" role="list">
{keyword && (
<span className="search-filter-chip" role="listitem">
<span className="search-filter-chip__text">关键词「{keyword}」</span>
<button
type="button"
className="search-filter-chip__remove"
aria-label={`移除关键词 ${keyword}`}
onClick={() => onRemove('keyword')}
>
<X size={12} aria-hidden />
</button>
</span>
)}
{author && (
<span className="search-filter-chip" role="listitem">
<span className="search-filter-chip__text">作者 {author}</span>
<button
type="button"
className="search-filter-chip__remove"
aria-label={`移除作者 ${author}`}
onClick={() => onRemove('author')}
>
<X size={12} aria-hidden />
</button>
</span>
)}
{titleOnly && keyword && (
<span className="search-filter-chip" role="listitem">
<span className="search-filter-chip__text">仅标题</span>
<button
type="button"
className="search-filter-chip__remove"
aria-label="取消仅标题"
onClick={() => onRemove('titleOnly')}
>
<X size={12} aria-hidden />
</button>
</span>
)}
{scopeBoardId > 0 && boardName && (
<span className="search-filter-chip" role="listitem">
<span className="search-filter-chip__text">板块:{boardName}</span>
<button
type="button"
className="search-filter-chip__remove"
aria-label={`移除板块 ${boardName}`}
onClick={() => onRemove('board')}
>
<X size={12} aria-hidden />
</button>
</span>
)}
</div>
<div className="search-filter-bar__actions">
<button type="button" className="search-filter-bar__link" onClick={dispatchOpenPostSearch}>
修改搜索
</button>
<button type="button" className="search-filter-bar__link search-filter-bar__link--muted" onClick={onClear}>
清除全部
</button>
</div>
</div>
);
}

View File

@@ -0,0 +1,310 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { Search, User } from 'lucide-react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { api } from '../../api/client';
import { useMediaQuery } from '../../hooks/useTheme';
import { useForumLimits } from '../../hooks/useForumLimits';
import {
getRecentSearches,
type PostSearchSubmitInput,
type RecentSearch,
} from '../../hooks/usePostSearch';
import { cn } from '@/lib/utils';
export interface PostSearchDraft {
keyword: string;
author: string;
titleOnly: boolean;
scopeBoardId: number;
}
interface Props {
open: boolean;
onOpenChange: (open: boolean) => void;
draft: PostSearchDraft;
contextBoardId: number;
contextBoardName?: string;
onSubmit: (input: PostSearchSubmitInput) => boolean;
onClear: () => void;
}
type UserSuggest = { id: number; username: string; nickname: string; avatar?: string };
export default function PostSearchPanel({
open,
onOpenChange,
draft,
contextBoardId,
contextBoardName = '',
onSubmit,
onClear,
}: Props) {
const isMobile = useMediaQuery('(max-width: 768px)');
const { limits } = useForumLimits();
const keywordRef = useRef<HTMLInputElement>(null);
const [keyword, setKeyword] = useState(draft.keyword);
const [author, setAuthor] = useState(draft.author);
const [titleOnly, setTitleOnly] = useState(draft.titleOnly);
const [scopeBoardId, setScopeBoardId] = useState(draft.scopeBoardId);
const [recent, setRecent] = useState<RecentSearch[]>([]);
const [suggestions, setSuggestions] = useState<UserSuggest[]>([]);
const [suggestOpen, setSuggestOpen] = useState(false);
const authorWrapRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
setKeyword(draft.keyword);
setAuthor(draft.author);
setTitleOnly(draft.titleOnly);
setScopeBoardId(draft.scopeBoardId);
setRecent(getRecentSearches());
setSuggestions([]);
setSuggestOpen(false);
const t = window.setTimeout(() => keywordRef.current?.focus(), 80);
return () => window.clearTimeout(t);
}, [open, draft]);
useEffect(() => {
if (!open) return;
const q = author.trim();
if (q.length < 1) {
setSuggestions([]);
setSuggestOpen(false);
return;
}
let cancelled = false;
const timer = window.setTimeout(() => {
api.searchUsers(q, 8).then((r) => {
if (cancelled) return;
const users = Array.isArray(r.users) ? r.users : [];
setSuggestions(users);
setSuggestOpen(users.length > 0);
}).catch(() => {
if (!cancelled) {
setSuggestions([]);
setSuggestOpen(false);
}
});
}, 300);
return () => {
cancelled = true;
window.clearTimeout(timer);
};
}, [author, open]);
useEffect(() => {
if (!suggestOpen) return;
const onDoc = (e: MouseEvent) => {
if (authorWrapRef.current?.contains(e.target as Node)) return;
setSuggestOpen(false);
};
document.addEventListener('mousedown', onDoc);
return () => document.removeEventListener('mousedown', onDoc);
}, [suggestOpen]);
const handleSubmit = useCallback(() => {
const ok = onSubmit({
keyword,
author,
titleOnly: !!keyword.trim() && titleOnly,
scopeBoardId: scopeBoardId > 0 ? scopeBoardId : 0,
});
if (ok) onOpenChange(false);
}, [keyword, author, titleOnly, scopeBoardId, onSubmit, onOpenChange]);
const applyRecent = (item: RecentSearch) => {
setKeyword(item.keyword);
setAuthor(item.author);
setTitleOnly(item.titleOnly);
setScopeBoardId(item.scopeBoardId);
};
const pickAuthor = (u: UserSuggest) => {
setAuthor(u.nickname || u.username);
setSuggestOpen(false);
};
const showBoardScope = contextBoardId > 0;
const kwHint = limits.search_keyword_min > 1
? `关键词 ${limits.search_keyword_min}–${limits.search_keyword_max} 字`
: `关键词最多 ${limits.search_keyword_max} 字`;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
className={cn(
'post-search-panel',
isMobile && 'post-search-panel--mobile',
)}
onOpenAutoFocus={(e) => e.preventDefault()}
>
{isMobile && <div className="post-search-panel__handle" aria-hidden />}
<DialogHeader className="post-search-panel__header">
<DialogTitle>搜索帖子</DialogTitle>
{!isMobile && (
<DialogDescription className="post-search-panel__desc">
按关键词、作者或板块范围查找帖子
</DialogDescription>
)}
</DialogHeader>
<div className="post-search-panel__body">
<label className="post-search-field">
<span className="post-search-field__label">关键词</span>
<div className="post-search-field__input-wrap">
<Search size={16} aria-hidden className="post-search-field__icon" />
<input
ref={keywordRef}
type="search"
className="post-search-field__input"
placeholder="输入标题或正文关键词…"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
maxLength={limits.search_keyword_max > 0 ? limits.search_keyword_max : undefined}
enterKeyHint="search"
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleSubmit();
}
}}
/>
</div>
<span className="post-search-field__hint">{kwHint}</span>
</label>
<label className="post-search-field">
<span className="post-search-field__label">作者</span>
<div className="post-search-field__input-wrap" ref={authorWrapRef}>
<User size={16} aria-hidden className="post-search-field__icon" />
<input
type="text"
className="post-search-field__input"
placeholder="用户名或昵称"
value={author}
onChange={(e) => setAuthor(e.target.value)}
onFocus={() => suggestions.length > 0 && setSuggestOpen(true)}
autoComplete="off"
/>
{suggestOpen && suggestions.length > 0 && (
<ul className="search-author-suggest" role="listbox">
{suggestions.map((u) => (
<li key={u.id}>
<button
type="button"
className="search-author-suggest__item"
role="option"
onClick={() => pickAuthor(u)}
>
{u.avatar
? <img src={u.avatar} alt="" className="search-author-suggest__avatar" loading="lazy" />
: <span className="search-author-suggest__avatar search-author-suggest__avatar--ph">{(u.nickname || u.username).charAt(0)}</span>}
<span className="search-author-suggest__name">{u.nickname || u.username}</span>
{u.nickname && u.username !== u.nickname && (
<span className="search-author-suggest__user">@{u.username}</span>
)}
</button>
</li>
))}
</ul>
)}
</div>
</label>
{showBoardScope && (
<div className="post-search-field">
<span className="post-search-field__label">范围</span>
<div className="search-scope-pills" role="group" aria-label="搜索范围">
<button
type="button"
className={cn('search-scope-pill', scopeBoardId === 0 && 'active')}
aria-pressed={scopeBoardId === 0}
onClick={() => setScopeBoardId(0)}
>
全站
</button>
<button
type="button"
className={cn('search-scope-pill', scopeBoardId === contextBoardId && 'active')}
aria-pressed={scopeBoardId === contextBoardId}
onClick={() => setScopeBoardId(contextBoardId)}
>
{contextBoardName || '当前板块'}
</button>
</div>
</div>
)}
<div className="post-search-field post-search-field--row">
<div>
<span className="post-search-field__label">仅搜标题</span>
<span className="post-search-field__hint">需填写关键词时生效</span>
</div>
<Switch
checked={titleOnly}
onCheckedChange={setTitleOnly}
disabled={!keyword.trim()}
aria-label="仅搜索标题"
/>
</div>
{recent.length > 0 && (
<div className="post-search-recent">
<span className="post-search-field__label">最近搜索</span>
<ul className="post-search-recent__list">
{recent.map((item) => {
const label = [
item.keyword && `「${item.keyword}」`,
item.author && `@${item.author}`,
item.titleOnly && '仅标题',
item.scopeBoardId > 0 && '本板块',
].filter(Boolean).join(' · ') || '搜索';
return (
<li key={`${item.keyword}-${item.author}-${item.at}`}>
<button
type="button"
className="post-search-recent__item"
onClick={() => applyRecent(item)}
>
{label}
</button>
</li>
);
})}
</ul>
</div>
)}
</div>
<div className={cn('post-search-panel__footer', isMobile && 'post-search-panel__footer--mobile')}>
<Button
type="button"
variant="outline"
className={isMobile ? 'post-search-panel__btn' : undefined}
onClick={() => {
setKeyword('');
setAuthor('');
setTitleOnly(false);
setScopeBoardId(0);
onClear();
}}
>
清除
</Button>
<Button type="button" className={isMobile ? 'post-search-panel__btn' : undefined} onClick={handleSubmit}>
搜索
</Button>
</div>
</DialogContent>
</Dialog>
);
}

View File

@@ -1,6 +1,9 @@
import { createContext, useContext, useEffect, useState, useCallback, ReactNode } from 'react';
import { createContext, useContext, useEffect, useState, useCallback, useRef, ReactNode } from 'react';
import { api } from '../api/client';
import type { User } from '../api/types';
import { clearAllFeedCache } from '../utils/feedCache';
import { clearSessionSnapshots } from '../utils/sessionPageCache';
import { peekAuthSeed } from '../utils/authBoot';
interface AuthCtx {
user: User | null;
@@ -15,8 +18,12 @@ const AuthContext = createContext<AuthCtx>({
});
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
// peek 不清种子,StrictMode 重挂 / initializer 双调仍与 SSR 同构
const [user, setUser] = useState<User | null>(() => {
const s = peekAuthSeed();
return s.hasSeed ? s.user : null;
});
const [loading, setLoading] = useState(() => !peekAuthSeed().hasSeed);
const refresh = useCallback(async () => {
try {
@@ -29,8 +36,24 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
}, []);
// 初始化只拉一次用户信息
useEffect(() => { refresh(); }, [refresh]);
// 有 SSR 种子时仍后台校验;无种子则首屏拉取
// 不清空 auth 种子:StrictMode 重挂会再次跑 useState initializer,破坏性 clear 会导致 user 空窗闪动
useEffect(() => { void refresh(); }, [refresh]);
const prevUserId = useRef<number | null | 'init'>('init');
useEffect(() => {
if (loading) return;
const id = user?.id ?? null;
if (prevUserId.current === 'init') {
prevUserId.current = id;
return;
}
if (prevUserId.current !== id) {
prevUserId.current = id;
clearSessionSnapshots();
clearAllFeedCache();
}
}, [user, loading]);
const logout = async () => {
await api.logout();

View File

@@ -0,0 +1,130 @@
import { useCallback, useEffect, useState } from 'react';
import { notify } from '@/lib/notify';
import { api } from '../api/client';
import type { CheckInStatus } from '../api/types';
import { getSessionSnapshot, setSessionSnapshot } from '../utils/sessionPageCache';
import { PAGE_FORCE_REFRESH_EVENT } from '../utils/feedCache';
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
import { useAuth } from './useAuth';
/** 签到会话快照键(与 prefetchRoute 共用) */
export function checkInCacheKey(userId: number) {
return `checkin:${userId}`;
}
/** 每日签到状态与操作(侧栏、积分页等复用) */
export function useCheckIn(enabled = true) {
const { user, refresh } = useAuth();
const userId = user?.id;
const [status, setStatus] = useState<CheckInStatus | null>(() => {
if (!userId || !enabled) return null;
return getSessionSnapshot<CheckInStatus>(checkInCacheKey(userId)) ?? null;
});
const [loading, setLoading] = useState(() => {
if (!userId || !enabled) return false;
return getSessionSnapshot<CheckInStatus>(checkInCacheKey(userId)) === undefined;
});
const [busy, setBusy] = useState(false);
const load = useCallback((opts?: { force?: boolean }) => {
if (!userId || !enabled) {
setStatus(null);
setLoading(false);
return;
}
const key = checkInCacheKey(userId);
if (!opts?.force) {
const hit = getSessionSnapshot<CheckInStatus>(key);
if (hit !== undefined) {
setStatus(hit);
setLoading(false);
return;
}
}
setLoading(true);
api.checkInStatus()
.then((d) => {
setSessionSnapshot(key, d.check_in);
setStatus(d.check_in);
})
.catch((e) => notify.error(e instanceof Error ? e.message : '加载签到状态失败'))
.finally(() => setLoading(false));
}, [userId, enabled]);
useEffect(() => {
if (!userId || !enabled) {
setStatus(null);
setLoading(false);
return;
}
const key = checkInCacheKey(userId);
const hit = getSessionSnapshot<CheckInStatus>(key);
if (hit !== undefined) {
setStatus(hit);
setLoading(false);
return;
}
setStatus(null);
setLoading(true);
load({ force: true });
}, [userId, enabled, load]);
// 软刷新 commit:仅快照命中才盖;未命中保持旧 UI,后台静默再拉
useEffect(() => {
const applyHitOrSilent = (forceLoading: boolean) => {
if (!userId || !enabled) return;
const key = checkInCacheKey(userId);
const hit = getSessionSnapshot<CheckInStatus>(key);
if (hit !== undefined) {
setStatus(hit);
setLoading(false);
return;
}
if (forceLoading) {
load({ force: true });
return;
}
// 软刷新未命中:不 setLoading,静默覆盖
api.checkInStatus()
.then((d) => {
setSessionSnapshot(key, d.check_in);
setStatus(d.check_in);
setLoading(false);
})
.catch(() => { /* 保持旧 UI */ });
};
const onForce = () => applyHitOrSilent(true);
const onCommit = () => applyHitOrSilent(false);
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
return () => {
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
};
}, [userId, enabled, load]);
const doCheckIn = useCallback(async () => {
if (!userId) return;
setBusy(true);
try {
const r = await api.checkIn();
notify.success(`签到成功,+${r.check_in.today_points} 积分`);
setSessionSnapshot(checkInCacheKey(userId), r.check_in);
setStatus(r.check_in);
await refresh();
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '签到失败');
} finally {
setBusy(false);
}
}, [userId, refresh]);
return {
status,
loading,
busy,
doCheckIn,
reload: () => load({ force: true }),
};
}

View File

@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
import { api } from '../api/client';
import type { ForumLimitsPublic } from '../api/types';
import { DEFAULT_ASIDE_WIDGETS, DEFAULT_FEED_SORT_TABS } from '../api/types';
const DEFAULT_LIMITS: ForumLimitsPublic = {
post_title_max: 128,
@@ -16,8 +17,20 @@ const DEFAULT_LIMITS: ForumLimitsPublic = {
signature_max: 200,
open_posts_in_new_tab: true,
open_content_links_in_new_tab: true,
aside_show_tag_cloud: false,
aside_show_recent_comments: false,
aside_show_friend_links: true,
aside_show_showcase: false,
aside_widgets: DEFAULT_ASIDE_WIDGETS,
nav_show_friend_links: true,
footer_show_friend_links: true,
nav_show_showcase: false,
footer_show_showcase: false,
feed_list_style: 'title',
feed_sort_tabs: DEFAULT_FEED_SORT_TABS,
permalink_enabled: false,
permalink_ext: 'html',
monitor_pageview: false,
};
let cached: ForumLimitsPublic | null = null;
@@ -67,6 +80,27 @@ export function useForumLimits() {
return { limits, loading };
}
/** 冷启动 / 预热:确保 limits 已写入模块缓存;force 时重拉并在成功后通知 hook */
export async function ensureForumLimitsLoaded(opts?: { force?: boolean }): Promise<ForumLimitsPublic> {
if (opts?.force) {
cached = null;
inflight = null;
}
const limits = await fetchLimits();
if (opts?.force) {
cacheEpoch += 1;
listeners.forEach(fn => fn());
}
return limits;
}
/** 文档 SSR / 管理端:同步写入 limits 模块缓存 */
export function seedForumLimitsCache(limits: ForumLimitsPublic) {
cached = limits;
cacheEpoch += 1;
listeners.forEach(fn => fn());
}
/** 清除缓存并通知已挂载的 hook 重新拉取 */
export function invalidateForumLimitsCache() {
cached = null;

View File

@@ -0,0 +1,41 @@
import { useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import { api } from '../api/client';
import { useForumLimits } from './useForumLimits';
const DEDUPE_MS = 800;
function shouldSkipPath(pathname: string) {
const p = pathname.toLowerCase();
return (
p === '/admin' ||
p.startsWith('/admin/') ||
p === '/login' ||
p === '/register' ||
p === '/forgot-password' ||
p.startsWith('/oauth')
);
}
/** 主站布局:路由变化时上报第一方 pageview(采集关闭则不请求) */
export function useMonitorPageview() {
const loc = useLocation();
const { limits } = useForumLimits();
const lastRef = useRef<{ key: string; at: number }>({ key: '', at: 0 });
const enabled = !!limits.monitor_pageview;
useEffect(() => {
if (!enabled) return;
if (shouldSkipPath(loc.pathname)) return;
const path = `${loc.pathname}${loc.search || ''}`;
const now = Date.now();
if (lastRef.current.key === path && now - lastRef.current.at < DEDUPE_MS) {
return;
}
lastRef.current = { key: path, at: now };
const referrer = typeof document !== 'undefined' ? document.referrer || '' : '';
void api.monitorPageview({ path, referrer });
}, [enabled, loc.pathname, loc.search]);
}

View File

@@ -0,0 +1,271 @@
import { useCallback, useMemo } from 'react';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import { buildHomeUrl } from '../components/FeedSortBar';
import { navigateFeed } from '../utils/feedCache';
import { transitionTo } from '../utils/spaTransition';
import { notify } from '@/lib/notify';
import { parsePermalinkID, type PermalinkOpts } from '../utils/permalink';
/** 打开搜索面板(全局事件) */
export const POST_SEARCH_OPEN_EVENT = 'post-search-open';
export type SearchFilterKey = 'keyword' | 'author' | 'titleOnly' | 'board';
export interface PostSearchSubmitInput {
keyword?: string;
author?: string;
titleOnly?: boolean;
/** 0 = 全站,>0 = 限定板块 */
scopeBoardId?: number;
}
export interface PostSearchState {
keyword: string;
author: string;
titleOnly: boolean;
scopeBoardId: number;
contextBoardId: number;
isFiltered: boolean;
hasAdvancedFilters: boolean;
}
export interface RecentSearch {
keyword: string;
author: string;
titleOnly: boolean;
scopeBoardId: number;
at: number;
}
const RECENT_KEY = 'jiang13-recent-searches';
const RECENT_MAX = 5;
export function parseBoardIdFromLocation(pathname: string, params: URLSearchParams): number {
const m = pathname.match(/^\/board\/(\d+(?:\.[A-Za-z0-9]{1,16})?)$/);
if (m) return parsePermalinkID(m[1]) || 0;
const q = Number(params.get('board')) || 0;
return q > 0 ? q : 0;
}
export function parseSearchFromUrl(
pathname: string,
params: URLSearchParams,
): Pick<PostSearchState, 'keyword' | 'author' | 'titleOnly' | 'scopeBoardId'> {
const keyword = params.get('keyword') || '';
const author = params.get('author') || '';
const titleOnly = params.get('title_only') === '1';
const pathBoardId = parseBoardIdFromLocation(pathname, params);
const scopeBoardId = (keyword || author) && pathBoardId > 0 ? pathBoardId : 0;
return { keyword, author, titleOnly, scopeBoardId };
}
function readRecentSearches(): RecentSearch[] {
try {
const raw = localStorage.getItem(RECENT_KEY);
if (!raw) return [];
const parsed = JSON.parse(raw) as RecentSearch[];
return Array.isArray(parsed) ? parsed.slice(0, RECENT_MAX) : [];
} catch {
return [];
}
}
function writeRecentSearches(items: RecentSearch[]) {
try {
localStorage.setItem(RECENT_KEY, JSON.stringify(items.slice(0, RECENT_MAX)));
} catch {
/* 忽略存储失败 */
}
}
export function saveRecentSearch(entry: Omit<RecentSearch, 'at'>) {
const kw = entry.keyword.trim();
const author = entry.author.trim();
if (!kw && !author) return;
const next: RecentSearch = { ...entry, keyword: kw, author, at: Date.now() };
const prev = readRecentSearches().filter(
(r) => !(r.keyword === next.keyword && r.author === next.author
&& r.titleOnly === next.titleOnly && r.scopeBoardId === next.scopeBoardId),
);
writeRecentSearches([next, ...prev]);
}
export function getRecentSearches(): RecentSearch[] {
return readRecentSearches();
}
function validateKeyword(kw: string, limits: PermalinkOpts & { search_keyword_min: number; search_keyword_max: number }): boolean {
if (!kw) return true;
const len = [...kw].length;
if (limits.search_keyword_min > 0 && len < limits.search_keyword_min) {
notify.warning(`搜索关键词至少 ${limits.search_keyword_min} 个字`);
return false;
}
if (limits.search_keyword_max > 0 && len > limits.search_keyword_max) {
notify.warning(`搜索关键词最多 ${limits.search_keyword_max} 个字`);
return false;
}
return true;
}
function isSameSearchTarget(
pathname: string,
params: URLSearchParams,
target: string,
input: Required<Pick<PostSearchSubmitInput, 'keyword' | 'author' | 'titleOnly' | 'scopeBoardId'>>,
): boolean {
const active = parseSearchFromUrl(pathname, params);
const activeBoard = parseBoardIdFromLocation(pathname, params);
const onFeed = pathname === '/' || /^\/board\/\d+/.test(pathname);
return onFeed
&& active.keyword === input.keyword
&& active.author === input.author
&& active.titleOnly === input.titleOnly
&& (input.scopeBoardId > 0 ? activeBoard === input.scopeBoardId : active.scopeBoardId === 0);
}
export function usePostSearch(
limits: PermalinkOpts & { search_keyword_min: number; search_keyword_max: number },
) {
const nav = useNavigate();
const loc = useLocation();
const [params] = useSearchParams();
const contextBoardId = useMemo(
() => parseBoardIdFromLocation(loc.pathname, params),
[loc.pathname, params],
);
const filters = useMemo((): PostSearchState => {
const parsed = parseSearchFromUrl(loc.pathname, params);
const isFiltered = !!(parsed.keyword || parsed.author);
const hasAdvancedFilters = !!(
parsed.author
|| (parsed.titleOnly && parsed.keyword)
|| parsed.scopeBoardId > 0
);
return { ...parsed, contextBoardId, isFiltered, hasAdvancedFilters };
}, [loc.pathname, params, contextBoardId]);
const buildUrl = useCallback((input: PostSearchSubmitInput) => {
const kw = (input.keyword ?? '').trim();
const author = (input.author ?? '').trim();
const titleOnly = !!kw && (input.titleOnly ?? false);
const scopeBoard = input.scopeBoardId ?? 0;
return buildHomeUrl(scopeBoard, 'latest', {
keyword: kw,
author,
titleOnly,
permalink: limits,
});
}, [limits]);
const submitSearch = useCallback((
input: PostSearchSubmitInput,
opts?: { refreshIfSame?: boolean },
) => {
const kw = (input.keyword ?? '').trim();
const author = (input.author ?? '').trim();
const activeKw = (params.get('keyword') || '').trim();
const activeAuthor = (params.get('author') || '').trim();
if (!kw && !author) {
if (activeKw || activeAuthor) navigateFeed(nav, '/');
return false;
}
if (!validateKeyword(kw, limits)) return false;
const titleOnly = !!kw && (input.titleOnly ?? false);
const scopeBoardId = input.scopeBoardId ?? 0;
const target = buildUrl({ keyword: kw, author, titleOnly, scopeBoardId });
const normalized = {
keyword: kw,
author,
titleOnly,
scopeBoardId,
};
if (isSameSearchTarget(loc.pathname, params, target, normalized)) {
if (opts?.refreshIfSame) navigateFeed(nav, target);
return true;
}
saveRecentSearch({ keyword: kw, author, titleOnly, scopeBoardId });
void transitionTo(nav, target);
return true;
}, [nav, params, loc.pathname, limits, buildUrl]);
const clearSearch = useCallback(() => {
navigateFeed(nav, '/');
}, [nav]);
const removeFilter = useCallback((key: SearchFilterKey) => {
const current = parseSearchFromUrl(loc.pathname, params);
if (!current.keyword && !current.author) return;
let next: PostSearchSubmitInput;
switch (key) {
case 'keyword':
next = {
keyword: '',
author: current.author,
titleOnly: false,
scopeBoardId: current.scopeBoardId,
};
break;
case 'author':
next = {
keyword: current.keyword,
author: '',
titleOnly: current.titleOnly,
scopeBoardId: current.scopeBoardId,
};
break;
case 'titleOnly':
next = {
keyword: current.keyword,
author: current.author,
titleOnly: false,
scopeBoardId: current.scopeBoardId,
};
break;
case 'board':
next = {
keyword: current.keyword,
author: current.author,
titleOnly: current.titleOnly,
scopeBoardId: 0,
};
break;
default:
return;
}
const kw = (next.keyword ?? '').trim();
const author = (next.author ?? '').trim();
if (!kw && !author) {
clearSearch();
return;
}
nav(buildUrl({
keyword: kw,
author,
titleOnly: next.titleOnly,
scopeBoardId: next.scopeBoardId,
}));
}, [loc.pathname, params, nav, buildUrl, clearSearch]);
return {
filters,
buildUrl,
submitSearch,
clearSearch,
removeFilter,
getRecentSearches,
saveRecentSearch,
};
}
export function dispatchOpenPostSearch() {
window.dispatchEvent(new CustomEvent(POST_SEARCH_OPEN_EVENT));
}

View File

@@ -0,0 +1,161 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { PAGE_FORCE_REFRESH_EVENT } from '../utils/feedCache';
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
import {
getSessionSnapshot,
setSessionSnapshot,
deleteSessionSnapshot,
} from '../utils/sessionPageCache';
type Fetcher<T> = () => Promise<T>;
/**
* 会话快照数据源:有缓存则跳过请求;无缓存时保留上一份画面直到新数据返回。
* 手机下拉软刷新 commit / PAGE_FORCE_REFRESH_EVENT 会应用新快照。
*/
function isEmptyArray(value: unknown): boolean {
return Array.isArray(value) && value.length === 0;
}
export function useSessionResource<T>(
key: string | null,
fetcher: Fetcher<T>,
opts?: {
enabled?: boolean;
onError?: (e: unknown) => void;
/** 缓存为空数组时仍后台再拉,避免启动竞态假空粘死 */
revalidateEmpty?: boolean;
},
) {
const enabled = opts?.enabled !== false;
const revalidateEmpty = opts?.revalidateEmpty === true;
const fetcherRef = useRef(fetcher);
fetcherRef.current = fetcher;
const onErrorRef = useRef(opts?.onError);
onErrorRef.current = opts?.onError;
const [data, setData] = useState<T | undefined>(() =>
key && enabled ? getSessionSnapshot<T>(key) : undefined,
);
const [loading, setLoading] = useState(() => {
if (!key || !enabled) return false;
return getSessionSnapshot<T>(key) === undefined;
});
const [pending, setPending] = useState(false);
const seqRef = useRef(0);
const dataRef = useRef(data);
dataRef.current = data;
useEffect(() => {
if (!key || !enabled) {
if (!enabled) {
setLoading(false);
setPending(false);
}
return;
}
const hit = getSessionSnapshot<T>(key);
if (hit !== undefined && !(revalidateEmpty && isEmptyArray(hit))) {
setData(hit);
setLoading(false);
setPending(false);
return;
}
const seq = ++seqRef.current;
const keep = dataRef.current !== undefined || (hit !== undefined && isEmptyArray(hit));
if (hit !== undefined && isEmptyArray(hit)) {
setData(hit);
setPending(true);
setLoading(false);
} else if (keep && dataRef.current !== undefined) {
setPending(true);
} else {
setLoading(true);
}
fetcherRef.current()
.then((next) => {
if (seq !== seqRef.current) return;
setSessionSnapshot(key, next);
setData(next);
})
.catch((e: unknown) => {
if (seq !== seqRef.current) return;
onErrorRef.current?.(e);
// 失败不写空快照;已有画面则保留
if (!keep) setData(undefined);
})
.finally(() => {
if (seq !== seqRef.current) return;
setLoading(false);
setPending(false);
});
return () => {
seqRef.current += 1;
};
}, [key, enabled, revalidateEmpty]);
const replace = useCallback((next: T | ((prev: T | undefined) => T)) => {
setData((prev) => {
const value = typeof next === 'function' ? (next as (p: T | undefined) => T)(prev) : next;
if (key) setSessionSnapshot(key, value);
return value;
});
}, [key]);
const invalidate = useCallback(() => {
if (key) deleteSessionSnapshot(key);
}, [key]);
useEffect(() => {
const reload = (opts: { allowLoading: boolean }) => {
if (!key || !enabled) return;
const warm = getSessionSnapshot<T>(key);
if (warm !== undefined && !(revalidateEmpty && isEmptyArray(warm))) {
setData(warm);
setLoading(false);
setPending(false);
return;
}
const seq = ++seqRef.current;
const keep = dataRef.current !== undefined || (warm !== undefined && isEmptyArray(warm));
if (opts.allowLoading) {
deleteSessionSnapshot(key);
if (keep) setPending(true);
else setLoading(true);
} else if (warm !== undefined && isEmptyArray(warm)) {
setPending(true);
}
fetcherRef.current()
.then((next) => {
if (seq !== seqRef.current) return;
setSessionSnapshot(key, next);
setData(next);
})
.catch((e: unknown) => {
if (seq !== seqRef.current) return;
onErrorRef.current?.(e);
if (opts.allowLoading && !keep) setData(undefined);
})
.finally(() => {
if (seq !== seqRef.current) return;
setLoading(false);
setPending(false);
});
};
const onForce = () => reload({ allowLoading: true });
// 软刷新 commit:未命中不卸 UI,后台静默再拉
const onCommit = () => reload({ allowLoading: false });
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
return () => {
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
};
}, [key, enabled, revalidateEmpty]);
return { data, loading, pending, replace, invalidate };
}

View File

@@ -46,9 +46,15 @@ function readBootBranding(): SiteBranding | null {
let cached: SiteBranding | null = readBootBranding();
let inflight: Promise<SiteBranding> | null = null;
let cacheEpoch = 0;
/** force 预热刚写入后,hook 因 epoch 重跑时复用缓存,避免连打两次 API */
let preferCacheOnce = false;
const listeners = new Set<() => void>();
function fetchBranding(): Promise<SiteBranding> {
if (preferCacheOnce && cached) {
preferCacheOnce = false;
return Promise.resolve(cached);
}
if (inflight) return inflight;
// 有 boot/缓存时首屏已可用;仍请求 API 以同步最新配置
inflight = api.siteBranding()
@@ -123,6 +129,30 @@ export function useSiteBranding() {
return { branding, loading };
}
/** 保留当前画面,后台重拉品牌配置(下拉刷新等) */
export function refetchSiteBranding() {
inflight = null;
cacheEpoch += 1;
listeners.forEach(fn => fn());
}
/** 冷启动 / 预热:确保品牌已写入模块缓存;force 时重拉并在成功后通知 hook */
export async function ensureSiteBrandingLoaded(opts?: { force?: boolean }): Promise<SiteBranding> {
if (!opts?.force && cached) return cached;
if (opts?.force) {
inflight = null;
preferCacheOnce = false;
}
const next = await fetchBranding();
applyDocumentBrand(next);
if (opts?.force) {
preferCacheOnce = true;
cacheEpoch += 1;
listeners.forEach(fn => fn());
}
return next;
}
/** 清除缓存并通知已挂载的 hook 重新拉取 */
export function invalidateSiteBrandingCache() {
cached = null;

View File

@@ -0,0 +1,75 @@
import { useEffect, useState } from 'react';
import { api } from '../api/client';
import type { SitePageSummary } from '../api/types';
import { PAGE_FORCE_REFRESH_EVENT } from '../utils/feedCache';
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
let cache: SitePageSummary[] | null = null;
let pending: Promise<SitePageSummary[]> | null = null;
/** 拉取或复用站点页摘要缓存(供冷启动门闩与 hook 共用) */
export function ensureSitePagesLoaded(opts?: { force?: boolean }): Promise<SitePageSummary[]> {
if (opts?.force) {
cache = null;
pending = null;
}
if (cache) return Promise.resolve(cache);
if (!pending) {
pending = api.pages()
.then(d => {
cache = d.pages ?? [];
return cache;
})
.catch(() => {
cache = [];
return cache;
})
.finally(() => { pending = null; });
}
return pending;
}
/** 已发布单页摘要(页脚/侧栏导航) */
export function useSitePages() {
const [pages, setPages] = useState<SitePageSummary[]>(cache ?? []);
useEffect(() => {
const load = () => {
void ensureSitePagesLoaded().then(setPages);
};
if (cache) setPages(cache);
else load();
const onForce = () => {
cache = null;
pending = null;
load();
};
const onCommit = () => {
// 软刷新:cache 已由 prefetch 写好,同步进 state
void ensureSitePagesLoaded().then(setPages);
};
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
return () => {
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
};
}, []);
return {
pages,
footerPages: pages.filter(p => p.show_in_footer),
navPages: pages.filter(p => p.show_in_nav),
};
}
export function invalidateSitePagesCache() {
cache = null;
}
/** 文档 SSR:同步写入站点页摘要缓存 */
export function seedSitePagesCache(pages: SitePageSummary[]) {
cache = Array.isArray(pages) ? pages : [];
pending = null;
}

View File

@@ -1,7 +1,7 @@
import { useEffect, useState, useCallback, useRef } from 'react';
import { Outlet, NavLink, useNavigate, useLocation } from 'react-router-dom';
import {
LayoutDashboard, FolderKanban, FileText, MessageSquare, Flag, Users, Images, Settings, ArrowLeft, Moon, Sun, Menu, X, Award,
LayoutDashboard, FolderKanban, FileText, MessageSquare, Flag, Users, Images, Settings, ArrowLeft, Moon, Sun, Menu, X, Award, Link2, BookOpen, Globe2, Activity,
} from 'lucide-react';
import { Spinner } from '@/components/ui/spinner';
import { useAuth } from '../hooks/useAuth';
@@ -16,13 +16,15 @@ import { useNoIndexSEO } from '../hooks/usePageSEO';
import SiteBrandMark from '../components/SiteBrandMark';
import { api } from '../api/client';
type BadgeKey = 'posts' | 'comments' | 'reports';
type BadgeKey = 'posts' | 'comments' | 'reports' | 'links';
type NavItem = {
to: string;
label: string;
icon: typeof LayoutDashboard;
badgeKey?: BadgeKey;
/** 仅社区枢纽开启时显示 */
hubOnly?: boolean;
};
type NavGroup = {
@@ -36,6 +38,8 @@ const NAV_GROUPS: NavGroup[] = [
label: '概览',
items: [
{ to: '/admin/dashboard', label: '仪表盘', icon: LayoutDashboard },
{ to: '/admin/monitor', label: '网站监控', icon: Activity },
{ to: '/admin/community', label: '公网实例', icon: Globe2, hubOnly: true },
],
},
{
@@ -50,8 +54,10 @@ const NAV_GROUPS: NavGroup[] = [
label: '社区',
items: [
{ to: '/admin/boards', label: '板块管理', icon: FolderKanban },
{ to: '/admin/pages', label: '单页管理', icon: BookOpen },
{ to: '/admin/users', label: '用户管理', icon: Users },
{ to: '/admin/badges', label: '徽章管理', icon: Award },
{ to: '/admin/links', label: '友情链接', icon: Link2, badgeKey: 'links' },
],
},
{
@@ -67,6 +73,7 @@ type PendingCounts = {
posts: number;
comments: number;
reports: number;
links: number;
};
function formatNavBadge(n: number) {
@@ -82,7 +89,8 @@ export default function AdminLayout() {
useNoIndexSEO('管理后台');
const isNarrow = useMediaQuery('(max-width: 768px)');
const [navOpen, setNavOpen] = useState(false);
const [pending, setPending] = useState<PendingCounts>({ posts: 0, comments: 0, reports: 0 });
const [pending, setPending] = useState<PendingCounts>({ posts: 0, comments: 0, reports: 0, links: 0 });
const [communityHub, setCommunityHub] = useState(false);
const nav = useNavigate();
const location = useLocation();
const drawerRef = useRef<HTMLElement>(null);
@@ -99,10 +107,30 @@ export default function AdminLayout() {
posts: d.pending_posts ?? 0,
comments: d.pending_comments ?? 0,
reports: d.pending_reports ?? 0,
links: d.pending_friend_links ?? 0,
}))
.catch(() => {});
}, []);
useEffect(() => {
if (loading || !user || user.role !== 'admin') return;
api.adminSettings()
.then(s => setCommunityHub(!!s.community?.hub_enabled))
.catch(() => setCommunityHub(false));
}, [loading, user]);
useEffect(() => {
if (loading || !user || user.role !== 'admin') return;
refreshPending();
const onRefresh = () => refreshPending();
window.addEventListener('admin-pending-refresh', onRefresh);
const timer = window.setInterval(refreshPending, 60_000);
return () => {
window.removeEventListener('admin-pending-refresh', onRefresh);
window.clearInterval(timer);
};
}, [loading, user, refreshPending]);
useEffect(() => {
if (loading) return;
if (!user) {
@@ -140,7 +168,7 @@ export default function AdminLayout() {
NAV_GROUPS.map(group => (
<div key={group.label} className="admin-nav-group">
<div className="admin-nav-group-label">{group.label}</div>
{group.items.map(({ to, label, icon: Icon, badgeKey }) => {
{group.items.filter(item => !item.hubOnly || communityHub).map(({ to, label, icon: Icon, badgeKey }) => {
const badge = badgeKey ? formatNavBadge(pending[badgeKey]) : null;
return (
<NavLink

View File

@@ -1,8 +1,6 @@
import { useState, useEffect, useCallback, useRef, useMemo, Suspense } from 'react';
import PageLoader from '../components/PageLoader';
import FeedPageSkeleton from '../components/FeedPageSkeleton';
import { useState, useEffect, useCallback, useRef, useMemo, Suspense, startTransition } from 'react';
import { Outlet, useNavigate, useSearchParams, useLocation } from 'react-router-dom';
import { Menu, Moon, Sun, Search, Plus, PanelRight, X, Mail } from 'lucide-react';
import { Menu, Moon, Sun, Search, Plus, PanelRight, X, Mail, SlidersHorizontal } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
@@ -14,41 +12,68 @@ import { useAuth } from '../hooks/useAuth';
import { useTheme, useMediaQuery } from '../hooks/useTheme';
import { useOverlayA11y, moveTabIndex } from '../hooks/useOverlayA11y';
import { api } from '../api/client';
import type { Board, PostItem, RecentComment, ForumStats, TagCount, User } from '../api/types';
import type { Board, RecentComment, RecentUser, ForumStats, TagCount, User } from '../api/types';
import type { PostHeading } from '../utils/postHeadings';
import { getCachedBoards, getCachedStats, getCachedHot, getCachedRecentComments, getCachedTags, hasCachedAside, setCachedBoards, setCachedStats, setCachedHot, setCachedRecentComments, setCachedTags } from '../utils/layoutCache';
import { getCachedBoards, getCachedStats, getCachedRecentComments, getCachedRecentUsers, getCachedTags, hasCachedAside, setCachedBoards, setCachedStats, setCachedRecentComments, setCachedRecentUsers, setCachedTags } from '../utils/layoutCache';
import Sidebar, { isNeutralSidebarRoute } from '../components/Sidebar';
import RightPanel from '../components/RightPanel';
import BackToTop from '../components/BackToTop';
import { useForumLimits } from '../hooks/useForumLimits';
import { resolveAsideWidgets } from '../utils/asideWidgets';
import { buildHomeUrl, parseFeedSort } from '../components/FeedSortBar';
import { navigateFeed } from '../utils/feedCache';
import { notify } from '@/lib/notify';
import { navigateFeed, PAGE_FORCE_REFRESH_EVENT } from '../utils/feedCache';
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
import { prefetchRoute, wasColdBootEnsured } from '../utils/prefetchRoute';
import {
transitionTo,
} from '../utils/spaTransition';
import PostSearchPanel from '../components/search/PostSearchPanel';
import {
POST_SEARCH_OPEN_EVENT,
usePostSearch,
} from '../hooks/usePostSearch';
import { cn } from '@/lib/utils';
import { getBoardThemeIndex } from '../utils/boardTheme';
import { loginPath } from '../utils/authRedirect';
import { openForumPost } from '../utils/openPost';
import { useSiteBranding } from '../hooks/useSiteBranding';
import { refetchSiteBranding, useSiteBranding } from '../hooks/useSiteBranding';
import { useMonitorPageview } from '../hooks/useMonitorPageview';
import SiteBrandMark from '../components/SiteBrandMark';
import SiteFooter from '../components/SiteFooter';
import { userPath } from '../utils/userPath';
import { parsePermalinkID } from '../utils/permalink';
import { ensureSitePagesLoaded } from '../hooks/useSitePages';
import { endHomeHydrate, isHomeHydrating } from '../utils/homeHydrate';
import { getBootUnread } from '../utils/authBoot';
export default function MainLayout() {
const { user, loading: authLoading, logout } = useAuth();
const { theme, toggle } = useTheme();
const { branding } = useSiteBranding();
const isMobile = useMediaQuery('(max-width: 768px)');
useMonitorPageview();
const mqMobile = useMediaQuery('(max-width: 768px)');
const hideAside = useMediaQuery('(max-width: 1100px)');
/** hydrate 首帧强制桌面布局(SSR 为桌面三栏),随后再跟 matchMedia */
const [forceDesktop, setForceDesktop] = useState(() => isHomeHydrating());
const isMobile = forceDesktop ? false : mqMobile;
const nav = useNavigate();
const loc = useLocation();
const [params] = useSearchParams();
const isCompose = loc.pathname.startsWith('/compose') || /\/post\/\d+\/edit$/.test(loc.pathname);
useEffect(() => {
if (!forceDesktop) return;
endHomeHydrate();
startTransition(() => setForceDesktop(false));
}, [forceDesktop]);
const [boards, setBoards] = useState<Board[]>(() => getCachedBoards());
const [stats, setStats] = useState<ForumStats | null>(() => getCachedStats());
const [hot, setHot] = useState<PostItem[]>(() => getCachedHot());
const [recentComments, setRecentComments] = useState<RecentComment[]>(() => getCachedRecentComments());
const [unreadMessages, setUnreadMessages] = useState(0);
const [recentUsers, setRecentUsers] = useState<RecentUser[]>(() => getCachedRecentUsers());
const [unreadMessages, setUnreadMessages] = useState(() => getBootUnread());
const [dmUnread, setDmUnread] = useState(0);
const [notifyUnread, setNotifyUnread] = useState(0);
const [tags, setTags] = useState<TagCount[]>(() => getCachedTags());
const [tagsLoading, setTagsLoading] = useState(() => getCachedTags().length === 0);
const [postOutline, setPostOutline] = useState<{
@@ -61,19 +86,29 @@ export default function MainLayout() {
} | null>(null);
const [asideOpen, setAsideOpen] = useState(false);
const [sidebarOpen, setSidebarOpen] = useState(false);
const [searchExpanded, setSearchExpanded] = useState(false);
const [searchPanelOpen, setSearchPanelOpen] = useState(false);
const searchInputRef = useRef<HTMLInputElement>(null);
const [asideLoading, setAsideLoading] = useState(() => !hasCachedAside());
const [boardsLoading, setBoardsLoading] = useState(() => getCachedBoards().length === 0);
const [layoutRefreshTick, setLayoutRefreshTick] = useState(0);
const asideEverLoaded = useRef(false);
const [boardId, setBoardId] = useState(Number(params.get('board')) || 0);
const [keyword, setKeyword] = useState(params.get('keyword') || '');
const [searchAuthor, setSearchAuthor] = useState(params.get('author') || '');
const [searchTitleOnly, setSearchTitleOnly] = useState(params.get('title_only') === '1');
const [searchInBoard, setSearchInBoard] = useState(!!params.get('board') && !!params.get('keyword'));
const [searchAdvanced, setSearchAdvanced] = useState(false);
const feedSort = parseFeedSort(params.get('sort'));
/** 冷启动门闩:main.tsx 已预热则可同步放行;否则等齐再呈现 */
const [shellReady, setShellReady] = useState(() => isCompose || wasColdBootEnsured());
const coldBootDone = useRef(isCompose || wasColdBootEnsured());
const bootGen = useRef(0);
const [boardId, setBoardId] = useState(() => {
const m = loc.pathname.match(/^\/board\/(\d+(?:\.[A-Za-z0-9]{1,16})?)$/);
if (m) return parsePermalinkID(m[1]) || 0;
return Number(params.get('board')) || 0;
});
const [keywordDraft, setKeywordDraft] = useState(params.get('keyword') || '');
const { limits: forumLimits } = useForumLimits();
const feedSort = parseFeedSort(params.get('sort'), forumLimits.feed_sort_tabs);
const postSearch = usePostSearch(forumLimits);
const asideWidgets = useMemo(() => resolveAsideWidgets(forumLimits), [forumLimits]);
const showTagCloud = asideWidgets.some(w => w.id === 'tag_cloud' && w.enabled);
const showRecentComments = asideWidgets.some(w => w.id === 'recent_comments' && w.enabled);
const showRecentUsers = asideWidgets.some(w => w.id === 'recent_users' && w.enabled);
const asideDrawerRef = useRef<HTMLElement>(null);
const asideCloseRef = useRef<HTMLButtonElement>(null);
@@ -99,35 +134,60 @@ export default function MainLayout() {
initialFocusRef: sidebarCloseRef,
});
useEffect(() => { setBoardId(Number(params.get('board')) || 0); }, [params]);
useEffect(() => {
setKeyword(params.get('keyword') || '');
setSearchAuthor(params.get('author') || '');
setSearchTitleOnly(params.get('title_only') === '1');
setSearchInBoard(!!params.get('board') && (!!params.get('keyword') || !!params.get('author')));
const m = loc.pathname.match(/^\/board\/(\d+(?:\.[A-Za-z0-9]{1,16})?)$/);
if (m) {
setBoardId(parsePermalinkID(m[1]) || 0);
return;
}
setBoardId(Number(params.get('board')) || 0);
}, [loc.pathname, params]);
useEffect(() => {
setKeywordDraft(params.get('keyword') || '');
}, [params]);
useEffect(() => {
setAsideOpen(false);
setSidebarOpen(false);
setSearchExpanded(false);
}, [loc.pathname, loc.search]);
useEffect(() => {
if (!/^\/post\/\d+/.test(loc.pathname)) setPostOutline(null);
const isArticleAside =
(/^\/post\/\d+/.test(loc.pathname) && !/\/edit$/.test(loc.pathname))
|| /^\/page\//.test(loc.pathname);
if (!isArticleAside) setPostOutline(null);
}, [loc.pathname]);
useEffect(() => {
if (!hideAside) setAsideOpen(false);
}, [hideAside]);
useEffect(() => {
if (!isMobile) {
setSidebarOpen(false);
setSearchExpanded(false);
}
if (!isMobile) setSidebarOpen(false);
}, [isMobile]);
const openSearchPanel = useCallback(() => setSearchPanelOpen(true), []);
useEffect(() => {
if (!searchExpanded) return;
const t = window.setTimeout(() => searchInputRef.current?.focus(), 50);
return () => window.clearTimeout(t);
}, [searchExpanded]);
const onOpen = () => setSearchPanelOpen(true);
window.addEventListener(POST_SEARCH_OPEN_EVENT, onOpen);
return () => window.removeEventListener(POST_SEARCH_OPEN_EVENT, onOpen);
}, []);
useEffect(() => {
if (isCompose) return;
const onKey = (e: KeyboardEvent) => {
if (!(e.ctrlKey || e.metaKey) || e.key.toLowerCase() !== 'k') return;
const tag = (e.target as HTMLElement | null)?.tagName;
const editable = (e.target as HTMLElement | null)?.isContentEditable;
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || editable) return;
e.preventDefault();
if (isMobile) {
setSearchPanelOpen(true);
} else {
searchInputRef.current?.focus();
searchInputRef.current?.select();
}
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [isCompose, isMobile]);
useEffect(() => {
if (!asideOpen && !sidebarOpen) return;
const prev = document.body.style.overflow;
@@ -160,16 +220,120 @@ export default function MainLayout() {
return () => window.removeEventListener('boards-refresh', onRefresh);
}, [refreshBoards]);
// 冷启动兜底:main 未预热时静默等齐(不打进度条);站内已预热则保持打开
useEffect(() => {
if (isCompose) {
coldBootDone.current = true;
setShellReady(true);
return;
}
if (coldBootDone.current || wasColdBootEnsured()) {
coldBootDone.current = true;
setShellReady(true);
setBoardsLoading(false);
setAsideLoading(false);
setTagsLoading(false);
asideEverLoaded.current = true;
return;
}
const gen = ++bootGen.current;
let cancelled = false;
(async () => {
try {
const path = `${loc.pathname}${loc.search}`;
const tasks: Promise<unknown>[] = [
prefetchRoute(path, { force: false }),
refreshBoards(),
ensureSitePagesLoaded(),
];
if (!hideAside) {
if (showRecentComments) {
tasks.push(
api.recentComments().then((d) => {
const next = Array.isArray(d.comments) ? d.comments : [];
setRecentComments(next);
setCachedRecentComments(next);
}).catch(() => undefined),
);
}
if (showRecentUsers) {
tasks.push(
api.recentUsers().then((d) => {
const next = Array.isArray(d.users) ? d.users : [];
setRecentUsers(next);
setCachedRecentUsers(next);
}).catch(() => undefined),
);
}
if (showTagCloud) {
tasks.push(
api.tags(40).then((d) => {
const next = Array.isArray(d.tags) ? d.tags : [];
setTags(next);
setCachedTags(next);
}).catch(() => undefined),
);
}
}
await Promise.all(tasks);
} catch {
// 失败也放行
} finally {
if (!cancelled && bootGen.current === gen) {
asideEverLoaded.current = true;
setAsideLoading(false);
setTagsLoading(false);
setBoardsLoading(false);
coldBootDone.current = true;
setShellReady(true);
}
}
})();
return () => {
cancelled = true;
};
}, [
isCompose,
loc.pathname,
loc.search,
hideAside,
showRecentComments,
showRecentUsers,
showTagCloud,
refreshBoards,
]);
const refreshUnreadMessages = useCallback(() => {
if (!user) {
setUnreadMessages(0);
setDmUnread(0);
setNotifyUnread(0);
return;
}
api.messageUnreadCount()
.then((r) => setUnreadMessages(r.count || 0))
.catch(() => setUnreadMessages(0));
.then((r) => {
setUnreadMessages(r.count || 0);
setDmUnread(r.dm_count ?? 0);
setNotifyUnread(r.notify_count ?? 0);
})
.catch(() => {
setUnreadMessages(0);
setDmUnread(0);
setNotifyUnread(0);
});
}, [user]);
/** 仅有通知未读时直达通知 Tab,避免先看到空私信列表 */
const openMessages = useCallback(() => {
const path = notifyUnread > 0 && dmUnread === 0 ? '/messages?tab=notify' : '/messages';
void transitionTo(nav, path);
}, [nav, notifyUnread, dmUnread]);
useEffect(() => {
refreshUnreadMessages();
const onRefresh = () => refreshUnreadMessages();
@@ -181,10 +345,49 @@ export default function MainLayout() {
};
}, [refreshUnreadMessages]);
// 标签云:进页/离开发帖页时拉取;不跟 posts-refresh 联动(置顶/精华等不改标签)
useEffect(() => {
if (isCompose) return;
const syncFromCache = () => {
// 仅当 cache 有内容时覆盖,避免空数组盖住已渲染的非空 UI
const nextBoards = getCachedBoards();
if (nextBoards.length > 0) setBoards(nextBoards);
setBoardsLoading(false);
const nextStats = getCachedStats();
if (nextStats) setStats(nextStats);
const nextComments = getCachedRecentComments();
if (nextComments.length > 0 || hasCachedAside()) setRecentComments(nextComments);
const nextUsers = getCachedRecentUsers();
if (nextUsers.length > 0 || hasCachedAside()) setRecentUsers(nextUsers);
const nextTags = getCachedTags();
if (nextTags.length > 0) setTags(nextTags);
setTagsLoading(false);
setAsideLoading(false);
asideEverLoaded.current = true;
refreshUnreadMessages();
};
const onForce = () => {
// 旧路径:仍可能被别处派发;尽量静默刷新壳层
refreshBoards();
refreshUnreadMessages();
refetchSiteBranding();
setLayoutRefreshTick(n => n + 1);
};
const onCommit = () => {
// 软刷新:预热已写入 cache,同一拍同步进 state,不触发分批 loading
syncFromCache();
};
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
return () => {
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
};
}, [refreshBoards, refreshUnreadMessages]);
// 标签云:进页/离开发帖页时拉取;不跟 posts-refresh 联动(置顶/推荐等不改标签)
useEffect(() => {
if (isCompose || !showTagCloud) return;
let cancelled = false;
// 有 session 缓存则静默刷新(软刷新不卸空白)
if (getCachedTags().length === 0) setTagsLoading(true);
api.tags(40).then(d => {
if (cancelled) return;
@@ -197,31 +400,24 @@ export default function MainLayout() {
return () => {
cancelled = true;
};
}, [isCompose]);
}, [isCompose, showTagCloud, layoutRefreshTick]);
const needAsideData = !isCompose && (!hideAside || asideOpen);
const needRecentComments = needAsideData && showRecentComments;
useEffect(() => {
if (!needAsideData) return;
if (!needRecentComments) return;
let cancelled = false;
// 无缓存时才显示加载态,有缓存则静默刷新,避免抽屉高度跳动
if (!asideEverLoaded.current && !hasCachedAside()) {
setAsideLoading(true);
}
Promise.all([
api.hotPosts().then(d => {
if (cancelled) return;
const next = Array.isArray(d.posts) ? d.posts : [];
setHot(next);
setCachedHot(next);
}).catch(() => {}),
api.recentComments().then(d => {
if (cancelled) return;
const next = Array.isArray(d.comments) ? d.comments : [];
setRecentComments(next);
setCachedRecentComments(next);
}).catch(() => {}),
]).finally(() => {
}).catch(() => {}).finally(() => {
if (!cancelled) {
asideEverLoaded.current = true;
setAsideLoading(false);
@@ -231,47 +427,55 @@ export default function MainLayout() {
return () => {
cancelled = true;
};
}, [needAsideData]);
}, [needRecentComments, layoutRefreshTick]);
const doSearch = () => {
const kw = keyword.trim();
const author = searchAuthor.trim();
const activeKw = (params.get('keyword') || '').trim();
const activeAuthor = (params.get('author') || '').trim();
const activeTitleOnly = params.get('title_only') === '1';
const activeBoard = Number(params.get('board')) || 0;
if (!kw && !author) {
if (activeKw || activeAuthor) navigateFeed(nav, '/');
return;
const needRecentUsers = needAsideData && showRecentUsers;
useEffect(() => {
if (!needRecentUsers) return;
let cancelled = false;
if (!asideEverLoaded.current && !hasCachedAside()) {
setAsideLoading(true);
}
if (kw) {
const len = [...kw].length;
if (forumLimits.search_keyword_min > 0 && len < forumLimits.search_keyword_min) {
notify.warning(`搜索关键词至少 ${forumLimits.search_keyword_min} 个字`);
return;
api.recentUsers().then(d => {
if (cancelled) return;
const next = Array.isArray(d.users) ? d.users : [];
setRecentUsers(next);
setCachedRecentUsers(next);
}).catch(() => {}).finally(() => {
if (!cancelled) {
asideEverLoaded.current = true;
setAsideLoading(false);
}
if (forumLimits.search_keyword_max > 0 && len > forumLimits.search_keyword_max) {
notify.warning(`搜索关键词最多 ${forumLimits.search_keyword_max} 个字`);
return;
}
}
const scopeBoard = searchInBoard && boardId > 0 ? boardId : 0;
const target = buildHomeUrl(scopeBoard, 'latest', {
keyword: kw,
author,
titleOnly: !!kw && searchTitleOnly,
});
const same =
loc.pathname === '/'
&& activeKw === kw
&& activeAuthor === author
&& activeTitleOnly === (!!kw && searchTitleOnly)
&& activeBoard === scopeBoard;
if (same) {
navigateFeed(nav, target);
return;
}
nav(target);
return () => {
cancelled = true;
};
}, [needRecentUsers, layoutRefreshTick]);
const doQuickSearch = () => {
const { author, titleOnly, scopeBoardId } = postSearch.filters;
postSearch.submitSearch({
keyword: keywordDraft,
author,
titleOnly,
scopeBoardId,
}, { refreshIfSame: true });
};
const handleHeaderClear = () => {
const hasUrlSearch = postSearch.filters.isFiltered;
setKeywordDraft('');
if (hasUrlSearch) postSearch.clearSearch();
};
const contextBoard = boards.find((b) => b.id === boardId);
const searchPanelDraft = {
keyword: keywordDraft,
author: postSearch.filters.author,
titleOnly: postSearch.filters.titleOnly,
scopeBoardId: postSearch.filters.scopeBoardId,
};
const openPost = useCallback((id: number, opts?: { floor?: number }) => {
@@ -280,7 +484,7 @@ export default function MainLayout() {
}, [nav, forumLimits.open_posts_in_new_tab]);
const userInitial = user?.nickname?.charAt(0) || '?';
const isFeedHome = loc.pathname === '/';
const isFeedHome = loc.pathname === '/' || /^\/board\/\d+/.test(loc.pathname);
const outletKeyword = params.get('keyword') || '';
const outletTag = params.get('tag') || '';
const outletAuthor = params.get('author') || '';
@@ -294,6 +498,10 @@ export default function MainLayout() {
const activeChipIndex = Math.max(0, boardChipIds.indexOf(mobileActiveBoard === -1 ? 0 : mobileActiveBoard));
const isPostDetail = /^\/post\/\d+/.test(loc.pathname) && !/\/edit$/.test(loc.pathname);
const isSitePage = /^\/page\//.test(loc.pathname);
const isArticleAside = isPostDetail || isSitePage;
// 帖子有作者 →「作者与目录」;单页仅目录
const articleAsideLabel = isPostDetail ? '作者与目录' : '文章目录';
const setPostOutlineSafe = useCallback((outline: {
headings: PostHeading[];
scrollRoot: HTMLElement | null;
@@ -318,7 +526,7 @@ export default function MainLayout() {
const selectBoardChip = (id: number) => {
setBoardId(id);
navigateFeed(nav, buildHomeUrl(id, feedSort));
navigateFeed(nav, buildHomeUrl(id, feedSort, { permalink: forumLimits }));
};
const onBoardBarKeyDown = (e: React.KeyboardEvent) => {
@@ -333,14 +541,14 @@ export default function MainLayout() {
};
return (
<div className="app-shell">
<div className={cn('app-shell', forceDesktop && 'ssr-home')}>
<div className="app-frame">
<header className={`app-header${searchExpanded && isMobile ? ' app-header--search-open' : ''}`}>
<header className="app-header">
<div className="header-inner">
{isMobile && !isCompose && !searchExpanded && (
{!isCompose && (
<button
type="button"
className="header-icon-btn"
className="header-icon-btn header-menu-btn"
onClick={openSidebar}
aria-label="打开导航菜单"
aria-expanded={sidebarOpen}
@@ -350,33 +558,42 @@ export default function MainLayout() {
<Menu size={18} aria-hidden />
</button>
)}
{!(isMobile && searchExpanded) && (
<button type="button" className="header-brand" onClick={() => navigateFeed(nav, '/')}>
{/* 任意页点 Logo:回首页并强制刷新,不展示会话缓存 */}
<button type="button" className="header-brand" onClick={() => navigateFeed(nav, '/', { refresh: true })}>
<SiteBrandMark branding={branding} className="header-logo-mark" />
{!isMobile && <span className="header-logo-text">{branding.name}</span>}
<span className="header-logo-text">{branding.name}</span>
</button>
)}
{!isCompose && isMobile && !searchExpanded && (
{!isCompose && isMobile && (
<button
type="button"
className="header-icon-btn header-search-toggle"
onClick={() => setSearchExpanded(true)}
className={cn(
'header-search-mobile-pill',
(keywordDraft || postSearch.filters.isFiltered) && 'header-search-mobile-pill--active',
)}
onClick={openSearchPanel}
aria-label="搜索帖子"
title="搜索"
>
<Search size={18} aria-hidden />
<Search size={15} aria-hidden className="header-search-mobile-pill__icon" />
<span className="header-search-mobile-pill__text">
{keywordDraft
|| postSearch.filters.keyword
|| postSearch.filters.author
|| '搜索帖子…'}
</span>
{postSearch.filters.hasAdvancedFilters && (
<span className="header-search-mobile-pill__dot" aria-hidden />
)}
</button>
)}
{!isCompose && (!isMobile || searchExpanded) && (
{!isCompose && !isMobile && (
<form
className={`header-search-wrap${isMobile && searchExpanded ? ' header-search-wrap--expanded' : ''}${searchAdvanced ? ' header-search-wrap--advanced' : ''}`}
className="header-search-wrap"
role="search"
onSubmit={e => {
e.preventDefault();
doSearch();
if (isMobile) setSearchExpanded(false);
doQuickSearch();
}}
>
<div className="header-search-row">
@@ -385,89 +602,51 @@ export default function MainLayout() {
ref={searchInputRef}
className="header-search-input"
type="search"
placeholder="搜索帖子..."
placeholder="搜索帖子…"
aria-label="搜索帖子"
value={keyword}
onChange={e => setKeyword(e.target.value)}
value={keywordDraft}
onChange={e => setKeywordDraft(e.target.value)}
maxLength={forumLimits.search_keyword_max > 0 ? forumLimits.search_keyword_max : undefined}
enterKeyHint="search"
/>
<button
type="button"
className={cn('header-search-adv-toggle', searchAdvanced && 'active')}
onClick={() => setSearchAdvanced((v) => !v)}
aria-expanded={searchAdvanced}
title="高级搜索"
className={cn(
'header-search-filter-btn',
postSearch.filters.hasAdvancedFilters && 'header-search-filter-btn--active',
)}
onClick={openSearchPanel}
aria-label="搜索筛选"
title="筛选"
>
筛选
<SlidersHorizontal size={15} aria-hidden />
{postSearch.filters.hasAdvancedFilters && (
<span className="header-search-filter-btn__dot" aria-hidden />
)}
</button>
{(keyword || searchAuthor) && (
{(keywordDraft || postSearch.filters.isFiltered) && (
<button
type="button"
className="header-search-clear"
onClick={() => {
setKeyword('');
setSearchAuthor('');
setSearchTitleOnly(false);
navigateFeed(nav, '/');
}}
onClick={handleHeaderClear}
aria-label="清除搜索"
>×</button>
)}
{isMobile && searchExpanded && (
<button
type="button"
className="header-search-cancel"
onClick={() => setSearchExpanded(false)}
>
取消
</button>
)}
<kbd className="header-search-kbd" aria-hidden>Ctrl K</kbd>
</div>
{searchAdvanced && (
<div className="header-search-advanced">
<label className="header-search-opt">
<input
type="checkbox"
checked={searchTitleOnly}
onChange={(e) => setSearchTitleOnly(e.target.checked)}
/>
仅标题
</label>
{boardId > 0 && (
<label className="header-search-opt">
<input
type="checkbox"
checked={searchInBoard}
onChange={(e) => setSearchInBoard(e.target.checked)}
/>
当前板块
</label>
)}
<input
className="header-search-author"
type="text"
placeholder="作者用户名/昵称"
aria-label="作者"
value={searchAuthor}
onChange={(e) => setSearchAuthor(e.target.value)}
/>
</div>
)}
</form>
)}
{!(isMobile && searchExpanded) && (
<div className="header-actions">
{!isCompose && (
<button
type="button"
className="header-compose-btn"
onClick={() => user ? nav('/compose') : nav(loginPath('/compose'))}
onClick={() => user ? void transitionTo(nav, '/compose') : nav(loginPath('/compose'))}
aria-label="发帖"
>
<Plus size={16} aria-hidden />
{!isMobile && <span>发帖</span>}
<span className="header-compose-btn__label">发帖</span>
</button>
)}
@@ -478,26 +657,24 @@ export default function MainLayout() {
type="button"
className="header-icon-btn"
onClick={openAside}
aria-label={isPostDetail ? '打开作者与目录' : '打开社区动态'}
aria-label={isArticleAside ? `打开${articleAsideLabel}` : '打开社区动态'}
aria-expanded={asideOpen}
aria-controls="aside-drawer"
title={isPostDetail ? '作者与目录' : '社区动态'}
title={isArticleAside ? articleAsideLabel : '社区动态'}
>
<PanelRight size={18} aria-hidden />
</button>
)}
{!isMobile && (
<button
type="button"
className="header-icon-btn"
className="header-icon-btn header-theme-btn"
onClick={toggle}
aria-label={theme === 'light' ? '切换暗色模式' : '切换亮色模式'}
title={theme === 'light' ? '切换暗色模式' : '切换亮色模式'}
>
{theme === 'light' ? <Moon size={18} aria-hidden /> : <Sun size={18} aria-hidden />}
</button>
)}
{authLoading ? (
<span className="header-auth-slot header-auth-slot--loading" aria-hidden />
@@ -508,7 +685,7 @@ export default function MainLayout() {
className="header-icon-btn header-msg-btn"
title={unreadMessages > 0 ? `${unreadMessages} 条未读消息` : '站内消息'}
aria-label={unreadMessages > 0 ? `站内消息,${unreadMessages} 条未读` : '站内消息'}
onClick={() => nav('/messages')}
onClick={openMessages}
>
<Mail size={18} aria-hidden />
{unreadMessages > 0 && (
@@ -528,14 +705,14 @@ export default function MainLayout() {
className="w-40"
onCloseAutoFocus={(e) => e.preventDefault()}
>
<DropdownMenuItem onClick={() => nav(userPath(user.id))}>个人主页</DropdownMenuItem>
<DropdownMenuItem onClick={() => nav('/profile')}>
<DropdownMenuItem onClick={() => void transitionTo(nav, userPath(user.id))}>个人主页</DropdownMenuItem>
<DropdownMenuItem onClick={() => void transitionTo(nav, '/profile')}>
账号设置{typeof user.points === 'number' ? ` · ${user.points} 积分` : ''}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => nav('/messages')}>
<DropdownMenuItem onClick={openMessages}>
站内消息{unreadMessages > 0 ? ` (${unreadMessages})` : ''}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => nav('/favorites')}>我的收藏</DropdownMenuItem>
<DropdownMenuItem onClick={() => void transitionTo(nav, '/favorites')}>我的收藏</DropdownMenuItem>
{isMobile && (
<DropdownMenuItem onClick={toggle}>
{theme === 'light' ? '切换暗色模式' : '切换亮色模式'}
@@ -561,17 +738,33 @@ export default function MainLayout() {
)}
</div>
</div>
)}
</div>
</header>
<div className={`app-body${isCompose ? ' app-body--compose' : ''}`}>
{!isCompose && (
<PostSearchPanel
open={searchPanelOpen}
onOpenChange={setSearchPanelOpen}
draft={searchPanelDraft}
contextBoardId={boardId}
contextBoardName={contextBoard?.name}
onSubmit={(input) => {
const ok = postSearch.submitSearch(input);
if (ok) setKeywordDraft((input.keyword ?? '').trim());
return ok;
}}
onClear={postSearch.clearSearch}
/>
)}
<div className={`app-body${isCompose ? ' app-body--compose' : ''}`}>
{!isCompose && shellReady && (
<Sidebar
boards={boards}
activeBoard={boardId}
onSelectBoard={setBoardId}
boardsLoading={boardsLoading}
/>
)}
@@ -580,13 +773,16 @@ export default function MainLayout() {
isCompose && 'content-workspace--compose',
hideAside && !isCompose && 'content-workspace--aside-hidden',
)}>
<main className={cn(
<main
className={cn(
'main-content',
isCompose && 'main-content--compose',
// 手机 Feed:整栏滚动,板块条 / 排序栏可滚出视口,多露出帖子列表
isMobile && !isCompose && isFeedHome && 'main-content--feed-mobile-scroll',
)}>
{isMobile && !isCompose && isFeedHome && (
)}
aria-busy={!shellReady}
>
{shellReady && isMobile && !isCompose && isFeedHome && (
<div
ref={boardBarRef}
className="mobile-board-bar"
@@ -624,21 +820,27 @@ export default function MainLayout() {
})}
</div>
)}
<Suspense fallback={isFeedHome ? <FeedPageSkeleton /> : <PageLoader />}>
{shellReady ? (
<Suspense fallback={null}>
<Outlet context={layoutCtx} />
</Suspense>
) : null}
</main>
{!isCompose && (
<aside className="aside-panel">
<aside className="aside-panel" aria-busy={!shellReady}>
{shellReady && (
<RightPanel
hot={hot}
recentComments={recentComments}
recentUsers={recentUsers}
tags={tags}
tagsLoading={tagsLoading}
stats={stats}
loading={asideLoading}
asideWidgets={asideWidgets}
onPostClick={openPost}
postDetail={isPostDetail ? {
postDetail={isArticleAside ? {
author: postOutline?.author ?? null,
publishedAt: postOutline?.publishedAt,
viewCount: postOutline?.viewCount,
@@ -647,6 +849,7 @@ export default function MainLayout() {
outlineTitle: postOutline?.title,
} : null}
/>
)}
</aside>
)}
</div>
@@ -686,12 +889,14 @@ export default function MainLayout() {
</button>
</div>
<div className="aside-drawer-body sidebar-drawer-body">
{shellReady && (
<Sidebar
boards={boards}
activeBoard={boardId}
onSelectBoard={setBoardId}
boardsLoading={boardsLoading}
/>
)}
<div className="sidebar-drawer-extras">
<button
type="button"
@@ -699,7 +904,7 @@ export default function MainLayout() {
onClick={() => { closeSidebar(); openAside(); }}
>
<PanelRight size={16} aria-hidden />
{isPostDetail ? '作者与目录' : '社区动态'}
{isArticleAside ? articleAsideLabel : '社区动态'}
</button>
<button
type="button"
@@ -730,10 +935,10 @@ export default function MainLayout() {
className="aside-drawer"
role="dialog"
aria-modal="true"
aria-label={isPostDetail ? '作者与目录' : '社区动态'}
aria-label={isArticleAside ? articleAsideLabel : '社区动态'}
>
<div className="aside-drawer-head">
<span>{isPostDetail ? '作者与目录' : '社区动态'}</span>
<span>{isArticleAside ? articleAsideLabel : '社区动态'}</span>
<button
ref={asideCloseRef}
type="button"
@@ -746,13 +951,15 @@ export default function MainLayout() {
</div>
<div className="aside-drawer-body">
<RightPanel
hot={hot}
recentComments={recentComments}
recentUsers={recentUsers}
tags={tags}
tagsLoading={tagsLoading}
stats={stats}
loading={asideLoading}
asideWidgets={asideWidgets}
onPostClick={openPost}
postDetail={isPostDetail ? {
postDetail={isArticleAside ? {
author: postOutline?.author ?? null,
publishedAt: postOutline?.publishedAt,
viewCount: postOutline?.viewCount,

View File

@@ -1,12 +1,96 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { hydrateRoot, createRoot } from 'react-dom/client';
import { applyTheme, getStoredTheme } from './utils/theme';
import App from './App';
import { consumeHomeBoot } from './utils/homeBoot';
import { beginHomeHydrate } from './utils/homeHydrate';
import { reloadForStaleChunk } from './utils/chunkLoad';
import { ensureColdBootReady, isMainLayoutPath } from './utils/prefetchRoute';
applyTheme(getStoredTheme());
consumeHomeBoot();
ReactDOM.createRoot(document.getElementById('root')!).render(
// Vite modulepreload / 动态 import 失败(发版后旧 hashed URL 404)
window.addEventListener('vite:preloadError', (event) => {
event.preventDefault();
reloadForStaleChunk();
});
function hasSSRHome(): boolean {
return !!document.querySelector('#root .ssr-home');
}
function waitForStylesheets(): Promise<void> {
const links = Array.from(document.querySelectorAll('link[rel="stylesheet"]'));
if (links.length === 0) return Promise.resolve();
return Promise.all(
links.map(
(node) =>
new Promise<void>((resolve) => {
const link = node as HTMLLinkElement;
try {
if (link.sheet) {
resolve();
return;
}
} catch {
/* cross-origin */
}
const finish = () => resolve();
link.addEventListener('load', finish, { once: true });
link.addEventListener('error', finish, { once: true });
}),
),
).then(() => undefined);
}
function renderApp() {
return (
<React.StrictMode>
<App />
</React.StrictMode>
);
);
}
function mountCreateRoot(el: HTMLElement) {
createRoot(el).render(renderApp());
}
/** 有 SSR 正文:hydrate 接管同一 DOM;失败则回退 createRoot */
function mountHydrateHome(el: HTMLElement) {
beginHomeHydrate();
try {
hydrateRoot(el, renderApp());
} catch (err) {
console.warn('[j13] hydrateRoot 失败,回退 createRoot', err);
el.innerHTML = '';
mountCreateRoot(el);
}
}
async function boot() {
const path = `${window.location.pathname}${window.location.search}`;
const ssr = hasSSRHome();
await waitForStylesheets();
try {
if (document.fonts?.ready) await document.fonts.ready;
} catch {
/* ignore */
}
if (isMainLayoutPath(window.location.pathname)) {
await ensureColdBootReady(path);
}
const root = document.getElementById('root');
if (!root) return;
if (ssr) {
mountHydrateHome(root);
} else {
mountCreateRoot(root);
}
}
void boot();

View File

@@ -30,6 +30,8 @@ import type { Board } from '../api/types';
import { BoardColorPicker, BoardIconPicker } from '../components/BoardAppearancePicker';
import BoardIconDisplay from '../components/BoardIconDisplay';
import { getBoardThemeIndex } from '../utils/boardTheme';
import AdminSortableList, { SortableDragHandle, SortableMoveButtons } from '../components/admin/AdminSortableList';
import { persistSortOrderChanges, shouldShowSortableMoveButtons } from '../utils/sortOrder';
const boardSchema = z.object({
name: z.string().min(1, '请输入名称').max(64),
@@ -48,6 +50,7 @@ export default function BoardsManagePage() {
const [modalOpen, setModalOpen] = useState(false);
const [editing, setEditing] = useState<Board | null>(null);
const [submitting, setSubmitting] = useState(false);
const [reordering, setReordering] = useState(false);
const form = useForm<BoardFormValues>({
resolver: zodResolver(boardSchema),
@@ -125,6 +128,32 @@ export default function BoardsManagePage() {
}
};
const handleBoardReorder = async (reordered: Board[]) => {
const before = [...boards];
setReordering(true);
try {
const after = await persistSortOrderChanges(before, reordered, board =>
api.updateBoard(board.id, {
name: board.name,
description: board.description ?? '',
sort_order: board.sort_order ?? 0,
icon: board.icon ?? '',
color_index: board.color_index ?? -1,
}).then(() => undefined),
);
setBoards(after);
notify.success('板块排序已更新');
window.dispatchEvent(new Event('boards-refresh'));
} catch (e: unknown) {
setBoards(before);
notify.error(e instanceof Error ? e.message : '排序保存失败');
} finally {
setReordering(false);
}
};
const showMoveButtons = shouldShowSortableMoveButtons(boards.length);
if (!ready) {
return <div className="flex justify-center py-16"><Spinner size="lg" /></div>;
}
@@ -152,20 +181,36 @@ export default function BoardsManagePage() {
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-[72px]">排序</TableHead>
<TableHead className="w-[60px]">ID</TableHead>
<TableHead className="w-[52px]">图标</TableHead>
<TableHead>名称</TableHead>
<TableHead>简介</TableHead>
<TableHead className="w-[70px]">排序</TableHead>
<TableHead className="w-[70px]">权重</TableHead>
<TableHead className="w-[80px]">帖子数</TableHead>
<TableHead className="w-[160px]">操作</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{boards.map(board => {
<AdminSortableList
as={TableBody}
items={boards}
getId={board => board.id}
onReorder={handleBoardReorder}
showMoveButtons="auto"
renderItem={(board, _index, controls) => {
const themeIdx = getBoardThemeIndex(board);
return (
<TableRow key={board.id}>
<TableRow
ref={controls.setNodeRef}
style={controls.style}
className={cn('admin-sortable-table-row', controls.isDragging && 'is-dragging')}
>
<TableCell>
<div className="flex items-center gap-0">
<SortableDragHandle label={`拖拽调整「${board.name}」顺序`} {...controls.dragHandleProps} />
{showMoveButtons && <SortableMoveButtons controls={controls} />}
</div>
</TableCell>
<TableCell>{board.id}</TableCell>
<TableCell>
<span className={cn('board-table-icon', `sidebar-board-icon--${themeIdx}`)}>
@@ -178,10 +223,10 @@ export default function BoardsManagePage() {
<TableCell><Badge variant="secondary">{board.post_count ?? 0}</Badge></TableCell>
<TableCell>
<div className="flex items-center gap-1">
<Button variant="ghost" size="sm" onClick={() => openEdit(board)}>编辑</Button>
<Button variant="ghost" size="sm" onClick={() => openEdit(board)} disabled={reordering}>编辑</Button>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="ghost" size="sm" className="text-destructive hover:text-destructive">
<Button variant="ghost" size="sm" className="text-destructive hover:text-destructive" disabled={reordering}>
删除
</Button>
</AlertDialogTrigger>
@@ -204,8 +249,8 @@ export default function BoardsManagePage() {
</TableCell>
</TableRow>
);
})}
</TableBody>
}}
/>
</Table>
{boards.length === 0 && (
<div className="empty-state">

View File

@@ -13,7 +13,16 @@ import { serializeTags, parseTags } from '../components/TagInput';
import { Spinner } from '@/components/ui/spinner';
import ComposeHeader from '../components/compose/ComposeHeader';
import ComposeContextBar, { type PostType } from '../components/compose/ComposeContextBar';
import ComposeSpecialFields, {
buildPollOptionsPayload,
countValidPollOptions,
defaultPollEndsAtLocal,
pollEndsAtISOToLocal,
pollEndsAtLocalToISO,
validatePollEndsAtLocal,
} from '../components/compose/ComposeSpecialFields';
import ComposeDocument from '../components/compose/ComposeDocument';
import { sortBoardsForCompose } from '../utils/board';
import { getCachedBoards } from '../utils/layoutCache';
import type { LayoutCtx } from '../layouts/MainLayout';
import { loginPath } from '../utils/authRedirect';
@@ -36,8 +45,8 @@ interface ComposeBaseline {
}
function resolveBoards(ctxBoards?: Board[]): Board[] {
if (ctxBoards && ctxBoards.length > 0) return ctxBoards;
return getCachedBoards();
const raw = ctxBoards && ctxBoards.length > 0 ? ctxBoards : getCachedBoards();
return sortBoardsForCompose(raw);
}
/** 格式化剩余可编辑时间 */
@@ -74,6 +83,13 @@ export default function ComposePage() {
const [tags, setTags] = useState('');
const [content, setContent] = useState('');
const [postType, setPostType] = useState<PostType>('normal');
const [pollOptions, setPollOptions] = useState(['', '']);
const [pollMulti, setPollMulti] = useState(false);
const [pollMaxChoices, setPollMaxChoices] = useState(2);
const [pollEndsAt, setPollEndsAt] = useState(defaultPollEndsAtLocal);
const [pollNoEndTime, setPollNoEndTime] = useState(false);
const [bountyPoints, setBountyPoints] = useState(0);
const [lotteryWinners, setLotteryWinners] = useState(1);
const [publishing, setPublishing] = useState(false);
const [loading, setLoading] = useState(isEdit);
/** 新建帖:板块列表是否已就绪(避免请求中误显空态) */
@@ -101,7 +117,7 @@ export default function ComposePage() {
: api.boards();
Promise.all([boardsPromise, api.post(editId!, { skipView: true })])
.then(([boardsData, postData]) => {
const list = boardsData.boards ?? [];
const list = sortBoardsForCompose(boardsData.boards ?? []);
setBoards(list);
const post = postData.post;
const isOwnerOrAdmin = user.role === 'admin' || post.user_id === user.id;
@@ -116,7 +132,13 @@ export default function ComposePage() {
return;
}
const loadedBoardId = String(post.board_id);
const loadedType = post.post_type === 'question' ? 'question' : 'normal';
const loadedType = (
post.post_type === 'question' ? 'question'
: post.post_type === 'poll' ? 'poll'
: post.post_type === 'bounty' ? 'bounty'
: post.post_type === 'lottery' ? 'lottery'
: 'normal'
) as PostType;
const serverBaseline: ComposeBaseline = {
title: post.title,
tags: post.tags ?? '',
@@ -130,6 +152,18 @@ export default function ComposePage() {
setTags(serverBaseline.tags);
setContent(serverBaseline.content);
setPostType(loadedType);
if (postData.poll) {
setPollOptions(postData.poll.options.map(o => o.text));
setPollMulti(postData.poll.multi);
setPollMaxChoices(postData.poll.max_choices);
if (postData.poll.ends_at) {
setPollNoEndTime(false);
setPollEndsAt(pollEndsAtISOToLocal(postData.poll.ends_at));
} else {
setPollNoEndTime(true);
setPollEndsAt(defaultPollEndsAtLocal());
}
}
const windowHours = postData.post_edit_window_hours ?? 0;
if (user.role !== 'admin' && windowHours > 0) {
@@ -175,6 +209,13 @@ export default function ComposePage() {
setTags(draft.tags);
setContent(draft.content);
setPostType(draft.postType);
if (draft.postType === 'poll') {
if (draft.pollOptions?.length) setPollOptions(draft.pollOptions);
if (typeof draft.pollMulti === 'boolean') setPollMulti(draft.pollMulti);
if (typeof draft.pollMaxChoices === 'number') setPollMaxChoices(draft.pollMaxChoices);
if (typeof draft.pollNoEndTime === 'boolean') setPollNoEndTime(draft.pollNoEndTime);
if (typeof draft.pollEndsAt === 'string' && draft.pollEndsAt) setPollEndsAt(draft.pollEndsAt);
}
setBaseline(emptyBaseline);
setDraftHint('已恢复本地草稿,编辑中将自动保存');
return;
@@ -229,11 +270,18 @@ export default function ComposePage() {
content,
boardId,
postType,
...(postType === 'poll' ? {
pollOptions,
pollMulti,
pollMaxChoices,
pollEndsAt,
pollNoEndTime,
} : {}),
});
setDraftHint('草稿已自动保存到本机');
}, 800);
return () => window.clearTimeout(timer);
}, [isEdit, baseline, isDirty, title, tags, content, boardId, postType]);
}, [isEdit, baseline, isDirty, title, tags, content, boardId, postType, pollOptions, pollMulti, pollMaxChoices, pollEndsAt, pollNoEndTime]);
const {
dialogOpen,
@@ -307,15 +355,42 @@ export default function ComposePage() {
if (!boardId) { notify.warning('请选择板块'); return; }
if (!trimmedTitle) { notify.warning('请输入标题'); return; }
if (isHtmlEmpty(content)) { notify.warning('请输入正文内容'); return; }
if (postType === 'poll' && !isEdit && countValidPollOptions(pollOptions) < 2) {
notify.warning('投票至少需要 2 个非空选项');
return;
}
if (postType === 'poll' && !isEdit && !pollNoEndTime) {
const err = validatePollEndsAtLocal(pollEndsAt);
if (err) { notify.warning(err); return; }
}
if (postType === 'bounty' && !isEdit) {
const balance = user?.points ?? 0;
if (bountyPoints < 1) {
notify.warning('请填写悬赏积分');
return;
}
if (bountyPoints > balance) {
notify.warning('积分不足');
return;
}
}
setPublishing(true);
try {
const pollEndsAtISO = postType === 'poll' && !pollNoEndTime
? pollEndsAtLocalToISO(pollEndsAt)
: null;
const payload = {
title: trimmedTitle,
content: content.trim(),
tags: serializeTags(parseTags(tags)),
board_id: boardId,
post_type: postType,
poll_options: postType === 'poll'
? buildPollOptionsPayload(pollOptions, pollMulti, pollMaxChoices, pollEndsAtISO)
: undefined,
bounty_points: postType === 'bounty' ? bountyPoints : undefined,
lottery_winner_count: postType === 'lottery' ? lotteryWinners : undefined,
};
if (isEdit) {
await api.updatePost(editId!, payload);
@@ -372,6 +447,25 @@ export default function ComposePage() {
onTagsChange={setTags}
limits={limits}
/>
<ComposeSpecialFields
postType={postType}
pollOptions={pollOptions}
onPollOptionsChange={setPollOptions}
pollMulti={pollMulti}
onPollMultiChange={setPollMulti}
pollMaxChoices={pollMaxChoices}
onPollMaxChoicesChange={setPollMaxChoices}
pollEndsAt={pollEndsAt}
onPollEndsAtChange={setPollEndsAt}
pollNoEndTime={pollNoEndTime}
onPollNoEndTimeChange={setPollNoEndTime}
bountyPoints={bountyPoints}
onBountyPointsChange={setBountyPoints}
userPointsBalance={!isEdit ? user?.points : undefined}
lotteryWinners={lotteryWinners}
onLotteryWinnersChange={setLotteryWinners}
disabled={isEdit && postType !== 'normal' && postType !== 'question'}
/>
</ComposeDocument>
</div>
</div>

View File

@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react';
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeft, Star } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -7,6 +7,7 @@ import { notify } from '@/lib/notify';
import { api } from '../api/client';
import type { PostItem } from '../api/types';
import { useAuth } from '../hooks/useAuth';
import { useSessionResource } from '../hooks/useSessionResource';
import PostListItem from '../components/PostListItem';
import { loginPath } from '../utils/authRedirect';
import { useForumLimits } from '../hooks/useForumLimits';
@@ -26,16 +27,19 @@ export default function FavoritesPage() {
const { user, loading: authLoading } = useAuth();
const { limits } = useForumLimits();
useNoIndexSEO('我的收藏');
const [list, setList] = useState<FavItem[]>([]);
const [loading, setLoading] = useState(true);
const { data: list = [], loading } = useSessionResource<FavItem[]>(
user ? 'favorites' : null,
() => api.favorites().then(d => (Array.isArray(d.favorites) ? d.favorites as FavItem[] : [])),
{
enabled: !!user && !authLoading,
onError: (e) => notify.error(e instanceof Error ? e.message : '加载失败'),
},
);
useEffect(() => {
if (authLoading) return;
if (!user) { nav(loginPath('/favorites')); return; }
api.favorites()
.then(d => setList(Array.isArray(d.favorites) ? d.favorites as FavItem[] : []))
.catch(e => notify.error(e.message))
.finally(() => setLoading(false));
if (!user) nav(loginPath('/favorites'));
}, [user, authLoading, nav]);
if (authLoading || loading) return <div className="flex justify-center py-16"><Spinner size="lg" /></div>;
@@ -44,16 +48,18 @@ export default function FavoritesPage() {
return (
<div className="page-wrap">
<div className="page-inner-wide">
<Button variant="ghost" className="mb-3" onClick={() => nav('/')}>
<div className="feed-panel list-page-panel">
<header className="list-page-panel__head">
<Button variant="ghost" size="sm" className="list-page-panel__back" onClick={() => nav('/')}>
<ArrowLeft />
返回
</Button>
<h1 className="page-title">我的收藏</h1>
<p className="page-desc">共 {list.length} 篇收藏帖子</p>
</header>
{list.length === 0 ? (
<div className="empty-state">
<div className="empty-state list-page-panel__empty">
<Star className="empty-state-icon" aria-hidden size={36} strokeWidth={1.5} />
<p>还没有收藏任何帖子</p>
<Button onClick={() => nav('/')}>去逛逛</Button>

View File

@@ -1,48 +1,112 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useNavigate, useOutletContext, useSearchParams, useLocation } from 'react-router-dom';
import { useState, useEffect, useCallback, useRef, useMemo, startTransition as reactStartTransition } from 'react';
import {
useNavigate,
useOutletContext,
useSearchParams,
useLocation,
useParams,
useNavigationType,
} from 'react-router-dom';
import { notify } from '@/lib/notify';
import { api } from '../api/client';
import type { PostItem } from '../api/types';
import type { LayoutCtx } from '../layouts/MainLayout';
import VirtualPostList from '../components/VirtualPostList';
import StaticFeedList from '../components/StaticFeedList';
import FeedHeader from '../components/FeedHeader';
import FeedPageSkeleton from '../components/FeedPageSkeleton';
import FeedSearchFilters from '../components/search/FeedSearchFilters';
import FeedSortBar, { parseFeedSort, buildHomeUrl, type FeedSort } from '../components/FeedSortBar';
import { useForumLimits } from '../hooks/useForumLimits';
import { parseSearchFromUrl, usePostSearch } from '../hooks/usePostSearch';
import {
getFeedCache,
setFeedCache,
clearAllFeedCache,
navigateFeed,
FEED_RESET_EVENT,
FEED_PULL_REFRESH_EVENT,
type FeedNavState,
} from '../utils/feedCache';
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
import { feedCacheKey, getHomeStoreState } from '../store/homeStore';
import { enabledFeedSortTabs, getDefaultFeedSort } from '../utils/feedSortTabs';
import { openForumPost } from '../utils/openPost';
import { startTransition, doneTransition } from '../utils/spaTransition';
import { isHomeHydrating } from '../utils/homeHydrate';
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
import { siteMetaDescription, useSiteBranding } from '../hooks/useSiteBranding';
import { boardPath, canonicalRedirectPath, parsePermalinkID } from '../utils/permalink';
import NotFoundPage from './NotFoundPage';
/** 仅从 URL 解析板块 ID(不以 layout 状态回退,避免回首页误用上一板块) */
function boardIdFromLocation(routeId: string | undefined, searchParams: URLSearchParams): number {
if (routeId) {
const id = parsePermalinkID(routeId);
return Number.isFinite(id) && id > 0 ? id : 0;
}
const q = Number(searchParams.get('board')) || 0;
return q > 0 ? q : 0;
}
type FeedHydrate = {
posts: PostItem[];
postTotal: number;
page: number;
scrollTop: number;
loading: boolean;
};
/** 首屏同步读取 Zustand,避免先骨架屏再恢复 */
function readHydrate(
boardId: number,
keyword: string,
sort: FeedSort,
tag: string,
author: string,
titleOnly: boolean,
): FeedHydrate {
const key = feedCacheKey({ boardId, keyword, sort, tag, author, titleOnly });
const cached = getHomeStoreState().getFeed(key);
if (cached && cached.posts.length > 0) {
return {
posts: cached.posts,
postTotal: cached.postTotal,
page: cached.page,
scrollTop: cached.scrollTop,
loading: false,
};
}
return { posts: [], postTotal: 0, page: 1, scrollTop: 0, loading: true };
}
export default function HomePage() {
const nav = useNavigate();
const location = useLocation();
const navType = useNavigationType();
const { id: boardRouteId } = useParams();
const [params] = useSearchParams();
const ctx = useOutletContext<LayoutCtx>();
const { branding } = useSiteBranding();
const { limits, loading: limitsLoading } = useForumLimits();
const postSearch = usePostSearch(limits);
const pageSize = Math.max(1, limits.page_size_default);
const boardId = Number(params.get('board')) || ctx?.boardId || 0;
const boardId = boardIdFromLocation(boardRouteId, params);
const queryBoardId = Number(params.get('board')) || 0;
const isBoardRoute = !!boardRouteId;
const isInvalidBoardRoute = isBoardRoute && boardId === 0;
const boardsLoading = ctx?.boardsLoading ?? true;
const isMissingBoard = isBoardRoute && boardId > 0 && !boardsLoading && !(ctx?.boards ?? []).some(b => b.id === boardId);
const keyword = params.get('keyword') || '';
const tag = params.get('tag') || '';
const author = params.get('author') || '';
const titleOnly = params.get('title_only') === '1';
const sort = parseFeedSort(params.get('sort'));
const rawSort = params.get('sort');
const sort = parseFeedSort(rawSort, limits.feed_sort_tabs);
const board = (ctx?.boards ?? []).find(b => b.id === boardId);
const isSiteHome = !boardId && !keyword && !tag && !author;
const siteIntro = siteMetaDescription(branding);
const feedTitle = tag
? `标签:${tag}`
: keyword || author
? `搜索:${keyword || ''}${author ? (keyword ? ` · 作者 ${author}` : `作者 ${author}`) : ''}${titleOnly ? '(仅标题)' : ''}`
? '搜索结果'
: (boardId && board ? board.name : '');
usePageSEO({
title: feedTitle || undefined,
@@ -51,25 +115,141 @@ export default function HomePage() {
canonicalPath: tag
? `/?tag=${encodeURIComponent(tag)}`
: boardId
? `/?board=${boardId}`
? boardPath(boardId, limits)
: '/',
ogType: 'website',
});
const [posts, setPosts] = useState<PostItem[]>([]);
const [postTotal, setPostTotal] = useState(0);
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(true);
const [restoreScrollTop, setRestoreScrollTop] = useState<number | null>(null);
const [listResetKey, setListResetKey] = useState(0);
// 旧版 /?board=id 重定向到规范板块路径
useEffect(() => {
if (queryBoardId && !boardRouteId) {
const p = new URLSearchParams(params);
p.delete('board');
const qs = p.toString();
const target = boardPath(queryBoardId, limits) + (qs ? `?${qs}` : '');
nav(target, { replace: true });
return;
}
if (boardRouteId && boardId > 0) {
const redirect = canonicalRedirectPath('board', boardId, location.pathname, limits);
if (redirect) {
const qs = location.search;
nav(redirect + qs, { replace: true });
}
}
}, [queryBoardId, boardId, boardRouteId, params, nav, limits, location.pathname, location.search]);
const scrollTopRef = useRef(0);
const skipCacheSaveRef = useRef(false);
const loadingRef = useRef(false);
const pageRef = useRef(1);
// URL 上的 sort 已被后台关闭时,纠正为默认排序
useEffect(() => {
if (limitsLoading) return;
if (rawSort !== 'latest' && rawSort !== 'hot' && rawSort !== 'reply') return;
const stillOn = enabledFeedSortTabs(limits.feed_sort_tabs).some(t => t.id === rawSort);
if (stillOn) return;
const def = getDefaultFeedSort(limits.feed_sort_tabs);
nav(buildHomeUrl(boardId, def, { keyword, tag, author, titleOnly, permalink: limits }), { replace: true });
}, [
limitsLoading,
limits.feed_sort_tabs,
limits,
rawSort,
boardId,
keyword,
tag,
author,
titleOnly,
nav,
]);
const cacheKey = useMemo(
() => feedCacheKey({ boardId, keyword, sort, tag, author, titleOnly }),
[boardId, keyword, sort, tag, author, titleOnly],
);
// 筛选键变化时同步水合(含首次挂载),保证第一帧就有列表数据
const initial = useMemo(
() => readHydrate(boardId, keyword, sort, tag, author, titleOnly),
// eslint-disable-next-line react-hooks/exhaustive-deps -- 仅随筛选键变化重置
[cacheKey],
);
const [posts, setPosts] = useState<PostItem[]>(initial.posts);
const [postTotal, setPostTotal] = useState(initial.postTotal);
const [page, setPage] = useState(initial.page);
const [loading, setLoading] = useState(initial.loading);
/** 画面上已提交的筛选(URL 已变但数据未到时仍画上一份) */
const [view, setView] = useState({
cacheKey,
sort,
boardId,
keyword,
tag,
author,
titleOnly,
});
const [listPending, setListPending] = useState(false);
const [restoreScrollTop, setRestoreScrollTop] = useState<number | null>(
initial.posts.length > 0 ? initial.scrollTop : null,
);
const [listResetKey, setListResetKey] = useState(0);
/** hydrate 首帧用静态列表;完成后升级 VirtualPostList */
const [useVirtualList, setUseVirtualList] = useState(() => !isHomeHydrating());
useEffect(() => {
if (useVirtualList) return;
reactStartTransition(() => setUseVirtualList(true));
}, [useVirtualList]);
const scrollTopRef = useRef(initial.scrollTop);
const fetchSeqRef = useRef(0);
const pageRef = useRef(initial.page);
const cacheKeyRef = useRef(cacheKey);
const viewKeyRef = useRef(view.cacheKey);
const postsRef = useRef(posts);
const scrollRafRef = useRef(0);
/** 当前筛选键是否已完成「进入页」水合(避免 effect 重跑时反复 setRestoreScrollTop) */
const hydratedKeyRef = useRef<string | null>(null);
/** 强制刷新已发起 loadFirst:消费 refreshFeed 后 effect 再跑时勿因空缓存重复请求 */
const refreshFetchKeyRef = useRef<string | null>(null);
pageRef.current = page;
// 与当前筛选一致的列表快照(供卸载/切换筛选时写入缓存)
const feedSnapRef = useRef({ boardId, keyword, tag, author, titleOnly, sort, posts, postTotal, page });
cacheKeyRef.current = cacheKey;
viewKeyRef.current = view.cacheKey;
postsRef.current = posts;
const commitDisplayed = useCallback((
next: FeedHydrate,
meta: { cacheKey: string; sort: FeedSort; boardId: number; keyword: string; tag: string; author: string; titleOnly: boolean },
) => {
setPosts(next.posts);
setPostTotal(next.postTotal);
setPage(next.page);
pageRef.current = next.page;
scrollTopRef.current = next.scrollTop;
setRestoreScrollTop(next.posts.length > 0 ? next.scrollTop : null);
setLoading(next.loading);
setListPending(false);
setView(meta);
}, []);
// 筛选键切换:有快照则立刻换页;否则保留当前画面等请求结束
useEffect(() => {
if ((location.state as FeedNavState | null)?.refreshFeed && navType !== 'POP') {
hydratedKeyRef.current = null;
return;
}
const next = readHydrate(boardId, keyword, sort, tag, author, titleOnly);
if (next.posts.length > 0) {
hydratedKeyRef.current = cacheKey;
commitDisplayed(next, { cacheKey, sort, boardId, keyword, tag, author, titleOnly });
return;
}
hydratedKeyRef.current = null;
if (postsRef.current.length > 0) {
setListPending(true);
setLoading(false);
return;
}
commitDisplayed(next, { cacheKey, sort, boardId, keyword, tag, author, titleOnly });
}, [cacheKey, boardId, keyword, sort, tag, author, titleOnly, commitDisplayed, location.state, navType]);
const totalPages = Math.max(1, Math.ceil(Math.max(postTotal, 0) / pageSize));
const showPagination = totalPages > 1 && posts.length > 0;
@@ -81,16 +261,39 @@ export default function HomePage() {
setListResetKey(k => k + 1);
}, []);
/** 同筛选强制刷新:只复位滚动,保留旧列表直到 loadFirst 覆盖 */
const beginFeedRefresh = useCallback(() => {
skipCacheSaveRef.current = true;
clearAllFeedCache();
resetFeedView();
}, [resetFeedView]);
const fetchPage = useCallback(async (p: number) => {
if (loadingRef.current) return;
loadingRef.current = true;
setLoading(true);
/** 把当前列表写入 Zustand(滚动位置用 ref,避免闭包过期) */
const persistFeed = useCallback((
nextPosts: PostItem[],
nextTotal: number,
nextPage: number,
opts?: { scrollTop?: number; touchFetchTime?: boolean; key?: string },
) => {
const key = opts?.key ?? cacheKeyRef.current;
const prev = getHomeStoreState().getFeed(key);
getHomeStoreState().setFeed(key, {
posts: nextPosts,
postTotal: nextTotal,
page: nextPage,
scrollTop: opts?.scrollTop ?? scrollTopRef.current,
lastFetchTime: opts?.touchFetchTime === false
? (prev?.lastFetchTime ?? Date.now())
: Date.now(),
});
}, []);
const fetchPage = useCallback(async (p: number, opts?: { silent?: boolean; resetScroll?: boolean }) => {
const seq = ++fetchSeqRef.current;
const requestKey = cacheKeyRef.current;
const silent = !!opts?.silent;
const keepView = postsRef.current.length > 0;
// 有旧列表时不卸页,只标 pending
if (!silent && !keepView) setLoading(true);
if (!silent && keepView) setListPending(true);
try {
const data = await api.posts({
page: p,
@@ -100,144 +303,242 @@ export default function HomePage() {
tag: tag || '',
author: tag ? '' : author,
title_only: !tag && titleOnly ? '1' : '',
sort: sort === 'latest' ? '' : sort,
sort,
});
if (seq !== fetchSeqRef.current) return;
const batch = Array.isArray(data.posts) ? data.posts : [];
const total = data.total ?? 0;
const jumpTop = opts?.resetScroll || (keepView && requestKey !== viewKeyRef.current);
const scrollTop = jumpTop ? 0 : scrollTopRef.current;
if (jumpTop) {
setRestoreScrollTop(null);
scrollTopRef.current = 0;
setListResetKey(k => k + 1);
}
setPosts(batch);
setPostTotal(total);
setPage(p);
pageRef.current = p;
setView({ cacheKey: requestKey, sort, boardId, keyword, tag, author, titleOnly });
persistFeed(batch, total, p, { scrollTop, touchFetchTime: true, key: requestKey });
} catch (e: unknown) {
if (seq !== fetchSeqRef.current) return;
if (!silent) {
notify.error(e instanceof Error ? e.message : '加载失败');
if (!keepView) {
setPosts([]);
setPostTotal(0);
setPage(1);
pageRef.current = 1;
} finally {
loadingRef.current = false;
setLoading(false);
}
}, [boardId, keyword, tag, author, titleOnly, sort, pageSize]);
}
} finally {
if (seq === fetchSeqRef.current) {
setLoading(false);
setListPending(false);
}
}
}, [boardId, keyword, tag, author, titleOnly, sort, pageSize, persistFeed]);
const loadFirst = useCallback(() => fetchPage(1), [fetchPage]);
const loadFirst = useCallback((opts?: { resetScroll?: boolean }) => (
fetchPage(1, { resetScroll: opts?.resetScroll })
), [fetchPage]);
const goToPage = useCallback((p: number) => {
if (loadingRef.current) return;
const maxPage = Math.max(1, Math.ceil(Math.max(postTotal, 0) / pageSize));
if (p < 1 || p > maxPage) return;
if (p === pageRef.current) return;
resetFeedView();
fetchPage(p);
}, [fetchPage, postTotal, pageSize, resetFeedView]);
void fetchPage(p, { resetScroll: true });
}, [fetchPage, postTotal, pageSize]);
const handleSelectPost = useCallback((id: number) => {
// 离开前再写一次滚动,确保详情页返回可还原
getHomeStoreState().patchScroll(viewKeyRef.current, scrollTopRef.current);
openForumPost(nav, id, limits.open_posts_in_new_tab);
}, [nav, limits.open_posts_in_new_tab]);
// 等限制就绪后再拉列表;筛选变化时重载
// 等限制就绪后再决定:强制刷新 / 用缓存 / 静默刷新 / 首拉
useEffect(() => {
if (limitsLoading) return;
if (limitsLoading || isInvalidBoardRoute || isMissingBoard) return;
const forceRefresh = (location.state as FeedNavState | null)?.refreshFeed;
if (forceRefresh) {
beginFeedRefresh();
loadFirst();
// 浏览器后退/前进(POP)忽略 history 上残留的 refreshFeed,避免误清空缓存
if (forceRefresh && navType !== 'POP') {
fetchSeqRef.current += 1;
hydratedKeyRef.current = cacheKey;
refreshFetchKeyRef.current = cacheKey;
// 排序等强制刷新:丢弃该键旧分页/滚动,置顶重拉第 1 页
getHomeStoreState().clearFeed(cacheKey);
resetFeedView();
setListPending(postsRef.current.length > 0);
if (postsRef.current.length === 0) setLoading(true);
setView({ cacheKey, sort, boardId, keyword, tag, author, titleOnly });
void loadFirst({ resetScroll: true });
// 消费后清掉 state,防止该 history 条目永远带着刷新标记
nav(`${location.pathname}${location.search}${location.hash}`, { replace: true, state: null });
return;
}
const cached = getFeedCache(boardId, keyword, sort, tag, author, titleOnly);
// POP 带回 refreshFeed 时也清掉,避免下次同条目再误触发
if (forceRefresh && navType === 'POP') {
nav(`${location.pathname}${location.search}${location.hash}`, { replace: true, state: null });
}
// 刚强制刷新并清缓存:跳过随后因 state 清空触发的空缓存首拉
if (refreshFetchKeyRef.current === cacheKey) {
refreshFetchKeyRef.current = null;
return;
}
const cached = getHomeStoreState().getFeed(cacheKey);
if (cached && cached.posts.length > 0) {
const needRestore = hydratedKeyRef.current !== cacheKey;
hydratedKeyRef.current = cacheKey;
if (needRestore) {
commitDisplayed({
posts: cached.posts,
postTotal: cached.postTotal,
page: cached.page,
scrollTop: cached.scrollTop,
loading: false,
}, { cacheKey, sort, boardId, keyword, tag, author, titleOnly });
} else {
setPosts(cached.posts);
setPostTotal(cached.postTotal);
setPage(cached.page);
pageRef.current = cached.page;
setRestoreScrollTop(cached.scrollTop);
scrollTopRef.current = cached.scrollTop;
setLoading(false);
setListPending(false);
setView({ cacheKey, sort, boardId, keyword, tag, author, titleOnly });
}
return;
}
hydratedKeyRef.current = cacheKey;
if (postsRef.current.length === 0) {
setRestoreScrollTop(null);
scrollTopRef.current = 0;
}
loadFirst();
}, [
limitsLoading,
pageSize,
cacheKey,
location.key,
location.state,
location.pathname,
location.search,
location.hash,
navType,
nav,
loadFirst,
commitDisplayed,
resetFeedView,
isInvalidBoardRoute,
isMissingBoard,
sort,
boardId,
keyword,
tag,
author,
titleOnly,
sort,
location.key,
location.state,
loadFirst,
beginFeedRefresh,
]);
// 筛选未变时同步列表快照;变筛选的那一帧先保留旧快照供 cleanup 写入
if (
feedSnapRef.current.boardId === boardId
&& feedSnapRef.current.keyword === keyword
&& feedSnapRef.current.tag === tag
&& feedSnapRef.current.author === author
&& feedSnapRef.current.titleOnly === titleOnly
&& feedSnapRef.current.sort === sort
) {
feedSnapRef.current = { boardId, keyword, tag, author, titleOnly, sort, posts, postTotal, page };
}
// 仅在筛选变化 / 卸载时缓存;勿把 posts 放进 deps(否则会用旧列表污染新 keyword)
useEffect(() => {
// cleanup 先保存上一档;再把快照重置为当前筛选的空占位
feedSnapRef.current = { boardId, keyword, tag, author, titleOnly, sort, posts: [], postTotal: 0, page: 1 };
return () => {
if (skipCacheSaveRef.current) return;
const snap = feedSnapRef.current;
if (snap.posts.length === 0) return;
setFeedCache(snap.boardId, snap.keyword, snap.sort, {
posts: snap.posts,
postTotal: snap.postTotal,
page: snap.page,
scrollTop: scrollTopRef.current,
}, snap.tag, snap.author, snap.titleOnly);
// Logo 等同 URL 强制刷新:仅复位滚动,不卸列表(数据由 transitionTo 预热)
const onFeedReset = () => {
fetchSeqRef.current += 1;
resetFeedView();
};
}, [boardId, keyword, tag, author, titleOnly, sort]);
useEffect(() => {
if (!loading && posts.length > 0) skipCacheSaveRef.current = false;
}, [loading, posts.length]);
useEffect(() => {
const onFeedReset = () => beginFeedRefresh();
window.addEventListener(FEED_RESET_EVENT, onFeedReset);
return () => window.removeEventListener(FEED_RESET_EVENT, onFeedReset);
}, [beginFeedRefresh]);
}, [resetFeedView]);
useEffect(() => {
const fn = () => {
beginFeedRefresh();
loadFirst();
};
window.addEventListener('posts-refresh', fn);
return () => window.removeEventListener('posts-refresh', fn);
}, [beginFeedRefresh, loadFirst]);
const handleSortChange = (next: FeedSort) => {
if (next === sort) {
beginFeedRefresh();
loadFirst();
// 下拉 / posts-refresh / 软刷新 commit:有预热则一次覆盖;禁止先卸列表
const applyWarmOrReload = () => {
fetchSeqRef.current += 1;
const key = cacheKeyRef.current;
const warm = getHomeStoreState().getFeed(key);
if (warm && warm.posts.length > 0) {
// 先写入新数据,再复位滚动(避免先 reset 造成空白闪一下)
commitDisplayed({
posts: warm.posts,
postTotal: warm.postTotal,
page: warm.page,
scrollTop: 0,
loading: false,
}, { cacheKey: key, sort, boardId, keyword, tag, author, titleOnly });
setListResetKey((k) => k + 1);
return;
}
navigateFeed(nav, buildHomeUrl(boardId, next, { keyword, tag, author, titleOnly }));
// 未命中:保留旧 posts,静默重拉
if (postsRef.current.length > 0) {
setListPending(true);
setLoading(false);
void loadFirst();
return;
}
setLoading(true);
void loadFirst();
};
window.addEventListener('posts-refresh', applyWarmOrReload);
window.addEventListener(FEED_PULL_REFRESH_EVENT, applyWarmOrReload);
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, applyWarmOrReload);
return () => {
window.removeEventListener('posts-refresh', applyWarmOrReload);
window.removeEventListener(FEED_PULL_REFRESH_EVENT, applyWarmOrReload);
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, applyWarmOrReload);
};
}, [
commitDisplayed, loadFirst,
sort, boardId, keyword, tag, author, titleOnly,
]);
// 卸载时取消未执行的 scroll rAF
useEffect(() => () => {
if (scrollRafRef.current) cancelAnimationFrame(scrollRafRef.current);
}, []);
const handleScrollTopChange = useCallback((top: number) => {
scrollTopRef.current = top;
// rAF 节流写入 store,避免每个 scroll 事件都触发订阅者
if (scrollRafRef.current) return;
scrollRafRef.current = requestAnimationFrame(() => {
scrollRafRef.current = 0;
getHomeStoreState().patchScroll(viewKeyRef.current, scrollTopRef.current);
});
}, []);
const handleSortChange = (next: FeedSort) => {
const url = buildHomeUrl(boardId, next, { keyword, tag, author, titleOnly, permalink: limits });
// 排序标签:一律强制刷新到第 1 页顶部,不恢复浏览进度
if (next === sort) {
const tid = startTransition();
getHomeStoreState().clearFeed(cacheKeyRef.current);
beginFeedRefresh();
void Promise.resolve(loadFirst({ resetScroll: true })).finally(() => doneTransition(tid));
return;
}
navigateFeed(nav, url, { refresh: true });
};
const showSortBar = !keyword && !tag && !author;
const showSortBar = !view.keyword && !view.tag && !view.author;
const searchFilters = parseSearchFromUrl(location.pathname, params);
const isSearchActive = !!(view.keyword || view.author);
// 首屏用同构骨架,避免标题/列表分区先后出现造成闪动
if ((loading || limitsLoading) && posts.length === 0) {
return <FeedPageSkeleton />;
if (isInvalidBoardRoute || isMissingBoard) {
return (
<NotFoundPage
title="板块不存在"
description="该板块不存在,或已被删除。"
/>
);
}
// 冷启动由门闩 / ensureColdBootReady 挡住;有旧列表时软刷新绝不卸空
if ((loading || limitsLoading || (isBoardRoute && boardsLoading)) && posts.length === 0) {
return null;
}
return (
@@ -245,26 +546,50 @@ export default function HomePage() {
<div className="feed-panel">
<div className="feed-top">
<div className="feed-top__bar">
{!useVirtualList ? (
(view.keyword || view.tag || view.author) ? (
<h1 className="feed-header-title">
{view.tag
? `#${view.tag}`
: view.keyword
? `搜索:${view.keyword}`
: `作者:${view.author}`}
</h1>
) : null
) : (
<FeedHeader
boardId={boardId}
keyword={keyword}
tag={tag}
author={author}
titleOnly={titleOnly}
boards={ctx?.boards ?? []}
stats={ctx?.stats ?? null}
keyword={view.keyword}
tag={view.tag}
author={view.author}
postTotal={postTotal}
titleAs={isSiteHome ? 'h2' : 'h1'}
/>
)}
{showSortBar && (
<FeedSortBar value={sort} onChange={handleSortChange} postTotal={postTotal} />
<FeedSortBar
value={view.sort}
pendingValue={listPending ? sort : null}
onChange={handleSortChange}
postTotal={postTotal}
/>
)}
</div>
{isSearchActive && (
<FeedSearchFilters
filters={postSearch.filters}
boards={ctx?.boards ?? []}
onRemove={postSearch.removeFilter}
onClear={postSearch.clearSearch}
/>
)}
</div>
{!useVirtualList ? (
<StaticFeedList posts={posts} sort={view.sort} boardId={view.boardId} />
) : (
<VirtualPostList
posts={posts}
sort={sort}
loading={loading || limitsLoading}
sort={view.sort}
loading={listPending ? false : (loading || limitsLoading)}
hasMore={hasMore}
showPagination={showPagination}
page={page}
@@ -274,13 +599,20 @@ export default function HomePage() {
onSelect={handleSelectPost}
restoreScrollTop={restoreScrollTop}
resetScrollKey={listResetKey}
onScrollTopChange={(top) => { scrollTopRef.current = top; }}
onScrollTopChange={handleScrollTopChange}
onScrollRestored={() => setRestoreScrollTop(null)}
keyword={keyword || tag || author}
boardId={boardId}
boardName={ctx?.boards?.find(b => b.id === boardId)?.name || ''}
keyword={view.keyword || view.tag || view.author}
isSearchMode={!!(view.keyword || view.author)}
searchKeyword={view.keyword}
searchAuthor={view.author}
searchTitleOnly={view.titleOnly}
searchScopeBoardId={searchFilters.scopeBoardId}
onClearSearch={postSearch.clearSearch}
boardId={view.boardId}
boardName={ctx?.boards?.find(b => b.id === view.boardId)?.name || ''}
noBoards={!ctx?.boardsLoading && (ctx?.boards?.length ?? 0) === 0}
/>
)}
</div>
</div>
);

View File

@@ -0,0 +1,361 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { ArrowLeft, Link2, Pencil, Plus, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Spinner } from '@/components/ui/spinner';
import { notify } from '@/lib/notify';
import { api } from '../api/client';
import type { FriendLink, FriendLinkApply } from '../api/types';
import { useAuth } from '../hooks/useAuth';
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
import { getCachedSiteBranding, invalidateSiteBrandingCache, useSiteBranding } from '../hooks/useSiteBranding';
import { formatTime } from '../utils/content';
import { loginPath } from '../utils/authRedirect';
import { resolveFriendLinkLogo, isReciprocalChecking, reciprocalStatusLabel } from '../utils/friendLink';
import { InFlowSiteFooter } from '../components/SiteFooter';
import FriendLinkApplyDialog from '../components/FriendLinkApplyDialog';
import { useSessionResource } from '../hooks/useSessionResource';
const APPLY_STATUS_ORDER: Record<FriendLinkApply['status'], number> = {
pending: 0,
rejected: 1,
approved: 2,
};
function applyStatusBadge(status: FriendLinkApply['status']) {
switch (status) {
case 'pending':
return <Badge variant="orange">待审核</Badge>;
case 'approved':
return <Badge variant="green">已通过</Badge>;
case 'rejected':
return <Badge variant="secondary">已拒绝</Badge>;
default:
return null;
}
}
function linkInitial(name: string): string {
const t = name.trim();
return t ? t.charAt(0).toUpperCase() : '?';
}
/** 友情链接独立页面:展示友链、申请与管理自己的申请 */
export default function LinksPage() {
const nav = useNavigate();
const [params, setParams] = useSearchParams();
const { branding } = useSiteBranding();
const { user } = useAuth();
const [applyOpen, setApplyOpen] = useState(false);
const [editApply, setEditApply] = useState<FriendLinkApply | null>(null);
const [cancelingId, setCancelingId] = useState<number | null>(null);
usePageSEO({
title: '友情链接',
description: `${branding.name} 的友情链接与申请入口`,
keywords: joinSEOKeywords('友情链接', getCachedSiteBranding().keywords),
canonicalPath: '/links',
});
const friendLinks = (branding.friend_links ?? []).filter(
(l: FriendLink) => l.name?.trim() && l.url?.trim(),
);
const { data: myApplies = [], loading: myLoading, replace: setMyApplies } = useSessionResource<FriendLinkApply[]>(
user ? 'links:applies' : null,
() => api.myFriendLinkApplies().then(r => r.applies ?? []),
{
enabled: !!user,
onError: (e) => notify.error(e instanceof Error ? e.message : '加载失败'),
},
);
const sortedApplies = useMemo(
() => [...myApplies].sort((a, b) => {
const byStatus = APPLY_STATUS_ORDER[a.status] - APPLY_STATUS_ORDER[b.status];
if (byStatus !== 0) return byStatus;
return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
}),
[myApplies],
);
const applyCounts = useMemo(() => {
let pending = 0;
let rejected = 0;
let approved = 0;
for (const a of myApplies) {
if (a.status === 'pending') pending += 1;
else if (a.status === 'rejected') rejected += 1;
else if (a.status === 'approved') approved += 1;
}
return { pending, rejected, approved };
}, [myApplies]);
const applySummaryText = useMemo(() => {
if (myApplies.length === 0) return '';
const parts: string[] = [];
if (applyCounts.pending > 0) parts.push(`${applyCounts.pending} 待审`);
if (applyCounts.rejected > 0) parts.push(`${applyCounts.rejected} 已拒绝`);
if (applyCounts.approved > 0) parts.push(`${applyCounts.approved} 已通过`);
return `我的申请 · ${parts.join(' / ')}`;
}, [myApplies.length, applyCounts]);
const loadMyApplies = useCallback(() => {
if (!user) {
setMyApplies([]);
return;
}
api.myFriendLinkApplies()
.then(r => setMyApplies(r.applies ?? []))
.catch(e => notify.error(e instanceof Error ? e.message : '加载失败'));
}, [user, setMyApplies]);
useEffect(() => {
if (!user || !myApplies.some(isReciprocalChecking)) return;
const timer = window.setInterval(loadMyApplies, 3000);
return () => window.clearInterval(timer);
}, [user, myApplies, loadMyApplies]);
useEffect(() => {
if (params.get('apply') === '1') {
if (!user) {
nav(loginPath('/links?apply=1'));
return;
}
setApplyOpen(true);
const next = new URLSearchParams(params);
next.delete('apply');
setParams(next, { replace: true });
}
}, [params, setParams, user, nav]);
const openApply = () => {
if (!user) {
nav(loginPath('/links?apply=1'));
return;
}
setEditApply(null);
setApplyOpen(true);
};
const openEditApply = (apply: FriendLinkApply) => {
setEditApply(apply);
setApplyOpen(true);
};
const handleApplyOpenChange = (open: boolean) => {
setApplyOpen(open);
if (!open) setEditApply(null);
};
const onApplySubmitted = useCallback(() => {
loadMyApplies();
invalidateSiteBrandingCache();
}, [loadMyApplies]);
const cancelApply = async (apply: FriendLinkApply) => {
if (apply.status !== 'pending') return;
setCancelingId(apply.id);
try {
const r = await api.cancelFriendLinkApply(apply.id);
notify.success(r.message);
loadMyApplies();
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '撤销失败');
} finally {
setCancelingId(null);
}
};
const friendLinksBlock = friendLinks.length === 0 ? (
<div className="empty-state links-page-empty list-page-panel__empty">
<Link2 className="empty-state-icon" aria-hidden size={36} strokeWidth={1.5} />
<p>暂无友情链接</p>
<p className="page-desc" style={{ marginTop: 8 }}>
注册登录后可提交申请,审核通过后将展示在此页
</p>
</div>
) : (
<div className="links-page-board">
<div className="links-page-grid">
{friendLinks.map(link => {
const logoURL = resolveFriendLinkLogo(link.logo, branding.site_url);
return (
<a
key={`${link.name}-${link.url}`}
href={link.url}
target="_blank"
rel="noopener noreferrer"
className="links-page-card"
title={link.name}
>
<div className="links-page-card__logo">
{logoURL ? (
<img src={logoURL} alt="" loading="lazy" decoding="async" />
) : (
<span>{linkInitial(link.name)}</span>
)}
</div>
<strong className="links-page-card__name">{link.name}</strong>
</a>
);
})}
</div>
</div>
);
const myAppliesBlock = user ? (
<section
id="my-applies"
className={`links-page-my${myApplies.length === 0 && !myLoading ? ' links-page-my--compact' : ''}`}
aria-label="我的友链申请"
>
<h2 className="links-page-my__title">我的申请</h2>
{myLoading ? (
<div className="flex justify-center py-10"><Spinner /></div>
) : myApplies.length === 0 ? (
<p className="links-page-my__empty">你还没有提交过友链申请,点击右上角「申请友链」即可提交</p>
) : (
<div className="links-page-my-list">
{sortedApplies.map(apply => (
<div key={apply.id} className="links-page-my-row">
{apply.logo?.trim() && (
<div className="links-page-my-row__logo">
<img src={resolveFriendLinkLogo(apply.logo, branding.site_url)} alt="" loading="lazy" decoding="async" />
</div>
)}
<div className="links-page-my-row__main">
<div className="links-page-my-row__title">
<strong>{apply.name}</strong>
{applyStatusBadge(apply.status)}
</div>
<a href={apply.url} target="_blank" rel="noopener noreferrer" className="links-page-my-row__url">
{apply.url}
</a>
{apply.status === 'rejected' && apply.review_note?.trim() && (
<p className="links-page-my-row__note">拒绝原因:{apply.review_note}</p>
)}
{apply.status === 'pending' && (
<p className="links-page-my-row__note">
回链检测:{reciprocalStatusLabel(apply).text}
</p>
)}
{apply.status === 'approved' && (
<p className="links-page-my-row__note">修改后将重新进入审核,友链会暂时从列表移除</p>
)}
<p className="links-page-my-row__meta">{formatTime(apply.created_at)}</p>
</div>
{apply.status === 'pending' && (
<div className="links-page-my-row__actions">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => openEditApply(apply)}
>
<Pencil size={14} aria-hidden />
修改
</Button>
<Button
type="button"
variant="outline"
size="sm"
disabled={cancelingId === apply.id}
onClick={() => cancelApply(apply)}
>
<Trash2 size={14} aria-hidden />
撤销
</Button>
</div>
)}
{apply.status === 'rejected' && (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => openEditApply(apply)}
>
<Pencil size={14} aria-hidden />
修改并重新提交
</Button>
)}
{apply.status === 'approved' && (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => openEditApply(apply)}
>
<Pencil size={14} aria-hidden />
修改
</Button>
)}
</div>
))}
</div>
)}
</section>
) : null;
return (
<div className="page-wrap">
<div className="feed-panel list-page-panel">
<header className="list-page-panel__head">
<Button variant="ghost" size="sm" className="list-page-panel__back" onClick={() => nav('/')}>
<ArrowLeft />
返回
</Button>
<div className="links-page-head">
<div>
<h1 className="page-title">友情链接</h1>
<p className="page-desc">
与本站互链的站点列表
{friendLinks.length > 0 ? ` · 共 ${friendLinks.length} 个` : ''}
</p>
{user && myApplies.length > 0 && applySummaryText ? (
<p
className={`links-page-summary${applyCounts.pending > 0 ? ' links-page-summary--pending' : applyCounts.rejected > 0 ? ' links-page-summary--rejected' : ''}`}
>
{applySummaryText}
</p>
) : null}
</div>
<Button type="button" onClick={openApply}>
<Plus size={16} aria-hidden />
申请友链
</Button>
</div>
</header>
{/* 登录:申请区在上;游客:友链在上 */}
{user ? (
<>
{myAppliesBlock}
{friendLinksBlock}
</>
) : (
<>
{friendLinksBlock}
<p className="links-page-login-hint">
<Link to={loginPath('/links')}>登录</Link>
或
<Link to="/register">注册</Link>
后可申请友链并管理自己的申请
</p>
</>
)}
</div>
<InFlowSiteFooter />
<FriendLinkApplyDialog
open={applyOpen}
onOpenChange={handleApplyOpenChange}
editApply={editApply}
onSubmitted={onApplySubmitted}
/>
</div>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
import { useState, useEffect, useLayoutEffect, useRef, useCallback } from 'react';
import { useParams, useNavigate, useOutletContext, useLocation } from 'react-router-dom';
import { ArrowLeft, ThumbsUp, Star, Pencil, Pin, History, Lock, LockOpen, MessageSquare, MessageSquareOff, Trash2, Sparkles, Flag, Ban, CircleCheck, CircleHelp, MoreHorizontal } from 'lucide-react';
import { useState, useEffect, useLayoutEffect, useRef, useCallback, useMemo } from 'react';
import { useParams, useNavigate, useOutletContext, useLocation, useNavigationType } from 'react-router-dom';
import { ArrowLeft, ThumbsUp, Star, Lock, MessageSquare, MessageSquareOff, Flag, MoreHorizontal } from 'lucide-react';
import FeaturedIcon from '@/components/FeaturedIcon';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
@@ -16,7 +16,6 @@ import {
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import {
DropdownMenu,
@@ -34,12 +33,17 @@ import {
} from '@/components/ui/dialog';
import { notify } from '@/lib/notify';
import { api } from '../api/client';
import type { PostItem, Comment, ReportReason } from '../api/types';
import type { PostItem, Comment, ReportReason, PollView, PostLotteryView } from '../api/types';
import { REPORT_REASON_OPTIONS } from '../utils/report';
import CommentThreadList from '../components/CommentThreadList';
import CommentBox, { type CommentSubmitData } from '../components/CommentBox';
import PostContent from '../components/PostContent';
import PostPollCard from '../components/PostPollCard';
import PostBountyBanner from '../components/PostBountyBanner';
import { findCommentFloor } from '../utils/bounty';
import PostLotteryCard from '../components/PostLotteryCard';
import PostRevisionPanel from '../components/PostRevisionPanel';
import PostManageMenu from '../components/PostManageMenu';
import ArticleOutline from '../components/ArticleOutline';
import { useAuth } from '../hooks/useAuth';
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
@@ -47,17 +51,41 @@ import { getCachedSiteBranding } from '../hooks/useSiteBranding';
import { formatDateTime, isTimeDiffSignificant } from '../utils/content';
import { collectCommentSubtreeIds } from '../utils/comment';
import { loadMyCommentIds } from '../utils/guest';
import { clearAllFeedCache } from '../utils/feedCache';
import { clearAllFeedCache, PAGE_FORCE_REFRESH_EVENT } from '../utils/feedCache';
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
import { deleteSessionSnapshot, getSessionSnapshot, setSessionSnapshot } from '../utils/sessionPageCache';
import { useGlobalWheelScroll } from '../hooks/useGlobalWheelScroll';
import { loginPath } from '../utils/authRedirect';
import { excerptFromHTML, firstImageFromHTML } from '../utils/seoText';
import { canonicalRedirectPath, parsePermalinkID, postPath } from '../utils/permalink';
import { useForumLimits } from '../hooks/useForumLimits';
import type { LayoutCtx } from '../layouts/MainLayout';
import type { PostHeading } from '../utils/postHeadings';
import { extractHeadingsFromHtml } from '../utils/postHeadings';
import { renderPostContentHtml } from '../utils/postContent';
import { InFlowSiteFooter } from '../components/SiteFooter';
import NotFoundPage from './NotFoundPage';
type PostDetailSnapshot = {
post: PostItem;
comments: Comment[];
poll: PollView | null;
lottery: PostLotteryView | null;
liked: boolean;
favorited: boolean;
canEdit: boolean;
isEdited: boolean;
editBlockReason: string;
editWindowHours: number;
bountyCanRefund: boolean;
bountyRefundBlockReason: string;
bountyEligibleReplyCount: number;
scrollTop: number;
};
function postDetailCacheKey(id: number) {
return `post:${id}`;
}
/** 格式化剩余可编辑时间 */
function formatEditRemaining(createdAt: string, windowHours: number): string {
if (windowHours <= 0) return '';
@@ -76,27 +104,35 @@ export default function PostDetailPage() {
const postId = parsePermalinkID(id);
const nav = useNavigate();
const location = useLocation();
const navType = useNavigationType();
const { user, refresh } = useAuth();
const { limits } = useForumLimits();
const { setPostOutline, isMobile } = useOutletContext<LayoutCtx>();
const [post, setPost] = useState<PostItem | null>(null);
const [comments, setComments] = useState<Comment[]>([]);
const [liked, setLiked] = useState(false);
const [favorited, setFavorited] = useState(false);
const initialSnap = (postId && !Number.isNaN(postId))
? getSessionSnapshot<PostDetailSnapshot>(postDetailCacheKey(postId))
: undefined;
const [post, setPost] = useState<PostItem | null>(initialSnap?.post ?? null);
const [poll, setPoll] = useState<PollView | null>(initialSnap?.poll ?? null);
const [lottery, setLottery] = useState<PostLotteryView | null>(initialSnap?.lottery ?? null);
const [comments, setComments] = useState<Comment[]>(initialSnap?.comments ?? []);
const [liked, setLiked] = useState(initialSnap?.liked ?? false);
const [favorited, setFavorited] = useState(initialSnap?.favorited ?? false);
const [replyTo, setReplyTo] = useState<Comment | null>(null);
const [editingCommentId, setEditingCommentId] = useState<number | null>(null);
const [submitting, setSubmitting] = useState(false);
const [loading, setLoading] = useState(true);
const [loading, setLoading] = useState(!initialSnap);
const [highlightFloor, setHighlightFloor] = useState<number | null>(null);
const [submitCount, setSubmitCount] = useState(0);
const [canEdit, setCanEdit] = useState(false);
const [isEdited, setIsEdited] = useState(false);
const [editBlockReason, setEditBlockReason] = useState('');
const [editWindowHours, setEditWindowHours] = useState(0);
const [canEdit, setCanEdit] = useState(initialSnap?.canEdit ?? false);
const [isEdited, setIsEdited] = useState(initialSnap?.isEdited ?? false);
const [editBlockReason, setEditBlockReason] = useState(initialSnap?.editBlockReason ?? '');
const [editWindowHours, setEditWindowHours] = useState(initialSnap?.editWindowHours ?? 0);
const [showRevisions, setShowRevisions] = useState(false);
const [deletingPost, setDeletingPost] = useState(false);
const [headings, setHeadings] = useState<PostHeading[]>([]);
const [deleteOpen, setDeleteOpen] = useState(false);
const [composerOpen, setComposerOpen] = useState(false);
const [reportOpen, setReportOpen] = useState(false);
const [reportReason, setReportReason] = useState<ReportReason>('spam');
const [reportDetail, setReportDetail] = useState('');
@@ -104,11 +140,27 @@ export default function PostDetailPage() {
const [rejectOpen, setRejectOpen] = useState(false);
const [rejectReason, setRejectReason] = useState('');
const [rejecting, setRejecting] = useState(false);
const [bountyAwardTarget, setBountyAwardTarget] = useState<number | null>(null);
const [bountyAwarding, setBountyAwarding] = useState(false);
const [bountyCanRefund, setBountyCanRefund] = useState(initialSnap?.bountyCanRefund ?? true);
const [bountyRefundBlockReason, setBountyRefundBlockReason] = useState(initialSnap?.bountyRefundBlockReason ?? '');
const [bountyEligibleReplyCount, setBountyEligibleReplyCount] = useState(initialSnap?.bountyEligibleReplyCount ?? 0);
/** 仅浏览器后退/前进还原滚动;从列表再次点进帖子从顶部开始 */
const [restoreScrollTop, setRestoreScrollTop] = useState<number | null>(() => {
if (!initialSnap) return null;
if (navType === 'POP' && !location.hash) return initialSnap.scrollTop;
return 0;
});
const pageRef = useRef<HTMLDivElement>(null);
const commentSectionRef = useRef<HTMLDivElement>(null);
const commentBoxRef = useRef<HTMLDivElement>(null);
const highlightTimer = useRef<ReturnType<typeof setTimeout>>();
const postRef = useRef<PostItem | null>(null);
const scrollTopRef = useRef(
initialSnap && navType === 'POP' && !location.hash ? initialSnap.scrollTop : 0,
);
postRef.current = post;
useGlobalWheelScroll(pageRef, !loading && !!post);
@@ -121,6 +173,15 @@ export default function PostDetailPage() {
const brand = getCachedSiteBranding();
const postContent = post?.content ?? '';
const isLoggedIn = !!user;
// 同步从正文派生目录,避免预取缓存命中后 setHeadings([]) 盖掉子组件上报且不再回调
const headings = useMemo(() => {
if (!postContent.trim()) return [];
const rendered = renderPostContentHtml(postContent, isLoggedIn, {
openLinksInNewTab: limits.open_content_links_in_new_tab,
});
return extractHeadingsFromHtml(rendered);
}, [postContent, isLoggedIn, limits.open_content_links_in_new_tab]);
const postSEO = post ? {
title: post.title,
description: excerptFromHTML(postContent),
@@ -144,10 +205,6 @@ export default function PostDetailPage() {
} : null;
usePageSEO(postSEO);
const handleHeadingsChange = useCallback((next: PostHeading[]) => {
setHeadings(next);
}, []);
useEffect(() => {
if (loading || !post) {
setPostOutline({ headings: [], scrollRoot: null, title: '文章目录' });
@@ -167,18 +224,62 @@ export default function PostDetailPage() {
const loadSeq = useRef(0);
const detailPath = postPath(postId, limits);
useEffect(() => {
const applySnapshot = useCallback((snap: PostDetailSnapshot, opts?: { restoreScroll?: boolean }) => {
setPost(snap.post);
setPoll(snap.poll);
setLottery(snap.lottery);
setLiked(snap.liked);
setFavorited(snap.favorited);
setCanEdit(snap.canEdit);
setIsEdited(snap.isEdited);
setEditBlockReason(snap.editBlockReason);
setEditWindowHours(snap.editWindowHours);
setBountyCanRefund(snap.bountyCanRefund);
setBountyRefundBlockReason(snap.bountyRefundBlockReason);
setBountyEligibleReplyCount(snap.bountyEligibleReplyCount);
setComments(snap.comments);
if (opts?.restoreScroll) {
scrollTopRef.current = snap.scrollTop;
setRestoreScrollTop(snap.scrollTop);
} else {
scrollTopRef.current = 0;
// 同组件换帖时容器可能仍停在上一帖位置;初次进入已是 0 则不动,避免覆盖 #floor-N
const el = pageRef.current;
if (el && el.scrollTop !== 0) setRestoreScrollTop(0);
}
}, []);
const loadPostRef = useRef<(mode: 'auto' | 'force') => void>(() => {});
loadPostRef.current = (mode: 'auto' | 'force') => {
if (!postId || Number.isNaN(postId)) {
setPost(null);
setLoading(false);
return;
}
if (mode === 'force') {
deleteSessionSnapshot(postDetailCacheKey(postId));
}
const cached = mode === 'force'
? undefined
: getSessionSnapshot<PostDetailSnapshot>(postDetailCacheKey(postId));
if (cached) {
loadSeq.current += 1;
applySnapshot(cached, { restoreScroll: navType === 'POP' && !location.hash });
setReplyTo(null);
setEditingCommentId(null);
setHeadings([]);
setComposerOpen(false);
setLoading(false);
return;
}
const seq = ++loadSeq.current;
const keep = !!postRef.current;
setReplyTo(null);
setEditingCommentId(null);
setComposerOpen(false);
if (!keep) {
setLoading(true);
setPost(null);
}
(async () => {
try {
@@ -188,25 +289,118 @@ export default function PostDetailPage() {
api.comments(postId, myIds),
]);
if (seq !== loadSeq.current) return;
setPost(detail.post);
setLiked(detail.liked);
setFavorited(detail.favorited);
setCanEdit(detail.can_edit ?? false);
setIsEdited(detail.is_edited ?? isTimeDiffSignificant(detail.post.created_at, detail.post.updated_at ?? detail.post.created_at));
setEditBlockReason(detail.edit_block_reason ?? '');
setEditWindowHours(detail.post_edit_window_hours ?? 0);
setComments(Array.isArray(comm.comments) ? comm.comments : []);
const commentsList = Array.isArray(comm.comments) ? comm.comments : [];
const snap: PostDetailSnapshot = {
post: detail.post,
comments: commentsList,
poll: detail.poll ?? null,
lottery: detail.lottery ?? null,
liked: detail.liked,
favorited: detail.favorited,
canEdit: detail.can_edit ?? false,
isEdited: detail.is_edited ?? isTimeDiffSignificant(detail.post.created_at, detail.post.updated_at ?? detail.post.created_at),
editBlockReason: detail.edit_block_reason ?? '',
editWindowHours: detail.post_edit_window_hours ?? 0,
bountyCanRefund: detail.bounty_can_refund ?? true,
bountyRefundBlockReason: detail.bounty_refund_block_reason ?? '',
bountyEligibleReplyCount: detail.bounty_eligible_reply_count ?? 0,
scrollTop: 0,
};
setSessionSnapshot(postDetailCacheKey(postId), snap);
applySnapshot(snap, { restoreScroll: false });
if (mode === 'force') {
const el = pageRef.current;
if (el) el.scrollTop = 0;
scrollTopRef.current = 0;
}
void refresh();
} catch {
if (seq !== loadSeq.current) return;
setPost(null);
if (!keep) setPost(null);
} finally {
if (seq === loadSeq.current) setLoading(false);
}
})();
};
useEffect(() => {
loadPostRef.current('auto');
// eslint-disable-next-line react-hooks/exhaustive-deps -- 仅 postId 变化时加载
}, [postId]);
useEffect(() => {
// 下拉已预热则应用快照;否则强制重拉
const onForce = () => {
if (!postId || Number.isNaN(postId)) return;
const warm = getSessionSnapshot<PostDetailSnapshot>(postDetailCacheKey(postId));
if (warm) {
loadSeq.current += 1;
applySnapshot(warm, { restoreScroll: false });
setLoading(false);
const el = pageRef.current;
if (el) el.scrollTop = 0;
scrollTopRef.current = 0;
return;
}
loadPostRef.current('force');
};
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onForce);
return () => {
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onForce);
};
}, [postId, applySnapshot]);
useEffect(() => {
const el = pageRef.current;
if (!el || loading || !post) return;
const onScroll = () => {
scrollTopRef.current = el.scrollTop;
};
el.addEventListener('scroll', onScroll, { passive: true });
return () => el.removeEventListener('scroll', onScroll);
}, [loading, post]);
useLayoutEffect(() => {
if (restoreScrollTop == null || !pageRef.current || loading || !post) return;
pageRef.current.scrollTop = restoreScrollTop;
scrollTopRef.current = restoreScrollTop;
setRestoreScrollTop(null);
}, [restoreScrollTop, loading, post]);
useEffect(() => {
if (!post || post.id !== postId || loading) return;
setSessionSnapshot(postDetailCacheKey(post.id), {
post,
comments,
poll,
lottery,
liked,
favorited,
canEdit,
isEdited,
editBlockReason,
editWindowHours,
bountyCanRefund,
bountyRefundBlockReason,
bountyEligibleReplyCount,
scrollTop: scrollTopRef.current,
});
}, [
post, comments, poll, lottery, liked, favorited, canEdit, isEdited,
editBlockReason, editWindowHours, bountyCanRefund, bountyRefundBlockReason,
bountyEligibleReplyCount, postId, loading,
]);
useEffect(() => () => {
const p = postRef.current;
if (!p) return;
const prev = getSessionSnapshot<PostDetailSnapshot>(postDetailCacheKey(p.id));
if (!prev) return;
setSessionSnapshot(postDetailCacheKey(p.id), { ...prev, scrollTop: scrollTopRef.current });
}, []);
const reloadComments = useCallback(async () => {
const myIds = user ? [] : loadMyCommentIds();
const comm = await api.comments(postId, myIds);
@@ -218,27 +412,111 @@ export default function PostDetailPage() {
try {
const detail = await api.post(postId, { skipView: true });
setPost(detail.post);
setPoll(detail.poll ?? null);
setLottery(detail.lottery ?? null);
setBountyCanRefund(detail.bounty_can_refund ?? true);
setBountyRefundBlockReason(detail.bounty_refund_block_reason ?? '');
setBountyEligibleReplyCount(detail.bounty_eligible_reply_count ?? 0);
} catch {
// 评论已成功,正文刷新失败不阻断
}
}, [postId]);
const focusCommentEditor = useCallback(() => {
const root = commentBoxRef.current;
if (!root) return;
const editable = root.querySelector<HTMLElement>('.ProseMirror, [contenteditable="true"]');
editable?.focus({ preventScroll: true });
}, []);
const scrollToCommentBox = useCallback(() => {
setComposerOpen(true);
// 等折叠条展开后再滚入视口并聚焦 TipTap
window.setTimeout(() => {
const target = commentBoxRef.current || commentSectionRef.current;
target?.scrollIntoView({ behavior: 'smooth', block: 'center' });
window.setTimeout(focusCommentEditor, 80);
}, 50);
}, [focusCommentEditor]);
// 手机端展开输入框后聚焦编辑器
useEffect(() => {
if (!composerOpen || !isMobile) return;
const timer = window.setTimeout(focusCommentEditor, 60);
return () => window.clearTimeout(timer);
}, [composerOpen, isMobile, focusCommentEditor]);
// 手机端:焦点离开评论输入区(含工具栏)后收起为「说点什么…」
useEffect(() => {
if (!isMobile || !composerOpen) return;
const root = commentBoxRef.current;
if (!root) return;
const onFocusOut = (e: FocusEvent) => {
const next = e.relatedTarget as Node | null;
if (next && root.contains(next)) return;
// 等焦点真正落定(工具栏 / Dialog / 系统弹窗)后再判断是否收起
window.setTimeout(() => {
const ta = commentBoxRef.current?.querySelector('textarea');
ta?.focus({ preventScroll: true });
}, 320);
}, []);
const active = document.activeElement;
if (active && root.contains(active)) return;
// 代码块 Dialog 等浮层打开时不收起
if (document.querySelector('[role="dialog"][data-state="open"]')) return;
setComposerOpen(false);
}, 50);
};
root.addEventListener('focusout', onFocusOut);
return () => root.removeEventListener('focusout', onFocusOut);
}, [isMobile, composerOpen]);
const jumpToFloor = useCallback((floor: number) => {
const el = document.getElementById(`floor-${floor}`);
if (!el) return;
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
if (!el) return false;
const root = pageRef.current;
if (!root) return false;
// 直接计算目标滚动位置
const rootRect = root.getBoundingClientRect();
const elRect = el.getBoundingClientRect();
const relativeTop = elRect.top - rootRect.top;
const initialMaxScrollTop = root.scrollHeight - root.clientHeight;
const targetTop = root.scrollTop + relativeTop - 24;
// 如果 relativeTop 非常异常(如 NaN 或 Infinity),说明布局可能还没完成
if (!isFinite(targetTop) || targetTop < -500) return false;
const clampedTop = Math.max(0, Math.min(targetTop, initialMaxScrollTop));
// 直接设置滚动位置(不使用平滑滚动,避免动画干扰)
root.scrollTop = clampedTop;
// 验证滚动结果,如果不准确则再次调整
// 注意:使用动态计算的 currentMaxScrollTop,因为评论可能在之后才渲染完成
const verifyAndFix = () => {
const currentElRect = el.getBoundingClientRect();
const currentRootRect = root.getBoundingClientRect();
const currentRelativeTop = currentElRect.top - currentRootRect.top;
const currentMaxScrollTop = root.scrollHeight - root.clientHeight;
// 如果元素在视口内但位置不准确,进行修正
if (root.scrollTop > 0 && Math.abs(currentRelativeTop - 24) > 10) {
const correction = currentRelativeTop - 24;
const newTarget = Math.max(0, Math.min(root.scrollTop + correction, currentMaxScrollTop));
root.scrollTop = newTarget;
}
};
// 在多个时间点验证和调整
requestAnimationFrame(verifyAndFix);
setTimeout(verifyAndFix, 50);
setTimeout(verifyAndFix, 150);
setHighlightFloor(floor);
clearTimeout(highlightTimer.current);
highlightTimer.current = setTimeout(() => setHighlightFloor(null), 2000);
return true;
}, []);
/** 正文标题锚点:滚动容器是 pageRef,原生 hash 定位无效,需手动滚 */
@@ -249,27 +527,72 @@ export default function PostDetailPage() {
if (!el) return false;
const root = pageRef.current;
const behavior: ScrollBehavior = smooth ? 'smooth' : 'auto';
if (root) {
if (!root) return false;
// 直接计算目标滚动位置
const rootRect = root.getBoundingClientRect();
const elRect = el.getBoundingClientRect();
const top = root.scrollTop + (elRect.top - rootRect.top) - 12;
root.scrollTo({ top: Math.max(0, top), behavior });
} else {
el.scrollIntoView({ behavior, block: 'start' });
const relativeTop = elRect.top - rootRect.top;
const initialMaxScrollTop = root.scrollHeight - root.clientHeight;
const targetTop = root.scrollTop + relativeTop - 12;
// 如果 relativeTop 非常异常(如 NaN 或 Infinity),说明布局可能还没完成
if (!isFinite(targetTop) || targetTop < -500) return false;
const clampedTop = Math.max(0, Math.min(targetTop, initialMaxScrollTop));
// 直接设置滚动位置
root.scrollTop = clampedTop;
// 验证滚动结果,如果不准确则再次调整
const verifyAndFix = () => {
const currentElRect = el.getBoundingClientRect();
const currentRootRect = root.getBoundingClientRect();
const currentRelativeTop = currentElRect.top - currentRootRect.top;
const currentMaxScrollTop = root.scrollHeight - root.clientHeight;
if (root.scrollTop > 0 && Math.abs(currentRelativeTop - 12) > 10) {
const correction = currentRelativeTop - 12;
const newTarget = Math.max(0, Math.min(root.scrollTop + correction, currentMaxScrollTop));
root.scrollTop = newTarget;
}
};
requestAnimationFrame(verifyAndFix);
if (smooth) {
setTimeout(verifyAndFix, 50);
setTimeout(verifyAndFix, 150);
}
return true;
}, []);
// 从 #floor-N 定位到对应评论(右栏最新评论等入口)
// 从 #floor-N 定位到对应评论(右栏最新评论等入口);等评论进 DOM 后重试,避免首屏 hash 失效
useEffect(() => {
if (loading || !post) return;
const m = location.hash.match(/^#floor-(\d+)$/);
if (!m) return;
const floor = Number(m[1]);
if (!floor) return;
const t = window.setTimeout(() => jumpToFloor(floor), 80);
return () => clearTimeout(t);
let cancelled = false;
let attempts = 0;
let timer = 0;
const tryJump = () => {
if (cancelled) return;
if (jumpToFloor(floor)) return;
attempts += 1;
if (attempts < 30) {
timer = window.setTimeout(tryJump, 50);
}
};
timer = window.setTimeout(tryJump, 0);
return () => {
cancelled = true;
window.clearTimeout(timer);
};
}, [loading, post, comments, location.hash, jumpToFloor]);
// 从 #heading-N(或任意标题 id)定位;等正文进 DOM 后重试,避免首屏 hash 失效
@@ -362,6 +685,7 @@ export default function PostDetailPage() {
});
setReplyTo(null);
setSubmitCount(c => c + 1);
if (isMobile) setComposerOpen(false);
notify.success(r.message || (r.status === 'pending' ? '评论已提交审核' : '评论成功'));
await Promise.all([reloadComments(), reloadPostContent()]);
setTimeout(() => jumpToFloor(r.floor), 100);
@@ -424,6 +748,7 @@ export default function PostDetailPage() {
setDeletingPost(true);
try {
await api.deletePost(postId);
deleteSessionSnapshot(postDetailCacheKey(postId));
clearAllFeedCache();
window.dispatchEvent(new Event('posts-refresh'));
notify.success('帖子已删除');
@@ -443,7 +768,7 @@ export default function PostDetailPage() {
onCancelReply: () => setReplyTo(null),
};
if (loading) return <div className="post-detail-loading flex justify-center py-16"><Spinner size="lg" /></div>;
if (loading && !post) return <div className="post-detail-loading flex justify-center py-16"><Spinner size="lg" /></div>;
if (!post) {
return (
<NotFoundPage
@@ -462,6 +787,32 @@ export default function PostDetailPage() {
? formatEditRemaining(post.created_at, editWindowHours)
: '';
const handleBountyAward = (commentId: number) => {
setBountyAwardTarget(commentId);
};
const confirmBountyAward = async () => {
if (bountyAwardTarget == null) return;
setBountyAwarding(true);
try {
await api.bountyAward(post.id, bountyAwardTarget);
notify.success('悬赏已发放');
setBountyAwardTarget(null);
await reloadPostContent();
await reloadComments();
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '操作失败');
} finally {
setBountyAwarding(false);
}
};
const awardedCommentFloor = findCommentFloor(comments, post.bounty_comment_id);
const canJumpToAwarded = awardedCommentFloor != null;
const handleJumpToAwarded = () => {
if (awardedCommentFloor != null) jumpToFloor(awardedCommentFloor);
};
const handlePin = async () => {
if (!post) return;
try {
@@ -606,6 +957,7 @@ export default function PostDetailPage() {
<article className="page-wrap post-detail-page" ref={pageRef}>
<div className="post-detail-header">
<div className="post-detail-nav">
<div className="post-detail-nav-left">
<Button variant="ghost" size="sm" onClick={() => nav(-1)}>
<ArrowLeft />
返回
@@ -614,6 +966,31 @@ export default function PostDetailPage() {
<BoardBadge board={post.board} className="post-detail-board-tag" />
)}
</div>
{(isOwnerOrAdmin || canEdit || isAdmin) && (
<PostManageMenu
post={post}
isAdmin={isAdmin}
isOwnerOrAdmin={isOwnerOrAdmin}
canEdit={canEdit}
isEdited={isEdited}
isMobile={isMobile}
editRemaining={editRemaining}
editBlockReason={editBlockReason}
deleting={deletingPost}
onEdit={() => nav(`/post/${postId}/edit`)}
onShowRevisions={() => setShowRevisions(true)}
onToggleResolved={handleToggleResolved}
onApprove={handleApprove}
onReject={() => setRejectOpen(true)}
onFeature={handleFeature}
onPin={handlePin}
onBoardPin={handleBoardPin}
onLock={handleLock}
onCommentsLock={handleCommentsLock}
onDelete={() => setDeleteOpen(true)}
/>
)}
</div>
{post.status === 'pending' && (
<div className="post-moderation-banner post-moderation-banner--pending">
@@ -644,6 +1021,20 @@ export default function PostDetailPage() {
{post.question_resolved ? '已解决' : '未解决'}
</span>
)}
{post.post_type === 'poll' && (
<span className="post-type-badge post-type-badge--poll">投票</span>
)}
{post.post_type === 'bounty' && post.bounty_status === 'open' && (post.bounty_points ?? 0) > 0 && (
<span className="post-bounty-badge post-bounty-badge--open post-bounty-badge--detail">悬赏 {post.bounty_points}</span>
)}
{post.post_type === 'bounty' && post.bounty_status === 'awarded' && (
<span className="post-bounty-badge post-bounty-badge--awarded post-bounty-badge--detail">已采纳</span>
)}
{post.post_type === 'lottery' && (
<span className="post-type-badge post-type-badge--lottery">
{post.lottery_status === 'drawn' ? '已开奖' : '抽奖'}
</span>
)}
{post.title}
</h1>
<div className="post-detail-author-row">
@@ -706,11 +1097,38 @@ export default function PostDetailPage() {
</details>
)}
{poll && (
<PostPollCard
postId={post.id}
poll={poll}
isOwnerOrAdmin={isOwnerOrAdmin}
onUpdate={setPoll}
/>
)}
<PostBountyBanner
post={post}
isOwnerOrAdmin={isOwnerOrAdmin}
isAdmin={isAdmin}
canRefund={bountyCanRefund}
refundBlockReason={bountyRefundBlockReason}
eligibleReplyCount={bountyEligibleReplyCount}
onUpdate={reloadPostContent}
onJumpToAwarded={handleJumpToAwarded}
canJumpToAwarded={canJumpToAwarded}
/>
{lottery && (
<PostLotteryCard
postId={post.id}
lottery={lottery}
isOwnerOrAdmin={isOwnerOrAdmin}
onUpdate={v => { setLottery(v); void reloadPostContent(); }}
/>
)}
<PostContent
html={post.content || ''}
isLoggedIn={!!user}
isLoggedIn={isLoggedIn}
postId={post.id}
onHeadingsChange={handleHeadingsChange}
onRequestReply={scrollToCommentBox}
onUnlocked={() => { void reloadPostContent(); }}
/>
@@ -769,39 +1187,10 @@ export default function PostDetailPage() {
</DropdownMenu>
) : null}
</div>
</div>
</div>
{(isOwnerOrAdmin || canEdit || isAdmin) && (
<div className="post-detail-actions-manage">
{isOwnerOrAdmin && post.post_type === 'question' && (
<Button
variant={post.question_resolved ? 'outline' : 'default'}
size="sm"
onClick={handleToggleResolved}
>
{post.question_resolved ? <CircleHelp /> : <CircleCheck />}
{post.question_resolved ? '标为未解决' : '标为已解决'}
</Button>
)}
{canEdit && (
<Button variant="outline" size="sm" onClick={() => nav(`/post/${postId}/edit`)}>
<Pencil />
编辑
</Button>
)}
{isOwnerOrAdmin && isEdited && (
<Button variant="outline" size="sm" onClick={() => setShowRevisions(true)}>
<History />
编辑历史
</Button>
)}
{isAdmin && (
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="outline" size="sm" disabled={deletingPost}>
<Trash2 />
删除
</Button>
</AlertDialogTrigger>
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>确定删除该帖子?</AlertDialogTitle>
@@ -810,59 +1199,19 @@ export default function PostDetailPage() {
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>取消</AlertDialogCancel>
<AlertDialogAction onClick={handleDeletePost}>删除</AlertDialogAction>
<AlertDialogCancel disabled={deletingPost}>取消</AlertDialogCancel>
<AlertDialogAction
disabled={deletingPost}
onClick={(e) => {
e.preventDefault();
void handleDeletePost();
}}
>
删除
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)}
{editRemaining && (
<span className="post-detail-edit-hint">{editRemaining}</span>
)}
{isOwnerOrAdmin && !canEdit && editBlockReason && (
<span className="post-detail-edit-hint" title={editBlockReason}>
{editBlockReason}
</span>
)}
{isAdmin && (
<>
{(post.status === 'pending' || post.status === 'rejected') && (
<Button variant="default" size="sm" onClick={handleApprove}>
通过审核
</Button>
)}
<Button variant="outline" size="sm" onClick={handleFeature}>
<Sparkles />
{post.featured ? '取消精华' : '设为精华'}
</Button>
<Button variant="outline" size="sm" onClick={handlePin}>
<Pin />
{post.pinned ? '取消全局置顶' : '全局置顶'}
</Button>
<Button variant="outline" size="sm" onClick={handleBoardPin}>
<Pin />
{post.board_pinned ? '取消板块置顶' : '板块置顶'}
</Button>
<Button variant="outline" size="sm" onClick={handleLock}>
<Lock />
{post.edit_locked ? '解锁编辑' : '锁定编辑'}
</Button>
<Button variant="outline" size="sm" onClick={handleCommentsLock}>
{post.comments_locked ? <LockOpen /> : <MessageSquareOff />}
{post.comments_locked ? '开放讨论' : '锁定讨论'}
</Button>
{post.status !== 'rejected' && (
<Button variant="outline" size="sm" onClick={() => setRejectOpen(true)}>
<Ban />
拒绝并通知
</Button>
)}
</>
)}
</div>
)}
</div>
</div>
<Dialog open={reportOpen} onOpenChange={setReportOpen}>
<DialogContent>
@@ -948,8 +1297,46 @@ export default function PostDetailPage() {
</div>
) : !replyTo && (
<div className="comment-box-wrap" ref={commentBoxRef}>
{isMobile && !composerOpen && (
<button
type="button"
className="comment-composer-collapsed"
onClick={() => {
if (!user) {
requireLogin('评论');
return;
}
setComposerOpen(true);
window.requestAnimationFrame(() => {
window.setTimeout(focusCommentEditor, 50);
});
}}
>
{user ? (
<>
<span className="comment-composer-collapsed-avatar" aria-hidden>
{user.avatar
? <img src={user.avatar} alt="" loading="lazy" decoding="async" />
: (user.nickname?.[0] || '?')}
</span>
<span className="comment-composer-collapsed-placeholder">说点什么…</span>
</>
) : (
<span className="comment-composer-collapsed-placeholder">登录后即可评论</span>
)}
</button>
)}
<div
className={
isMobile && !composerOpen
? 'comment-box-expanded-slot is-collapsed'
: 'comment-box-expanded-slot'
}
aria-hidden={isMobile && !composerOpen}
>
<CommentBox {...commentBoxProps} />
</div>
</div>
)}
<div className="comment-list-area">
@@ -993,10 +1380,42 @@ export default function PostDetailPage() {
inline
/>
)}
bountyAward={post.post_type === 'bounty' ? {
open: post.bounty_status === 'open' && (post.bounty_points ?? 0) > 0,
awardedCommentId: post.bounty_comment_id,
postAuthorId: post.user_id,
canAward: isOwnerOrAdmin,
onAward: handleBountyAward,
} : undefined}
/>
)}
</div>
</div>
<AlertDialog
open={bountyAwardTarget != null}
onOpenChange={(open) => { if (!open && !bountyAwarding) setBountyAwardTarget(null); }}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>采纳该回复?</AlertDialogTitle>
<AlertDialogDescription>
确定采纳该回复并发放 {post.bounty_points ?? 0} 悬赏积分?此操作不可撤销。
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={bountyAwarding}>取消</AlertDialogCancel>
<AlertDialogAction
disabled={bountyAwarding}
onClick={(e) => {
e.preventDefault();
void confirmBountyAward();
}}
>
{bountyAwarding ? '发放中…' : '确认采纳'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<InFlowSiteFooter />
</article>
);

View File

@@ -43,6 +43,7 @@ import { openForumPost } from '../utils/openPost';
import { formatDateTime } from '../utils/content';
import { InFlowSiteFooter } from '../components/SiteFooter';
import { userPath } from '../utils/userPath';
import { useSessionResource } from '../hooks/useSessionResource';
const nickSchema = z.object({
nickname: z.string().min(1, '请输入昵称').max(64),
@@ -75,7 +76,7 @@ export default function ProfilePage() {
const nav = useNavigate();
const [params, setParams] = useSearchParams();
const tab = parseTab(params.get('tab'));
const { user, loading: authLoading, refresh } = useAuth();
const { user, loading: authLoading, refresh, logout } = useAuth();
useNoIndexSEO('个人中心');
const [nickLoading, setNickLoading] = useState(false);
const [sigLoading, setSigLoading] = useState(false);
@@ -88,12 +89,6 @@ export default function ProfilePage() {
const [cropFileName, setCropFileName] = useState('');
const [dragOver, setDragOver] = useState(false);
const [idCopied, setIdCopied] = useState(false);
const [stats, setStats] = useState<UserActivityStats | null>(null);
const [statsLoading, setStatsLoading] = useState(true);
const [posts, setPosts] = useState<PostItem[]>([]);
const [postsLoading, setPostsLoading] = useState(false);
const [postPage, setPostPage] = useState(1);
const [postTotal, setPostTotal] = useState(0);
const fileRef = useRef<HTMLInputElement>(null);
const dragCounter = useRef(0);
const copyTimer = useRef<ReturnType<typeof setTimeout>>();
@@ -102,7 +97,6 @@ export default function ProfilePage() {
const { limits } = useForumLimits();
const pageSize = limits.page_size_default > 0 ? limits.page_size_default : 20;
const totalPages = Math.max(1, Math.ceil(postTotal / pageSize));
const nickForm = useForm<NickValues>({
resolver: zodResolver(nickSchema),
@@ -181,37 +175,26 @@ export default function ProfilePage() {
if (copyTimer.current) clearTimeout(copyTimer.current);
}, []);
const loadStats = useCallback(() => {
setStatsLoading(true);
api.profileStats()
.then(d => setStats(d.stats))
.catch(() => setStats(null))
.finally(() => setStatsLoading(false));
}, []);
const { data: stats = null, loading: statsLoading } = useSessionResource<UserActivityStats | null>(
user ? `profile:stats:${user.id}` : null,
() => api.profileStats().then(d => d.stats ?? null),
{ enabled: !!user },
);
useEffect(() => {
if (!user) return;
loadStats();
}, [user, loadStats]);
useEffect(() => {
if (!user || tab !== 'posts') return;
let cancelled = false;
setPostsLoading(true);
api.posts({ user_id: user.id, page: postPage, size: pageSize, sort: 'latest' })
.then(d => {
if (cancelled) return;
setPosts(Array.isArray(d.posts) ? d.posts : []);
setPostTotal(d.total ?? 0);
})
.catch(e => {
if (!cancelled) notify.error(e instanceof Error ? e.message : '加载帖子失败');
})
.finally(() => {
if (!cancelled) setPostsLoading(false);
});
return () => { cancelled = true; };
}, [user, tab, postPage, pageSize]);
const [postPage, setPostPage] = useState(1);
const postsKey = user && tab === 'posts' ? `profile:posts:${user.id}:${postPage}:${pageSize}` : null;
const { data: postsSnap, loading: postsLoading } = useSessionResource<{ posts: PostItem[]; total: number }>(
postsKey,
() => api.posts({ user_id: user!.id, page: postPage, size: pageSize, sort: 'latest' })
.then(d => ({ posts: Array.isArray(d.posts) ? d.posts : [], total: d.total ?? 0 })),
{
enabled: !!postsKey,
onError: (e) => notify.error(e instanceof Error ? e.message : '加载帖子失败'),
},
);
const posts = postsSnap?.posts ?? [];
const postTotal = postsSnap?.total ?? 0;
const totalPages = Math.max(1, Math.ceil(postTotal / pageSize));
const closeCropDialog = useCallback((open: boolean) => {
if (!open) {
@@ -263,7 +246,7 @@ export default function ProfilePage() {
await api.updatePassword(values.old_password, values.new_password);
notify.success('密码已修改,请重新登录');
pwdForm.reset();
await api.logout();
await logout();
nav('/login');
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '修改失败');

View File

@@ -1,58 +1,64 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeft, ExternalLink, FolderGit2 } from 'lucide-react';
import { ArrowLeft, FolderGit2, Search } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import { notify } from '@/lib/notify';
import { api } from '../api/client';
import type { GiteaProject } from '../api/types';
import ProjectListItem from '../components/ProjectListItem';
import { InFlowSiteFooter } from '../components/SiteFooter';
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
import { getCachedSiteBranding } from '../hooks/useSiteBranding';
import { InFlowSiteFooter } from '../components/SiteFooter';
import { useSessionResource } from '../hooks/useSessionResource';
function formatRemoteTime(raw?: string | null): string {
if (!raw) return '';
const d = new Date(raw);
if (Number.isNaN(d.getTime())) return '';
return d.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
});
}
type ProjectsSnap = { list: GiteaProject[]; total: number; totalPages: number };
export default function ProjectsPage() {
const nav = useNavigate();
const [list, setList] = useState<GiteaProject[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(0);
const [loading, setLoading] = useState(true);
const [queryInput, setQueryInput] = useState('');
const [query, setQuery] = useState('');
usePageSEO({
title: '项目',
description: '公开项目列表',
keywords: joinSEOKeywords('项目', getCachedSiteBranding().keywords),
title: '开源码桶',
description: '论坛会员在 Gitea 上的公开仓库',
keywords: joinSEOKeywords('开源码桶', '项目', getCachedSiteBranding().keywords),
canonicalPath: '/projects',
});
useEffect(() => {
setLoading(true);
api.projects({ page, limit: 30 })
.then(d => {
setList(Array.isArray(d.projects) ? d.projects : []);
setTotal(d.total ?? 0);
setTotalPages(d.total_pages ?? 0);
})
.catch(e => notify.error(e instanceof Error ? e.message : '加载失败'))
.finally(() => setLoading(false));
}, [page]);
const t = window.setTimeout(() => {
const next = queryInput.trim();
setQuery(prev => {
if (prev === next) return prev;
setPage(1);
return next;
});
}, 300);
return () => window.clearTimeout(t);
}, [queryInput]);
const { data, loading } = useSessionResource<ProjectsSnap>(
`projects:${page}:${query}`,
() => api.projects({ page, limit: 30, q: query || undefined }).then(d => ({
list: Array.isArray(d.projects) ? d.projects : [],
total: d.total ?? 0,
totalPages: d.total_pages ?? 0,
})),
{
onError: (e) => notify.error(e instanceof Error ? e.message : '加载失败'),
},
);
const list = data?.list ?? [];
const total = data?.total ?? 0;
const totalPages = data?.totalPages ?? 0;
return (
<div className="page-wrap">
<div className="page-inner-wide">
<Button variant="ghost" className="mb-3" onClick={() => nav('/')}>
<div className="feed-panel list-page-panel">
<header className="list-page-panel__head">
<Button variant="ghost" size="sm" className="list-page-panel__back" onClick={() => nav('/')}>
<ArrowLeft />
返回
</Button>
@@ -61,44 +67,36 @@ export default function ProjectsPage() {
论坛会员在 Gitea 上的公开仓库
{total > 0 ? ` · 共 ${total} 个` : ''}
</p>
<label className="projects-search">
<Search className="projects-search__icon" size={16} aria-hidden />
<input
type="search"
className="projects-search__input"
placeholder="搜索仓库名、描述或所有者…"
value={queryInput}
onChange={e => setQueryInput(e.target.value)}
autoComplete="off"
/>
</label>
</header>
{loading ? (
<div className="flex justify-center py-16"><Spinner size="lg" /></div>
) : list.length === 0 ? (
<div className="empty-state">
<div className="empty-state list-page-panel__empty">
<FolderGit2 className="empty-state-icon" aria-hidden size={36} strokeWidth={1.5} />
<p>暂无同步到的公开项目</p>
<p>{query ? '没有匹配的仓库' : '暂无同步到的公开项目'}</p>
<p className="page-desc" style={{ marginTop: 8 }}>
管理员可在「系统设置 → Gitea 同步」配置后执行同步
{query
? '试试其他关键词,或清空搜索'
: '需管理员在「系统设置 → Gitea 同步」开启并执行同步后才会出现仓库'}
</p>
</div>
) : (
<>
<div className="content-surface projects-list">
<div className="content-surface post-list projects-list">
{list.map(p => (
<article key={p.id} className="project-row">
<div className="project-row-body">
<h2 className="project-row-title">{p.full_name || p.name}</h2>
{p.description ? (
<p className="project-row-desc">{p.description}</p>
) : null}
<div className="project-row-meta">
<span>{p.owner_login}</span>
{p.updated_at_remote && (
<span>更新于 {formatRemoteTime(p.updated_at_remote)}</span>
)}
</div>
</div>
<a
className="project-row-link"
href={p.html_url}
target="_blank"
rel="noopener noreferrer"
>
在 Gitea 打开
<ExternalLink size={14} aria-hidden />
</a>
</article>
<ProjectListItem key={p.id} project={p} />
))}
</div>
{totalPages > 1 && (

View File

@@ -0,0 +1,145 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeft, ExternalLink, Globe2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import { api } from '../api/client';
import type { CommunityShowcaseItem } from '../api/types';
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
import { getCachedSiteBranding, useSiteBranding } from '../hooks/useSiteBranding';
import { InFlowSiteFooter } from '../components/SiteFooter';
import { useSessionResource } from '../hooks/useSessionResource';
function siteMark(name: string, url: string): string {
const raw = (name || '').trim() || url.replace(/^https?:\/\//i, '');
const ch = Array.from(raw)[0];
return ch ? ch.toUpperCase() : '?';
}
function hostLabel(url: string): string {
try {
return new URL(url).host;
} catch {
return url.replace(/^https?:\/\//i, '');
}
}
/** 目标站约定路径 /favicon.ico */
function faviconURL(siteURL: string): string | null {
try {
return new URL('/favicon.ico', siteURL).href;
} catch {
return null;
}
}
function ShowcaseFavicon({ name, url }: { name: string; url: string }) {
const src = faviconURL(url);
const [failed, setFailed] = useState(!src);
const mark = siteMark(name, url);
if (failed || !src) {
return (
<span className="showcase-item-mark" aria-hidden>
{mark}
</span>
);
}
return (
<span className="showcase-item-favicon">
<img
src={src}
alt=""
width={40}
height={40}
referrerPolicy="no-referrer"
decoding="async"
onError={() => setFailed(true)}
/>
</span>
);
}
/** 官方精选的公网部署展柜(只读;仅人工精选条目) */
export default function ShowcasePage() {
const nav = useNavigate();
const { branding } = useSiteBranding();
const { data: items = [], loading } = useSessionResource<CommunityShowcaseItem[]>(
'showcase',
() => api.communityShowcase().then((r) => (Array.isArray(r.items) ? r.items : [])),
{ revalidateEmpty: true },
);
usePageSEO({
title: '开源部署展柜',
description: `${branding.name} 精选的姜十三论坛公网部署`,
keywords: joinSEOKeywords('开源', '部署', '展柜', getCachedSiteBranding().keywords),
canonicalPath: '/showcase',
});
return (
<div className="page-wrap">
<div className="feed-panel list-page-panel showcase-panel">
<header className="list-page-panel__head showcase-head">
<Button variant="ghost" size="sm" className="list-page-panel__back" onClick={() => nav('/')}>
<ArrowLeft />
返回
</Button>
<div className="showcase-head__title-row">
<h1 className="page-title">开源部署展柜</h1>
{!loading && items.length > 0 && (
<span className="showcase-head__count">精选 {items.length} 站</span>
)}
</div>
<p className="page-desc">
以下站点自愿开启社区上报,并由官方演示站精选推荐(非全量目录)
</p>
</header>
{loading ? (
<div className="flex justify-center py-16"><Spinner size="lg" /></div>
) : items.length === 0 ? (
<div className="showcase-empty list-page-panel__empty">
<Globe2 size={28} strokeWidth={1.5} aria-hidden />
<p>暂无精选实例</p>
<span>有站点被官方推荐后会出现在这里</span>
</div>
) : (
<ul className="showcase-list">
{items.map((item) => {
const name = item.site_name || '未命名站点';
return (
<li key={item.site_url} className="showcase-item">
<a
href={item.site_url}
target="_blank"
rel="noopener noreferrer"
className="showcase-item-link"
>
<ShowcaseFavicon name={name} url={item.site_url} />
<span className="showcase-item-body">
<span className="showcase-item-name">{name}</span>
<span className="showcase-item-url">
{hostLabel(item.site_url)}
<ExternalLink size={12} aria-hidden />
</span>
{item.featured_note ? (
<span className="showcase-item-note">{item.featured_note}</span>
) : null}
</span>
{item.version ? (
<span className="showcase-item-version">v{item.version}</span>
) : null}
</a>
</li>
);
})}
</ul>
)}
<InFlowSiteFooter />
</div>
</div>
);
}

View File

@@ -0,0 +1,91 @@
import { useEffect, useMemo, useRef } from 'react';
import { useOutletContext, useParams } from 'react-router-dom';
import NotFoundPage from './NotFoundPage';
import { api } from '../api/client';
import type { SitePage } from '../api/types';
import ArticleOutline from '../components/ArticleOutline';
import PostContent from '../components/PostContent';
import { usePageSEO } from '../hooks/usePageSEO';
import { parsePermalinkSlug, pagePath } from '../utils/permalink';
import { useForumLimits } from '../hooks/useForumLimits';
import { useAuth } from '../hooks/useAuth';
import { useSessionResource } from '../hooks/useSessionResource';
import type { LayoutCtx } from '../layouts/MainLayout';
import { extractHeadingsFromHtml } from '../utils/postHeadings';
import { renderPostContentHtml } from '../utils/postContent';
/** 自定义单页(关于我们、版规等) */
export default function SitePageView() {
const { slug: rawSlug } = useParams();
const slug = parsePermalinkSlug(rawSlug);
const { limits } = useForumLimits();
const { user } = useAuth();
const { setPostOutline, isMobile } = useOutletContext<LayoutCtx>();
const pageRef = useRef<HTMLDivElement>(null);
const { data: page, loading } = useSessionResource<SitePage | null>(
slug ? `sitepage:${slug}` : null,
() => api.page(slug).then(d => d.page),
{ enabled: !!slug },
);
const notFound = !slug || (!loading && !page);
const isLoggedIn = !!user;
const pageContent = page?.content ?? '';
// 同步从正文派生目录,与帖子详情共用右侧栏目录布局
const headings = useMemo(() => {
if (!pageContent.trim()) return [];
const rendered = renderPostContentHtml(pageContent, isLoggedIn, {
openLinksInNewTab: limits.open_content_links_in_new_tab,
});
return extractHeadingsFromHtml(rendered);
}, [pageContent, isLoggedIn, limits.open_content_links_in_new_tab]);
usePageSEO({
title: page?.title,
description: page?.title,
canonicalPath: slug ? pagePath(slug, limits) : undefined,
ogType: 'article',
});
useEffect(() => {
if (loading || !page) {
setPostOutline({ headings: [], scrollRoot: null, title: '文章目录' });
return () => setPostOutline(null);
}
setPostOutline({
headings,
scrollRoot: pageRef.current,
title: '文章目录',
});
return () => setPostOutline(null);
}, [headings, loading, page, setPostOutline]);
if (!slug) return <NotFoundPage title="页面不存在" />;
if (loading) return null;
if (notFound || !page) return <NotFoundPage title="页面不存在" description="该页面不存在或未发布" />;
return (
<div className="page-wrap" ref={pageRef}>
<article className="site-page">
<header className="site-page__head">
<h1>{page.title}</h1>
</header>
{isMobile && headings.length > 0 && (
<details className="post-detail-toc-mobile">
<summary>文章目录({headings.length})</summary>
<ArticleOutline
headings={headings}
scrollRoot={pageRef.current}
title="目录"
/>
</details>
)}
<PostContent
html={page.content}
isLoggedIn={isLoggedIn}
className="site-page__body post-detail-content"
/>
</article>
</div>
);
}

View File

@@ -20,9 +20,9 @@ import { api } from '../api/client';
import type { PostItem, UserActivityStats, UserPublic } from '../api/types';
import { useAuth } from '../hooks/useAuth';
import { useForumLimits } from '../hooks/useForumLimits';
import { useSessionResource } from '../hooks/useSessionResource';
import PostListItem from '../components/PostListItem';
import FeedPagination from '../components/FeedPagination';
import ComposeMessageDialog from '../components/ComposeMessageDialog';
import { openForumPost } from '../utils/openPost';
import { formatDateTime } from '../utils/content';
import { usePageSEO } from '../hooks/usePageSEO';
@@ -31,6 +31,9 @@ import { canonicalRedirectPath, parsePermalinkID, userPath } from '../utils/perm
import NotFoundPage from './NotFoundPage';
import { InFlowSiteFooter } from '../components/SiteFooter';
type ProfileSnap = { profile: UserPublic; stats: UserActivityStats | null };
type PostsSnap = { posts: PostItem[]; total: number };
export default function UserProfilePage() {
const { id: idParam } = useParams();
const userId = parsePermalinkID(idParam);
@@ -40,15 +43,33 @@ export default function UserProfilePage() {
const { limits } = useForumLimits();
const pageSize = limits.page_size_default > 0 ? limits.page_size_default : 20;
const [profile, setProfile] = useState<UserPublic | null>(null);
const [stats, setStats] = useState<UserActivityStats | null>(null);
const [msgOpen, setMsgOpen] = useState(false);
const [loading, setLoading] = useState(true);
const [notFound, setNotFound] = useState(false);
const [posts, setPosts] = useState<PostItem[]>([]);
const [postsLoading, setPostsLoading] = useState(false);
const [postPage, setPostPage] = useState(1);
const [postTotal, setPostTotal] = useState(0);
const profileKey = userId && !Number.isNaN(userId) ? `user:${userId}` : null;
const { data: profileSnap, loading } = useSessionResource<ProfileSnap>(
profileKey,
() => api.userProfile(userId).then(d => ({ profile: d.user, stats: d.stats ?? null })),
{
enabled: !!profileKey,
onError: () => setNotFound(true),
},
);
const profile = profileSnap?.profile ?? null;
const stats = profileSnap?.stats ?? null;
const postsKey = profileKey && profile ? `${profileKey}:posts:${postPage}:${pageSize}` : null;
const { data: postsSnap, loading: postsLoading } = useSessionResource<PostsSnap>(
postsKey,
() => api.posts({ user_id: userId, page: postPage, size: pageSize, sort: 'latest' })
.then(d => ({ posts: Array.isArray(d.posts) ? d.posts : [], total: d.total ?? 0 })),
{
enabled: !!postsKey,
onError: (e) => notify.error(e instanceof Error ? e.message : '加载帖子失败'),
},
);
const posts = postsSnap?.posts ?? [];
const postTotal = postsSnap?.total ?? 0;
const isSelf = !!me && me.id === userId;
const totalPages = Math.max(1, Math.ceil(postTotal / pageSize));
@@ -56,43 +77,13 @@ export default function UserProfilePage() {
useEffect(() => {
if (!userId || Number.isNaN(userId)) {
setNotFound(true);
setLoading(false);
return;
}
setLoading(true);
setNotFound(false);
setPostPage(1);
api.userProfile(userId)
.then(d => {
setProfile(d.user);
setStats(d.stats);
})
.catch(() => {
setProfile(null);
setStats(null);
setNotFound(true);
})
.finally(() => setLoading(false));
}, [userId]);
useEffect(() => {
if (!userId || Number.isNaN(userId) || !profile) return;
let cancelled = false;
setPostsLoading(true);
api.posts({ user_id: userId, page: postPage, size: pageSize, sort: 'latest' })
.then(d => {
if (cancelled) return;
setPosts(Array.isArray(d.posts) ? d.posts : []);
setPostTotal(d.total ?? 0);
})
.catch(e => {
if (!cancelled) notify.error(e instanceof Error ? e.message : '加载帖子失败');
})
.finally(() => {
if (!cancelled) setPostsLoading(false);
});
return () => { cancelled = true; };
}, [userId, profile, postPage, pageSize]);
setNotFound(false);
setPostPage(1);
}, [userId]);
useEffect(() => {
if (!userId || Number.isNaN(userId)) return;
@@ -190,7 +181,7 @@ export default function UserProfilePage() {
nav(loginPath(userPath(profile.id)));
return;
}
setMsgOpen(true);
nav(`/messages?peer=${profile.id}`);
}}
>
<Mail size={14} />
@@ -272,16 +263,6 @@ export default function UserProfilePage() {
</div>
</div>
<InFlowSiteFooter />
{!isSelf && profile && me && (
<ComposeMessageDialog
open={msgOpen}
onOpenChange={setMsgOpen}
toUserId={profile.id}
toNickname={profile.nickname}
onSent={() => nav(`/messages?peer=${profile.id}`)}
/>
)}
</div>
);
}

View File

@@ -27,6 +27,8 @@ import {
badgeIcon,
formatBadgeCondition,
} from '../../utils/badgeIcons';
import AdminSortableList, { SortableDragHandle, SortableMoveButtons } from '../../components/admin/AdminSortableList';
import { mergeReorderedSubset, persistSortOrderChanges, shouldShowSortableMoveButtons } from '../../utils/sortOrder';
type KindTab = 'all' | 'auto' | 'limited';
@@ -62,6 +64,7 @@ export default function AdminBadgesPage() {
const [form, setForm] = useState<Partial<BadgeDef>>({ ...EMPTY });
const [saving, setSaving] = useState(false);
const [togglingId, setTogglingId] = useState<number | null>(null);
const [reordering, setReordering] = useState(false);
const load = () => {
setLoading(true);
@@ -161,6 +164,27 @@ export default function AdminBadgesPage() {
}
};
const handleBadgeReorder = async (reorderedFiltered: BadgeDef[]) => {
const subsetBefore = [...filtered];
const before = [...rows];
setReordering(true);
try {
const merged = mergeReorderedSubset(before, subsetBefore, reorderedFiltered);
const after = await persistSortOrderChanges(before, merged, badge =>
api.adminUpsertBadge({ ...badge, sort_order: badge.sort_order }),
);
setRows(after);
notify.success('徽章排序已更新');
} catch (e: unknown) {
setRows(before);
notify.error(e instanceof Error ? e.message : '排序保存失败');
} finally {
setReordering(false);
}
};
const showMoveButtons = shouldShowSortableMoveButtons(filtered.length);
if (!ready) return null;
const PreviewIcon = badgeIcon(form.icon);
@@ -249,14 +273,30 @@ export default function AdminBadgesPage() {
)}
</div>
) : (
<div className="admin-badge-grid">
{filtered.map(b => {
<AdminSortableList
strategy="grid"
className="admin-badge-grid"
items={filtered}
getId={b => b.id}
onReorder={handleBadgeReorder}
showMoveButtons="auto"
ariaLabel="徽章列表排序"
renderItem={(b, _index, controls) => {
const Icon = badgeIcon(b.icon);
return (
<article
key={b.id}
className={cn('admin-badge-card', !b.enabled && 'is-disabled')}
ref={controls.setNodeRef}
style={controls.style}
className={cn(
'admin-badge-card',
'admin-sortable-grid-item',
!b.enabled && 'is-disabled',
controls.isDragging && 'is-dragging',
)}
>
<div className="admin-sortable-grid-item__handle-wrap">
<SortableDragHandle label={`拖拽调整「${b.name}」顺序`} {...controls.dragHandleProps} />
</div>
<div className="admin-badge-card-top">
<div className={cn('admin-badge-preview', b.kind === 'limited' && 'is-limited')}>
<Icon size={22} aria-hidden />
@@ -283,15 +323,16 @@ export default function AdminBadgesPage() {
{formatBadgeCondition(b)}
</span>
<div className="admin-badge-card-actions">
{showMoveButtons && <SortableMoveButtons controls={controls} />}
<label className="admin-badge-switch" title={b.enabled ? '点击停用' : '点击启用'}>
<span className="sr-only">启用</span>
<Switch
checked={b.enabled}
disabled={togglingId === b.id}
disabled={togglingId === b.id || reordering}
onCheckedChange={() => toggleEnabled(b)}
/>
</label>
<Button size="sm" variant="outline" onClick={() => openEdit(b)}>
<Button size="sm" variant="outline" onClick={() => openEdit(b)} disabled={reordering}>
<Pencil size={13} />
编辑
</Button>
@@ -299,8 +340,8 @@ export default function AdminBadgesPage() {
</div>
</article>
);
})}
</div>
}}
/>
)}
<Dialog open={dialogOpen} onOpenChange={(open) => {

View File

@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Trash2, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
@@ -40,6 +40,8 @@ function formatAdminTime(iso: string) {
export default function AdminCommentsPage() {
const nav = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const focusId = Number(searchParams.get('id') || 0) || 0;
const { ready } = useAdminGuard();
const [tab, setTab] = useState<Tab>('pending');
const [comments, setComments] = useState<Comment[]>([]);
@@ -49,6 +51,9 @@ export default function AdminCommentsPage() {
const [totalPages, setTotalPages] = useState(1);
const [pendingCount, setPendingCount] = useState(0);
const [revComment, setRevComment] = useState<Comment | null>(null);
const [highlightId, setHighlightId] = useState<number | null>(focusId > 0 ? focusId : null);
const focusTriedRef = useRef(false);
const highlightTimer = useRef<ReturnType<typeof setTimeout>>();
const loadList = (p = page, st: Tab = tab) => {
setLoading(true);
@@ -90,6 +95,45 @@ export default function AdminCommentsPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ready, tab]);
// 从通知深链 ?id= 定位并高亮待审行
useEffect(() => {
if (!ready || loading || focusId <= 0 || focusTriedRef.current) return;
if (tab === 'trash') return;
const found = comments.find((c) => c.id === focusId);
if (found) {
focusTriedRef.current = true;
setHighlightId(focusId);
requestAnimationFrame(() => {
document.getElementById(`admin-comment-row-${focusId}`)?.scrollIntoView({
behavior: 'smooth',
block: 'center',
});
});
clearTimeout(highlightTimer.current);
highlightTimer.current = setTimeout(() => setHighlightId(null), 2800);
const next = new URLSearchParams(searchParams);
next.delete('id');
setSearchParams(next, { replace: true });
return;
}
// pending 未找到则切到全部再试一次
if (tab === 'pending') {
setTab('all');
setPage(1);
return;
}
focusTriedRef.current = true;
notify.warning('该评论可能已审核或不在当前列表');
const next = new URLSearchParams(searchParams);
next.delete('id');
setSearchParams(next, { replace: true });
}, [ready, loading, comments, focusId, tab, searchParams, setSearchParams]);
useEffect(() => () => clearTimeout(highlightTimer.current), []);
const approve = async (id: number) => {
try {
const r = await api.adminApproveComment(id);
@@ -268,7 +312,11 @@ export default function AdminCommentsPage() {
</thead>
<tbody>
{comments.map(c => (
<tr key={c.id}>
<tr
key={c.id}
id={`admin-comment-row-${c.id}`}
className={cn(highlightId === c.id && 'admin-row-highlight')}
>
<td>{c.id}</td>
<td>#{c.floor}</td>
<td>

Some files were not shown because too many files have changed in this diff Show More