42 Commits

Author SHA1 Message Date
f3f50d7e90 chore: bump version to 1.1.8 2026-09-02 19:40:35 +08:00
67bef6dc08 chore: 同步 Cursor 构建规则到 Trae,优化 .gitignore
- 新增 .trae/rules/build-scripts.mdc,与 Cursor 的 .cursor/rules/build-scripts.mdc 保持一致
- .gitignore 从忽略整个 .trae/ 改为仅忽略 .trae/documents/、.trae/chat/、.trae/image/ 等临时产物
- 保留 .trae/rules/ 可被 git 追踪,规则可跨机器同步
- 取消追踪已存在的 .trae/documents/ 临时规划文档
2026-09-02 19:34:49 +08:00
23e304ac53 chore: 在 .gitignore 中添加 .trae/ 目录 2026-09-02 19:30:33 +08:00
cad53942e8 fix: 修复消息未读数同步和帖子详情快照逻辑
- MessagesPage: 新增 updateConvUnread 统一更新会话未读数及 session 缓存,
  缓存命中时仍调用 markConversationRead 并触发未读刷新,
  全部标为已读时同步更新 session 缓存避免 stale 数据
- PostDetailPage: 仅 POP 导航类型使用 session 快照恢复,
  非 POP 导航和下拉刷新始终强制重拉确保拿到最新数据
2026-09-02 19:29:01 +08:00
76be8926f2 feat: 完善表情选择与评论富文本展示
发帖编辑器支持 OwO 贴纸;评论区复用文章列表、段落与代码块阅读态,并优化表情面板间距与悬停反馈。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 03:57:41 +08:00
4d93e455f9 fix: 私信表情插入编辑框,不再作为图片附件发送
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-02 03:12:33 +08:00
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
154 changed files with 19233 additions and 3408 deletions

6
.gitignore vendored
View File

@@ -20,6 +20,12 @@ tmp-cookie.txt
# 编辑器 / OS # 编辑器 / OS
.idea/ .idea/
.vscode/ .vscode/
.trae/documents/
.trae/chat/
.trae/image/
*.swp *.swp
Thumbs.db Thumbs.db
.DS_Store .DS_Store
# Lucide path <20><>ȡ<EFBFBD><C8A1>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD>
frontend/tmp-lucide-paths.json

View File

@@ -1,151 +0,0 @@
# 表情效果调整计划
## 问题分析
当前实现存在 5 个问题,根因如下:
### 1. 插入表情后有选择状态(蓝色高亮)
- **根因**: Tiptap `setImage` 插入图片节点后,节点处于 "node-selected" 状态,显示蓝色选中框
- **位置**: [CommentEditor.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/CommentEditor.tsx) L155-163
### 2. 输入框表情太大
- **根因**: CSS 选择器 `img[src^="data:image/svg"]` 只匹配旧 SVG data URI不匹配新的 AVIF URL`/stickers/tieba/tb_01.avif`),导致表情图片无尺寸约束,以原始大尺寸渲染
- **位置**: [global.css](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/styles/global.css) L5584-5603
### 3. 插入表情后光标换行
- **根因**: `ArticleImage.configure({ inline: false })` 使图片为块级节点,插入后自动换行
- **位置**: [CommentEditor.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/CommentEditor.tsx) L92
### 4. 表情栏目太宽松
- **根因**: Grid 仅 6 列gap 4pxpadding 10px
- **位置**: [global.css](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/styles/global.css) L5502-5510
### 5. 颜文字太小
- **根因**: `.sticker-picker-text``font-size: 8px`,极小
- **位置**: [global.css](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/styles/global.css) L5606-5616
## 改动方案
### 文件 1: CommentEditor.tsx
**改动 A — 图片改为内联** (L92):
```typescript
// 旧
ArticleImage.configure({ inline: false, allowBase64: true }),
// 新
ArticleImage.configure({ inline: true, allowBase64: true }),
```
**改动 B — insertSticker 插入后取消选中和换行** (L155-163):
```typescript
const insertSticker = useCallback((sticker: Sticker) => {
if (!editor) return;
if (sticker.type === 'text' && sticker.text) {
editor.chain().focus().insertContent(sticker.text).run();
} else if (sticker.url) {
// 插入内联图片 + 尾随零宽空格,确保光标在图片后面而非选中图片
editor.chain().focus().insertContent([
{ type: 'image', attrs: { src: sticker.url, alt: sticker.name } },
{ type: 'text', text: '\u200b' },
]).run();
}
setShowSticker(false);
}, [editor]);
```
> 用 `insertContent` + 零宽空格替代 `setImage`,避免 node-selected 状态,光标自然落在图片后。
### 文件 2: StickerPicker.tsx
**改动 C — 键盘导航列数匹配新网格** (L44):
```typescript
// 旧
const cols = 6;
// 新
const cols = 8;
```
### 文件 3: global.css
**改动 D — 表情选择器密度提升** (L5502-5510):
```css
.sticker-picker-grid {
display: grid;
grid-template-columns: repeat(8, 1fr); /* 6 → 8 */
gap: 2px; /* 4px → 2px */
padding: 6px; /* 10px → 6px */
overflow-y: auto;
flex: 1;
min-height: 0;
}
```
**改动 E — 选择器项缩小** (L5512-5522):
```css
.sticker-picker-item {
padding: 2px; /* 4px → 2px */
/* 其余不变 */
}
```
**改动 F — 颜文字字体放大** (L5606-5616):
```css
.sticker-picker-text {
font-size: 14px; /* 8px → 14px */
line-height: 1.4; /* 1.2 → 1.4 */
/* 其余不变 */
}
```
**改动 G — 替换旧 SVG 选择器为通用贴纸选择器** (L5584-5603):
删除旧的 `img[src^="data:image/svg"]` 选择器,替换为基于 `/stickers/` 路径的选择器:
```css
/* 编辑器内贴纸 img 尺寸约束 */
.comment-editor .article-prosemirror img[src*="/stickers/"],
.comment-editor .article-editor-content img[src*="/stickers/"] {
display: inline-block;
width: 28px;
height: 28px;
vertical-align: middle;
margin: 0 1px;
border-radius: 4px;
object-fit: contain;
}
/* 评论正文中的贴纸 img */
.floor-body img[src*="/stickers/"],
.comment-body img[src*="/stickers/"] {
display: inline-block;
vertical-align: middle;
width: 28px;
height: 28px;
margin: 0 1px;
background: transparent;
border-radius: 4px;
object-fit: contain;
}
```
**改动 H — 移动端网格也改为 8 列** (L5619-5624):
```css
@media (max-width: 640px) {
.sticker-picker { max-height: 240px; }
.sticker-picker-grid { grid-template-columns: repeat(6, 1fr); } /* 移动端 6 列 */
.sticker-picker-tab { padding: 6px 10px; font-size: 12px; }
.comment-editor .article-tool-btn { width: 30px; height: 30px; }
}
```
> 移动端保持 6 列(屏幕窄),桌面端 8 列。
## 不改动
- `ArticleImageExtension.tsx` — 无需修改,`inline: true` 通过 `configure()` 传入即可
- `kaomoji.ts` / `emojiData.ts` / `hot.ts` — 数据层不变
- `CommentContent.tsx` — 渲染层不变CSS 覆盖即可)
- PostEditor帖子编辑器— 不受影响,仍使用 `inline: false`
## 验证
1. `npm run build` 无报错
2. 浏览器验证:
- 选择表情后插入无蓝色选中框
- 表情在输入框中显示 28px内联在文字中
- 插入表情后光标紧跟表情后方,不换行
- 表情选择器 8 列密度更高
- 颜文字标签内字体清晰可读

View File

@@ -1,597 +0,0 @@
# 评论表情包改造 + 富文本评论编辑器计划
## 一、摘要
将评论系统从「纯文本 textarea + Unicode Emoji」升级为「Tiptap 富文本编辑器 + 姜十三专属 SVG 贴纸」,实现:
1. 去除所有 Unicode Emoji替换为自定义 SVG 贴纸(懒加载)
2. 姜十三专属表情包:萌系吉祥物表情 + 中文网络流行语文字气泡(混合风格)
3. 评论复用帖子编辑器核心能力(精简变体),支持代码块、链接、图片、格式化等
---
## 二、当前状态分析
### 2.1 评论输入:纯文本 textarea
[CommentBox.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/CommentBox.tsx) 使用 `<textarea>` 输入评论,功能包括:
- `@` 用户提及textarea 选区扫描 + API 搜索用户)
- Unicode Emoji 面板([EmojiPicker.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/EmojiPicker.tsx) + [emojis.ts](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/utils/emojis.ts)
- 隐私评论开关
- 无富文本格式化能力
### 2.2 评论渲染:纯文本转义
[CommentContent.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/CommentContent.tsx) 通过 [content.ts](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/utils/content.ts) 的 `highlightMentions()` 渲染评论:
- `escapeWithBreaks()` 转义 HTML 并将 `\n` 转为 `<br>`
- 正则匹配 `@username` 包裹为可点击 `<span class="mention">`
- 不支持 HTML/Markdown 渲染
### 2.3 评论编辑:纯 textarea
[CommentThreadList.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/CommentThreadList.tsx#L276-L297) 编辑模式使用 `<textarea>` 直接修改文本。
### 2.4 帖子编辑器Tiptap 富文本
[ArticleEditor.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/ArticleEditor.tsx) 是功能完整的 Tiptap 编辑器900 行),包含:
- 富文本模式 + Markdown 模式切换
- 工具栏:标题/加粗/斜体/下划线/删除线/分割线/引用/列表/代码块/表格/链接/图片/图组
- 门控区块:登录可见/回复可见/积分可见
- 全屏模式
- `forwardRef` 暴露 `getHTML()` / `isEmpty()` / `focus()`
- 使用 `DOMPurify` + `POST_CONTENT_PURIFY_CONFIG` 净化 HTML
### 2.5 后端评论存储
- [models.go](file:///c:/Users/freefire/Documents/jiang13-forum/model/models.go#L143-L164): `Comment.Content` 字段类型为 `text`,存储纯文本
- [comment.go](file:///c:/Users/freefire/Documents/jiang13-forum/service/comment.go#L172-L176): `Create()` 仅做 `TrimSpace` + 敏感词过滤,**无 HTML 净化**
- [handlers.go](file:///c:/Users/freefire/Documents/jiang13-forum/handler/handlers.go#L508-L530): `APICreateComment` 从 FormData 取 `content` 字段
- [sanitize_html.go](file:///c:/Users/freefire/Documents/jiang13-forum/service/sanitize_html.go): `SanitizePostHTML` 已有 HTML 白名单策略bluemonday但**仅用于帖子,未用于评论**
### 2.6 表情数据
[emojis.ts](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/utils/emojis.ts) 定义约 160 个 Unicode Emoji 字符,无分类、无搜索。
---
## 三、修改方案
### Part A姜十三专属 SVG 贴纸系统
#### A1. 贴纸数据定义
**新建** `frontend/src/data/stickers.ts`
```typescript
export interface Sticker {
id: string; // 唯一ID如 "j13-happy"
name: string; // 名称,如 "开心"
category: StickerCategory;
aliases?: string[]; // 搜索别名
svg: string; // 完整 SVG 字符串(含 viewBox 0 0 64 64
}
export type StickerCategory = '热门' | '姜十三' | '文字气泡';
export const STICKER_CATEGORIES: StickerCategory[] = ['热门', '姜十三', '文字气泡'];
export const STICKERS: Sticker[] = [ /* ... */ ];
```
**贴纸内容设计(约 40 个):**
| 分类 | 数量 | 内容 |
|------|------|------|
| 姜十三 | 16 | 萌系姜色ginger色 #D4A574)圆脸吉祥物,额头带"13"标记,各种表情:开心/大笑/哭泣/生气/惊讶/思考/点赞/心心眼/睡觉/疑惑/酷/捂脸/送花/鼓掌/加油/拜托 |
| 文字气泡 | 16 | 圆角气泡 + 中文网络流行语666/大佬/同问/给力/沙发/学习了/已赞/佩服/妙啊/牛批/感谢/收藏了/围观/催更/瑞思拜/芜湖 |
| 热门 | 8 | 从上述两类中精选最常用的 8 个 |
**SVG 设计规范:**
- `viewBox="0 0 64 64"` 统一尺寸
- 所有 fill 使用内联颜色(不依赖 CSS 变量)
- 姜十三吉祥物主色系:`#D4A574`(姜色)/ `#FFF3E0`(浅姜)/ `#E8B87C`(深姜)
- 文字气泡:`#FF6B6B`(红)/ `#4ECDC4`(青)/ `#FFE66D`(黄)/ `#95E1D3`(绿)四色循环
- 线条圆润stroke-linecap: round
#### A2. SVG 贴纸渲染组件
**新建** `frontend/src/components/emoji/StickerSvg.tsx`
```typescript
interface StickerSvgProps {
id: string;
size?: number; // 默认 28
className?: string;
}
```
-`STICKERS` 查找对应 id渲染 `dangerouslySetInnerHTML={{ __html: sticker.svg }}`
- SVG 已自包含 fill 颜色,无需额外样式
#### A3. 贴纸选择器(懒加载)
**新建** `frontend/src/components/emoji/StickerPicker.tsx`
```typescript
interface StickerPickerProps {
onSelect: (stickerId: string) => void;
}
```
**UI 结构:**
```
┌──────────────────────────────┐
│ [热门] [姜十三] [文字气泡] │ ← 分类 Tab
├──────────────────────────────┤
│ [🙂] [😂] [❤️] [👍] [🎉] ... │ ← SVG 贴纸网格6列桌面/4列移动端
└──────────────────────────────┘
```
**懒加载策略:**
- 贴纸数据按分类拆分为独立 chunk`data/stickers/j13.ts``data/stickers/text.ts``data/stickers/hot.ts`
- `StickerPicker` 使用 `React.lazy()` + `Suspense` 按需加载当前分类
- 切换分类时才加载对应 chunk首次打开只加载"热门"分类
- 每个贴纸 SVG 在组件挂载时渲染(已在数据中内联,无需额外网络请求)
**交互:**
- 分类 Tab 点击切换,带下划线动画
- 贴纸 hover: `transform: scale(1.15)`, 0.1s 过渡
- 点击贴纸触发 `onSelect(sticker.id)`
- 键盘导航:方向键浏览 + Enter 选中
#### A4. 删除旧 Emoji 系统
- **删除** [emojis.ts](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/utils/emojis.ts)`EMOJI_LIST` 导出)
- **删除** [EmojiPicker.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/EmojiPicker.tsx)
- **保留** `.emoji-picker*` CSS 类(避免影响其他可能的引用),新增 `.sticker-picker*`
---
### Part B评论富文本编辑器精简变体
#### B1. 创建 CommentEditor 组件
**新建** `frontend/src/components/CommentEditor.tsx`
不直接复用 ArticleEditor900 行,含全屏/Markdown/门控区块等评论不需要的功能),而是创建独立的精简 Tiptap 编辑器,**复用 ArticleEditor 的扩展组件**。
```typescript
export interface CommentEditorHandle {
getHTML: () => string;
isEmpty: () => boolean;
focus: () => void;
}
interface CommentEditorProps {
value: string;
onChange: (html: string) => void;
placeholder?: string;
}
```
**使用的 Tiptap 扩展(复用现有):**
- `StarterKit`(含 heading H2-H4、bold/italic/strike、blockquote、bulletList/orderedList、horizontalRule
- `Underline`(来自 @tiptap/extension-underline已安装
- `Link`(来自 @tiptap/extension-link已安装
- `ArticleCodeBlock`(来自 [ArticleCodeBlockExtension.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/editor/ArticleCodeBlockExtension.tsx),复用)
- `Placeholder`(来自 @tiptap/extension-placeholder已安装
- `TabIndent`(来自 [TabIndentExtension.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/editor/TabIndentExtension.tsx),复用)
- `ArticleImage`(来自 [ArticleImageExtension.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/editor/ArticleImageExtension.tsx),复用,用于插入图片)
**不使用的扩展(评论场景不需要):**
- ~~TableKit~~(表格)
- ~~ImageGroup~~(图组)
- ~~MembersOnly / ReplyOnly / PointsOnly~~(门控区块)
- ~~ClearFloatParagraph~~(清除浮动段落)
- ~~Markdown 模式~~
- ~~全屏模式~~
**工具栏按钮(精简版):**
```
[H] [B] [I] [U] [S] [引用] [列表] [有序列表] [代码块] [链接] [图片] [贴纸]
```
**贴纸集成:**
- 工具栏增加贴纸按钮Lucide `Sticker` 图标)
- 点击弹出 `StickerPicker`
- 选中贴纸后,将 SVG 作为 inline `<img>` 插入编辑器:
```typescript
const sticker = STICKERS.find(s => s.id === id);
const dataUri = `data:image/svg+xml,${encodeURIComponent(sticker.svg)}`;
editor.chain().focus().setImage({ src: dataUri, alt: sticker.name }).run();
```
**HTML 净化:**
- 使用 `DOMPurify.sanitize(html, POST_CONTENT_PURIFY_CONFIG)` 与 ArticleEditor 一致
- `POST_CONTENT_PURIFY_CONFIG` 来自 [postContent.ts](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/utils/postContent.ts),复用现有配置
#### B2. 改造 CommentBox
**修改** [CommentBox.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/CommentBox.tsx)
**主要变更:**
1. 用 `CommentEditor` 替换 `<textarea>`
2. 用 `CommentEditorHandle` ref 替代 `textareaRef`
3. `content` 状态存储 HTML 而非纯文本
4. 移除 `EmojiPicker` 导入和使用,贴纸功能已集成到 `CommentEditor`
5. 移除 `owoRef` 和 `showEmoji` 状态
6. `@` 提及功能:暂时保留为文本输入(在编辑器中输入 `@username`,渲染时由 `processCommentHtml` 处理高亮),编辑器内自动补全作为后续增强
7. `insertEmoji` 改为 `insertSticker`,调用 `CommentEditor` ref 方法
8. 隐私评论开关保留
9. 发送时 `content` 为 HTML直接传给 API
**改动前:**
```tsx
<textarea ref={textareaRef} value={content} onChange={handleChange} ... />
<button ref={owoRef} onClick={() => setShowEmoji(v => !v)}>OwO</button>
{showEmoji && <EmojiPicker onSelect={insertEmoji} />}
```
**改动后:**
```tsx
<CommentEditor ref={editorRef} value={content} onChange={setContent} placeholder="说点什么吧…" />
```
#### B3. 改造评论编辑模式
**修改** [CommentThreadList.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/CommentThreadList.tsx#L276-L297)
编辑模式从 `<textarea>` 改为 `CommentEditor`
```tsx
// 改动前
<textarea value={editText} onChange={e => setEditText(e.target.value)} rows={3} />
// 改动后
<CommentEditor value={editText} onChange={setEditText} placeholder="编辑评论…" />
```
需要 import `CommentEditor`,并在 `handleSave` 中提交 HTML 内容。
---
### Part C评论内容渲染
#### C1. 更新 content.ts 支持富文本
**修改** [content.ts](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/utils/content.ts)
当前 `highlightMentions()` 处理纯文本(转义 HTML + 换行 + @高亮)。需要新增 HTML 处理能力。
```typescript
import DOMPurify from 'dompurify';
import { POST_CONTENT_PURIFY_CONFIG } from '../utils/postContent';
/** 判断内容是否为 HTML包含常见 HTML 标签) */
function isHtmlContent(text: string): boolean {
return /<(?:p|div|span|br|h[1-6]|ul|ol|li|pre|code|blockquote|a|img|table|strong|em|u|s)\b/i.test(text);
}
/** 在 HTML 文本节点中高亮 @ 提及DOM 遍历,避免破坏标签) */
function processMentionsInHtml(html: string): string {
const div = document.createElement('div');
div.innerHTML = html;
const walker = document.createTreeWalker(div, NodeFilter.SHOW_TEXT);
const textNodes: Text[] = [];
let node: Node | null;
while ((node = walker.nextNode())) {
textNodes.push(node as Text);
}
for (const textNode of textNodes) {
const text = textNode.textContent ?? '';
if (!/@[\w\u4e00-\u9fa5_-]/.test(text)) continue;
const frag = document.createDocumentFragment();
const parts = text.split(/(@[\w\u4e00-\u9fa5_-]+)/);
for (const part of parts) {
const m = part.match(/^@([\w\u4e00-\u9fa5_-]+)$/);
if (m) {
const span = document.createElement('span');
span.className = 'mention';
span.setAttribute('data-name', m[1]);
span.setAttribute('role', 'link');
span.setAttribute('tabindex', '0');
span.textContent = part;
frag.appendChild(span);
} else if (part) {
frag.appendChild(document.createTextNode(part));
}
}
textNode.parentNode?.replaceChild(frag, textNode);
}
return div.innerHTML;
}
/** 渲染评论内容HTML 净化 + @提及高亮,兼容旧版纯文本 */
export function renderCommentContent(content: string): string {
if (isHtmlContent(content)) {
// 新版 HTML 评论
const sanitized = DOMPurify.sanitize(content, POST_CONTENT_PURIFY_CONFIG);
return processMentionsInHtml(sanitized);
}
// 旧版纯文本评论(向后兼容)
return escapeWithBreaks(content).replace(
/@([\w\u4e00-\u9fa5_-]+)/g,
'<span class="mention" data-name="$1" role="link" tabindex="0">@$1</span>',
);
}
```
保留原 `highlightMentions()` 函数不删除(可能有其他引用),新增 `renderCommentContent()`。
#### C2. 更新 CommentContent 组件
**修改** [CommentContent.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/CommentContent.tsx)
```tsx
import { renderCommentContent } from '../utils/content';
// 改动前
dangerouslySetInnerHTML={{ __html: highlightMentions(content) }}
// 改动后
dangerouslySetInnerHTML={{ __html: renderCommentContent(content) }}
```
评论内容中的贴纸 `<img>` 标签会被 `POST_CONTENT_PURIFY_CONFIG` 保留(已允许 `<img>` + `src`),自然渲染为 SVG 图。
---
### Part D后端评论 HTML 净化
#### D1. 评论创建时净化
**修改** [comment.go](file:///c:/Users/freefire/Documents/jiang13-forum/service/comment.go#L172-L176)
```go
func (s *CommentService) Create(in CommentCreateInput) (*model.Comment, error) {
content := SanitizePostHTML(strings.TrimSpace(in.Content)) // 新增 HTML 净化
content = s.filter.Filter(content) // 敏感词过滤
// ... 其余不变
}
```
#### D2. 评论更新时净化
**修改** [comment.go](file:///c:/Users/freefire/Documents/jiang13-forum/service/comment.go#L354-L376)
```go
func (s *CommentService) Update(userID, commentID uint, isAdmin, skipModeration bool, content string) (string, bool, error) {
// ...
content = SanitizePostHTML(strings.TrimSpace(content)) // 新增
content = s.filter.Filter(content) // 敏感词过滤
// ... 其余不变
}
```
`SanitizePostHTML` 已在 [sanitize_html.go](file:///c:/Users/freefire/Documents/jiang13-forum/service/sanitize_html.go) 中定义,使用 bluemonday 白名单策略,允许 Tiptap 产出的 HTML 标签和属性,禁止 `<script>`、`<style>` 等。
---
### Part ECSS 样式
#### E1. 贴纸选择器样式
**修改** [global.css](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/styles/global.css#L5427-L5462) 区域
新增样式块(在现有 `.emoji-picker*` 样式之后):
```css
/* 贴纸选择器 */
.sticker-picker {
display: flex;
flex-direction: column;
margin-top: 8px;
border: 1px solid var(--j13-border-light);
border-radius: 8px;
background: var(--j13-bg-surface);
max-height: 280px;
overflow: hidden;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}
.sticker-picker-tabs {
display: flex;
border-bottom: 1px solid var(--j13-border-light);
padding: 0 8px;
}
.sticker-picker-tab {
border: none;
background: none;
padding: 8px 12px;
font-size: 13px;
color: var(--color-text-3);
cursor: pointer;
border-bottom: 2px solid transparent;
transition: color 0.15s, border-color 0.15s;
}
.sticker-picker-tab.active {
color: var(--j13-green);
border-bottom-color: var(--j13-green);
}
.sticker-picker-grid {
display: grid;
grid-template-columns: repeat(6, 1fr);
gap: 4px;
padding: 10px;
overflow-y: auto;
flex: 1;
}
.sticker-picker-item {
border: none;
background: none;
padding: 4px;
cursor: pointer;
border-radius: 8px;
transition: background 0.1s, transform 0.1s;
display: flex;
align-items: center;
justify-content: center;
}
.sticker-picker-item:hover {
background: var(--color-fill-2);
transform: scale(1.15);
}
/* 贴纸加载占位 */
.sticker-picker-loading {
grid-column: 1 / -1;
text-align: center;
padding: 24px;
color: var(--color-text-4);
font-size: 13px;
}
/* 移动端 */
@media (max-width: 640px) {
.sticker-picker-grid {
grid-template-columns: repeat(4, 1fr);
}
}
```
#### E2. 评论编辑器样式
新增 `.comment-editor` 相关样式,复用 `.article-editor-bar`、`.article-tool-btn` 等现有类名,仅做覆盖调整:
```css
/* 评论富文本编辑器 */
.comment-editor .article-editor-bar {
padding: 4px 8px;
}
.comment-editor .article-tool-btn {
width: 28px;
height: 28px;
}
.comment-editor .article-editor-content {
min-height: 80px;
max-height: 300px;
overflow-y: auto;
padding: 8px 12px;
font-size: 14px;
}
.comment-editor .article-editor-status {
padding: 4px 10px;
}
/* 评论内贴纸图片 */
.comment-sticker {
display: inline-block;
vertical-align: middle;
width: 28px;
height: 28px;
margin: 0 2px;
}
```
---
## 四、文件变更清单
### 新增文件
| 文件路径 | 用途 |
|----------|------|
| `frontend/src/data/stickers/hot.ts` | 热门贴纸数据(懒加载 chunk |
| `frontend/src/data/stickers/j13.ts` | 姜十三吉祥物贴纸数据(懒加载 chunk |
| `frontend/src/data/stickers/text.ts` | 文字气泡贴纸数据(懒加载 chunk |
| `frontend/src/data/stickers/index.ts` | 贴纸类型定义 + 统一导出 |
| `frontend/src/components/emoji/StickerSvg.tsx` | SVG 贴纸渲染组件 |
| `frontend/src/components/emoji/StickerPicker.tsx` | 贴纸选择器(懒加载) |
| `frontend/src/components/CommentEditor.tsx` | 评论富文本编辑器(精简 Tiptap |
### 修改文件
| 文件 | 变更 |
|------|------|
| [CommentBox.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/CommentBox.tsx) | textarea → CommentEditor移除 EmojiPickercontent 改为 HTML |
| [CommentThreadList.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/CommentThreadList.tsx#L276-L297) | 编辑模式 textarea → CommentEditor |
| [CommentContent.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/CommentContent.tsx) | 使用 `renderCommentContent()` 替代 `highlightMentions()` |
| [content.ts](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/utils/content.ts) | 新增 `renderCommentContent()` + `processMentionsInHtml()` |
| [global.css](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/styles/global.css#L5427-L5462) | 新增 `.sticker-picker*` 和 `.comment-editor*` 样式 |
| [comment.go](file:///c:/Users/freefire/Documents/jiang13-forum/service/comment.go#L172-L176) | Create() 增加 `SanitizePostHTML` |
| [comment.go](file:///c:/Users/freefire/Documents/jiang13-forum/service/comment.go#L354-L376) | Update() 增加 `SanitizePostHTML` |
### 删除文件
| 文件 | 原因 |
|------|------|
| [emojis.ts](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/utils/emojis.ts) | Unicode Emoji 数据不再需要 |
| [EmojiPicker.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/components/EmojiPicker.tsx) | 被 StickerPicker 替代 |
---
## 五、假设与决策
### 5.1 编辑器决策
- **不直接复用 ArticleEditor 组件**,而是创建独立的 CommentEditor原因
- ArticleEditor 900 行,含全屏/Markdown/门控区块等评论不需要的功能
- 复用 ArticleEditor 的 Tiptap 扩展组件ArticleCodeBlock、ArticleImage、TabIndent 等),避免代码重复
- CommentEditor 更轻量,每个评论实例加载更快
- **@ 提及**:暂不在编辑器中实现自动补全(需要 Tiptap Mention 扩展或自定义扩展),用户手动输入 `@username`,渲染时由 `processMentionsInHtml` 高亮。后续可增强为 Tiptap Mention 扩展。
### 5.2 贴纸存储格式
- 贴纸以 `data:image/svg+xml` URI 内联在 `<img src="...">` 中
- 每个 SVG 约 300-800 字节,单条评论即使 10 个贴纸也仅 ~8KB
- 后端 `SanitizePostHTML` 白名单已允许 `<img src="...">`,无需额外修改
- 旧评论(纯文本)不受影响,`renderCommentContent` 自动检测并兼容
### 5.3 懒加载策略
- 贴纸数据按分类拆分为 3 个 chunkhot/j13/text`React.lazy()` 动态导入
- 首次打开选择器只加载"热门"chunk8 个贴纸),切换分类时才加载其他 chunk
- 每个 chunk 约 5-10KB加载延迟 < 100ms
### 5.4 向后兼容
- 旧评论为纯文本,新 `renderCommentContent()` 通过 `isHtmlContent()` 检测自动走旧路径escapeWithBreaks + 正则高亮)
- 新评论为 HTML走 DOMPurify 净化 + DOM 遍历高亮路径
- 后端 `SanitizePostHTML` 对纯文本也安全bluemonday 会保留纯文本,仅过滤危险标签)
---
## 六、实施顺序
1. **Part A**:贴纸数据 + 组件stickers/*.ts → StickerSvg → StickerPicker
2. **Part D**:后端评论 HTML 净化comment.go Create/Update 加 SanitizePostHTML
3. **Part B**CommentEditor 组件 → CommentBox 集成 → CommentThreadList 编辑模式
4. **Part C**content.ts 渲染函数 → CommentContent 更新
5. **Part E**CSS 样式
6. 删除旧 EmojiPicker / emojis.ts
7. 验证测试
---
## 七、验证步骤
1. **贴纸系统验证**
- 点击贴纸按钮选择器弹出3 个分类 Tab 可切换
- 切换分类时加载对应贴纸Network 面板确认懒加载)
- 点击贴纸后编辑器中出现对应 SVG 图
2. **评论编辑器验证**
- 评论框支持加粗/斜体/下划线/删除线/标题/引用/列表/代码块/链接/图片/贴纸
- 代码块支持语法高亮和折叠
- 图片可上传并插入
- 无全屏/Markdown/表格/门控区块按钮
3. **评论渲染验证**
- 新评论 HTML 正确渲染(格式化、代码块、图片、贴纸)
- `@username` 在 HTML 评论中正确高亮为可点击链接
- 旧评论(纯文本)仍正常渲染
- 贴纸图片在评论中正确显示
4. **后端验证**
- 发送含 `<script>alert(1)</script>` 的评论,后端净化后移除 script 标签
- 发送正常 HTML 评论,后端存储完整 HTML
- 旧纯文本评论正常存储和渲染
5. **编辑模式验证**
- 编辑已有评论时CommentEditor 正确加载 HTML 内容
- 保存后评论更新正确

View File

@@ -1,138 +0,0 @@
# 修复主页右侧栏评论点击定位问题
## 问题描述
用户在主页右侧栏点击评论时,如果该评论不是帖子的第一个评论(`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

@@ -1,117 +0,0 @@
# 修复:再次进入帖子时滚动位置异常保留
## 问题
浏览帖子滑到下方 → 返回主页 → 再次进入同一帖子,滚动条停在之前阅读的位置,而非顶部。
## 根因
项目未设置 `history.scrollRestoration`(默认 `'auto'`)。浏览器在导航时会对**内部滚动容器**`overflow: auto``.page-wrap`)执行滚动位置恢复。虽然 PostDetailPage 重新挂载后 `.page-wrap` 是新 DOM 元素,浏览器仍会在 paint 前将其 `scrollTop` 恢复到上次记录的值。
项目没有 ScrollToTop 机制来覆盖此行为。
## 与刷新恢复的冲突
之前实现的 `useScrollRestoration`MainLayout mount-only负责刷新场景的位置恢复。本修复必须与之共存
| 场景 | 期望行为 | 处理者 |
|---|---|---|
| 刷新帖子页 | 恢复到上次位置 | `useScrollRestoration`sessionStorage + rAF |
| SPA 导航进入帖子 | 从顶部开始 | 本修复(重置 scrollTop=0 |
| `/post/123``/post/456` | 从顶部开始 | 本修复(重置 scrollTop=0 |
**区分依据**`pagehide``saveScrollPositions` 将当前 URL 的滚动记录存入 sessionStorage。刷新后该记录存在SPA 导航进入时该记录不存在(从未为此 URL 保存过,或已被 `restoreScrollPositions` 消费清除)。因此 PostDetailPage 渲染 `.page-wrap` 时检查 sessionStorage 是否有当前 URL 的记录即可区分两种场景。
**时序保证**React 的 effect 执行顺序是子组件先于父组件。PostDetailPage 的 `useLayoutEffect` 在 MainLayout 的 `useEffect`(含 `useScrollRestoration`)之前执行。此时 sessionStorage 记录尚未被消费,`hasPendingScrollRestore()` 返回准确值。
## 改动计划
### 1. `frontend/src/utils/scrollRestore.ts` — 新增 `hasPendingScrollRestore`
在现有文件中新增导出函数:
```ts
/** 检查 sessionStorage 中是否有指定 URL 的待恢复滚动记录(不消费/不删除) */
export function hasPendingScrollRestore(url: string = getCurrentUrl()): boolean {
try {
const raw = sessionStorage.getItem(storageKey(url));
if (!raw) return false;
const entry = JSON.parse(raw) as SavedPositions;
return !!entry?.containers && Object.keys(entry.containers).length > 0;
} catch {
return false;
}
}
```
纯读取,不删除记录(`restoreScrollPositions` 的 rAF 循环仍需要它来恢复)。
### 2. 新建 `frontend/src/hooks/useScrollToTopOnMount.ts`
通用 hook在滚动容器渲染就绪后重置到顶部刷新场景跳过
```ts
import { useLayoutEffect, useRef, type RefObject } from 'react';
import { hasPendingScrollRestore } from '../utils/scrollRestore';
/**
* 滚动容器渲染就绪后重置到顶部。
* - 首次就绪刷新场景sessionStorage 有记录)跳过,让 useScrollRestoration 恢复;
* SPA 导航(无记录)重置到顶部。
* - deps 变化(如 postId 变化):始终重置到顶部。
* - 同 deps 的 ready 状态变化(如评论刷新导致 loading 短暂为 true不处理避免误重置。
*/
export function useScrollToTopOnMount(
scrollRef: RefObject<HTMLElement | null>,
deps: React.DependencyList,
ready: boolean,
): void {
const lastKeyRef = useRef<string | null>(null);
const key = JSON.stringify(deps);
useLayoutEffect(() => {
if (!ready || !scrollRef.current) return;
if (lastKeyRef.current === null) {
lastKeyRef.current = key;
if (!hasPendingScrollRestore()) {
scrollRef.current.scrollTop = 0;
}
return;
}
if (lastKeyRef.current !== key) {
lastKeyRef.current = key;
scrollRef.current.scrollTop = 0;
}
}, [key, ready]); // ready 变化时重新检查
}
```
### 3. `frontend/src/pages/PostDetailPage.tsx` — 调用 hook
`pageRef` 定义之后L108 之后)、`useGlobalWheelScroll` 调用处附近添加:
```ts
import { useScrollToTopOnMount } from '../hooks/useScrollToTopOnMount';
// ...
useScrollToTopOnMount(pageRef, [postId], !loading && !!post);
```
- `deps: [postId]``/post/123``/post/456` 时重置
- `ready: !loading && !!post``.page-wrap` 仅在此时渲染L446 loading return、L447 !post returnpageRef.current 才有效
### 不需要改动的部分
- **其他页面**FavoritesPage、MessagesPage、ProfilePage 等):用户仅报告了帖子页问题。这些页面内容较短,滚动保留不明显。如后续报告可复用此 hook。
- **MainLayout / AdminLayout**`useScrollRestoration` 不变。
- **`history.scrollRestoration`**:不设为 `'manual'`,避免影响 back/forward 时其他页面的浏览器原生恢复。
## 验证步骤
1. **SPA 导航进入帖子**:从首页点击帖子 → 滑到下方 → 返回首页 → 再次点击同一帖子 → 应从顶部开始。
2. **帖子间切换**`/post/123` 滑到下方 → 直接导航到 `/post/456` → 应从顶部开始。
3. **刷新保持位置**:在帖子页滑到下方 → F5 刷新 → 应恢复到原位置(`useScrollRestoration` 生效hook 跳过)。
4. **硬刷新保持位置**:同上但用 Ctrl+F5 → 应恢复到原位置。
5. **首次访问**:从未访问过的帖子 → 应从顶部开始sessionStorage 无记录)。
6. **诊断无错误**TypeScript 编译通过。

View File

@@ -1,55 +0,0 @@
# 修复生产环境表情图片无法显示 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 typehttp.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 静态文件服务方案

View File

@@ -0,0 +1,36 @@
---
description: 编译与构建脚本约定Windows build.bat/ps1、Makefile、跨平台同步
alwaysApply: true
---
# 编译与构建脚本
Go 单二进制 + `go:embed` 前端;产物在 `dist/`。
## 运行编译(优先用封装命令,不要猜命令)
| 平台 | 命令 |
|------|------|
| Windows | `build.bat` 或 `build.bat -Target <target>` |
| Linux / macOS | `make` 或 `make <target>` |
**不要**在 Windows 上直接运行 `make`(系统自带多为 Embarcadero MAKE不兼容本项目 Makefile
Windows 上**不要**让用户直接 `.\build.ps1`(默认 ExecutionPolicy 会拦截);应通过 `build.bat`(内部 `-ExecutionPolicy Bypass`)调用。
常用 target`build`(默认)、`dev`、`run`、`frontend`、`clean`、`build-all`、`build-windows`、`build-linux`、`tidy`、`help`。
## 修改构建脚本时的约定
1. **双轨同步**`build.ps1` 与 `Makefile` 目标与行为保持一致;改其一须同步另一份。
2. **`build.bat` 仅用 ASCII 注释**`.bat` 会被 cmd 按 GBK 解析UTF-8 中文注释会导致整行乱码、`powershell` 无法执行。
3. **`build.ps1` 可用 UTF-8**:由 PowerShell 执行,中文注释无妨。
4. **构建顺序**:先 `frontend` 内 `npm run build`,再 `go build -trimpath -ldflags "-s -w -X main.version=..." -o dist/jiang13 ./cmd/jiang13`。
5. **入口包**`./cmd/jiang13`Windows 产物带 `.exe`。
## 新增 target 检查清单
- [ ] `build.ps1` 的 `ValidateSet` 与 `switch` 分支
- [ ] `Makefile` 对应 `.PHONY` 与 recipe
- [ ] `build.bat -Target help` 说明help 输出在 ps1 内)
- [ ] README「快速开始」如需对外暴露再更新

View File

@@ -5,7 +5,7 @@ APP_NAME := jiang13
MAIN_PKG := ./cmd/jiang13 MAIN_PKG := ./cmd/jiang13
BUILD_DIR := dist BUILD_DIR := dist
DEV_DATA_DIR := dist/data DEV_DATA_DIR := dist/data
VERSION := 1.0.0 VERSION := 1.1.8
LDFLAGS := -s -w -X main.version=$(VERSION) LDFLAGS := -s -w -X main.version=$(VERSION)
REGISTRY_IMAGE := hangzhang714128/jiang13-forum REGISTRY_IMAGE := hangzhang714128/jiang13-forum

View File

@@ -20,6 +20,7 @@
[快速开始](#-快速开始) · [快速开始](#-快速开始) ·
[界面预览](#-界面预览) · [界面预览](#-界面预览) ·
[功能亮点](#-功能亮点) · [功能亮点](#-功能亮点) ·
[更新日志](docs/site-posts/changelog.md) ·
[路线图](ROADMAP.md) · [路线图](ROADMAP.md) ·
[参与贡献](CONTRIBUTING.md) [参与贡献](CONTRIBUTING.md)
@@ -172,6 +173,11 @@ make compose-up
浏览器打开 `http://localhost:3000/register` 注册;**首个用户自动成为管理员**。 浏览器打开 `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** **拉取已构建镜像Docker Hub**
```bash ```bash
@@ -196,6 +202,7 @@ docker run -d --name jiang13 \
| `JIANG13_JWT_SECRET` | JWT 密钥(留空则自动生成并写入 `/data/.jwt_secret` | | `JIANG13_JWT_SECRET` | JWT 密钥(留空则自动生成并写入 `/data/.jwt_secret` |
| `JIANG13_CONFIG` | 配置文件路径 | | `JIANG13_CONFIG` | 配置文件路径 |
| `JIANG13_WORK_PATH` | 工作目录 | | `JIANG13_WORK_PATH` | 工作目录 |
| `JIANG13_COMMUNITY_HUB` | 维护者选项:设为 `1` 时本站作为社区枢纽收报。官方站 `bbs.iioio.com` 会按域名自动成为枢纽,无需此变量;仅非官网的枢纽镜像 / 预发需要显式开启(见 `app.ini.example` |
**健康检查:** `GET /health` 返回 `{"status":"ok"}`,供 Docker / 负载均衡探活。 **健康检查:** `GET /health` 返回 `{"status":"ok"}`,供 Docker / 负载均衡探活。
@@ -205,15 +212,15 @@ docker run -d --name jiang13 \
docker login docker login
.\build.bat -Target docker # Windows .\build.bat -Target docker # Windows
# make docker # Linux/macOS # make docker # Linux/macOS
docker push hangzhang714128/jiang13-forum:1.0.0 docker push hangzhang714128/jiang13-forum:1.1.7
docker push hangzhang714128/jiang13-forum:latest docker push hangzhang714128/jiang13-forum:latest
``` ```
或直接构建: 或直接构建:
```bash ```bash
docker build --build-arg VERSION=1.0.0 -t hangzhang714128/jiang13-forum:1.0.0 -t hangzhang714128/jiang13-forum:latest . 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.0.0 docker push hangzhang714128/jiang13-forum:1.1.7
docker push hangzhang714128/jiang13-forum:latest docker push hangzhang714128/jiang13-forum:latest
``` ```
@@ -238,7 +245,29 @@ docker push hangzhang714128/jiang13-forum:latest
### 3. 直接启动(二进制) ### 3. 直接启动(二进制)
把二进制放到目标目录后直接运行(首次会在同目录生成 `app.ini` 不想自己编译时,从 [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 ```bash
# Windows # Windows
@@ -292,7 +321,7 @@ JWT_SECRET =
| `--jwt-secret` | 自动生成 | JWT 签名密钥(留空则持久化到 `data/.jwt_secret` | | `--jwt-secret` | 自动生成 | JWT 签名密钥(留空则持久化到 `data/.jwt_secret` |
| `--service` | (空) | `install` / `uninstall` / `start` / `stop` / `restart` / `status` | | `--service` | (空) | `install` / `uninstall` / `start` / `stop` / `restart` / `status` |
**环境变量(容器 / 编排,优先级低于命令行):** `JIANG13_HTTP_PORT``JIANG13_DATA``JIANG13_JWT_SECRET``JIANG13_CONFIG``JIANG13_WORK_PATH` **环境变量(容器 / 编排,优先级低于命令行):** `JIANG13_HTTP_PORT``JIANG13_DATA``JIANG13_JWT_SECRET``JIANG13_CONFIG``JIANG13_WORK_PATH``JIANG13_COMMUNITY_HUB`(非官网枢纽镜像用;`bbs.iioio.com` 按域名自动为枢纽,见上表)
### 5. 注册为系统服务(可选) ### 5. 注册为系统服务(可选)
@@ -405,13 +434,15 @@ jiang13-forum/
``` ```
data/ data/
├── jiang13.db # SQLite 主数据库 ├── jiang13.db # SQLite 主数据库(不含浏览量)
├── monitor.db # 网站监控 page_views
├── jiang13.log # 运行日志 ├── jiang13.log # 运行日志
├── filter_words.txt # 敏感词配置 ├── filter_words.txt # 敏感词配置
├── .jwt_secret # JWT 密钥(自动生成) ├── .jwt_secret # JWT 密钥(自动生成)
├── logs/access/ # 网站监控请求日志(按日 jsonl
├── uploads/avatars/ # 用户头像 ├── uploads/avatars/ # 用户头像
├── uploads/posts/ # 帖子正文图片 ├── uploads/posts/ # 帖子正文图片
└── jiang13_backup_*.db # 后台导出的备份 └── jiang13_backup_*.db # 后台导出的主库备份
``` ```
--- ---

View File

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

View File

@@ -12,7 +12,7 @@ $AppName = 'jiang13'
$MainPkg = './cmd/jiang13' $MainPkg = './cmd/jiang13'
$BuildDir = 'dist' $BuildDir = 'dist'
$DevDataDir = 'dist/data' $DevDataDir = 'dist/data'
$Version = '1.0.0' $Version = '1.1.8'
$RegistryImage = 'hangzhang714128/jiang13-forum' $RegistryImage = 'hangzhang714128/jiang13-forum'
$Ldlags = "-s -w -X main.version=$Version" $Ldlags = "-s -w -X main.version=$Version"

View File

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

View File

@@ -12,6 +12,7 @@ import (
"github.com/kardianos/service" "github.com/kardianos/service"
"git.iioio.com/freefire/jiang13-forum/config" "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/model"
"git.iioio.com/freefire/jiang13-forum/router" "git.iioio.com/freefire/jiang13-forum/router"
) )
@@ -78,6 +79,12 @@ func (p *program) setup() error {
if err := model.InitDB(cfg.DBPath()); err != nil { if err := model.InitDB(cfg.DBPath()); err != nil {
return fmt.Errorf("数据库初始化失败: %w", err) 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) engine, err := router.Setup(cfg)
if err != nil { 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 日省级 Topcountry / 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,6 +32,9 @@ type Config struct {
ServiceAction string ServiceAction string
// 开发模式:后端代理前端请求到 Vite 开发服务器(非内嵌静态资源) // 开发模式:后端代理前端请求到 Vite 开发服务器(非内嵌静态资源)
DevMode bool DevMode bool
// CommunityHub 维护者选项:开启后本站接收其它实例自愿上报(默认关闭)。
// 官方站 bbs.iioio.com 会按域名自动识别为枢纽,无需开启;本项仅给非官网枢纽镜像。
CommunityHub bool
} }
// Parse 解析命令行、环境变量与 app.ini并初始化数据目录 // Parse 解析命令行、环境变量与 app.ini并初始化数据目录
@@ -108,6 +111,11 @@ func Parse() (*Config, error) {
jwtSecret = strings.TrimSpace(*jwtFlag) jwtSecret = strings.TrimSpace(*jwtFlag)
} }
communityHub := fileCfg.CommunityHub
if v := envBoolOrNil(envCommunityHub); v != nil {
communityHub = *v
}
cfg := &Config{ cfg := &Config{
WorkPath: workPath, WorkPath: workPath,
ConfigFile: configFile, ConfigFile: configFile,
@@ -117,6 +125,7 @@ func Parse() (*Config, error) {
LogFile: filepath.Join(absData, "jiang13.log"), LogFile: filepath.Join(absData, "jiang13.log"),
ServiceAction: action, ServiceAction: action,
DevMode: *devFlag, DevMode: *devFlag,
CommunityHub: communityHub,
} }
needDirs := action == "" || action == "install" needDirs := action == "" || action == "install"
@@ -184,6 +193,7 @@ func ensureDataDirs(dataDir string) error {
filepath.Join(dataDir, "uploads", "avatars"), filepath.Join(dataDir, "uploads", "avatars"),
filepath.Join(dataDir, "uploads", "posts"), filepath.Join(dataDir, "uploads", "posts"),
filepath.Join(dataDir, "uploads", "site"), filepath.Join(dataDir, "uploads", "site"),
filepath.Join(dataDir, "logs", "access"),
} { } {
if err := os.MkdirAll(sub, 0755); err != nil { if err := os.MkdirAll(sub, 0755); err != nil {
return fmt.Errorf("创建上传目录失败: %w", err) return fmt.Errorf("创建上传目录失败: %w", err)
@@ -218,11 +228,16 @@ func validServiceAction(action string) bool {
} }
} }
// DBPath 返回 SQLite 数据库文件路径 // DBPath 返回主库 SQLite 路径
func (c *Config) DBPath() string { func (c *Config) DBPath() string {
return filepath.Join(c.DataDir, "jiang13.db") return filepath.Join(c.DataDir, "jiang13.db")
} }
// MonitorDBPath 返回监控独立库路径page_views
func (c *Config) MonitorDBPath() string {
return filepath.Join(c.DataDir, "monitor.db")
}
// AvatarUploadDir 返回头像上传目录 // AvatarUploadDir 返回头像上传目录
func (c *Config) AvatarUploadDir() string { func (c *Config) AvatarUploadDir() string {
return filepath.Join(c.DataDir, "uploads", "avatars") return filepath.Join(c.DataDir, "uploads", "avatars")

View File

@@ -8,11 +8,12 @@ import (
// 容器 / 编排常用环境变量(优先级:命令行 > 环境变量 > app.ini > 内置默认) // 容器 / 编排常用环境变量(优先级:命令行 > 环境变量 > app.ini > 内置默认)
const ( const (
envWorkPath = "JIANG13_WORK_PATH" envWorkPath = "JIANG13_WORK_PATH"
envConfig = "JIANG13_CONFIG" envConfig = "JIANG13_CONFIG"
envHTTPPort = "JIANG13_HTTP_PORT" envHTTPPort = "JIANG13_HTTP_PORT"
envData = "JIANG13_DATA" envData = "JIANG13_DATA"
envJWTSecret = "JIANG13_JWT_SECRET" envJWTSecret = "JIANG13_JWT_SECRET"
envCommunityHub = "JIANG13_COMMUNITY_HUB"
) )
func envOrDefault(key string) string { func envOrDefault(key string) string {
@@ -30,3 +31,21 @@ func envIntOrZero(key string) int {
} }
return n 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

@@ -18,9 +18,10 @@ const (
// fileSettings 从 app.ini 读出的原始值(尚未解析为绝对路径) // fileSettings 从 app.ini 读出的原始值(尚未解析为绝对路径)
type fileSettings struct { type fileSettings struct {
Port int Port int
DataRel string DataRel string
JWTSecret string JWTSecret string
CommunityHub bool // 维护者选项:是否作为社区枢纽收报
} }
func defaultFileSettings() fileSettings { func defaultFileSettings() fileSettings {
@@ -62,6 +63,12 @@ func loadAppINI(path string) (fileSettings, error) {
out.JWTSecret = strings.TrimSpace(sec.Key("JWT_SECRET").String()) 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 return out, nil
} }

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) 若站务区希望不止一篇,见 [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
网站监控的地理信息与口径更准确。
- 补全 IP2LocationIP 地理位置库)中国城市中文名,同名城市按省消歧
- 对齐监控概览「双通道」口径文案与诊断抽样说明
## 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

@@ -14,9 +14,10 @@ import (
var staticFS embed.FS var staticFS embed.FS
var ( var (
spaTitleRe = regexp.MustCompile(`(?s)<title>.*?</title>`) spaTitleRe = regexp.MustCompile(`(?s)<title>.*?</title>`)
spaBrandTitleFn func() string spaBrandTitleFn func() string
spaBrandJSONFn func() []byte // 站点品牌 JSON注入 window.__J13_BRANDING__ spaBrandJSONFn func() []byte // 站点品牌 JSON注入 window.__J13_BRANDING__
spaBrandFaviconFn func() string // 站点 Favicon URL注入 <link rel="icon">
) )
// SetSPADocumentTitle 注册站点标题提供者ServeSPA 会注入到入口 HTML避免刷新闪烁 // SetSPADocumentTitle 注册站点标题提供者ServeSPA 会注入到入口 HTML避免刷新闪烁
@@ -29,13 +30,19 @@ func SetSPABrandingJSON(fn func() []byte) {
spaBrandJSONFn = fn spaBrandJSONFn = fn
} }
// SetSPAFaviconURL 注册 Favicon URL 提供者,注入到入口 HTML 的 <link rel="icon">
func SetSPAFaviconURL(fn func() string) {
spaBrandFaviconFn = fn
}
// SetupEmbed 配置内嵌资源React SPA 静态资源 // SetupEmbed 配置内嵌资源React SPA 静态资源
func SetupEmbed(r *gin.Engine) error { func SetupEmbed(r *gin.Engine) error {
if sub, err := fs.Sub(staticFS, "static/spa/assets"); err == nil { if sub, err := fs.Sub(staticFS, "static/spa/assets"); err == nil {
fileServer := http.StripPrefix("/assets", http.FileServer(http.FS(sub))) fileServer := http.StripPrefix("/assets", http.FileServer(http.FS(sub)))
r.GET("/assets/*filepath", func(c *gin.Context) { r.GET("/assets/*filepath", func(c *gin.Context) {
// hashed 资源可长期缓存;发版后文件名变更,旧 URL 自然 404 // 仅 200 写 immutable避免中间层把旧 chunk 的 404 长期缓存
c.Header("Cache-Control", "public, max-age=31536000, immutable") w := &cacheOnOKWriter{ResponseWriter: c.Writer, cacheControl: "public, max-age=31536000, immutable"}
c.Writer = w
fileServer.ServeHTTP(c.Writer, c.Request) fileServer.ServeHTTP(c.Writer, c.Request)
}) })
} }
@@ -51,6 +58,30 @@ func SetupEmbed(r *gin.Engine) error {
return nil 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 入口(仅注入站点默认标题) // ServeSPA 返回 React SPA 入口(仅注入站点默认标题)
func ServeSPA(c *gin.Context) { func ServeSPA(c *gin.Context) {
ServeSPAWithMeta(c, nil) ServeSPAWithMeta(c, nil)

View File

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

View File

@@ -5,23 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="description" content="拾三一隅,自在交流" /> <meta name="description" content="拾三一隅,自在交流" />
<title>姜十三论坛 - 拾三一隅,自在交流</title> <title>姜十三论坛 - 拾三一隅,自在交流</title>
<style> <!-- 样式由 Vite 构建注入外链 CSS不在此内联 style -->
/* 关键布局样式:在 JS/CSS 包加载前即固定三栏结构,避免刷新时组件错位 */
html { scrollbar-gutter: stable; }
html, body, #root { height: 100%; margin: 0; touch-action: pan-x pan-y; }
body { overflow: hidden; font-size: 14px; line-height: 1.5; }
.app-shell { height: 100%; max-height: 100dvh; display: flex; flex-direction: column; overflow: hidden; touch-action: pan-x pan-y; }
.app-frame { flex: 1; min-height: 0; height: 100%; max-width: 1400px; width: 100%; margin: 0 auto; display: flex; flex-direction: column; overflow: hidden; touch-action: pan-x pan-y; }
.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; touch-action: pan-x pan-y; }
.content-workspace { flex: 1; display: flex; min-width: 0; min-height: 0; overflow: hidden; touch-action: pan-x pan-y; }
.sidebar { width: 210px; flex-shrink: 0; }
.main-content { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: hidden; touch-action: pan-x pan-y; }
.aside-panel { width: 280px; flex-shrink: 0; }
@media (max-width: 1100px) { .aside-panel { display: none; } }
@media (max-width: 768px) { .sidebar { display: none; } }
</style>
<script> <script>
(function () { (function () {
var theme = localStorage.getItem('j13-theme') || 'light'; var theme = localStorage.getItem('j13-theme') || 'light';

View File

@@ -18,6 +18,8 @@
"@radix-ui/react-label": "^2.1.9", "@radix-ui/react-label": "^2.1.9",
"@radix-ui/react-slot": "^1.2.5", "@radix-ui/react-slot": "^1.2.5",
"@radix-ui/react-switch": "^1.3.0", "@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", "@tanstack/react-virtual": "^3.11.2",
"@tiptap/core": "^3.26.1", "@tiptap/core": "^3.26.1",
"@tiptap/extension-code-block": "^3.26.1", "@tiptap/extension-code-block": "^3.26.1",
@@ -49,7 +51,8 @@
"tailwindcss": "^3.4.19", "tailwindcss": "^3.4.19",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"turndown": "^7.2.4", "turndown": "^7.2.4",
"zod": "^4.4.3" "zod": "^4.4.3",
"zustand": "^4.5.7"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^25.9.3", "@types/node": "^25.9.3",
@@ -1971,6 +1974,18 @@
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==", "integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
"license": "MIT" "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": { "node_modules/@tanstack/react-virtual": {
"version": "3.14.2", "version": "3.14.2",
"resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.14.2.tgz", "resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.14.2.tgz",
@@ -4466,6 +4481,34 @@
"funding": { "funding": {
"url": "https://github.com/sponsors/colinhacks" "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

@@ -19,6 +19,8 @@
"@radix-ui/react-label": "^2.1.9", "@radix-ui/react-label": "^2.1.9",
"@radix-ui/react-slot": "^1.2.5", "@radix-ui/react-slot": "^1.2.5",
"@radix-ui/react-switch": "^1.3.0", "@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", "@tanstack/react-virtual": "^3.11.2",
"@tiptap/core": "^3.26.1", "@tiptap/core": "^3.26.1",
"@tiptap/extension-code-block": "^3.26.1", "@tiptap/extension-code-block": "^3.26.1",
@@ -50,7 +52,8 @@
"tailwindcss": "^3.4.19", "tailwindcss": "^3.4.19",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"turndown": "^7.2.4", "turndown": "^7.2.4",
"zod": "^4.4.3" "zod": "^4.4.3",
"zustand": "^4.5.7"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^25.9.3", "@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"
)
// 内联 SVGpath 对齐 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 += '// 板块图标 pathkey 对齐 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 AuthPageFallback from './components/AuthPageFallback';
import { Toaster } from './components/ui/sonner'; import { Toaster } from './components/ui/sonner';
import PullToRefresh from './components/PullToRefresh'; import PullToRefresh from './components/PullToRefresh';
import TopProgressBar from './components/TopProgressBar';
import { lazyWithRetry } from './utils/lazyWithRetry'; import { lazyWithRetry } from './utils/lazyWithRetry';
const HomePage = lazyWithRetry(() => import('./pages/HomePage')); const HomePage = lazyWithRetry(() => import('./pages/HomePage'));
@@ -32,6 +33,7 @@ const FavoritesPage = lazyWithRetry(() => import('./pages/FavoritesPage'));
const MessagesPage = lazyWithRetry(() => import('./pages/MessagesPage')); const MessagesPage = lazyWithRetry(() => import('./pages/MessagesPage'));
const ProjectsPage = lazyWithRetry(() => import('./pages/ProjectsPage')); const ProjectsPage = lazyWithRetry(() => import('./pages/ProjectsPage'));
const LinksPage = lazyWithRetry(() => import('./pages/LinksPage')); const LinksPage = lazyWithRetry(() => import('./pages/LinksPage'));
const ShowcasePage = lazyWithRetry(() => import('./pages/ShowcasePage'));
const AdminDashboardPage = lazyWithRetry(() => import('./pages/admin/AdminDashboardPage')); const AdminDashboardPage = lazyWithRetry(() => import('./pages/admin/AdminDashboardPage'));
const AdminPostsPage = lazyWithRetry(() => import('./pages/admin/AdminPostsPage')); const AdminPostsPage = lazyWithRetry(() => import('./pages/admin/AdminPostsPage'));
const AdminCommentsPage = lazyWithRetry(() => import('./pages/admin/AdminCommentsPage')); const AdminCommentsPage = lazyWithRetry(() => import('./pages/admin/AdminCommentsPage'));
@@ -39,11 +41,13 @@ const AdminReportsPage = lazyWithRetry(() => import('./pages/admin/AdminReportsP
const AdminUsersPage = lazyWithRetry(() => import('./pages/admin/AdminUsersPage')); const AdminUsersPage = lazyWithRetry(() => import('./pages/admin/AdminUsersPage'));
const AdminBadgesPage = lazyWithRetry(() => import('./pages/admin/AdminBadgesPage')); const AdminBadgesPage = lazyWithRetry(() => import('./pages/admin/AdminBadgesPage'));
const AdminMediaPage = lazyWithRetry(() => import('./pages/admin/AdminMediaPage')); const AdminMediaPage = lazyWithRetry(() => import('./pages/admin/AdminMediaPage'));
const AdminMonitorPage = lazyWithRetry(() => import('./pages/admin/AdminMonitorPage'));
const AdminPagesPage = lazyWithRetry(() => import('./pages/admin/AdminPagesPage')); const AdminPagesPage = lazyWithRetry(() => import('./pages/admin/AdminPagesPage'));
const AdminSitePageEditPage = lazyWithRetry(() => import('./pages/admin/AdminSitePageEditPage')); const AdminSitePageEditPage = lazyWithRetry(() => import('./pages/admin/AdminSitePageEditPage'));
const AdminLinksPage = lazyWithRetry(() => import('./pages/admin/AdminLinksPage')); const AdminLinksPage = lazyWithRetry(() => import('./pages/admin/AdminLinksPage'));
const SitePageView = lazyWithRetry(() => import('./pages/SitePageView')); const SitePageView = lazyWithRetry(() => import('./pages/SitePageView'));
const AdminSettingsPage = lazyWithRetry(() => import('./pages/admin/AdminSettingsPage')); const AdminSettingsPage = lazyWithRetry(() => import('./pages/admin/AdminSettingsPage'));
const AdminCommunityPage = lazyWithRetry(() => import('./pages/admin/AdminCommunityPage'));
const NotFoundPage = lazyWithRetry(() => import('./pages/NotFoundPage')); const NotFoundPage = lazyWithRetry(() => import('./pages/NotFoundPage'));
const router = createBrowserRouter( const router = createBrowserRouter(
@@ -61,12 +65,14 @@ const router = createBrowserRouter(
<Route path="pages/:id/edit" 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="pages" element={<Suspense fallback={<PageLoader />}><AdminPagesPage /></Suspense>} />
<Route path="links" element={<Suspense fallback={<PageLoader />}><AdminLinksPage /></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="posts" element={<Suspense fallback={<PageLoader />}><AdminPostsPage /></Suspense>} />
<Route path="comments" element={<Suspense fallback={<PageLoader />}><AdminCommentsPage /></Suspense>} /> <Route path="comments" element={<Suspense fallback={<PageLoader />}><AdminCommentsPage /></Suspense>} />
<Route path="reports" element={<Suspense fallback={<PageLoader />}><AdminReportsPage /></Suspense>} /> <Route path="reports" element={<Suspense fallback={<PageLoader />}><AdminReportsPage /></Suspense>} />
<Route path="users" element={<Suspense fallback={<PageLoader />}><AdminUsersPage /></Suspense>} /> <Route path="users" element={<Suspense fallback={<PageLoader />}><AdminUsersPage /></Suspense>} />
<Route path="badges" element={<Suspense fallback={<PageLoader />}><AdminBadgesPage /></Suspense>} /> <Route path="badges" element={<Suspense fallback={<PageLoader />}><AdminBadgesPage /></Suspense>} />
<Route path="media" element={<Suspense fallback={<PageLoader />}><AdminMediaPage /></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="settings" element={<Suspense fallback={<PageLoader />}><AdminSettingsPage /></Suspense>} />
<Route path="*" element={<Suspense fallback={<PageLoader />}><NotFoundPage title="后台页面不存在" /></Suspense>} /> <Route path="*" element={<Suspense fallback={<PageLoader />}><NotFoundPage title="后台页面不存在" /></Suspense>} />
</Route> </Route>
@@ -82,9 +88,10 @@ const router = createBrowserRouter(
<Route path="/favorites" element={<FavoritesPage />} /> <Route path="/favorites" element={<FavoritesPage />} />
<Route path="/projects" element={<ProjectsPage />} /> <Route path="/projects" element={<ProjectsPage />} />
<Route path="/links" element={<LinksPage />} /> <Route path="/links" element={<LinksPage />} />
<Route path="/showcase" element={<Suspense fallback={null}><ShowcasePage /></Suspense>} />
<Route path="/messages" element={<MessagesPage />} /> <Route path="/messages" element={<MessagesPage />} />
<Route path="/page/:slug" element={<Suspense fallback={<PageLoader />}><SitePageView /></Suspense>} /> <Route path="/page/:slug" element={<Suspense fallback={null}><SitePageView /></Suspense>} />
<Route path="*" element={<Suspense fallback={<PageLoader />}><NotFoundPage /></Suspense>} /> <Route path="*" element={<Suspense fallback={null}><NotFoundPage /></Suspense>} />
</Route> </Route>
<Route path="*" element={<Suspense fallback={<PageLoader fullScreen />}><NotFoundPage standalone /></Suspense>} /> <Route path="*" element={<Suspense fallback={<PageLoader fullScreen />}><NotFoundPage standalone /></Suspense>} />
</Route>, </Route>,
@@ -97,6 +104,7 @@ export default function App() {
<AuthProvider> <AuthProvider>
<ErrorBoundary> <ErrorBoundary>
<RouterProvider router={router} /> <RouterProvider router={router} />
<TopProgressBar />
<PullToRefresh /> <PullToRefresh />
<Toaster /> <Toaster />
</ErrorBoundary> </ErrorBoundary>

View File

@@ -1,4 +1,4 @@
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 } 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 = ''; const BASE = '';
@@ -25,6 +25,27 @@ export const api = {
me: () => request<{ user: User | null }>('/api/me'), me: () => request<{ user: User | null }>('/api/me'),
stats: () => request<ForumStats>('/api/stats'), stats: () => request<ForumStats>('/api/stats'),
forumLimits: () => request<ForumLimitsPublic>('/api/forum-limits'), 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'), siteBranding: () => request<SiteBranding>('/api/site-branding'),
pages: () => request<{ pages: SitePageSummary[] }>('/api/pages'), pages: () => request<{ pages: SitePageSummary[] }>('/api/pages'),
page: (slug: string) => request<{ page: SitePage }>(`/api/pages/${encodeURIComponent(slug)}`), page: (slug: string) => request<{ page: SitePage }>(`/api/pages/${encodeURIComponent(slug)}`),
@@ -63,6 +84,59 @@ export const api = {
// 管理后台 API // 管理后台 API
adminDashboard: () => request<AdminDashboard>('/api/admin/dashboard'), adminDashboard: () => request<AdminDashboard>('/api/admin/dashboard'),
adminSettings: () => request<AdminSettings>('/api/admin/settings'), 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 }) => { adminPosts: (params: { page?: number; keyword?: string; status?: string }) => {
const q = new URLSearchParams(); const q = new URLSearchParams();
if (params.page) q.set('page', String(params.page)); if (params.page) q.set('page', String(params.page));
@@ -345,6 +419,14 @@ export const api = {
fd.append('image', file); fd.append('image', file);
return request<{ url: string }>('/api/uploads/image', { method: 'POST', body: fd, headers: {} }); return request<{ url: string }>('/api/uploads/image', { method: 'POST', body: fd, headers: {} });
}, },
/** 当前用户历史上传的帖子图片 */
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: { createPost: (data: {
board_id: string; title: string; content: string; tags?: string; post_type?: string; board_id: string; title: string; content: string; tags?: string; post_type?: string;
poll_options?: string; bounty_points?: number; lottery_winner_count?: number; poll_options?: string; bounty_points?: number; lottery_winner_count?: number;
@@ -582,6 +664,8 @@ export const api = {
}, },
markNotificationsRead: () => markNotificationsRead: () =>
request<{ message: string }>('/api/messages/notifications/read', { method: 'POST' }), 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 }) => sendMessage: (body: { to_user_id: number; subject?: string; content: string }) =>
request<{ message: PrivateMessage }>('/api/messages', { request<{ message: PrivateMessage }>('/api/messages', {
method: 'POST', body: JSON.stringify(body), method: 'POST', body: JSON.stringify(body),

View File

@@ -179,6 +179,14 @@ export interface Comment {
reply_target?: Comment; reply_target?: Comment;
} }
export interface AdminDashboardTraffic {
enabled: boolean;
today_pv: number;
today_uv: number;
yesterday_pv: number;
total_pv: number;
}
export interface AdminDashboard { export interface AdminDashboard {
users: number; users: number;
posts: number; posts: number;
@@ -189,9 +197,10 @@ export interface AdminDashboard {
pending_reports?: number; pending_reports?: number;
pending_friend_links?: number; pending_friend_links?: number;
recent_posts: PostItem[]; recent_posts: PostItem[];
traffic?: AdminDashboardTraffic;
} }
export type AsideWidgetId = 'tag_cloud' | 'recent_comments' | 'recent_users' | 'friend_links'; export type AsideWidgetId = 'tag_cloud' | 'recent_comments' | 'recent_users' | 'friend_links' | 'showcase';
export interface AsideWidget { export interface AsideWidget {
id: AsideWidgetId; id: AsideWidgetId;
@@ -203,6 +212,21 @@ export const DEFAULT_ASIDE_WIDGETS: AsideWidget[] = [
{ id: 'recent_comments', enabled: false }, { id: 'recent_comments', enabled: false },
{ id: 'recent_users', enabled: false }, { id: 'recent_users', enabled: false },
{ id: 'friend_links', enabled: true }, { 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 { export interface ForumLimits {
@@ -231,14 +255,22 @@ export interface ForumLimits {
aside_show_recent_comments: boolean; aside_show_recent_comments: boolean;
/** 右侧栏友情链接 */ /** 右侧栏友情链接 */
aside_show_friend_links: boolean; aside_show_friend_links: boolean;
/** 右侧栏开源展柜 */
aside_show_showcase: boolean;
/** 右侧栏可选组件顺序与开关 */ /** 右侧栏可选组件顺序与开关 */
aside_widgets: AsideWidget[]; aside_widgets: AsideWidget[];
/** 左侧栏「站点」展示友情链接入口 */ /** 左侧栏「站点」展示友情链接入口 */
nav_show_friend_links: boolean; nav_show_friend_links: boolean;
/** 页脚展示友情链接入口 */ /** 页脚展示友情链接入口 */
footer_show_friend_links: boolean; footer_show_friend_links: boolean;
/** 左侧栏「站点」展示开源展柜入口 */
nav_show_showcase: boolean;
/** 页脚展示开源展柜入口 */
footer_show_showcase: boolean;
/** 首页列表样式title 仅标题 / thumbnail 缩略图 */ /** 首页列表样式title 仅标题 / thumbnail 缩略图 */
feed_list_style: 'title' | 'excerpt' | 'thumbnail'; feed_list_style: 'title' | 'excerpt' | 'thumbnail';
/** 首页排序标签:名称、顺序、启停 */
feed_sort_tabs: FeedSortTab[];
/** 伪静态(固定链接)开关 */ /** 伪静态(固定链接)开关 */
permalink_enabled: boolean; permalink_enabled: boolean;
/** 伪静态后缀,不含点,如 html / htm */ /** 伪静态后缀,不含点,如 html / htm */
@@ -262,12 +294,18 @@ export interface ForumLimitsPublic {
aside_show_tag_cloud: boolean; aside_show_tag_cloud: boolean;
aside_show_recent_comments: boolean; aside_show_recent_comments: boolean;
aside_show_friend_links: boolean; aside_show_friend_links: boolean;
aside_show_showcase: boolean;
aside_widgets: AsideWidget[]; aside_widgets: AsideWidget[];
nav_show_friend_links: boolean; nav_show_friend_links: boolean;
footer_show_friend_links: boolean; footer_show_friend_links: boolean;
nav_show_showcase: boolean;
footer_show_showcase: boolean;
feed_list_style: 'title' | 'excerpt' | 'thumbnail'; feed_list_style: 'title' | 'excerpt' | 'thumbnail';
feed_sort_tabs: FeedSortTab[];
permalink_enabled: boolean; permalink_enabled: boolean;
permalink_ext: string; permalink_ext: string;
/** 是否上报前台路由 pageview与后台监控采集开关同步 */
monitor_pageview: boolean;
} }
export interface FriendLink { export interface FriendLink {
@@ -376,10 +414,148 @@ export interface AdminSettings {
gitea?: GiteaSyncConfig; gitea?: GiteaSyncConfig;
storage?: StorageConfig; storage?: StorageConfig;
branding?: SiteBranding; branding?: SiteBranding;
community?: CommunityConfig;
filter_words: string; filter_words: string;
filter_word_count: number; 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 { export interface StorageConfig {
type: 'local' | 's3'; type: 'local' | 's3';
endpoint: string; endpoint: string;
@@ -541,9 +717,13 @@ export interface PrivateMessage {
to_user_id: number; to_user_id: number;
subject: string; subject: string;
content: 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_post_id?: number;
related_report_id?: number; related_report_id?: number;
related_comment_id?: number;
related_floor?: number;
/** 待审目标实时状态pending|published|rejected|deleted */
related_status?: string;
is_read: boolean; is_read: boolean;
created_at: string; created_at: string;
from_user?: User; from_user?: User;

View File

@@ -1,5 +1,6 @@
import { import {
useRef, useEffect, useImperativeHandle, forwardRef, useCallback, useState, useMemo, type ReactNode, useRef, useEffect, useImperativeHandle, forwardRef, useCallback, useState, useMemo,
type ReactNode, type Ref,
} from 'react'; } from 'react';
import { useEditor, EditorContent, type Editor } from '@tiptap/react'; import { useEditor, EditorContent, type Editor } from '@tiptap/react';
import { TextSelection, NodeSelection } from '@tiptap/pm/state'; import { TextSelection, NodeSelection } from '@tiptap/pm/state';
@@ -31,16 +32,19 @@ import {
insertMarkdownLink, insertMarkdownLink,
} from '../utils/markdownFormat'; } from '../utils/markdownFormat';
import { countWords } from '../utils/text'; import { countWords } from '../utils/text';
import { api } from '../api/client';
import { notify } from '@/lib/notify'; import { notify } from '@/lib/notify';
import { MembersOnly } from './editor/MembersOnlyExtension'; import { MembersOnly } from './editor/MembersOnlyExtension';
import { ReplyOnly } from './editor/ReplyOnlyExtension'; import { ReplyOnly } from './editor/ReplyOnlyExtension';
import { PointsOnly } from './editor/PointsOnlyExtension'; import { PointsOnly } from './editor/PointsOnlyExtension';
import { TabIndent } from './editor/TabIndentExtension'; import { TabIndent } from './editor/TabIndentExtension';
import { ArticleImage, type ImageDisplay } from './editor/ArticleImageExtension'; import { ArticleImage, type ImageDisplay } from './editor/ArticleImageExtension';
import { ArticleSticker } from './editor/ArticleStickerExtension';
import { ImageGroup, suggestImageGroupLayout } from './editor/ImageGroupExtension'; import { ImageGroup, suggestImageGroupLayout } from './editor/ImageGroupExtension';
import StickerPicker from './emoji/StickerPicker';
import type { Sticker } from '../data/stickers';
import { ClearFloatParagraph, ClearFloatSync } from './editor/ClearFloatParagraph'; 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 { ArticleCodeBlockDialog } from './editor/ArticleCodeBlockDialog';
import { ArticleCodeBlock } from './editor/ArticleCodeBlockExtension'; import { ArticleCodeBlock } from './editor/ArticleCodeBlockExtension';
import { import {
@@ -73,6 +77,7 @@ interface Props {
type EditorMode = 'rich' | 'markdown'; type EditorMode = 'rich' | 'markdown';
type LinkTarget = 'rich' | 'markdown'; type LinkTarget = 'rich' | 'markdown';
type ImagePickerTarget = 'rich' | 'markdown';
type CodeBlockTarget = 'rich' | 'markdown'; type CodeBlockTarget = 'rich' | 'markdown';
type TableTarget = 'rich' | 'markdown'; type TableTarget = 'rich' | 'markdown';
@@ -83,6 +88,7 @@ interface ToolBtn {
align?: 'start' | 'center' | 'end'; align?: 'start' | 'center' | 'end';
active?: boolean; active?: boolean;
className?: string; className?: string;
buttonRef?: Ref<HTMLButtonElement>;
action: () => void; action: () => void;
} }
@@ -118,9 +124,17 @@ function sanitizeHtml(html: string): string {
return DOMPurify.sanitize(html, POST_CONTENT_PURIFY_CONFIG); return DOMPurify.sanitize(html, POST_CONTENT_PURIFY_CONFIG);
} }
/** 判断编辑器内容是否为空 */ /** 判断编辑器内容是否为空(纯贴纸/图片也算有内容) */
function isEditorEmpty(editor: Editor): boolean { function isEditorEmpty(editor: Editor): boolean {
return editor.state.doc.textContent.trim().length === 0; if (editor.state.doc.textContent.trim().length > 0) return false;
let hasMedia = false;
editor.state.doc.descendants((node) => {
if (node.type.name === 'image' || node.type.name === 'sticker' || node.type.name === 'imageGroup') {
hasMedia = true;
return false;
}
});
return !hasMedia;
} }
/** /**
@@ -167,34 +181,6 @@ function cycleHeading(editor: Editor) {
editor.chain().focus().toggleHeading({ level: 2 }).run(); 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[]) { function renderToolButtons(tools: ToolBtn[]) {
return tools.map((t, i) => ( return tools.map((t, i) => (
@@ -204,10 +190,12 @@ function renderToolButtons(tools: ToolBtn[]) {
) : null} ) : null}
<Tooltip content={t.title} hint={t.hint} align={t.align} side="bottom"> <Tooltip content={t.title} hint={t.hint} align={t.align} side="bottom">
<button <button
ref={t.buttonRef}
type="button" type="button"
className={`article-tool-btn${t.active ? ' active' : ''}${t.className ? ` ${t.className}` : ''}`} className={`article-tool-btn${t.active ? ' active' : ''}${t.className ? ` ${t.className}` : ''}`}
onMouseDown={e => e.preventDefault()} onMouseDown={e => e.preventDefault()}
onClick={t.action} onClick={t.action}
aria-pressed={t.active || undefined}
> >
{t.icon} {t.icon}
</button> </button>
@@ -228,7 +216,11 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
const [markdownSource, setMarkdownSource] = useState(''); const [markdownSource, setMarkdownSource] = useState('');
const [linkDialogOpen, setLinkDialogOpen] = useState(false); const [linkDialogOpen, setLinkDialogOpen] = useState(false);
const [linkDialogUrl, setLinkDialogUrl] = useState(''); const [linkDialogUrl, setLinkDialogUrl] = useState('');
const [linkDialogText, setLinkDialogText] = useState('');
const [linkDialogEditing, setLinkDialogEditing] = useState(false);
const [linkTarget, setLinkTarget] = useState<LinkTarget>('rich'); const [linkTarget, setLinkTarget] = useState<LinkTarget>('rich');
const [imagePickerOpen, setImagePickerOpen] = useState(false);
const [imagePickerTarget, setImagePickerTarget] = useState<ImagePickerTarget>('rich');
const [codeBlockDialogOpen, setCodeBlockDialogOpen] = useState(false); const [codeBlockDialogOpen, setCodeBlockDialogOpen] = useState(false);
const [codeBlockTarget, setCodeBlockTarget] = useState<CodeBlockTarget>('rich'); const [codeBlockTarget, setCodeBlockTarget] = useState<CodeBlockTarget>('rich');
const [codeBlockEditing, setCodeBlockEditing] = useState(false); const [codeBlockEditing, setCodeBlockEditing] = useState(false);
@@ -236,7 +228,10 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
const [tableDialogOpen, setTableDialogOpen] = useState(false); const [tableDialogOpen, setTableDialogOpen] = useState(false);
const [tableTarget, setTableTarget] = useState<TableTarget>('rich'); const [tableTarget, setTableTarget] = useState<TableTarget>('rich');
const [tableEditing, setTableEditing] = useState(false); const [tableEditing, setTableEditing] = useState(false);
const [showSticker, setShowSticker] = useState(false);
const markdownRef = useRef<HTMLTextAreaElement>(null); const markdownRef = useRef<HTMLTextAreaElement>(null);
const editorBoxRef = useRef<HTMLDivElement>(null);
const stickerBtnRef = useRef<HTMLButtonElement>(null);
const editor = useEditor({ const editor = useEditor({
extensions: [ extensions: [
@@ -262,8 +257,14 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
openOnClick: false, openOnClick: false,
autolink: true, autolink: true,
defaultProtocol: 'https', defaultProtocol: 'https',
// 新标签由全站设置在展示层处理,编辑器不写 target/rel
HTMLAttributes: {
target: null,
rel: null,
},
}), }),
ArticleImage.configure({ inline: false, allowBase64: false }), ArticleImage.configure({ inline: false, allowBase64: false }),
ArticleSticker,
ImageGroup, ImageGroup,
Placeholder.configure({ Placeholder.configure({
placeholder: ({ node }) => { placeholder: ({ node }) => {
@@ -340,23 +341,42 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
placeCaretInFirstTextblock(editor); placeCaretInFirstTextblock(editor);
}, [value, editor, mode]); }, [value, editor, mode]);
// 全屏时锁定页面滚动Esc 退出 // 全屏时锁定页面滚动Esc 先关表情面板,再退出全屏
useEffect(() => { useEffect(() => {
if (!fullscreen) return undefined; if (!fullscreen && !showSticker) return undefined;
const prevOverflow = document.body.style.overflow; const prevOverflow = fullscreen ? document.body.style.overflow : null;
document.body.style.overflow = 'hidden'; if (fullscreen) document.body.style.overflow = 'hidden';
const onKeyDown = (e: KeyboardEvent) => { const onKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') setFullscreen(false); if (e.key !== 'Escape') return;
if (showSticker) {
setShowSticker(false);
stickerBtnRef.current?.focus();
return;
}
if (fullscreen) setFullscreen(false);
}; };
window.addEventListener('keydown', onKeyDown); window.addEventListener('keydown', onKeyDown);
return () => { return () => {
document.body.style.overflow = prevOverflow; if (prevOverflow !== null) document.body.style.overflow = prevOverflow;
window.removeEventListener('keydown', onKeyDown); window.removeEventListener('keydown', onKeyDown);
}; };
}, [fullscreen]); }, [fullscreen, showSticker]);
// 点击编辑器外关闭贴纸面板
useEffect(() => {
if (!showSticker) return;
const onPointer = (e: MouseEvent) => {
if (editorBoxRef.current && !editorBoxRef.current.contains(e.target as Node)) {
setShowSticker(false);
stickerBtnRef.current?.focus();
}
};
document.addEventListener('mousedown', onPointer);
return () => document.removeEventListener('mousedown', onPointer);
}, [showSticker]);
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
getHTML: () => { getHTML: () => {
@@ -393,14 +413,33 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
const openLinkDialog = useCallback((target: LinkTarget) => { const openLinkDialog = useCallback((target: LinkTarget) => {
if (target === 'rich') { if (target === 'rich') {
if (!editor) return; if (!editor) return;
const prev = editor.getAttributes('link').href as string | undefined; const { from, to, empty } = editor.state.selection;
setLinkDialogUrl(prev ?? ''); 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 { } else {
const textarea = markdownRef.current;
const selected = textarea
? markdownSource.slice(textarea.selectionStart, textarea.selectionEnd)
: '';
setLinkDialogUrl(''); setLinkDialogUrl('');
setLinkDialogText(selected);
setLinkDialogEditing(false);
} }
setLinkTarget(target); setLinkTarget(target);
setLinkDialogOpen(true); setLinkDialogOpen(true);
}, [editor]); }, [editor, markdownSource]);
const openCodeBlockDialog = useCallback((target: CodeBlockTarget) => { const openCodeBlockDialog = useCallback((target: CodeBlockTarget) => {
setCodeBlockTarget(target); setCodeBlockTarget(target);
@@ -477,11 +516,12 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
} }
}, [editor]); }, [editor]);
const applyLink = useCallback((url: string) => { const applyLink = useCallback((payload: ArticleLinkConfirm) => {
const { url, text } = payload;
if (linkTarget === 'markdown') { if (linkTarget === 'markdown') {
const textarea = markdownRef.current; const textarea = markdownRef.current;
if (!textarea || !url) return; if (!textarea || !url) return;
insertMarkdownLink(textarea, markdownSource, url, handleMarkdownChange); insertMarkdownLink(textarea, markdownSource, url, handleMarkdownChange, { text });
return; return;
} }
if (!editor) return; if (!editor) return;
@@ -489,7 +529,31 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
editor.chain().focus().extendMarkRange('link').unsetLink().run(); editor.chain().focus().extendMarkRange('link').unsetLink().run();
return; 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]); }, [editor, linkTarget, markdownSource, handleMarkdownChange]);
const removeLink = useCallback(() => { const removeLink = useCallback(() => {
@@ -497,16 +561,57 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
editor.chain().focus().extendMarkRange('link').unsetLink().run(); editor.chain().focus().extendMarkRange('link').unsetLink().run();
}, [editor]); }, [editor]);
const setImage = useCallback(async () => { const insertSticker = useCallback((sticker: Sticker) => {
if (mode === 'markdown') {
const textarea = markdownRef.current;
if (!textarea) return;
const snippet = (sticker.type === 'text' && sticker.text)
? sticker.text
: (sticker.url ? `![${sticker.name || '表情'}](${sticker.url})` : '');
if (!snippet) return;
insertAtCursor(textarea, markdownSource, snippet, handleMarkdownChange);
setShowSticker(false);
return;
}
if (!editor) return; if (!editor) return;
const urls = await uploadPostImageFiles(true); if (sticker.type === 'text' && sticker.text) {
editor.chain().focus().insertContent(sticker.text).run();
} else if (sticker.url) {
editor.chain().focus().insertContent([
{ type: 'sticker', attrs: { src: sticker.url, alt: sticker.name } },
{ type: 'text', text: ' ' },
]).run();
}
setShowSticker(false);
}, [editor, mode, markdownSource, handleMarkdownChange]);
const openImagePicker = useCallback((target: ImagePickerTarget) => {
setImagePickerTarget(target);
setImagePickerOpen(true);
}, []);
const applyImageUrls = useCallback((urls: string[]) => {
if (!urls.length) return; 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) { if (urls.length === 1) {
editor.chain().focus().setImage({ src: urls[0] }).run(); editor.chain().focus().setImage({ src: urls[0] }).run();
return; return;
} }
editor.chain().focus().insertImageGroup(urls, suggestImageGroupLayout(urls.length)).run(); editor.chain().focus().insertImageGroup(urls, suggestImageGroupLayout(urls.length)).run();
}, [editor]); }, [editor, imagePickerTarget, markdownSource, handleMarkdownChange]);
const setImageDisplay = useCallback((display: ImageDisplay) => { const setImageDisplay = useCallback((display: ImageDisplay) => {
if (!editor) return; if (!editor) return;
@@ -571,6 +676,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
const html = sanitizeHtml(editor.getHTML()); const html = sanitizeHtml(editor.getHTML());
lastValueRef.current = html; lastValueRef.current = html;
setMarkdownSource(htmlToMarkdown(html)); setMarkdownSource(htmlToMarkdown(html));
setShowSticker(false);
setMode('markdown'); setMode('markdown');
}, [editor]); }, [editor]);
@@ -583,6 +689,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
editor.commands.setContent(html || '', { emitUpdate: false }); editor.commands.setContent(html || '', { emitUpdate: false });
placeCaretInFirstTextblock(editor); placeCaretInFirstTextblock(editor);
} }
setShowSticker(false);
setMode('rich'); setMode('rich');
}, [editor, markdownSource, onChange]); }, [editor, markdownSource, onChange]);
@@ -596,21 +703,6 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
fn(textarea, markdownSource, handleMarkdownChange); fn(textarea, markdownSource, handleMarkdownChange);
}, [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( const markdownPreviewHtml = useMemo(
() => sanitizeHtml(markdownToHtml(markdownSource)), () => sanitizeHtml(markdownToHtml(markdownSource)),
[markdownSource], [markdownSource],
@@ -637,9 +729,9 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
{ icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: () => openLinkDialog('rich') }, { icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: () => openLinkDialog('rich') },
{ {
icon: <ImageIcon size={15} />, icon: <ImageIcon size={15} />,
title: '上传图片', title: '图片',
hint: '可多选;多张自动并排成图组', hint: '上传、链接或从已上传中选择',
action: setImage, action: () => openImagePicker('rich'),
}, },
{ {
icon: <Columns2 size={15} />, icon: <Columns2 size={15} />,
@@ -648,6 +740,15 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
active: groupActive, active: groupActive,
action: wrapSelectedAsGroup, action: wrapSelectedAsGroup,
}, },
{
icon: <span className="article-tool-btn__owo">OwO</span>,
title: '表情 OwO',
hint: '插入贴纸或颜文字',
active: showSticker,
className: 'article-tool-btn--owo',
buttonRef: stickerBtnRef,
action: () => setShowSticker(v => !v),
},
]; ];
if (editor.isActive('table')) { if (editor.isActive('table')) {
@@ -732,7 +833,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
} }
return tools; return tools;
}, [editor, enableContentGates, openLinkDialog, openCodeBlockDialog, openTableDialog, setImage, wrapMembersOnly, wrapReplyOnly, wrapPointsOnly, wrapSelectedAsGroup, setImageDisplay]); }, [editor, enableContentGates, showSticker, openLinkDialog, openCodeBlockDialog, openTableDialog, openImagePicker, wrapMembersOnly, wrapReplyOnly, wrapPointsOnly, wrapSelectedAsGroup, setImageDisplay]);
const buildMarkdownTools = useCallback((): ToolBtn[] => { const buildMarkdownTools = useCallback((): ToolBtn[] => {
const tools: ToolBtn[] = [ const tools: ToolBtn[] = [
@@ -748,7 +849,21 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
{ icon: <Code size={15} />, title: '代码块', hint: '语言、行号与折叠', action: () => openCodeBlockDialog('markdown') }, { icon: <Code size={15} />, title: '代码块', hint: '语言、行号与折叠', action: () => openCodeBlockDialog('markdown') },
{ icon: <TableIcon size={15} />, title: '表格', hint: '插入 GFM 管道表', action: () => openTableDialog('markdown') }, { icon: <TableIcon size={15} />, title: '表格', hint: '插入 GFM 管道表', action: () => openTableDialog('markdown') },
{ icon: <LinkIcon size={15} />, title: '链接', action: () => openLinkDialog('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'),
},
{
icon: <span className="article-tool-btn__owo">OwO</span>,
title: '表情 OwO',
hint: '插入贴纸或颜文字',
active: showSticker,
className: 'article-tool-btn--owo',
buttonRef: stickerBtnRef,
action: () => setShowSticker(v => !v),
},
]; ];
if (enableContentGates) { if (enableContentGates) {
tools.push( tools.push(
@@ -776,7 +891,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
); );
} }
return tools; return tools;
}, [enableContentGates, withMarkdown, openLinkDialog, openCodeBlockDialog, openTableDialog, insertMarkdownImage]); }, [enableContentGates, showSticker, withMarkdown, openLinkDialog, openCodeBlockDialog, openTableDialog, openImagePicker]);
const tools = mode === 'rich' ? buildRichTools() : buildMarkdownTools(); const tools = mode === 'rich' ? buildRichTools() : buildMarkdownTools();
const words = mode === 'markdown' const words = mode === 'markdown'
@@ -784,12 +899,16 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
: (editor ? countWords(editor.getText()) : 0); : (editor ? countWords(editor.getText()) : 0);
return ( return (
<div className={`article-editor article-editor--${mode}${fullscreen ? ' article-editor--fullscreen' : ''}`}> <div
ref={editorBoxRef}
className={`article-editor article-editor--${mode}${fullscreen ? ' article-editor--fullscreen' : ''}`}
>
<div className="article-editor-bar"> <div className="article-editor-bar">
<div className="article-editor-tools"> <div className="article-editor-tools">
{renderToolButtons(tools)} {renderToolButtons(tools)}
</div> </div>
</div> </div>
{showSticker && <StickerPicker onSelect={insertSticker} />}
<div className="article-editor-body"> <div className="article-editor-body">
{mode === 'rich' ? ( {mode === 'rich' ? (
@@ -897,8 +1016,15 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
open={linkDialogOpen} open={linkDialogOpen}
onOpenChange={setLinkDialogOpen} onOpenChange={setLinkDialogOpen}
initialUrl={linkDialogUrl} initialUrl={linkDialogUrl}
initialText={linkDialogText}
editing={linkDialogEditing}
onConfirm={applyLink} onConfirm={applyLink}
onRemove={linkTarget === 'rich' && linkDialogUrl ? removeLink : undefined} onRemove={linkTarget === 'rich' && linkDialogEditing ? removeLink : undefined}
/>
<ArticleImagePickerDialog
open={imagePickerOpen}
onOpenChange={setImagePickerOpen}
onInsert={applyImageUrls}
/> />
<ArticleCodeBlockDialog <ArticleCodeBlockDialog
open={codeBlockDialogOpen} open={codeBlockDialogOpen}

View File

@@ -1,6 +1,5 @@
import { CalendarCheck, Check, Gift, Loader2 } from 'lucide-react'; import { CalendarCheck, Check, Gift, Loader2 } from 'lucide-react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { Skeleton } from '@/components/ui/skeleton';
import { useCheckIn } from '../hooks/useCheckIn'; import { useCheckIn } from '../hooks/useCheckIn';
import { useAuth } from '../hooks/useAuth'; import { useAuth } from '../hooks/useAuth';
import { loginPath } from '../utils/authRedirect'; import { loginPath } from '../utils/authRedirect';
@@ -8,8 +7,14 @@ import { loginPath } from '../utils/authRedirect';
/** 右侧栏首块底部:每日签到 */ /** 右侧栏首块底部:每日签到 */
export default function AsideCheckInStrip() { export default function AsideCheckInStrip() {
const nav = useNavigate(); const nav = useNavigate();
const { user } = useAuth(); const { user, loading: authLoading } = useAuth();
const { status, loading, busy, doCheckIn } = useCheckIn(); const { status, loading, busy, doCheckIn } = useCheckIn(!!user && !authLoading);
// 鉴权未完成且无种子:空白,避免访客签到卡闪一下再消失
// 有 SSR boot 时 loading 一开始就是 false
if (authLoading) {
return null;
}
if (!user) { if (!user) {
return ( return (
@@ -37,17 +42,14 @@ export default function AsideCheckInStrip() {
); );
} }
if (loading && !status) { // 登录用户status 未到齐前不渲染最终态
return ( if (loading || !status) {
<div className="widget-checkin" aria-busy="true" aria-label="签到加载中"> return null;
<Skeleton className="widget-checkin-skeleton" />
</div>
);
} }
const checkedIn = !!status?.checked_in; const checkedIn = !!status.checked_in;
const streak = status?.streak ?? 0; const streak = status.streak ?? 0;
const todayPoints = status?.today_points ?? 5; const todayPoints = status.today_points ?? 5;
const meta = checkedIn const meta = checkedIn
? (streak > 0 ? `连续 ${streak} 天 · 今日已获得 ${todayPoints} 积分` : `今日已获得 ${todayPoints} 积分`) ? (streak > 0 ? `连续 ${streak} 天 · 今日已获得 ${todayPoints} 积分` : `今日已获得 ${todayPoints} 积分`)

View File

@@ -1,15 +1,19 @@
import { useMemo, useCallback } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { api } from '../api/client'; import { api } from '../api/client';
import { renderCommentContent } from '../utils/content'; import { renderCommentContent } from '../utils/content';
import { handleMdCodeBlockUiClick } from '../utils/enhanceCodeBlocks';
import { userPath } from '../utils/userPath'; import { userPath } from '../utils/userPath';
import { notify } from '@/lib/notify';
interface Props { interface Props {
content: string; content: string;
} }
/** 渲染评论正文(支持正文内 @ 高亮与点击跳转) */ /** 渲染评论正文(支持正文内 @ 高亮、代码块阅读态与点击跳转) */
export default function CommentContent({ content }: Props) { export default function CommentContent({ content }: Props) {
const nav = useNavigate(); const nav = useNavigate();
const html = useMemo(() => renderCommentContent(content), [content]);
const openMention = async (name: string) => { const openMention = async (name: string) => {
try { try {
@@ -26,17 +30,29 @@ export default function CommentContent({ content }: Props) {
} }
}; };
const onClick = useCallback(async (e: React.MouseEvent) => {
try {
if (await handleMdCodeBlockUiClick(e.target)) {
e.preventDefault();
return;
}
} catch {
notify.error('复制失败');
return;
}
const el = (e.target as HTMLElement).closest('.mention') as HTMLElement | null;
if (!el) return;
const name = el.getAttribute('data-name');
if (!name) return;
e.preventDefault();
void openMention(name);
}, [nav]);
return ( return (
<div <div
className="floor-body" className="floor-body post-detail-content"
onClick={(e) => { onClick={(e) => { void onClick(e); }}
const el = (e.target as HTMLElement).closest('.mention') as HTMLElement | null;
if (!el) return;
const name = el.getAttribute('data-name');
if (!name) return;
e.preventDefault();
void openMention(name);
}}
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key !== 'Enter' && e.key !== ' ') return; if (e.key !== 'Enter' && e.key !== ' ') return;
const el = e.target as HTMLElement; const el = e.target as HTMLElement;
@@ -46,9 +62,7 @@ export default function CommentContent({ content }: Props) {
e.preventDefault(); e.preventDefault();
void openMention(name); void openMention(name);
}} }}
dangerouslySetInnerHTML={{ dangerouslySetInnerHTML={{ __html: html }}
__html: renderCommentContent(content),
}}
/> />
); );
} }

View File

@@ -12,11 +12,11 @@ import {
List, ListOrdered, Code, Link as LinkIcon, Image as ImageIcon, List, ListOrdered, Code, Link as LinkIcon, Image as ImageIcon,
} from 'lucide-react'; } from 'lucide-react';
import { POST_CONTENT_PURIFY_CONFIG } from '../utils/postContent'; import { POST_CONTENT_PURIFY_CONFIG } from '../utils/postContent';
import { api } from '../api/client';
import { notify } from '@/lib/notify';
import { ArticleCodeBlock } from './editor/ArticleCodeBlockExtension'; import { ArticleCodeBlock } from './editor/ArticleCodeBlockExtension';
import { ArticleCodeBlockDialog } from './editor/ArticleCodeBlockDialog'; import { ArticleCodeBlockDialog } from './editor/ArticleCodeBlockDialog';
import { ArticleImage } from './editor/ArticleImageExtension'; import { ArticleImage } from './editor/ArticleImageExtension';
import { ArticleImagePickerDialog } from './editor/ArticleImagePickerDialog';
import { ArticleLinkDialog, type ArticleLinkConfirm } from './editor/ArticleLinkDialog';
import { TabIndent } from './editor/TabIndentExtension'; import { TabIndent } from './editor/TabIndentExtension';
import type { CodeBlockInsertOptions } from '../utils/codeBlockOptions'; import type { CodeBlockInsertOptions } from '../utils/codeBlockOptions';
import { Tooltip } from './ui/Tooltip'; import { Tooltip } from './ui/Tooltip';
@@ -49,28 +49,6 @@ function isEditorEmpty(editor: Editor): boolean {
return !hasImage; 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( const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEditor(
{ value, onChange, placeholder = '说点什么吧…' }, { value, onChange, placeholder = '说点什么吧…' },
ref, ref,
@@ -79,6 +57,11 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
const lastValueRef = useRef(value); const lastValueRef = useRef(value);
const [, setTick] = useState(0); const [, setTick] = useState(0);
const [showSticker, setShowSticker] = useState(false); 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 [codeBlockDialogOpen, setCodeBlockDialogOpen] = useState(false);
const [codeBlockEditing, setCodeBlockEditing] = useState(false); const [codeBlockEditing, setCodeBlockEditing] = useState(false);
const [codeBlockInitial, setCodeBlockInitial] = useState<CodeBlockInsertOptions | null>(null); const [codeBlockInitial, setCodeBlockInitial] = useState<CodeBlockInsertOptions | null>(null);
@@ -99,6 +82,11 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
openOnClick: false, openOnClick: false,
autolink: true, autolink: true,
defaultProtocol: 'https', defaultProtocol: 'https',
// 新标签由全站设置在展示层处理,编辑器不写 target/rel
HTMLAttributes: {
target: null,
rel: null,
},
}), }),
ArticleImage.configure({ inline: true, allowBase64: true }), ArticleImage.configure({ inline: true, allowBase64: true }),
Placeholder.configure({ placeholder }), Placeholder.configure({ placeholder }),
@@ -179,11 +167,14 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
setShowSticker(false); setShowSticker(false);
}, [editor]); }, [editor]);
const setImage = useCallback(async () => { const applyImageUrls = useCallback((urls: string[]) => {
if (!editor) return; if (!editor || !urls.length) return;
const urls = await uploadImageFiles(); // 评论为 inline 图,无图组:逐张插入并跟空格,便于光标落在右侧
if (!urls.length) return; const nodes = urls.flatMap(src => [
editor.chain().focus().setImage({ src: urls[0] }).run(); { type: 'image' as const, attrs: { src } },
{ type: 'text' as const, text: ' ' },
]);
editor.chain().focus().insertContent(nodes).run();
}, [editor]); }, [editor]);
const openCodeBlockDialog = useCallback(() => { const openCodeBlockDialog = useCallback(() => {
@@ -213,23 +204,70 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
}).run(); }).run();
}, [editor]); }, [editor]);
const setLink = useCallback(() => { const openLinkDialog = useCallback(() => {
if (!editor) return; if (!editor) return;
const prev = editor.getAttributes('link').href as string | undefined; const { from, to, empty } = editor.state.selection;
const url = window.prompt('链接地址', prev ?? 'https://'); let text = empty ? '' : editor.state.doc.textBetween(from, to, '');
if (url === null) return; 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) { if (!url) {
editor.chain().focus().extendMarkRange('link').unsetLink().run(); editor.chain().focus().extendMarkRange('link').unsetLink().run();
return; 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]); }, [editor]);
if (!editor) { if (!editor) {
return <div className="comment-editor"><div className="article-editor-bar" /><div className="article-editor-body" /></div>; 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; className?: string }[] = [ 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: <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: <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: <UnderlineIcon size={15} />, title: '下划线', active: editor.isActive('underline'), action: () => editor.chain().focus().toggleUnderline().run() },
@@ -237,8 +275,13 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
{ icon: <List size={15} />, title: '无序列表', active: editor.isActive('bulletList'), action: () => editor.chain().focus().toggleBulletList().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: <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: <Code size={15} />, title: '代码块', active: editor.isActive('codeBlock'), action: openCodeBlockDialog },
{ icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: setLink }, { icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: openLinkDialog },
{ icon: <ImageIcon size={15} />, title: '上传图片', action: setImage }, {
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' }, { icon: <span className="article-tool-btn__owo">OwO</span>, title: '表情 OwO', active: showSticker, action: () => setShowSticker(v => !v), className: 'article-tool-btn--owo' },
]; ];
@@ -247,14 +290,14 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
<div className="article-editor-bar"> <div className="article-editor-bar">
<div className="article-editor-tools"> <div className="article-editor-tools">
{tools.map((t, i) => ( {tools.map((t, i) => (
<Tooltip key={i} content={t.title} side="bottom"> <Tooltip key={i} content={t.title} hint={t.hint} side="bottom">
<button <button
ref={i === tools.length - 1 ? stickerBtnRef : undefined} ref={i === tools.length - 1 ? stickerBtnRef : undefined}
type="button" type="button"
className={`article-tool-btn${t.active ? ' active' : ''}${t.className ? ` ${t.className}` : ''}`} className={`article-tool-btn${t.active ? ' active' : ''}${t.className ? ` ${t.className}` : ''}`}
onMouseDown={e => e.preventDefault()} onMouseDown={e => e.preventDefault()}
onClick={t.action} onClick={t.action}
aria-label={t.title} aria-label={t.hint ? `${t.title}${t.hint}` : t.title}
> >
{t.icon} {t.icon}
</button> </button>
@@ -268,6 +311,20 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
</div> </div>
</div> </div>
{showSticker && <StickerPicker onSelect={insertSticker} />} {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 <ArticleCodeBlockDialog
open={codeBlockDialogOpen} open={codeBlockDialogOpen}
onOpenChange={setCodeBlockDialogOpen} onOpenChange={setCodeBlockDialogOpen}

View File

@@ -18,7 +18,6 @@ import {
AlertDialogFooter, AlertDialogFooter,
AlertDialogHeader, AlertDialogHeader,
AlertDialogTitle, AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog'; } from '@/components/ui/alert-dialog';
import { import {
Dialog, Dialog,
@@ -32,6 +31,8 @@ import {
DropdownMenu, DropdownMenu,
DropdownMenuContent, DropdownMenuContent,
DropdownMenuItem, DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger, DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'; } from '@/components/ui/dropdown-menu';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -144,6 +145,11 @@ function CommentItem({
&& !!onApprove; && !!onApprove;
const showEdited = !hidden && !!c.updated_at && isTimeDiffSignificant(c.created_at, c.updated_at); const showEdited = !hidden && !!c.updated_at && isTimeDiffSignificant(c.created_at, c.updated_at);
const canReport = !hidden && !isEditing && !isCommentAuthor(c, currentUser); 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 [editText, setEditText] = useState(c.content);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [deleting, setDeleting] = useState(false); const [deleting, setDeleting] = useState(false);
@@ -152,6 +158,7 @@ function CommentItem({
const [liked, setLiked] = useState(!!c.liked); const [liked, setLiked] = useState(!!c.liked);
const [likeCount, setLikeCount] = useState(c.like_count ?? 0); const [likeCount, setLikeCount] = useState(c.like_count ?? 0);
const [revOpen, setRevOpen] = useState(false); const [revOpen, setRevOpen] = useState(false);
const [deleteOpen, setDeleteOpen] = useState(false);
const [reportOpen, setReportOpen] = useState(false); const [reportOpen, setReportOpen] = useState(false);
const [reportReason, setReportReason] = useState<ReportReason>('spam'); const [reportReason, setReportReason] = useState<ReportReason>('spam');
const [reportDetail, setReportDetail] = useState(''); const [reportDetail, setReportDetail] = useState('');
@@ -333,24 +340,6 @@ function CommentItem({
{c.reply_target && ( {c.reply_target && (
<span className="waline-reply-at">@{commentNick(c.reply_target)}</span> <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 && ( {!hidden && !isEditing && !!renderReplyBox && (
isReplying ? ( isReplying ? (
<button type="button" className="waline-comment-reply-btn cancel" onClick={onCancelReply}> <button type="button" className="waline-comment-reply-btn cancel" onClick={onCancelReply}>
@@ -366,12 +355,6 @@ function CommentItem({
</Tooltip> </Tooltip>
) )
)} )}
{!hidden && !isEditing && canEdit && (
<button type="button" className="waline-comment-reply-btn" onClick={() => onStartEdit(c)}>
<Pencil size={14} />
</button>
)}
{bountyAward?.open && bountyAward.canAward && c.user_id !== bountyAward.postAuthorId {bountyAward?.open && bountyAward.canAward && c.user_id !== bountyAward.postAuthorId
&& c.status === 'published' && !hidden && ( && c.status === 'published' && !hidden && (
<button <button
@@ -383,46 +366,7 @@ function CommentItem({
</button> </button>
)} )}
{!hidden && !isEditing && isAdmin && showEdited && ( {showManageMenu && (
<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);
}
}}
>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)}
{canReport && (
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
<button <button
@@ -433,19 +377,98 @@ function CommentItem({
<MoreHorizontal size={14} /> <MoreHorizontal size={14} />
</button> </button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="center" className="report-more-menu"> <DropdownMenuContent align="end" className="comment-manage-menu">
<DropdownMenuItem {showManageGroup && (
className="report-more-menu__item" <>
onSelect={openReport} <DropdownMenuLabel></DropdownMenuLabel>
> {canApprove && (
<Flag size={14} /> <DropdownMenuItem
disabled={approving}
</DropdownMenuItem> 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} aria-hidden />
</DropdownMenuItem>
)}
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
)} )}
</div> </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 && ( {isAdmin && (
<CommentRevisionDialog open={revOpen} onOpenChange={setRevOpen} comment={c} /> <CommentRevisionDialog open={revOpen} onOpenChange={setRevOpen} comment={c} />
)} )}

View File

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

View File

@@ -1,29 +0,0 @@
import { Skeleton } from '@/components/ui/skeleton';
import PostListSkeleton from './PostListSkeleton';
import { useForumLimits } from '../hooks/useForumLimits';
/** 首页 Feed 初始骨架(排序栏 + 列表) */
export default function FeedPageSkeleton() {
const { limits } = useForumLimits();
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-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 listStyle={limits.feed_list_style ?? 'title'} />
</div>
</div>
</div>
);
}

View File

@@ -1,39 +1,56 @@
import { useRef } from 'react'; import { useMemo, useRef } from 'react';
import { boardPath, type PermalinkOpts } from '../utils/permalink'; import { useParams, useSearchParams } from 'react-router-dom';
import { getCachedForumLimits } from '../hooks/useForumLimits'; import { boardPath, parsePermalinkID, type PermalinkOpts } from '../utils/permalink';
import { Clock, MessageCircle, Flame } from 'lucide-react'; import { getCachedForumLimits, useForumLimits } from '../hooks/useForumLimits';
import { Clock, MessageCircle, BadgeCheck, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { moveTabIndex } from '../hooks/useOverlayA11y'; import { moveTabIndex } from '../hooks/useOverlayA11y';
import {
enabledFeedSortTabs,
getDefaultFeedSort,
normalizeFeedSortTabs,
} from '../utils/feedSortTabs';
import type { FeedSortTab } from '../api/types';
export type FeedSort = 'latest' | 'reply' | 'hot'; export type FeedSort = 'latest' | 'reply' | 'hot';
const SORT_OPTIONS: { const SORT_META: Record<FeedSort, { hint: string; icon: typeof Clock }> = {
key: FeedSort; reply: { hint: '按最近活动(发帖或评论)', icon: MessageCircle },
label: string; latest: { hint: '按发帖时间', icon: Clock },
hint: string; hot: { hint: '仅展示推荐帖', icon: BadgeCheck },
icon: typeof Clock; };
}[] = [
{ key: 'latest', label: '最新发帖', hint: '按发布时间', icon: Clock },
{ key: 'reply', label: '最新回复', hint: '最近有人回复', icon: MessageCircle },
{ key: 'hot', label: '热门讨论', hint: '按互动热度', icon: Flame },
];
interface Props { interface Props {
value: FeedSort; value: FeedSort;
onChange: (sort: FeedSort) => void; onChange: (sort: FeedSort) => void;
postTotal?: number; postTotal?: number;
/** 正在加载、尚未提交到画面的目标排序 */
pendingValue?: FeedSort | null;
} }
export function parseFeedSort(raw: string | null): FeedSort { /** 当前配置下的默认排序(读缓存,供非 hook 路径) */
if (raw === 'reply' || raw === 'hot') return raw; export function getDefaultFeedSortFromCache(): FeedSort {
return 'latest'; 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( export function buildHomeUrl(
boardId: number, boardId: number,
sort: FeedSort = 'latest', sort?: FeedSort,
opts?: { keyword?: string; tag?: string; author?: string; titleOnly?: boolean; permalink?: PermalinkOpts }, opts?: { keyword?: string; tag?: string; author?: string; titleOnly?: boolean; permalink?: PermalinkOpts },
) { ) {
const def = getDefaultFeedSortFromCache();
const effective = sort ?? def;
const p = new URLSearchParams(); const p = new URLSearchParams();
const tag = opts?.tag?.trim(); const tag = opts?.tag?.trim();
const keyword = opts?.keyword?.trim(); const keyword = opts?.keyword?.trim();
@@ -47,7 +64,8 @@ export function buildHomeUrl(
} else if (author) { } else if (author) {
p.set('author', author); p.set('author', author);
} }
if (sort !== 'latest') p.set('sort', sort); // 默认排序不写进 URL
if (effective !== def) p.set('sort', effective);
const qs = p.toString(); const qs = p.toString();
if (boardId) { if (boardId) {
@@ -57,25 +75,65 @@ export function buildHomeUrl(
return qs ? `/?${qs}` : '/'; return qs ? `/?${qs}` : '/';
} }
export function feedSortLabel(sort: FeedSort): string { export function feedSortLabel(sort: FeedSort, tabs?: FeedSortTab[] | null): string {
return SORT_OPTIONS.find(o => o.key === sort)?.label ?? '帖子列表'; 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 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 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; if (next == null) return;
e.preventDefault(); e.preventDefault();
onChange(SORT_OPTIONS[next].key); onChange(options[next].key);
requestAnimationFrame(() => { requestAnimationFrame(() => {
const tabs = listRef.current?.querySelectorAll<HTMLElement>('[role="tab"]'); const tabs = listRef.current?.querySelectorAll<HTMLElement>('[role="tab"]');
tabs?.[next]?.focus(); tabs?.[next]?.focus();
}); });
}; };
if (options.length === 0) return null;
return ( return (
<div className="feed-toolbar"> <div className="feed-toolbar">
<div <div
@@ -85,21 +143,30 @@ export default function FeedSortBar({ value, onChange, postTotal }: Props) {
aria-label="帖子排序" aria-label="帖子排序"
onKeyDown={onKeyDown} onKeyDown={onKeyDown}
> >
{SORT_OPTIONS.map(({ key, label, hint, icon: Icon }, i) => ( {options.map(({ key, label, hint, icon: Icon, href }, i) => {
<button const pending = pendingValue === key;
key={key} return (
type="button" <a
role="tab" key={key}
tabIndex={activeIndex === i ? 0 : -1} href={href}
aria-selected={value === key} role="tab"
title={`${label} · ${hint}`} tabIndex={activeIndex === i ? 0 : -1}
className={cn('feed-sort-tab', value === key && 'active')} aria-selected={value === key}
onClick={() => onChange(key)} aria-busy={pending || undefined}
> title={`${label} · ${hint}`}
<Icon aria-hidden /> className={cn('feed-sort-tab', value === key && 'active', pending && 'is-pending')}
<span className="feed-sort-tab__label">{label}</span> onClick={(e) => {
</button> e.preventDefault();
))} onChange(key);
}}
>
{pending
? <Loader2 className="feed-sort-tab__spin" aria-hidden />
: <Icon aria-hidden />}
<span className="feed-sort-tab__label">{label}</span>
</a>
);
})}
</div> </div>
{postTotal != null && ( {postTotal != null && (
<span className="feed-toolbar__count"> {postTotal} </span> <span className="feed-toolbar__count"> {postTotal} </span>

View File

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

View File

@@ -0,0 +1,227 @@
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef } from 'react';
import type { Sticker } from '../data/stickers';
export type PmComposerInputHandle = {
insertSticker: (sticker: Sticker) => void;
insertText: (text: string) => void;
focus: () => void;
};
type Props = {
value: string;
onChange: (next: string) => void;
placeholder?: string;
maxLength?: number;
disabled?: boolean;
onSubmit?: () => void;
};
/** 站点内置贴纸路径(评论/私信共用) */
export function isPmStickerSrc(src: string) {
return src.includes('/stickers/');
}
function escapeHtml(s: string) {
return s
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function draftToHtml(text: string): string {
if (!text) return '';
const parts = text.split(/(!\[[^\]]*]\([^)]+\))/g);
return parts.map((part) => {
const m = part.match(/^!\[([^\]]*)]\(([^)]+)\)$/);
if (m) {
const alt = escapeHtml(m[1] || '表情');
const src = escapeHtml(m[2]);
const cls = isPmStickerSrc(m[2]) ? 'pm-composer__sticker' : 'pm-composer__inline-img';
return `<img class="${cls}" src="${src}" alt="${alt}" draggable="false">`;
}
return escapeHtml(part).replace(/\n/g, '<br>');
}).join('');
}
function serializeComposer(root: HTMLElement): string {
let out = '';
const walk = (node: Node) => {
if (node.nodeType === Node.TEXT_NODE) {
out += node.textContent || '';
return;
}
if (node.nodeType !== Node.ELEMENT_NODE) return;
const el = node as HTMLElement;
const tag = el.tagName;
if (tag === 'IMG') {
const src = el.getAttribute('src') || '';
const alt = el.getAttribute('alt') || '表情';
out += `![${alt}](${src})`;
return;
}
if (tag === 'BR') {
out += '\n';
return;
}
if (tag === 'DIV' || tag === 'P') {
if (out.length > 0 && !out.endsWith('\n')) out += '\n';
el.childNodes.forEach(walk);
return;
}
el.childNodes.forEach(walk);
};
root.childNodes.forEach(walk);
return out.replace(/\n$/, '');
}
function placeCaretAfter(node: Node) {
const sel = window.getSelection();
if (!sel) return;
const range = document.createRange();
range.setStartAfter(node);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
/** 私信输入框:可内联插入贴纸(与评论编辑器一致),序列化为 markdown 图片语法 */
const PmComposerInput = forwardRef<PmComposerInputHandle, Props>(function PmComposerInput(
{ value, onChange, placeholder, maxLength = 4000, disabled, onSubmit },
ref,
) {
const elRef = useRef<HTMLDivElement>(null);
const savedRangeRef = useRef<Range | null>(null);
const valueRef = useRef(value);
valueRef.current = value;
const emit = useCallback(() => {
const el = elRef.current;
if (!el) return;
const next = serializeComposer(el);
if (maxLength && next.length > maxLength) {
el.innerHTML = draftToHtml(valueRef.current);
return;
}
el.dataset.empty = next ? 'false' : 'true';
if (next !== valueRef.current) onChange(next);
}, [maxLength, onChange]);
const restoreRange = useCallback(() => {
const el = elRef.current;
if (!el) return;
el.focus();
const sel = window.getSelection();
if (!sel) return;
const saved = savedRangeRef.current;
if (saved && el.contains(saved.startContainer)) {
sel.removeAllRanges();
sel.addRange(saved);
return;
}
const range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
}, []);
const saveRange = useCallback(() => {
const el = elRef.current;
const sel = window.getSelection();
if (!el || !sel || sel.rangeCount === 0) return;
if (!el.contains(sel.anchorNode)) return;
savedRangeRef.current = sel.getRangeAt(0).cloneRange();
}, []);
const insertNodes = useCallback((nodes: Node[]) => {
const el = elRef.current;
if (!el || !nodes.length) return;
restoreRange();
const sel = window.getSelection();
if (!sel) return;
const range = sel.rangeCount > 0 ? sel.getRangeAt(0) : document.createRange();
range.deleteContents();
const frag = document.createDocumentFragment();
nodes.forEach((n) => frag.appendChild(n));
const last = nodes[nodes.length - 1];
range.insertNode(frag);
placeCaretAfter(last);
saveRange();
emit();
}, [emit, restoreRange, saveRange]);
useImperativeHandle(ref, () => ({
insertSticker(sticker) {
if (!sticker.url) return;
const img = document.createElement('img');
img.className = 'pm-composer__sticker';
img.src = sticker.url;
img.alt = sticker.name || '表情';
img.draggable = false;
// 尾随空格,光标可停在贴纸右侧(对齐评论编辑器)
insertNodes([img, document.createTextNode(' ')]);
},
insertText(text) {
if (!text) return;
insertNodes([document.createTextNode(text)]);
},
focus() {
restoreRange();
},
}), [insertNodes, restoreRange]);
// 外部改 value切会话 / 发送清空)时回填;输入过程中 serialize 与 value 一致则不重绘
useEffect(() => {
const el = elRef.current;
if (!el) return;
if (serializeComposer(el) === value) {
el.dataset.empty = value ? 'false' : 'true';
return;
}
el.innerHTML = draftToHtml(value);
el.dataset.empty = value ? 'false' : 'true';
}, [value]);
useEffect(() => {
const onSel = () => saveRange();
document.addEventListener('selectionchange', onSel);
return () => document.removeEventListener('selectionchange', onSel);
}, [saveRange]);
return (
<div
ref={elRef}
className="pm-composer__input"
role="textbox"
aria-multiline="true"
aria-label="私信内容"
contentEditable={!disabled}
data-placeholder={placeholder || ''}
data-empty={value ? 'false' : 'true'}
suppressContentEditableWarning
onInput={emit}
onBlur={saveRange}
onPaste={(e) => {
e.preventDefault();
const text = e.clipboardData.getData('text/plain');
if (text) insertNodes([document.createTextNode(text)]);
}}
onDrop={(e) => {
// 禁止把文件拖成「大图附件」;贴纸只走选择器
if (e.dataTransfer?.files?.length) e.preventDefault();
}}
onKeyDown={(e) => {
if (e.nativeEvent.isComposing) return;
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
onSubmit?.();
}
}}
/>
);
});
export default PmComposerInput;

View File

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

View File

@@ -1,7 +1,7 @@
import { useMemo, useCallback, useEffect, useState } from 'react'; import { useMemo, useCallback, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom'; import { useNavigate, useParams } from 'react-router-dom';
import { renderPostContentHtml } from '../utils/postContent'; import { renderPostContentHtml } from '../utils/postContent';
import { extractHeadingsFromHtml, type PostHeading } from '../utils/postHeadings'; import { handleMdCodeBlockUiClick } from '../utils/enhanceCodeBlocks';
import { loginPath, registerPath } from '../utils/authRedirect'; import { loginPath, registerPath } from '../utils/authRedirect';
import { useForumLimits } from '../hooks/useForumLimits'; import { useForumLimits } from '../hooks/useForumLimits';
import { notify } from '@/lib/notify'; import { notify } from '@/lib/notify';
@@ -12,8 +12,6 @@ interface Props {
html: string; html: string;
isLoggedIn: boolean; isLoggedIn: boolean;
className?: string; className?: string;
/** 正文标题树变化时回调(用于侧栏目录) */
onHeadingsChange?: (headings: PostHeading[]) => void;
/** 点击「回复可见」门控的「去回复」 */ /** 点击「回复可见」门控的「去回复」 */
onRequestReply?: () => void; onRequestReply?: () => void;
/** 积分解锁成功后刷新正文 */ /** 积分解锁成功后刷新正文 */
@@ -26,7 +24,6 @@ export default function PostContent({
html, html,
isLoggedIn, isLoggedIn,
className = 'post-detail-content', className = 'post-detail-content',
onHeadingsChange,
onRequestReply, onRequestReply,
onUnlocked, onUnlocked,
postId: postIdProp, postId: postIdProp,
@@ -39,19 +36,12 @@ export default function PostContent({
const [lightboxAlt, setLightboxAlt] = useState(''); const [lightboxAlt, setLightboxAlt] = useState('');
const [unlocking, setUnlocking] = useState(false); const [unlocking, setUnlocking] = useState(false);
const prepared = useMemo(() => { const preparedHtml = useMemo(
const rendered = renderPostContentHtml(html, isLoggedIn, { () => renderPostContentHtml(html, isLoggedIn, {
openLinksInNewTab: limits.open_content_links_in_new_tab, openLinksInNewTab: limits.open_content_links_in_new_tab,
}); }),
return { [html, isLoggedIn, limits.open_content_links_in_new_tab],
html: rendered, );
headings: extractHeadingsFromHtml(rendered),
};
}, [html, isLoggedIn, limits.open_content_links_in_new_tab]);
useEffect(() => {
onHeadingsChange?.(prepared.headings);
}, [prepared.headings, onHeadingsChange]);
const openLightbox = useCallback((img: HTMLImageElement) => { const openLightbox = useCallback((img: HTMLImageElement) => {
const full = img.getAttribute('data-full') || img.currentSrc || img.src; const full = img.getAttribute('data-full') || img.currentSrc || img.src;
@@ -116,40 +106,12 @@ export default function PostContent({
} }
return; return;
} }
const foldBtn = target.closest<HTMLElement>('[data-code-fold]'); try {
if (foldBtn) { if (await handleMdCodeBlockUiClick(target)) {
e.preventDefault(); e.preventDefault();
const block = foldBtn.closest('.md-codeblock');
if (!block) return;
const collapsed = block.classList.toggle('md-codeblock--collapsed');
const lineCount = parseInt(block.getAttribute('data-line-count') || '0', 10)
|| block.querySelectorAll('.md-code-line').length
|| 1;
if (collapsed && lineCount <= 5) block.classList.add('md-codeblock--short');
else block.classList.remove('md-codeblock--short');
foldBtn.textContent = collapsed ? '展开' : '收起';
return;
}
const copyBtn = target.closest<HTMLElement>('[data-code-copy]');
if (copyBtn) {
e.preventDefault();
const block = copyBtn.closest('.md-codeblock');
const bodies = block?.querySelectorAll('.md-code-line__body');
const text = bodies && bodies.length
? [...bodies].map(el => el.textContent ?? '').join('\n')
: (block?.querySelector('pre')?.textContent ?? '');
try {
await navigator.clipboard.writeText(text);
const prev = copyBtn.textContent;
copyBtn.textContent = '已复制';
copyBtn.classList.add('is-copied');
window.setTimeout(() => {
copyBtn.textContent = prev || '复制';
copyBtn.classList.remove('is-copied');
}, 1600);
} catch {
notify.error('复制失败');
} }
} catch {
notify.error('复制失败');
} }
}, [nav, openLightbox, onRequestReply, onUnlocked, postId, unlocking]); }, [nav, openLightbox, onRequestReply, onUnlocked, postId, unlocking]);
@@ -167,7 +129,7 @@ export default function PostContent({
className={className} className={className}
onClick={handleClick} onClick={handleClick}
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
dangerouslySetInnerHTML={{ __html: prepared.html }} dangerouslySetInnerHTML={{ __html: preparedHtml }}
/> />
<ImageLightbox <ImageLightbox
src={lightboxSrc} src={lightboxSrc}

View File

@@ -61,6 +61,14 @@ function PostListItem({ post, sort = 'latest', boardId = 0, onSelect }: Props) {
openPost(); 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 = ( const titleRow = (
<div className="post-title-row"> <div className="post-title-row">
{post.pinned && ( {post.pinned && (
@@ -70,9 +78,9 @@ function PostListItem({ post, sort = 'latest', boardId = 0, onSelect }: Props) {
<span className="post-pin-badge post-pin-badge--board" title="板块置顶"></span> <span className="post-pin-badge post-pin-badge--board" title="板块置顶"></span>
)} )}
{post.featured && ( {post.featured && (
<span className="post-feature-badge" title="精华"> <span className="post-feature-badge" title="推荐">
<FeaturedIcon size={12} /> <FeaturedIcon size={12} />
</span> </span>
)} )}
{post.status === 'pending' && ( {post.status === 'pending' && (
@@ -81,31 +89,36 @@ function PostListItem({ post, sort = 'latest', boardId = 0, onSelect }: Props) {
{post.status === 'rejected' && ( {post.status === 'rejected' && (
<span className="post-status-badge post-status-badge--rejected" title="未通过"></span> <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>
)}
{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>
)}
<a href={href} className="post-title" onClick={onTitleClick}> <a href={href} className="post-title" onClick={onTitleClick}>
{post.title} {post.title}
</a> </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> </div>
); );

View File

@@ -1,4 +1,3 @@
import { Skeleton } from '@/components/ui/skeleton';
import type { ForumLimitsPublic } from '../api/types'; import type { ForumLimitsPublic } from '../api/types';
export type FeedListStyle = ForumLimitsPublic['feed_list_style']; export type FeedListStyle = ForumLimitsPublic['feed_list_style'];
@@ -11,69 +10,3 @@ export function feedListRowEstimate(style: FeedListStyle): number {
default: return 64; default: return 64;
} }
} }
interface Props {
count?: number;
listStyle?: FeedListStyle;
}
/** 帖子列表加载骨架屏(对齐 v2 紧凑列表) */
export default function PostListSkeleton({ count = 8, listStyle = 'title' }: Props) {
const showExcerpt = listStyle === 'excerpt' || listStyle === 'thumbnail';
const showThumb = listStyle === 'thumbnail';
const titleOnly = listStyle === 'title';
return (
<div className="post-list-skeleton" aria-busy="true" aria-label="加载中">
{Array.from({ length: count }, (_, i) => {
const hasThumb = showThumb && i % 3 === 0;
return (
<div
key={i}
className={`post-row post-row--v2 post-row--skeleton${titleOnly ? ' post-row--title-only' : ''}${hasThumb ? ' post-row--has-thumb' : ''}`}
>
<Skeleton className="skeleton--avatar skeleton--avatar-v2" />
{hasThumb ? (
<div className="post-main post-main--with-thumb">
<div className="post-content">
<Skeleton className="skeleton--title skeleton--title-v2" style={{ width: `${58 + (i % 4) * 9}%` }} />
{showExcerpt && (
<Skeleton className="skeleton--excerpt skeleton--excerpt-v2" style={{ width: `${72 + (i % 3) * 8}%` }} />
)}
<div className="post-meta-left post-meta-left--skeleton">
<Skeleton className="skeleton--board-badge" />
<Skeleton className="skeleton--meta-line" style={{ width: `${45 + (i % 3) * 10}%` }} />
</div>
</div>
<div className="post-aside">
<Skeleton className="skeleton--thumb skeleton--thumb-tall" />
<div className="post-stats">
<Skeleton className="skeleton--stat" />
</div>
</div>
</div>
) : (
<div className="post-main">
<div className="post-text">
<Skeleton className="skeleton--title skeleton--title-v2" style={{ width: `${58 + (i % 4) * 9}%` }} />
{showExcerpt && (
<Skeleton className="skeleton--excerpt skeleton--excerpt-v2" style={{ width: `${72 + (i % 3) * 8}%` }} />
)}
</div>
<div className="post-meta">
<div className="post-meta-left post-meta-left--skeleton">
<Skeleton className="skeleton--board-badge" />
<Skeleton className="skeleton--meta-line" style={{ width: `${45 + (i % 3) * 10}%` }} />
</div>
<div className="post-stats">
<Skeleton className="skeleton--stat" />
</div>
</div>
</div>
)}
</div>
);
})}
</div>
);
}

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

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

View File

@@ -1,8 +1,6 @@
import { useMemo } from 'react'; import { useMemo } from 'react';
import { ListTree, MessageCircle, Tags, Link2, UserPlus } from 'lucide-react'; import { ListTree, MessageCircle, Tags, Link2, UserPlus } from 'lucide-react';
import { useLocation, useSearchParams, useNavigate } from 'react-router-dom'; import { useLocation, useSearchParams, useNavigate } from 'react-router-dom';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import type { AsideWidget, RecentComment, RecentUser, TagCount, User, ForumStats, FriendLink } from '../api/types'; import type { AsideWidget, RecentComment, RecentUser, TagCount, User, ForumStats, FriendLink } from '../api/types';
import type { PostHeading } from '../utils/postHeadings'; import type { PostHeading } from '../utils/postHeadings';
import { useSiteBranding } from '../hooks/useSiteBranding'; import { useSiteBranding } from '../hooks/useSiteBranding';
@@ -13,6 +11,7 @@ import UserLink from './UserLink';
import ArticleOutline from './ArticleOutline'; import ArticleOutline from './ArticleOutline';
import PostAuthorCard from './PostAuthorCard'; import PostAuthorCard from './PostAuthorCard';
import AsideCheckInStrip from './AsideCheckInStrip'; import AsideCheckInStrip from './AsideCheckInStrip';
import ShowcaseAsideWidget from './ShowcaseAsideWidget';
export type PostDetailAside = { export type PostDetailAside = {
author?: User | null; author?: User | null;
@@ -30,7 +29,7 @@ interface Props {
tagsLoading?: boolean; tagsLoading?: boolean;
stats?: ForumStats | null; stats?: ForumStats | null;
onPostClick: (id: number, opts?: { floor?: number }) => void; onPostClick: (id: number, opts?: { floor?: number }) => void;
/** 首次拉取中,显示骨架避免空态闪烁 */ /** 首次拉取中:不渲染该块内容(由冷启动门闩保证首屏已齐或空白) */
loading?: boolean; loading?: boolean;
/** 右侧栏可选组件顺序与开关 */ /** 右侧栏可选组件顺序与开关 */
asideWidgets: AsideWidget[]; asideWidgets: AsideWidget[];
@@ -38,35 +37,6 @@ interface Props {
postDetail?: PostDetailAside | null; postDetail?: PostDetailAside | null;
} }
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" />
<div className="widget-item-comment-main">
<Skeleton className="skeleton--widget-title" style={{ width: `${72 + (i % 3) * 8}%` }} />
<Skeleton className="skeleton--widget-meta" />
</div>
</div>
))}
</div>
);
}
function UserSkeleton() {
return (
<div className="widget-recent-users-grid" aria-busy="true" aria-label="用户加载中">
{Array.from({ length: 8 }, (_, i) => (
<div key={i} className="widget-recent-user-cell widget-recent-user-cell--skeleton">
<Skeleton className="skeleton--recent-user-avatar" />
<Skeleton className="skeleton--recent-user-name" style={{ width: `${48 + (i % 3) * 10}%` }} />
</div>
))}
</div>
);
}
export default function RightPanel({ export default function RightPanel({
recentComments, recentComments,
recentUsers, recentUsers,
@@ -108,12 +78,10 @@ export default function RightPanel({
[asideWidgets], [asideWidgets],
); );
const handleApplyClick = () => {
nav('/links?apply=1');
};
const renderWidget = (widget: AsideWidget) => { const renderWidget = (widget: AsideWidget) => {
switch (widget.id) { switch (widget.id) {
case 'showcase':
return <ShowcaseAsideWidget key="showcase" />;
case 'friend_links': case 'friend_links':
return ( return (
<div key="friend_links" className="widget-card widget-card--friend-links"> <div key="friend_links" className="widget-card widget-card--friend-links">
@@ -124,15 +92,9 @@ export default function RightPanel({
</button> </button>
</span> </span>
<Button <a href="/links?apply=1" className="widget-friend-links-apply">
type="button"
variant="ghost"
size="sm"
className="widget-friend-links-apply"
onClick={handleApplyClick}
>
</Button> </a>
</div> </div>
<div className="widget-card-body widget-card-body--friend-links"> <div className="widget-card-body widget-card-body--friend-links">
{friendLinks.length === 0 ? ( {friendLinks.length === 0 ? (
@@ -178,9 +140,7 @@ export default function RightPanel({
</div> </div>
<div className="widget-card-body"> <div className="widget-card-body">
{loading && commentList.length === 0 ? ( {loading && commentList.length === 0 ? null : commentList.length === 0 ? (
<CommentSkeleton />
) : commentList.length === 0 ? (
<div className="widget-empty"></div> <div className="widget-empty"></div>
) : commentList.map(item => ( ) : commentList.map(item => (
<div <div
@@ -238,9 +198,7 @@ export default function RightPanel({
</div> </div>
<div className="widget-card-body widget-card-body--users"> <div className="widget-card-body widget-card-body--users">
{loading && userList.length === 0 ? ( {loading && userList.length === 0 ? null : userList.length === 0 ? (
<UserSkeleton />
) : userList.length === 0 ? (
<div className="widget-empty"></div> <div className="widget-empty"></div>
) : ( ) : (
<div className="widget-recent-users-grid"> <div className="widget-recent-users-grid">
@@ -274,11 +232,13 @@ export default function RightPanel({
<div className={`aside-panel-inner${isPostDetail ? ' aside-panel-inner--post-detail' : ''}`}> <div className={`aside-panel-inner${isPostDetail ? ' aside-panel-inner--post-detail' : ''}`}>
{isPostDetail && ( {isPostDetail && (
<> <>
<PostAuthorCard {postDetail.author?.id ? (
author={postDetail.author} <PostAuthorCard
publishedAt={postDetail.publishedAt} author={postDetail.author}
viewCount={postDetail.viewCount} publishedAt={postDetail.publishedAt}
/> viewCount={postDetail.viewCount}
/>
) : null}
<div className="widget-card widget-card--outline"> <div className="widget-card widget-card--outline">
<div className="widget-card-head"> <div className="widget-card-head">
<ListTree className="widget-card-icon widget-card-icon--outline" aria-hidden /> <ListTree className="widget-card-icon widget-card-icon--outline" aria-hidden />

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,14 +1,14 @@
import { import {
Home, Star, LayoutDashboard, FolderGit2, FolderKanban, ArrowLeft, FileText, Link2, Home, Star, LayoutDashboard, FolderGit2, FolderKanban, ArrowLeft, FileText, Link2, Globe2,
} from 'lucide-react'; } from 'lucide-react';
import { useNavigate, useLocation, useSearchParams, Link } from 'react-router-dom'; import { useNavigate, useLocation, useSearchParams, Link } from 'react-router-dom';
import type { Board } from '../api/types'; import type { Board } from '../api/types';
import type { PostHeading } from '../utils/postHeadings'; import type { PostHeading } from '../utils/postHeadings';
import { useAuth } from '../hooks/useAuth'; import { useAuth } from '../hooks/useAuth';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { Skeleton } from '@/components/ui/skeleton';
import { buildHomeUrl, parseFeedSort } from './FeedSortBar'; import { buildHomeUrl, parseFeedSort } from './FeedSortBar';
import { navigateFeed } from '../utils/feedCache'; import { navigateFeed } from '../utils/feedCache';
import { transitionTo } from '../utils/spaTransition';
import BoardIconDisplay from './BoardIconDisplay'; import BoardIconDisplay from './BoardIconDisplay';
import { getBoardThemeIndex } from '../utils/boardTheme'; import { getBoardThemeIndex } from '../utils/boardTheme';
import ArticleOutline from './ArticleOutline'; import ArticleOutline from './ArticleOutline';
@@ -30,6 +30,7 @@ function resolveMenuKey(pathname: string, activeBoard: number, keyword = ''): st
if (pathname.startsWith('/favorites')) return 'favorites'; if (pathname.startsWith('/favorites')) return 'favorites';
if (pathname.startsWith('/projects')) return 'projects'; if (pathname.startsWith('/projects')) return 'projects';
if (pathname.startsWith('/links')) return 'links'; if (pathname.startsWith('/links')) return 'links';
if (pathname.startsWith('/showcase')) return 'showcase';
if (pathname.startsWith('/page/')) return 'pages'; if (pathname.startsWith('/page/')) return 'pages';
if (pathname.startsWith('/admin')) return 'admin'; if (pathname.startsWith('/admin')) return 'admin';
return activeBoard === 0 ? 'all' : String(activeBoard); return activeBoard === 0 ? 'all' : String(activeBoard);
@@ -61,13 +62,14 @@ export default function Sidebar({
const nav = useNavigate(); const nav = useNavigate();
const loc = useLocation(); const loc = useLocation();
const [params] = useSearchParams(); const [params] = useSearchParams();
const sort = parseFeedSort(params.get('sort'));
const { user } = useAuth(); const { user } = useAuth();
const isAdmin = user?.role === 'admin'; const isAdmin = user?.role === 'admin';
const { navPages } = useSitePages(); const { navPages } = useSitePages();
const { limits } = useForumLimits(); const { limits } = useForumLimits();
const sort = parseFeedSort(params.get('sort'), limits.feed_sort_tabs);
const showFriendLinksNav = limits.nav_show_friend_links !== false; const showFriendLinksNav = limits.nav_show_friend_links !== false;
const showSiteSection = navPages.length > 0 || showFriendLinksNav; const showShowcaseNav = !!limits.nav_show_showcase;
const showSiteSection = navPages.length > 0 || showFriendLinksNav || showShowcaseNav;
const keyword = params.get('keyword') || ''; const keyword = params.get('keyword') || '';
const menuKey = resolveMenuKey(loc.pathname, activeBoard, keyword); const menuKey = resolveMenuKey(loc.pathname, activeBoard, keyword);
@@ -135,22 +137,12 @@ export default function Sidebar({
<div className="sidebar-section"></div> <div className="sidebar-section"></div>
<nav className="sidebar-nav"> <nav className="sidebar-nav">
{feedNavLink('all', buildHomeUrl(0, sort, permalinkOpts), '全部帖子', <Home aria-hidden />, 0)} {feedNavLink('all', buildHomeUrl(0, sort, permalinkOpts), '全部帖子', <Home aria-hidden />, 0)}
{user && navItem('favorites', '我的收藏', <Star aria-hidden />, () => nav('/favorites'))} {user && navItem('favorites', '我的收藏', <Star aria-hidden />, () => void transitionTo(nav, '/favorites'))}
{navItem('projects', '开源码桶', <FolderGit2 aria-hidden />, () => nav('/projects'))} {navItem('projects', '开源码桶', <FolderGit2 aria-hidden />, () => void transitionTo(nav, '/projects'))}
</nav> </nav>
{(boardsLoading && boards.length === 0) ? ( {(boardsLoading && boards.length === 0) ? (
<> <div className="sidebar-section sidebar-section--boards"></div>
<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 ? ( ) : boards.length > 0 ? (
<> <>
<div className="sidebar-section sidebar-section--boards"></div> <div className="sidebar-section sidebar-section--boards"></div>
@@ -196,9 +188,10 @@ export default function Sidebar({
<> <>
<div className="sidebar-section sidebar-section--spaced"></div> <div className="sidebar-section sidebar-section--spaced"></div>
<nav className="sidebar-nav"> <nav className="sidebar-nav">
{showFriendLinksNav && navItem('links', '友情链接', <Link2 aria-hidden />, () => nav('/links'))} {showFriendLinksNav && navItem('links', '友情链接', <Link2 aria-hidden />, () => void transitionTo(nav, '/links'))}
{showShowcaseNav && navItem('showcase', '开源展柜', <Globe2 aria-hidden />, () => void transitionTo(nav, '/showcase'))}
{navPages.map(p => ( {navPages.map(p => (
navItem(`page-${p.slug}`, p.title, <FileText aria-hidden />, () => nav(pagePath(p.slug, limits))) navItem(`page-${p.slug}`, p.title, <FileText aria-hidden />, () => void transitionTo(nav, pagePath(p.slug, limits)))
))} ))}
</nav> </nav>
</> </>

View File

@@ -9,7 +9,7 @@ function FooterSep() {
return <span className="site-footer__sep" aria-hidden>·</span>; return <span className="site-footer__sep" aria-hidden>·</span>;
} }
/** 站点页脚:版权、Sitemap、备案号 */ /** 站点页脚:版权、友链/展柜入口、单页、备案号(结构与 Go writeSSRFooter 对齐) */
export default function SiteFooter() { export default function SiteFooter() {
const { branding } = useSiteBranding(); const { branding } = useSiteBranding();
const { footerPages } = useSitePages(); const { footerPages } = useSitePages();
@@ -17,6 +17,44 @@ export default function SiteFooter() {
const year = new Date().getFullYear(); const year = new Date().getFullYear();
const icp = branding.icp_beian?.trim() || ''; const icp = branding.icp_beian?.trim() || '';
const icpURL = branding.icp_beian_url?.trim() || 'https://beian.miit.gov.cn/'; 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 ( return (
<footer className="site-footer"> <footer className="site-footer">
@@ -34,29 +72,8 @@ export default function SiteFooter() {
</div> </div>
<nav className="site-footer__nav" aria-label="站点链接"> <nav className="site-footer__nav" aria-label="站点链接">
{limits.footer_show_friend_links !== false && ( {navItems.flatMap((node, i) =>
<span className="site-footer__friend"> i === 0 ? [node] : [<FooterSep key={`sep-${i}`} />, node],
<Link to="/links"></Link>
</span>
)}
{footerPages.map((p, i) => (
<span key={p.slug} className="site-footer__friend">
{(limits.footer_show_friend_links !== false || i > 0) && <FooterSep />}
<Link to={pagePath(p.slug, limits)}>{p.title}</Link>
</span>
))}
{icp && (
<>
{(limits.footer_show_friend_links !== false || footerPages.length > 0) && <FooterSep />}
<a
href={icpURL}
target="_blank"
rel="noopener noreferrer"
className="site-footer__icp"
>
{icp}
</a>
</>
)} )}
</nav> </nav>
</div> </div>

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 { useMemo } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import type { TagCount } from '../api/types'; import type { TagCount } from '../api/types';
import { Skeleton } from '@/components/ui/skeleton';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
interface Props { interface Props {
@@ -63,20 +62,7 @@ export default function TagCloud({ tags, loading = false, activeTag = '' }: Prop
}, [tags]); }, [tags]);
if (loading && tags.length === 0) { if (loading && tags.length === 0) {
return ( return null;
<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>
);
} }
if (items.length === 0) { 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,7 +4,7 @@ import { useVirtualizer } from '@tanstack/react-virtual';
import { Inbox, SearchX } from 'lucide-react'; import { Inbox, SearchX } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import PostListItem from './PostListItem'; import PostListItem from './PostListItem';
import PostListSkeleton, { feedListRowEstimate } from './PostListSkeleton'; import { feedListRowEstimate } from './PostListSkeleton';
import FeedPagination from './FeedPagination'; import FeedPagination from './FeedPagination';
import { InFlowSiteFooter } from './SiteFooter'; import { InFlowSiteFooter } from './SiteFooter';
import { useAuth } from '../hooks/useAuth'; import { useAuth } from '../hooks/useAuth';
@@ -14,6 +14,7 @@ import { loginPath } from '../utils/authRedirect';
import { dispatchOpenPostSearch } from '../hooks/usePostSearch'; import { dispatchOpenPostSearch } from '../hooks/usePostSearch';
import type { PostItem } from '../api/types'; import type { PostItem } from '../api/types';
import type { FeedSort } from './FeedSortBar'; import type { FeedSort } from './FeedSortBar';
import { getDefaultFeedSortFromCache } from './FeedSortBar';
interface Props { interface Props {
posts: PostItem[]; posts: PostItem[];
@@ -56,7 +57,7 @@ function getMobileFeedScrollEl(): HTMLElement | null {
export default function VirtualPostList({ export default function VirtualPostList({
posts, posts,
sort = 'latest', sort = getDefaultFeedSortFromCache(),
loading, loading,
hasMore, hasMore,
showPagination, showPagination,
@@ -161,6 +162,12 @@ export default function VirtualPostList({
onScrollTopChangeRef.current?.(0); onScrollTopChangeRef.current?.(0);
}, [resetScrollKey, virtualizer, getScrollElement]); }, [resetScrollKey, virtualizer, getScrollElement]);
useLayoutEffect(() => {
// 收到新的恢复目标时允许再次 restorenull 表示已消费,勿动标记
if (restoreScrollTop == null) return;
restoredRef.current = false;
}, [restoreScrollTop]);
useLayoutEffect(() => { useLayoutEffect(() => {
if (restoreScrollTop == null || restoredRef.current || posts.length === 0) return; if (restoreScrollTop == null || restoredRef.current || posts.length === 0) return;
const el = getScrollElement(); const el = getScrollElement();
@@ -173,10 +180,6 @@ export default function VirtualPostList({
onScrollRestoredRef.current?.(); onScrollRestoredRef.current?.();
}, [restoreScrollTop, posts.length, virtualizer, getScrollElement]); }, [restoreScrollTop, posts.length, virtualizer, getScrollElement]);
useEffect(() => {
restoredRef.current = false;
}, [restoreScrollTop]);
useEffect(() => { useEffect(() => {
const el = getScrollElement(); const el = getScrollElement();
if (!el) return; if (!el) return;
@@ -240,9 +243,7 @@ export default function VirtualPostList({
return ( return (
<div className="post-list-scroll" ref={parentRef}> <div className="post-list-scroll" ref={parentRef}>
{isInitialLoad ? ( {isInitialLoad ? null : isEmpty ? (
<PostListSkeleton listStyle={feedStyle} />
) : isEmpty ? (
<div className="empty-feed" role="status"> <div className="empty-feed" role="status">
{isSearchEmpty {isSearchEmpty
? <SearchX className="empty-feed-icon" aria-hidden size={36} strokeWidth={1.5} /> ? <SearchX className="empty-feed-icon" aria-hidden size={36} strokeWidth={1.5} />

View File

@@ -18,6 +18,10 @@ const WIDGET_META: Record<AsideWidgetId, { label: string; hint: string }> = {
label: '友情链接', label: '友情链接',
hint: '关闭后不在右侧栏展示,友链仍可在「友情链接」页面查看与申请', hint: '关闭后不在右侧栏展示,友链仍可在「友情链接」页面查看与申请',
}, },
showcase: {
label: '开源展柜',
hint: '展示精选公网部署;关闭后仍可直接访问 /showcase',
},
}; };
type Props = { type Props = {

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

@@ -1,5 +1,6 @@
import Image from '@tiptap/extension-image'; import Image from '@tiptap/extension-image';
import { mergeAttributes } from '@tiptap/core'; import { mergeAttributes } from '@tiptap/core';
import { isStickerSrc } from './ArticleStickerExtension';
/** 单图展示形态(对齐 Notion / Medium 常见选项) */ /** 单图展示形态(对齐 Notion / Medium 常见选项) */
export type ImageDisplay = 'default' | 'wide' | 'float-left' | 'float-right'; export type ImageDisplay = 'default' | 'wide' | 'float-left' | 'float-right';
@@ -19,6 +20,19 @@ declare module '@tiptap/core' {
export const ArticleImage = Image.extend({ export const ArticleImage = Image.extend({
name: 'image', name: 'image',
parseHTML() {
return [
{
tag: this.options.allowBase64 ? 'img[src]' : 'img[src]:not([src^="data:"])',
getAttrs: (node) => {
if (typeof node === 'string') return false;
if (isStickerSrc(node.getAttribute('src'))) return false;
return null;
},
},
];
},
addAttributes() { addAttributes() {
return { return {
...this.parent?.(), ...this.parent?.(),

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 { import {
Dialog, Dialog,
DialogContent, DialogContent,
DialogDescription,
DialogFooter, DialogFooter,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from '@/components/ui/dialog'; } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button'; 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 { interface Props {
open: boolean; open: boolean;
onOpenChange: (open: boolean) => void; onOpenChange: (open: boolean) => void;
initialUrl?: string; initialUrl?: string;
onConfirm: (url: string) => void; initialText?: string;
/** 是否正在编辑已有链接 */
editing?: boolean;
onConfirm: (payload: ArticleLinkConfirm) => void;
onRemove?: () => 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({ export function ArticleLinkDialog({
open, open,
onOpenChange, onOpenChange,
initialUrl = '', initialUrl = '',
initialText = '',
editing = false,
onConfirm, onConfirm,
onRemove, onRemove,
}: Props) { }: 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(() => { useEffect(() => {
if (open) setUrl(initialUrl || 'https://'); if (!open) return;
}, [open, initialUrl]); 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 = () => { 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); onOpenChange(false);
}; };
@@ -41,25 +174,119 @@ export function ArticleLinkDialog({
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="article-link-dialog"> <DialogContent className="article-link-dialog">
<DialogHeader> <DialogHeader>
<DialogTitle></DialogTitle> <DialogTitle></DialogTitle>
<DialogDescription> URL</DialogDescription>
</DialogHeader> </DialogHeader>
<Input
type="url" <section className="article-link-dialog__section">
value={url} <div className="article-link-dialog__field">
placeholder="https://" <Label htmlFor="article-link-url"></Label>
onChange={e => setUrl(e.target.value)} <Input
onKeyDown={e => { id="article-link-url"
if (e.key === 'Enter') { type="url"
e.preventDefault(); value={url}
handleConfirm(); placeholder="https://… 或 /post/123"
} onChange={e => setUrl(e.target.value)}
}} onKeyDown={e => {
autoFocus if (e.key === 'Enter') {
/> e.preventDefault();
handleConfirm();
}
}}
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"> <DialogFooter className="article-link-dialog__footer">
{onRemove && initialUrl ? ( {editing && onRemove ? (
<Button type="button" variant="outline" onClick={() => { onRemove(); onOpenChange(false); }}> <Button
type="button"
variant="outline"
className="article-link-dialog__remove"
onClick={() => {
onRemove();
onOpenChange(false);
}}
>
</Button> </Button>
) : null} ) : null}
@@ -67,7 +294,7 @@ export function ArticleLinkDialog({
</Button> </Button>
<Button type="button" onClick={handleConfirm}> <Button type="button" onClick={handleConfirm}>
{editing ? '更新链接' : '添加链接'}
</Button> </Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>

View File

@@ -0,0 +1,54 @@
import { Node, mergeAttributes } from '@tiptap/core';
/** 贴纸资源路径:评论、私信、发帖共用 /stickers/ */
export function isStickerSrc(src: string | null | undefined): boolean {
return typeof src === 'string' && src.includes('/stickers/');
}
/**
* 行内表情贴纸。文章 Image 是 block不能拿来插表情否则会独自占一段。
* 解析 HTML 时优先于普通 img避免贴纸被收成通栏大图。
*/
export const ArticleSticker = Node.create({
name: 'sticker',
group: 'inline',
inline: true,
atom: true,
selectable: true,
draggable: true,
priority: 60,
addAttributes() {
return {
src: { default: null },
alt: { default: '' },
};
},
parseHTML() {
return [
{
tag: 'img[src]',
getAttrs: (node) => {
if (typeof node === 'string') return false;
const src = node.getAttribute('src') || '';
if (!isStickerSrc(src)) return false;
return {
src,
alt: node.getAttribute('alt') || '',
};
},
},
];
},
renderHTML({ HTMLAttributes }) {
return [
'img',
mergeAttributes(HTMLAttributes, {
class: 'article-sticker',
draggable: 'false',
}),
];
},
});

View File

@@ -36,17 +36,58 @@ export default function StickerPicker({ onSelect }: Props) {
}, [active]); }, [active]);
useEffect(() => { useEffect(() => {
const el = gridRef.current?.querySelectorAll<HTMLElement>('[role="option"]')[focusIndex]; if (loading || stickers.length === 0) return;
el?.focus(); gridRef.current?.focus();
}, [focusIndex, stickers]); }, [loading, stickers]);
const onKeyDown = useCallback((e: React.KeyboardEvent) => { const onKeyDown = useCallback((e: React.KeyboardEvent) => {
const cols = 8; const items = gridRef.current?.querySelectorAll<HTMLElement>('[role="option"]');
if (e.key === 'ArrowRight') { e.preventDefault(); setFocusIndex((i) => Math.min(stickers.length - 1, i + 1)); } if (!items?.length) return;
else if (e.key === 'ArrowLeft') { e.preventDefault(); setFocusIndex((i) => Math.max(0, i - 1)); }
else if (e.key === 'ArrowDown') { e.preventDefault(); setFocusIndex((i) => Math.min(stickers.length - 1, i + cols)); } const moveTo = (next: number) => {
else if (e.key === 'ArrowUp') { e.preventDefault(); setFocusIndex((i) => Math.max(0, i - cols)); } e.preventDefault();
else if (e.key === 'Enter' || e.key === ' ') { const i = Math.max(0, Math.min(items.length - 1, next));
setFocusIndex(i);
items[i]?.focus();
};
if (e.key === 'ArrowRight') {
moveTo(focusIndex + 1);
return;
}
if (e.key === 'ArrowLeft') {
moveTo(focusIndex - 1);
return;
}
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
// 颜文字宽度不固定,按视觉行列找下一格,避免按固定 8 列错位
e.preventDefault();
const cur = items[focusIndex];
if (!cur) return;
const cr = cur.getBoundingClientRect();
const cx = cr.left + cr.width / 2;
const cy = cr.top + cr.height / 2;
const dir = e.key === 'ArrowDown' ? 1 : -1;
let best = -1;
let bestScore = Infinity;
items.forEach((el, i) => {
if (i === focusIndex) return;
const r = el.getBoundingClientRect();
const dy = (r.top + r.height / 2) - cy;
if (dy * dir <= 6) return;
const score = Math.abs(dy) * 24 + Math.abs((r.left + r.width / 2) - cx);
if (score < bestScore) {
bestScore = score;
best = i;
}
});
if (best >= 0) {
setFocusIndex(best);
items[best]?.focus();
}
return;
}
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault(); e.preventDefault();
const s = stickers[focusIndex]; const s = stickers[focusIndex];
if (s) onSelect(s); if (s) onSelect(s);
@@ -73,6 +114,7 @@ export default function StickerPicker({ onSelect }: Props) {
ref={gridRef} ref={gridRef}
className="sticker-picker-grid" className="sticker-picker-grid"
role="listbox" role="listbox"
tabIndex={0}
aria-label={`${active}贴纸`} aria-label={`${active}贴纸`}
aria-activedescendant={`${autoId}-opt-${focusIndex}`} aria-activedescendant={`${autoId}-opt-${focusIndex}`}
onKeyDown={onKeyDown} onKeyDown={onKeyDown}
@@ -82,33 +124,35 @@ export default function StickerPicker({ onSelect }: Props) {
) : stickers.length === 0 ? ( ) : stickers.length === 0 ? (
<div className="sticker-picker-loading"></div> <div className="sticker-picker-loading"></div>
) : ( ) : (
stickers.map((s, i) => ( stickers.map((s, i) => {
<button const isText = s.type === 'text' && !!s.text;
key={s.id} return (
id={`${autoId}-opt-${i}`} <button
type="button" key={s.id}
role="option" id={`${autoId}-opt-${i}`}
tabIndex={focusIndex === i ? 0 : -1} type="button"
aria-selected={focusIndex === i} role="option"
aria-label={s.name} tabIndex={focusIndex === i ? 0 : -1}
className="sticker-picker-item" aria-selected={focusIndex === i}
onClick={() => onSelect(s)} aria-label={s.name}
onFocus={() => setFocusIndex(i)} className={isText ? 'sticker-picker-item sticker-picker-item--text' : 'sticker-picker-item sticker-picker-item--image'}
> onClick={() => onSelect(s)}
{s.type === 'text' && s.text ? ( onFocus={() => setFocusIndex(i)}
<span className="sticker-picker-text">{s.text}</span> >
) : ( {isText ? (
<img <span className="sticker-picker-text">{s.text}</span>
src={s.url} ) : (
alt={s.name} <img
width={32} src={s.url}
height={32} alt={s.name}
style={{ width: 32, height: 32, objectFit: 'contain' }} width={32}
loading="lazy" height={32}
/> loading="lazy"
)} />
</button> )}
)) </button>
);
})
)} )}
</div> </div>
</div> </div>

View File

@@ -15,10 +15,7 @@ export async function loadHotStickers(): Promise<Sticker[]> {
const allEmoji = getAllStickers(); const allEmoji = getAllStickers();
const all = [...allEmoji, ...KAOMOJI_STICKERS]; const all = [...allEmoji, ...KAOMOJI_STICKERS];
return all return all
.filter((s) => { .filter((s) => s.aliases?.some((a) => HOT_KEYWORDS.includes(a)) || HOT_KEYWORDS.includes(s.name))
if (s.category === '颜文字') return true;
return s.aliases?.some((a) => HOT_KEYWORDS.includes(a)) || HOT_KEYWORDS.includes(s.name);
})
.slice(0, 30) .slice(0, 30)
.map((s) => ({ ...s, category: '热门' as const })); .map((s) => ({ ...s, category: '热门' as const }));
} }

View File

@@ -3,30 +3,54 @@ import type { Sticker } from './index';
/** 颜文字贴纸 — 纯文本类型,选择器和编辑器中均作为纯文本显示 */ /** 颜文字贴纸 — 纯文本类型,选择器和编辑器中均作为纯文本显示 */
export const KAOMOJI_STICKERS: Sticker[] = [ export const KAOMOJI_STICKERS: Sticker[] = [
{ id: 'km-happy', name: '开心', category: '颜文字', type: 'text', text: '(ノ´∀`)', aliases: ['哈哈', '开心'] }, { id: 'km-wave-half', name: '勉强挥手', category: '颜文字', type: 'text', text: '( ̄▽ ̄)', aliases: ['挥手', ''] },
{ id: 'km-laugh', name: '大笑', category: '颜文字', type: 'text', text: '(≧∇≦)ノ', aliases: ['哈哈哈', '笑死'] }, { id: 'km-shrug-ascii', name: '摊手', category: '颜文字', type: 'text', text: '¯\\_(ツ)_/¯', aliases: ['摊手', '无奈'] },
{ id: 'km-cry', name: '', category: '颜文字', type: 'text', text: '(´;ω;`)', aliases: ['呜呜', '伤心'] }, { id: 'km-eyeroll', name: '翻白眼', category: '颜文字', type: 'text', text: '(¬_¬)', aliases: ['白眼', '嫌弃'] },
{ id: 'km-angry', name: '生气', category: '颜文字', type: 'text', text: 'ヽ(`⌒´)ノ', aliases: ['', '气死'] }, { id: 'km-speechless', name: '无语凝噎', category: '颜文字', type: 'text', text: '(一_一)', aliases: ['无语', '沉默'] },
{ id: 'km-shrug', name: '无奈', category: '颜文字', type: 'text', text: '╮(°-°)╭', aliases: ['呵呵', '无语'] }, { id: 'km-shock-idle', name: '震惊但不想管', category: '颜文字', type: 'text', text: '( ゚д゚)', aliases: ['震惊', '惊讶'] },
{ id: 'km-determined', name: '加油', category: '颜文字', type: 'text', text: '(๑•̀ㅁ•́ฅ)', aliases: ['', '奥利给'] }, { id: 'km-dead-inside', name: '心死', category: '颜文字', type: 'text', text: '。_。', aliases: ['心死', '无力'] },
{ id: 'km-sad', name: '难过', category: '颜文字', type: 'text', text: '( ´・ω・`)', aliases: ['失落', '低落'] }, { id: 'km-lazy', name: '懒得动', category: '颜文字', type: 'text', text: '( ˘ω˘ )', aliases: ['', '摆烂'] },
{ id: 'km-sparkle', name: '兴奋', category: '颜文字', type: 'text', text: '(ノ´ヮ`)ノ*: ・゚', aliases: ['太棒了', ''] }, { id: 'km-awkward-smile', name: '尴尬微笑', category: '颜文字', type: 'text', text: '( ̄ω ̄;)', aliases: ['尴尬', '呵呵'] },
{ id: 'km-tear', name: '泪奔', category: '颜文字', type: 'text', text: '(╥﹏╥)', aliases: ['泪流', '呜呜'] }, { id: 'km-sob', name: '哭到抽搐', category: '颜文字', type: 'text', text: '(´;ω;`)', aliases: ['', '大哭'] },
{ id: 'km-love', name: '喜欢', category: '颜文字', type: 'text', text: '(◕ᴗ◕✿)', aliases: ['', '心动'] }, { id: 'km-grievance', name: '委屈巴巴', category: '颜文字', type: 'text', text: '(๑•́ ₃ •̀๑)', aliases: ['委屈', '嘤嘤'] },
{ id: 'km-cool', name: '', category: '颜文字', type: 'text', text: '(⌐■_■)', aliases: ['', '墨镜'] }, { id: 'km-blush-blur', name: '害羞到糊掉', category: '颜文字', type: 'text', text: '( ⁄•⁄ω⁄•⁄ )', aliases: ['害羞', '脸红'] },
{ id: 'km-stare', name: '', category: '颜文字', type: 'text', text: 'ಠ_ಠ', aliases: ['凝视', '盯着看'] }, { id: 'km-grit', name: '咬牙切齿', category: '颜文字', type: 'text', text: '(╬  ̄皿 ̄)', aliases: ['', '生气'] },
{ id: 'km-tableflip', name: '掀桌', category: '颜文字', type: 'text', text: '(╯°□°)╯︵ ┻━┻', aliases: ['掀桌', '愤怒'] }, { id: 'km-short-rage', name: '暴怒短号', category: '颜文字', type: 'text', text: '(`Д´)', aliases: ['', '气死'] },
{ id: 'km-bow', name: '拜托', category: '颜文字', type: 'text', text: '(人・ω・)💦', aliases: ['求求', '拜托了'] }, { id: 'km-fist-rage', name: '气到挥拳', category: '颜文字', type: 'text', text: '٩(๑`^´๑)۶', aliases: ['', '挥拳'] },
{ id: 'km-proud', name: '得意', category: '颜文字', type: 'text', text: '( ̄▽ ̄)"', aliases: ['嘿嘿', '自满'] }, { id: 'km-grit-spark', name: '憋屈但要干', category: '颜文字', type: 'text', text: '(๑•̀ㅂ•́)و✧', aliases: ['', '加油'] },
{ id: 'km-sleep', name: '', category: '颜文字', type: 'text', text: '(-ω-)Zzz', aliases: ['睡觉', '晚安'] }, { id: 'km-weep', name: '哭唧唧', category: '颜文字', type: 'text', text: '( ˃̣̣̥ω˂̣̣̥ )', aliases: ['', '呜呜'] },
{ id: 'km-wave', name: '招手', category: '颜文字', type: 'text', text: '(´・ω・)', aliases: ['你好', '拜拜'] }, { id: 'km-scamper', name: '撒欢跑走', category: '颜文字', type: 'text', text: 'ᕕ( ᐛ )ᕗ', aliases: ['', '溜了'] },
{ id: 'km-wink', name: '眨眼', category: '颜文字', type: 'text', text: '(◠‿◠)', aliases: ['抛媚眼', '嘿嘿'] }, { id: 'km-star-throw', name: '丢星星', category: '颜文字', type: 'text', text: '(ノ≧∀≦)ノ ‥…━━━★', aliases: ['', '星星'] },
{ id: 'km-sorry', name: '抱歉', category: '颜文字', type: 'text', text: 'm(._.)m', aliases: ['对不起', '跪了'] }, { id: 'km-flee', name: '落荒而逃', category: '颜文字', type: 'text', text: 'ε=ε=ε=┌(;*´Д`)ノ', aliases: ['', ''] },
{ id: 'km-doubt', name: '疑惑', category: '颜文字', type: 'text', text: '(╬ Ò _ Ó)', aliases: ['什么', '???'] }, { id: 'km-unflip', name: '把桌摆回去', category: '颜文字', type: 'text', text: '┬─┬ノ( º _ ºノ)', aliases: ['摆桌', '冷静'] },
{ id: 'km-hungry', name: '饿了', category: '颜文字', type: 'text', text: '(๑´ㅂ`๑)', aliases: ['想吃', '吃货'] }, { id: 'km-flip-hard', name: '狠掀桌', category: '颜文字', type: 'text', text: '(┛ಠ_ಠ)┛彡┻━┻', aliases: ['掀桌', ''] },
{ id: 'km-gameover', name: 'GG', category: '颜文字', type: 'text', text: '(╯︿╰﹀ )', aliases: ['GG', '完了'] }, { id: 'km-victory-l', name: '胜利举手', category: '颜文字', type: 'text', text: '┏(0)┛', aliases: ['胜利', ''] },
{ id: 'km-gift', name: '送花', category: '颜文字', type: 'text', text: '(✿◠‿◠)', aliases: ['送花', '谢谢'] }, { id: 'km-victory-r', name: '对面胜利', category: '颜文字', type: 'text', text: '┗(0)┓', aliases: ['胜利', ''] },
{ id: 'km-clap', name: '鼓掌', category: '颜文字', type: 'text', text: 'ヾ(´▽`;)ゝ', aliases: ['呱唧', '鼓掌'] }, { id: 'km-point', name: '指你呢', category: '颜文字', type: 'text', text: '(☞゚ヮ゚)☞', aliases: ['', '就是你'] },
{ id: 'km-cheer', name: '加油', category: '颜文字', type: 'text', text: '(^ω^)', aliases: ['冲鸭', 'go'] }, { id: 'km-point-back', name: '指回去', category: '颜文字', type: 'text', text: '☜(゚ヮ゚☜)', aliases: ['指回去', '你才'] },
{ id: 'km-please', name: '拜托了', category: '颜文字', type: 'text', text: '( ´・ω・`)', aliases: ['嘤嘤', '求求了'] }, { id: 'km-cat', name: '', category: '颜文字', type: 'text', text: '(=^・ω・^=)', aliases: ['', ''] },
{ id: 'km-cat-round', name: '圆眼猫', category: '颜文字', type: 'text', text: '(ΦωΦ)', aliases: ['猫', '圆眼'] },
{ id: 'km-bear', name: '熊', category: '颜文字', type: 'text', text: 'ʕ•ᴥ•ʔ', aliases: ['熊', '抱抱'] },
{ id: 'km-flower-ear', name: '花耳', category: '颜文字', type: 'text', text: '◕‿◕✿', aliases: ['花', '可爱'] },
{ id: 'km-angry-bird', name: '怒鸟', category: '颜文字', type: 'text', text: '(ꐦ°᷄д°᷅)', aliases: ['怒', '生气'] },
{ id: 'km-smug-wolf', name: '狼尾得意', category: '颜文字', type: 'text', text: '( •̀ ω •́ )✧', aliases: ['得意', '酷'] },
{ id: 'km-cat-wave', name: '猫招手', category: '颜文字', type: 'text', text: '~(=^‥^)', aliases: ['猫', '招手'] },
{ id: 'km-hehe', name: '呵呵', category: '颜文字', type: 'text', text: '( ´_ゝ)', aliases: ['呵呵', '滑稽'] },
{ id: 'km-server-down', name: '服务器炸了', category: '颜文字', type: 'text', text: '(;´Д`)', aliases: ['炸了', '宕机'] },
{ id: 'km-double-shock', name: '双重震惊', category: '颜文字', type: 'text', text: '(゚Д゚≡゚д゚)!?', aliases: ['震惊', '惊讶'] },
{ id: 'km-cold-sweat', name: '冷汗惊恐', category: '颜文字', type: 'text', text: 'Σ(°△°|||)︴', aliases: ['惊恐', '惊讶'] },
{ id: 'km-hang', name: '宕机', category: '颜文字', type: 'text', text: '(;°○° )', aliases: ['宕机', '卡死'] },
{ id: 'km-pass-box', name: '递箱子', category: '颜文字', type: 'text', text: '( ゚∀゚)つ□', aliases: ['递', '补丁'] },
{ id: 'km-shoulder', name: '拍对方肩', category: '颜文字', type: 'text', text: '( ´▽`)σ)Д`)', aliases: ['拍肩', '兄弟'] },
{ id: 'km-silent-crash', name: '无声崩溃', category: '颜文字', type: 'text', text: '(-_-;)・・・', aliases: ['崩溃', '尴尬'] },
{ id: 'km-blank', name: '呆滞', category: '颜文字', type: 'text', text: '(。ŏ_ŏ)', aliases: ['发呆', '呆'] },
{ id: 'km-side-eye', name: '眯眼嫌弃', category: '颜文字', type: 'text', text: '(๑¯ω¯๑)', aliases: ['嫌弃', '眯眼'] },
{ id: 'km-lick', name: '舔嘴', category: '颜文字', type: 'text', text: '(๑´ڡ`๑)', aliases: ['好吃', '馋'] },
{ id: 'km-round-laugh', name: '圆滚滚笑', category: '颜文字', type: 'text', text: '( ˶˚ ᗨ ˚˶ )', aliases: ['哈哈', '大笑'] },
{ id: 'km-hug-ask', name: '求抱抱', category: '颜文字', type: 'text', text: '(っ˘̩╭╮˘̩)っ', aliases: ['抱抱', '求抱'] },
{ id: 'km-rage-yi', name: '暴怒益字', category: '颜文字', type: 'text', text: '(╬ಠ益ಠ)', aliases: ['怒', '生气'] },
{ id: 'km-fight', name: '对线准备', category: '颜文字', type: 'text', text: "(ง'̀-'́)ง", aliases: ['对线', '来战'] },
{ id: 'km-cat-minimal', name: '极简猫', category: '颜文字', type: 'text', text: 'ᓚᘏᗢ', aliases: ['猫', '喵'] },
{ id: 'km-pounce', name: '飞扑拥抱', category: '颜文字', type: 'text', text: '(づ。◕‿‿◕。)づ', aliases: ['拥抱', '爱'] },
{ id: 'km-suspect', name: '怀疑人生', category: '颜文字', type: 'text', text: '( ◔ ʖ̯ ◔ )', aliases: ['怀疑', '思考'] },
]; ];

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 { api } from '../api/client';
import type { User } from '../api/types'; import type { User } from '../api/types';
import { clearAllFeedCache } from '../utils/feedCache';
import { clearSessionSnapshots } from '../utils/sessionPageCache';
import { peekAuthSeed } from '../utils/authBoot';
interface AuthCtx { interface AuthCtx {
user: User | null; user: User | null;
@@ -15,8 +18,12 @@ const AuthContext = createContext<AuthCtx>({
}); });
export function AuthProvider({ children }: { children: ReactNode }) { export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null); // peek 不清种子StrictMode 重挂 / initializer 双调仍与 SSR 同构
const [loading, setLoading] = useState(true); 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 () => { const refresh = useCallback(async () => {
try { try {
@@ -29,8 +36,24 @@ export function AuthProvider({ children }: { children: ReactNode }) {
} }
}, []); }, []);
// 初始化只拉一次用户信息 // 有 SSR 种子时仍后台校验;无种子则首屏拉取
useEffect(() => { refresh(); }, [refresh]); // 不清空 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 () => { const logout = async () => {
await api.logout(); await api.logout();

View File

@@ -2,38 +2,115 @@ import { useCallback, useEffect, useState } from 'react';
import { notify } from '@/lib/notify'; import { notify } from '@/lib/notify';
import { api } from '../api/client'; import { api } from '../api/client';
import type { CheckInStatus } from '../api/types'; 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'; import { useAuth } from './useAuth';
/** 签到会话快照键(与 prefetchRoute 共用) */
export function checkInCacheKey(userId: number) {
return `checkin:${userId}`;
}
/** 每日签到状态与操作(侧栏、积分页等复用) */ /** 每日签到状态与操作(侧栏、积分页等复用) */
export function useCheckIn(enabled = true) { export function useCheckIn(enabled = true) {
const { user, refresh } = useAuth(); const { user, refresh } = useAuth();
const [status, setStatus] = useState<CheckInStatus | null>(null); const userId = user?.id;
const [loading, setLoading] = useState(false);
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 [busy, setBusy] = useState(false);
const load = useCallback(() => { const load = useCallback((opts?: { force?: boolean }) => {
if (!user || !enabled) { if (!userId || !enabled) {
setStatus(null); setStatus(null);
setLoading(false); setLoading(false);
return; return;
} }
const key = checkInCacheKey(userId);
if (!opts?.force) {
const hit = getSessionSnapshot<CheckInStatus>(key);
if (hit !== undefined) {
setStatus(hit);
setLoading(false);
return;
}
}
setLoading(true); setLoading(true);
api.checkInStatus() api.checkInStatus()
.then(d => setStatus(d.check_in)) .then((d) => {
.catch(e => notify.error(e instanceof Error ? e.message : '加载签到状态失败')) setSessionSnapshot(key, d.check_in);
setStatus(d.check_in);
})
.catch((e) => notify.error(e instanceof Error ? e.message : '加载签到状态失败'))
.finally(() => setLoading(false)); .finally(() => setLoading(false));
}, [user, enabled]); }, [userId, enabled]);
useEffect(() => { useEffect(() => {
load(); if (!userId || !enabled) {
}, [load]); 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 () => { const doCheckIn = useCallback(async () => {
if (!user) return; if (!userId) return;
setBusy(true); setBusy(true);
try { try {
const r = await api.checkIn(); const r = await api.checkIn();
notify.success(`签到成功,+${r.check_in.today_points} 积分`); notify.success(`签到成功,+${r.check_in.today_points} 积分`);
setSessionSnapshot(checkInCacheKey(userId), r.check_in);
setStatus(r.check_in); setStatus(r.check_in);
await refresh(); await refresh();
} catch (e: unknown) { } catch (e: unknown) {
@@ -41,13 +118,13 @@ export function useCheckIn(enabled = true) {
} finally { } finally {
setBusy(false); setBusy(false);
} }
}, [user, refresh]); }, [userId, refresh]);
return { return {
status, status,
loading, loading,
busy, busy,
doCheckIn, doCheckIn,
reload: load, reload: () => load({ force: true }),
}; };
} }

View File

@@ -1,7 +1,7 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { api } from '../api/client'; import { api } from '../api/client';
import type { ForumLimitsPublic } from '../api/types'; import type { ForumLimitsPublic } from '../api/types';
import { DEFAULT_ASIDE_WIDGETS } from '../api/types'; import { DEFAULT_ASIDE_WIDGETS, DEFAULT_FEED_SORT_TABS } from '../api/types';
const DEFAULT_LIMITS: ForumLimitsPublic = { const DEFAULT_LIMITS: ForumLimitsPublic = {
post_title_max: 128, post_title_max: 128,
@@ -20,12 +20,17 @@ const DEFAULT_LIMITS: ForumLimitsPublic = {
aside_show_tag_cloud: false, aside_show_tag_cloud: false,
aside_show_recent_comments: false, aside_show_recent_comments: false,
aside_show_friend_links: true, aside_show_friend_links: true,
aside_show_showcase: false,
aside_widgets: DEFAULT_ASIDE_WIDGETS, aside_widgets: DEFAULT_ASIDE_WIDGETS,
nav_show_friend_links: true, nav_show_friend_links: true,
footer_show_friend_links: true, footer_show_friend_links: true,
nav_show_showcase: false,
footer_show_showcase: false,
feed_list_style: 'title', feed_list_style: 'title',
feed_sort_tabs: DEFAULT_FEED_SORT_TABS,
permalink_enabled: false, permalink_enabled: false,
permalink_ext: 'html', permalink_ext: 'html',
monitor_pageview: false,
}; };
let cached: ForumLimitsPublic | null = null; let cached: ForumLimitsPublic | null = null;
@@ -75,6 +80,27 @@ export function useForumLimits() {
return { limits, loading }; 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 重新拉取 */ /** 清除缓存并通知已挂载的 hook 重新拉取 */
export function invalidateForumLimitsCache() { export function invalidateForumLimitsCache() {
cached = null; 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

@@ -2,6 +2,7 @@ import { useCallback, useMemo } from 'react';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'; import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import { buildHomeUrl } from '../components/FeedSortBar'; import { buildHomeUrl } from '../components/FeedSortBar';
import { navigateFeed } from '../utils/feedCache'; import { navigateFeed } from '../utils/feedCache';
import { transitionTo } from '../utils/spaTransition';
import { notify } from '@/lib/notify'; import { notify } from '@/lib/notify';
import { parsePermalinkID, type PermalinkOpts } from '../utils/permalink'; import { parsePermalinkID, type PermalinkOpts } from '../utils/permalink';
@@ -190,7 +191,7 @@ export function usePostSearch(
} }
saveRecentSearch({ keyword: kw, author, titleOnly, scopeBoardId }); saveRecentSearch({ keyword: kw, author, titleOnly, scopeBoardId });
nav(target); void transitionTo(nav, target);
return true; return true;
}, [nav, params, loc.pathname, limits, buildUrl]); }, [nav, params, loc.pathname, limits, buildUrl]);

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 cached: SiteBranding | null = readBootBranding();
let inflight: Promise<SiteBranding> | null = null; let inflight: Promise<SiteBranding> | null = null;
let cacheEpoch = 0; let cacheEpoch = 0;
/** force 预热刚写入后hook 因 epoch 重跑时复用缓存,避免连打两次 API */
let preferCacheOnce = false;
const listeners = new Set<() => void>(); const listeners = new Set<() => void>();
function fetchBranding(): Promise<SiteBranding> { function fetchBranding(): Promise<SiteBranding> {
if (preferCacheOnce && cached) {
preferCacheOnce = false;
return Promise.resolve(cached);
}
if (inflight) return inflight; if (inflight) return inflight;
// 有 boot/缓存时首屏已可用;仍请求 API 以同步最新配置 // 有 boot/缓存时首屏已可用;仍请求 API 以同步最新配置
inflight = api.siteBranding() inflight = api.siteBranding()
@@ -123,6 +129,30 @@ export function useSiteBranding() {
return { branding, loading }; 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 重新拉取 */ /** 清除缓存并通知已挂载的 hook 重新拉取 */
export function invalidateSiteBrandingCache() { export function invalidateSiteBrandingCache() {
cached = null; cached = null;

View File

@@ -1,32 +1,60 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { api } from '../api/client'; import { api } from '../api/client';
import type { SitePageSummary } from '../api/types'; 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 cache: SitePageSummary[] | null = null;
let pending: Promise<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() { export function useSitePages() {
const [pages, setPages] = useState<SitePageSummary[]>(cache ?? []); const [pages, setPages] = useState<SitePageSummary[]>(cache ?? []);
useEffect(() => { useEffect(() => {
if (cache) { const load = () => {
setPages(cache); void ensureSitePagesLoaded().then(setPages);
return; };
} if (cache) setPages(cache);
if (!pending) { else load();
pending = api.pages()
.then(d => { const onForce = () => {
cache = d.pages ?? []; cache = null;
return cache; pending = null;
}) load();
.catch(() => { };
cache = []; const onCommit = () => {
return cache; // 软刷新cache 已由 prefetch 写好,同步进 state
}) void ensureSitePagesLoaded().then(setPages);
.finally(() => { pending = null; }); };
} window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
pending.then(setPages); 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 { return {
@@ -39,3 +67,9 @@ export function useSitePages() {
export function invalidateSitePagesCache() { export function invalidateSitePagesCache() {
cache = null; 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 { useEffect, useState, useCallback, useRef } from 'react';
import { Outlet, NavLink, useNavigate, useLocation } from 'react-router-dom'; import { Outlet, NavLink, useNavigate, useLocation } from 'react-router-dom';
import { import {
LayoutDashboard, FolderKanban, FileText, MessageSquare, Flag, Users, Images, Settings, ArrowLeft, Moon, Sun, Menu, X, Award, Link2, BookOpen, LayoutDashboard, FolderKanban, FileText, MessageSquare, Flag, Users, Images, Settings, ArrowLeft, Moon, Sun, Menu, X, Award, Link2, BookOpen, Globe2, Activity,
} from 'lucide-react'; } from 'lucide-react';
import { Spinner } from '@/components/ui/spinner'; import { Spinner } from '@/components/ui/spinner';
import { useAuth } from '../hooks/useAuth'; import { useAuth } from '../hooks/useAuth';
@@ -23,6 +23,8 @@ type NavItem = {
label: string; label: string;
icon: typeof LayoutDashboard; icon: typeof LayoutDashboard;
badgeKey?: BadgeKey; badgeKey?: BadgeKey;
/** 仅社区枢纽开启时显示 */
hubOnly?: boolean;
}; };
type NavGroup = { type NavGroup = {
@@ -36,6 +38,8 @@ const NAV_GROUPS: NavGroup[] = [
label: '概览', label: '概览',
items: [ items: [
{ to: '/admin/dashboard', label: '仪表盘', icon: LayoutDashboard }, { to: '/admin/dashboard', label: '仪表盘', icon: LayoutDashboard },
{ to: '/admin/monitor', label: '网站监控', icon: Activity },
{ to: '/admin/community', label: '公网实例', icon: Globe2, hubOnly: true },
], ],
}, },
{ {
@@ -86,6 +90,7 @@ export default function AdminLayout() {
const isNarrow = useMediaQuery('(max-width: 768px)'); const isNarrow = useMediaQuery('(max-width: 768px)');
const [navOpen, setNavOpen] = useState(false); const [navOpen, setNavOpen] = useState(false);
const [pending, setPending] = useState<PendingCounts>({ posts: 0, comments: 0, reports: 0, links: 0 }); const [pending, setPending] = useState<PendingCounts>({ posts: 0, comments: 0, reports: 0, links: 0 });
const [communityHub, setCommunityHub] = useState(false);
const nav = useNavigate(); const nav = useNavigate();
const location = useLocation(); const location = useLocation();
const drawerRef = useRef<HTMLElement>(null); const drawerRef = useRef<HTMLElement>(null);
@@ -107,6 +112,13 @@ export default function AdminLayout() {
.catch(() => {}); .catch(() => {});
}, []); }, []);
useEffect(() => {
if (loading || !user || user.role !== 'admin') return;
api.adminSettings()
.then(s => setCommunityHub(!!s.community?.hub_enabled))
.catch(() => setCommunityHub(false));
}, [loading, user]);
useEffect(() => { useEffect(() => {
if (loading || !user || user.role !== 'admin') return; if (loading || !user || user.role !== 'admin') return;
refreshPending(); refreshPending();
@@ -156,7 +168,7 @@ export default function AdminLayout() {
NAV_GROUPS.map(group => ( NAV_GROUPS.map(group => (
<div key={group.label} className="admin-nav-group"> <div key={group.label} className="admin-nav-group">
<div className="admin-nav-group-label">{group.label}</div> <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; const badge = badgeKey ? formatNavBadge(pending[badgeKey]) : null;
return ( return (
<NavLink <NavLink

View File

@@ -1,6 +1,4 @@
import { useState, useEffect, useCallback, useRef, useMemo, Suspense } from 'react'; import { useState, useEffect, useCallback, useRef, useMemo, Suspense, startTransition } from 'react';
import PageLoader from '../components/PageLoader';
import FeedPageSkeleton from '../components/FeedPageSkeleton';
import { Outlet, useNavigate, useSearchParams, useLocation } from 'react-router-dom'; import { Outlet, useNavigate, useSearchParams, useLocation } from 'react-router-dom';
import { Menu, Moon, Sun, Search, Plus, PanelRight, X, Mail, SlidersHorizontal } from 'lucide-react'; import { Menu, Moon, Sun, Search, Plus, PanelRight, X, Mail, SlidersHorizontal } from 'lucide-react';
import { import {
@@ -23,7 +21,12 @@ import BackToTop from '../components/BackToTop';
import { useForumLimits } from '../hooks/useForumLimits'; import { useForumLimits } from '../hooks/useForumLimits';
import { resolveAsideWidgets } from '../utils/asideWidgets'; import { resolveAsideWidgets } from '../utils/asideWidgets';
import { buildHomeUrl, parseFeedSort } from '../components/FeedSortBar'; import { buildHomeUrl, parseFeedSort } from '../components/FeedSortBar';
import { navigateFeed } from '../utils/feedCache'; 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 PostSearchPanel from '../components/search/PostSearchPanel';
import { import {
POST_SEARCH_OPEN_EVENT, POST_SEARCH_OPEN_EVENT,
@@ -33,28 +36,44 @@ import { cn } from '@/lib/utils';
import { getBoardThemeIndex } from '../utils/boardTheme'; import { getBoardThemeIndex } from '../utils/boardTheme';
import { loginPath } from '../utils/authRedirect'; import { loginPath } from '../utils/authRedirect';
import { openForumPost } from '../utils/openPost'; 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 SiteBrandMark from '../components/SiteBrandMark';
import SiteFooter from '../components/SiteFooter'; import SiteFooter from '../components/SiteFooter';
import { userPath } from '../utils/userPath'; import { userPath } from '../utils/userPath';
import { parsePermalinkID } from '../utils/permalink'; 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() { export default function MainLayout() {
const { user, loading: authLoading, logout } = useAuth(); const { user, loading: authLoading, logout } = useAuth();
const { theme, toggle } = useTheme(); const { theme, toggle } = useTheme();
const { branding } = useSiteBranding(); const { branding } = useSiteBranding();
const isMobile = useMediaQuery('(max-width: 768px)'); useMonitorPageview();
const mqMobile = useMediaQuery('(max-width: 768px)');
const hideAside = useMediaQuery('(max-width: 1100px)'); const hideAside = useMediaQuery('(max-width: 1100px)');
/** hydrate 首帧强制桌面布局SSR 为桌面三栏),随后再跟 matchMedia */
const [forceDesktop, setForceDesktop] = useState(() => isHomeHydrating());
const isMobile = forceDesktop ? false : mqMobile;
const nav = useNavigate(); const nav = useNavigate();
const loc = useLocation(); const loc = useLocation();
const [params] = useSearchParams(); const [params] = useSearchParams();
const isCompose = loc.pathname.startsWith('/compose') || /\/post\/\d+\/edit$/.test(loc.pathname); 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 [boards, setBoards] = useState<Board[]>(() => getCachedBoards());
const [stats, setStats] = useState<ForumStats | null>(() => getCachedStats()); const [stats, setStats] = useState<ForumStats | null>(() => getCachedStats());
const [recentComments, setRecentComments] = useState<RecentComment[]>(() => getCachedRecentComments()); const [recentComments, setRecentComments] = useState<RecentComment[]>(() => getCachedRecentComments());
const [recentUsers, setRecentUsers] = useState<RecentUser[]>(() => getCachedRecentUsers()); const [recentUsers, setRecentUsers] = useState<RecentUser[]>(() => getCachedRecentUsers());
const [unreadMessages, setUnreadMessages] = useState(0); const [unreadMessages, setUnreadMessages] = useState(() => getBootUnread());
const [dmUnread, setDmUnread] = useState(0);
const [notifyUnread, setNotifyUnread] = useState(0);
const [tags, setTags] = useState<TagCount[]>(() => getCachedTags()); const [tags, setTags] = useState<TagCount[]>(() => getCachedTags());
const [tagsLoading, setTagsLoading] = useState(() => getCachedTags().length === 0); const [tagsLoading, setTagsLoading] = useState(() => getCachedTags().length === 0);
const [postOutline, setPostOutline] = useState<{ const [postOutline, setPostOutline] = useState<{
@@ -71,15 +90,20 @@ export default function MainLayout() {
const searchInputRef = useRef<HTMLInputElement>(null); const searchInputRef = useRef<HTMLInputElement>(null);
const [asideLoading, setAsideLoading] = useState(() => !hasCachedAside()); const [asideLoading, setAsideLoading] = useState(() => !hasCachedAside());
const [boardsLoading, setBoardsLoading] = useState(() => getCachedBoards().length === 0); const [boardsLoading, setBoardsLoading] = useState(() => getCachedBoards().length === 0);
const [layoutRefreshTick, setLayoutRefreshTick] = useState(0);
const asideEverLoaded = useRef(false); const asideEverLoaded = useRef(false);
/** 冷启动门闩main.tsx 已预热则可同步放行;否则等齐再呈现 */
const [shellReady, setShellReady] = useState(() => isCompose || wasColdBootEnsured());
const coldBootDone = useRef(isCompose || wasColdBootEnsured());
const bootGen = useRef(0);
const [boardId, setBoardId] = useState(() => { const [boardId, setBoardId] = useState(() => {
const m = loc.pathname.match(/^\/board\/(\d+(?:\.[A-Za-z0-9]{1,16})?)$/); const m = loc.pathname.match(/^\/board\/(\d+(?:\.[A-Za-z0-9]{1,16})?)$/);
if (m) return parsePermalinkID(m[1]) || 0; if (m) return parsePermalinkID(m[1]) || 0;
return Number(params.get('board')) || 0; return Number(params.get('board')) || 0;
}); });
const [keywordDraft, setKeywordDraft] = useState(params.get('keyword') || ''); const [keywordDraft, setKeywordDraft] = useState(params.get('keyword') || '');
const feedSort = parseFeedSort(params.get('sort'));
const { limits: forumLimits } = useForumLimits(); const { limits: forumLimits } = useForumLimits();
const feedSort = parseFeedSort(params.get('sort'), forumLimits.feed_sort_tabs);
const postSearch = usePostSearch(forumLimits); const postSearch = usePostSearch(forumLimits);
const asideWidgets = useMemo(() => resolveAsideWidgets(forumLimits), [forumLimits]); const asideWidgets = useMemo(() => resolveAsideWidgets(forumLimits), [forumLimits]);
const showTagCloud = asideWidgets.some(w => w.id === 'tag_cloud' && w.enabled); const showTagCloud = asideWidgets.some(w => w.id === 'tag_cloud' && w.enabled);
@@ -126,7 +150,10 @@ export default function MainLayout() {
setSidebarOpen(false); setSidebarOpen(false);
}, [loc.pathname, loc.search]); }, [loc.pathname, loc.search]);
useEffect(() => { 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]); }, [loc.pathname]);
useEffect(() => { useEffect(() => {
if (!hideAside) setAsideOpen(false); if (!hideAside) setAsideOpen(false);
@@ -193,16 +220,120 @@ export default function MainLayout() {
return () => window.removeEventListener('boards-refresh', onRefresh); return () => window.removeEventListener('boards-refresh', onRefresh);
}, [refreshBoards]); }, [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(() => { const refreshUnreadMessages = useCallback(() => {
if (!user) { if (!user) {
setUnreadMessages(0); setUnreadMessages(0);
setDmUnread(0);
setNotifyUnread(0);
return; return;
} }
api.messageUnreadCount() api.messageUnreadCount()
.then((r) => setUnreadMessages(r.count || 0)) .then((r) => {
.catch(() => setUnreadMessages(0)); setUnreadMessages(r.count || 0);
setDmUnread(r.dm_count ?? 0);
setNotifyUnread(r.notify_count ?? 0);
})
.catch(() => {
setUnreadMessages(0);
setDmUnread(0);
setNotifyUnread(0);
});
}, [user]); }, [user]);
/** 仅有通知未读时直达通知 Tab避免先看到空私信列表 */
const openMessages = useCallback(() => {
const path = notifyUnread > 0 && dmUnread === 0 ? '/messages?tab=notify' : '/messages';
void transitionTo(nav, path);
}, [nav, notifyUnread, dmUnread]);
useEffect(() => { useEffect(() => {
refreshUnreadMessages(); refreshUnreadMessages();
const onRefresh = () => refreshUnreadMessages(); const onRefresh = () => refreshUnreadMessages();
@@ -214,10 +345,49 @@ export default function MainLayout() {
}; };
}, [refreshUnreadMessages]); }, [refreshUnreadMessages]);
// 标签云:进页/离开发帖页时拉取;不跟 posts-refresh 联动(置顶/精华等不改标签) useEffect(() => {
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(() => { useEffect(() => {
if (isCompose || !showTagCloud) return; if (isCompose || !showTagCloud) return;
let cancelled = false; let cancelled = false;
// 有 session 缓存则静默刷新(软刷新不卸空白)
if (getCachedTags().length === 0) setTagsLoading(true); if (getCachedTags().length === 0) setTagsLoading(true);
api.tags(40).then(d => { api.tags(40).then(d => {
if (cancelled) return; if (cancelled) return;
@@ -230,7 +400,7 @@ export default function MainLayout() {
return () => { return () => {
cancelled = true; cancelled = true;
}; };
}, [isCompose, showTagCloud]); }, [isCompose, showTagCloud, layoutRefreshTick]);
const needAsideData = !isCompose && (!hideAside || asideOpen); const needAsideData = !isCompose && (!hideAside || asideOpen);
const needRecentComments = needAsideData && showRecentComments; const needRecentComments = needAsideData && showRecentComments;
@@ -257,7 +427,7 @@ export default function MainLayout() {
return () => { return () => {
cancelled = true; cancelled = true;
}; };
}, [needRecentComments]); }, [needRecentComments, layoutRefreshTick]);
const needRecentUsers = needAsideData && showRecentUsers; const needRecentUsers = needAsideData && showRecentUsers;
useEffect(() => { useEffect(() => {
@@ -282,7 +452,7 @@ export default function MainLayout() {
return () => { return () => {
cancelled = true; cancelled = true;
}; };
}, [needRecentUsers]); }, [needRecentUsers, layoutRefreshTick]);
const doQuickSearch = () => { const doQuickSearch = () => {
const { author, titleOnly, scopeBoardId } = postSearch.filters; const { author, titleOnly, scopeBoardId } = postSearch.filters;
@@ -328,6 +498,10 @@ export default function MainLayout() {
const activeChipIndex = Math.max(0, boardChipIds.indexOf(mobileActiveBoard === -1 ? 0 : mobileActiveBoard)); const activeChipIndex = Math.max(0, boardChipIds.indexOf(mobileActiveBoard === -1 ? 0 : mobileActiveBoard));
const isPostDetail = /^\/post\/\d+/.test(loc.pathname) && !/\/edit$/.test(loc.pathname); 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: { const setPostOutlineSafe = useCallback((outline: {
headings: PostHeading[]; headings: PostHeading[];
scrollRoot: HTMLElement | null; scrollRoot: HTMLElement | null;
@@ -367,14 +541,14 @@ export default function MainLayout() {
}; };
return ( return (
<div className="app-shell"> <div className={cn('app-shell', forceDesktop && 'ssr-home')}>
<div className="app-frame"> <div className="app-frame">
<header className="app-header"> <header className="app-header">
<div className="header-inner"> <div className="header-inner">
{isMobile && !isCompose && ( {!isCompose && (
<button <button
type="button" type="button"
className="header-icon-btn" className="header-icon-btn header-menu-btn"
onClick={openSidebar} onClick={openSidebar}
aria-label="打开导航菜单" aria-label="打开导航菜单"
aria-expanded={sidebarOpen} aria-expanded={sidebarOpen}
@@ -384,9 +558,10 @@ export default function MainLayout() {
<Menu size={18} aria-hidden /> <Menu size={18} aria-hidden />
</button> </button>
)} )}
<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" /> <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> </button>
{!isCompose && isMobile && ( {!isCompose && isMobile && (
@@ -467,11 +642,11 @@ export default function MainLayout() {
<button <button
type="button" type="button"
className="header-compose-btn" className="header-compose-btn"
onClick={() => user ? nav('/compose') : nav(loginPath('/compose'))} onClick={() => user ? void transitionTo(nav, '/compose') : nav(loginPath('/compose'))}
aria-label="发帖" aria-label="发帖"
> >
<Plus size={16} aria-hidden /> <Plus size={16} aria-hidden />
{!isMobile && <span></span>} <span className="header-compose-btn__label"></span>
</button> </button>
)} )}
@@ -482,26 +657,24 @@ export default function MainLayout() {
type="button" type="button"
className="header-icon-btn" className="header-icon-btn"
onClick={openAside} onClick={openAside}
aria-label={isPostDetail ? '打开作者与目录' : '打开社区动态'} aria-label={isArticleAside ? `打开${articleAsideLabel}` : '打开社区动态'}
aria-expanded={asideOpen} aria-expanded={asideOpen}
aria-controls="aside-drawer" aria-controls="aside-drawer"
title={isPostDetail ? '作者与目录' : '社区动态'} title={isArticleAside ? articleAsideLabel : '社区动态'}
> >
<PanelRight size={18} aria-hidden /> <PanelRight size={18} aria-hidden />
</button> </button>
)} )}
{!isMobile && ( <button
<button
type="button" type="button"
className="header-icon-btn" className="header-icon-btn header-theme-btn"
onClick={toggle} onClick={toggle}
aria-label={theme === 'light' ? '切换暗色模式' : '切换亮色模式'} aria-label={theme === 'light' ? '切换暗色模式' : '切换亮色模式'}
title={theme === 'light' ? '切换暗色模式' : '切换亮色模式'} title={theme === 'light' ? '切换暗色模式' : '切换亮色模式'}
> >
{theme === 'light' ? <Moon size={18} aria-hidden /> : <Sun size={18} aria-hidden />} {theme === 'light' ? <Moon size={18} aria-hidden /> : <Sun size={18} aria-hidden />}
</button> </button>
)}
{authLoading ? ( {authLoading ? (
<span className="header-auth-slot header-auth-slot--loading" aria-hidden /> <span className="header-auth-slot header-auth-slot--loading" aria-hidden />
@@ -512,7 +685,7 @@ export default function MainLayout() {
className="header-icon-btn header-msg-btn" className="header-icon-btn header-msg-btn"
title={unreadMessages > 0 ? `${unreadMessages} 条未读消息` : '站内消息'} title={unreadMessages > 0 ? `${unreadMessages} 条未读消息` : '站内消息'}
aria-label={unreadMessages > 0 ? `站内消息,${unreadMessages} 条未读` : '站内消息'} aria-label={unreadMessages > 0 ? `站内消息,${unreadMessages} 条未读` : '站内消息'}
onClick={() => nav('/messages')} onClick={openMessages}
> >
<Mail size={18} aria-hidden /> <Mail size={18} aria-hidden />
{unreadMessages > 0 && ( {unreadMessages > 0 && (
@@ -532,14 +705,14 @@ export default function MainLayout() {
className="w-40" className="w-40"
onCloseAutoFocus={(e) => e.preventDefault()} onCloseAutoFocus={(e) => e.preventDefault()}
> >
<DropdownMenuItem onClick={() => nav(userPath(user.id))}></DropdownMenuItem> <DropdownMenuItem onClick={() => void transitionTo(nav, userPath(user.id))}></DropdownMenuItem>
<DropdownMenuItem onClick={() => nav('/profile')}> <DropdownMenuItem onClick={() => void transitionTo(nav, '/profile')}>
{typeof user.points === 'number' ? ` · ${user.points} 积分` : ''} {typeof user.points === 'number' ? ` · ${user.points} 积分` : ''}
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem onClick={() => nav('/messages')}> <DropdownMenuItem onClick={openMessages}>
{unreadMessages > 0 ? ` (${unreadMessages})` : ''} {unreadMessages > 0 ? ` (${unreadMessages})` : ''}
</DropdownMenuItem> </DropdownMenuItem>
<DropdownMenuItem onClick={() => nav('/favorites')}></DropdownMenuItem> <DropdownMenuItem onClick={() => void transitionTo(nav, '/favorites')}></DropdownMenuItem>
{isMobile && ( {isMobile && (
<DropdownMenuItem onClick={toggle}> <DropdownMenuItem onClick={toggle}>
{theme === 'light' ? '切换暗色模式' : '切换亮色模式'} {theme === 'light' ? '切换暗色模式' : '切换亮色模式'}
@@ -585,12 +758,13 @@ export default function MainLayout() {
)} )}
<div className={`app-body${isCompose ? ' app-body--compose' : ''}`}> <div className={`app-body${isCompose ? ' app-body--compose' : ''}`}>
{!isCompose && ( {!isCompose && shellReady && (
<Sidebar <Sidebar
boards={boards} boards={boards}
activeBoard={boardId} activeBoard={boardId}
onSelectBoard={setBoardId} onSelectBoard={setBoardId}
boardsLoading={boardsLoading} boardsLoading={boardsLoading}
/> />
)} )}
@@ -599,13 +773,16 @@ export default function MainLayout() {
isCompose && 'content-workspace--compose', isCompose && 'content-workspace--compose',
hideAside && !isCompose && 'content-workspace--aside-hidden', hideAside && !isCompose && 'content-workspace--aside-hidden',
)}> )}>
<main className={cn( <main
'main-content', className={cn(
isCompose && 'main-content--compose', 'main-content',
// 手机 Feed整栏滚动板块条 / 排序栏可滚出视口,多露出帖子列表 isCompose && 'main-content--compose',
isMobile && !isCompose && isFeedHome && 'main-content--feed-mobile-scroll', // 手机 Feed整栏滚动板块条 / 排序栏可滚出视口,多露出帖子列表
)}> isMobile && !isCompose && isFeedHome && 'main-content--feed-mobile-scroll',
{isMobile && !isCompose && isFeedHome && ( )}
aria-busy={!shellReady}
>
{shellReady && isMobile && !isCompose && isFeedHome && (
<div <div
ref={boardBarRef} ref={boardBarRef}
className="mobile-board-bar" className="mobile-board-bar"
@@ -643,13 +820,16 @@ export default function MainLayout() {
})} })}
</div> </div>
)} )}
<Suspense fallback={isFeedHome ? <FeedPageSkeleton /> : <PageLoader />}> {shellReady ? (
<Outlet context={layoutCtx} /> <Suspense fallback={null}>
</Suspense> <Outlet context={layoutCtx} />
</Suspense>
) : null}
</main> </main>
{!isCompose && ( {!isCompose && (
<aside className="aside-panel"> <aside className="aside-panel" aria-busy={!shellReady}>
{shellReady && (
<RightPanel <RightPanel
recentComments={recentComments} recentComments={recentComments}
recentUsers={recentUsers} recentUsers={recentUsers}
@@ -659,7 +839,8 @@ export default function MainLayout() {
loading={asideLoading} loading={asideLoading}
asideWidgets={asideWidgets} asideWidgets={asideWidgets}
onPostClick={openPost} onPostClick={openPost}
postDetail={isPostDetail ? {
postDetail={isArticleAside ? {
author: postOutline?.author ?? null, author: postOutline?.author ?? null,
publishedAt: postOutline?.publishedAt, publishedAt: postOutline?.publishedAt,
viewCount: postOutline?.viewCount, viewCount: postOutline?.viewCount,
@@ -668,6 +849,7 @@ export default function MainLayout() {
outlineTitle: postOutline?.title, outlineTitle: postOutline?.title,
} : null} } : null}
/> />
)}
</aside> </aside>
)} )}
</div> </div>
@@ -707,12 +889,14 @@ export default function MainLayout() {
</button> </button>
</div> </div>
<div className="aside-drawer-body sidebar-drawer-body"> <div className="aside-drawer-body sidebar-drawer-body">
{shellReady && (
<Sidebar <Sidebar
boards={boards} boards={boards}
activeBoard={boardId} activeBoard={boardId}
onSelectBoard={setBoardId} onSelectBoard={setBoardId}
boardsLoading={boardsLoading} boardsLoading={boardsLoading}
/> />
)}
<div className="sidebar-drawer-extras"> <div className="sidebar-drawer-extras">
<button <button
type="button" type="button"
@@ -720,7 +904,7 @@ export default function MainLayout() {
onClick={() => { closeSidebar(); openAside(); }} onClick={() => { closeSidebar(); openAside(); }}
> >
<PanelRight size={16} aria-hidden /> <PanelRight size={16} aria-hidden />
{isPostDetail ? '作者与目录' : '社区动态'} {isArticleAside ? articleAsideLabel : '社区动态'}
</button> </button>
<button <button
type="button" type="button"
@@ -751,10 +935,10 @@ export default function MainLayout() {
className="aside-drawer" className="aside-drawer"
role="dialog" role="dialog"
aria-modal="true" aria-modal="true"
aria-label={isPostDetail ? '作者与目录' : '社区动态'} aria-label={isArticleAside ? articleAsideLabel : '社区动态'}
> >
<div className="aside-drawer-head"> <div className="aside-drawer-head">
<span>{isPostDetail ? '作者与目录' : '社区动态'}</span> <span>{isArticleAside ? articleAsideLabel : '社区动态'}</span>
<button <button
ref={asideCloseRef} ref={asideCloseRef}
type="button" type="button"
@@ -775,7 +959,7 @@ export default function MainLayout() {
loading={asideLoading} loading={asideLoading}
asideWidgets={asideWidgets} asideWidgets={asideWidgets}
onPostClick={openPost} onPostClick={openPost}
postDetail={isPostDetail ? { postDetail={isArticleAside ? {
author: postOutline?.author ?? null, author: postOutline?.author ?? null,
publishedAt: postOutline?.publishedAt, publishedAt: postOutline?.publishedAt,
viewCount: postOutline?.viewCount, viewCount: postOutline?.viewCount,

View File

@@ -1,12 +1,96 @@
import React from 'react'; import React from 'react';
import ReactDOM from 'react-dom/client'; import { hydrateRoot, createRoot } from 'react-dom/client';
import { applyTheme, getStoredTheme } from './utils/theme'; import { applyTheme, getStoredTheme } from './utils/theme';
import App from './App'; 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()); applyTheme(getStoredTheme());
consumeHomeBoot();
ReactDOM.createRoot(document.getElementById('root')!).render( // Vite modulepreload / 动态 import 失败(发版后旧 hashed URL 404
<React.StrictMode> window.addEventListener('vite:preloadError', (event) => {
<App /> event.preventDefault();
</React.StrictMode> 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

@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react'; import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { ArrowLeft, Star } from 'lucide-react'; import { ArrowLeft, Star } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -7,6 +7,7 @@ import { notify } from '@/lib/notify';
import { api } from '../api/client'; import { api } from '../api/client';
import type { PostItem } from '../api/types'; import type { PostItem } from '../api/types';
import { useAuth } from '../hooks/useAuth'; import { useAuth } from '../hooks/useAuth';
import { useSessionResource } from '../hooks/useSessionResource';
import PostListItem from '../components/PostListItem'; import PostListItem from '../components/PostListItem';
import { loginPath } from '../utils/authRedirect'; import { loginPath } from '../utils/authRedirect';
import { useForumLimits } from '../hooks/useForumLimits'; import { useForumLimits } from '../hooks/useForumLimits';
@@ -26,16 +27,19 @@ export default function FavoritesPage() {
const { user, loading: authLoading } = useAuth(); const { user, loading: authLoading } = useAuth();
const { limits } = useForumLimits(); const { limits } = useForumLimits();
useNoIndexSEO('我的收藏'); 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(() => { useEffect(() => {
if (authLoading) return; if (authLoading) return;
if (!user) { nav(loginPath('/favorites')); return; } if (!user) nav(loginPath('/favorites'));
api.favorites()
.then(d => setList(Array.isArray(d.favorites) ? d.favorites as FavItem[] : []))
.catch(e => notify.error(e.message))
.finally(() => setLoading(false));
}, [user, authLoading, nav]); }, [user, authLoading, nav]);
if (authLoading || loading) return <div className="flex justify-center py-16"><Spinner size="lg" /></div>; if (authLoading || loading) return <div className="flex justify-center py-16"><Spinner size="lg" /></div>;

View File

@@ -1,25 +1,35 @@
import { useState, useEffect, useCallback, useRef } from 'react'; import { useState, useEffect, useCallback, useRef, useMemo, startTransition as reactStartTransition } from 'react';
import { useNavigate, useOutletContext, useSearchParams, useLocation, useParams } from 'react-router-dom'; import {
useNavigate,
useOutletContext,
useSearchParams,
useLocation,
useParams,
useNavigationType,
} from 'react-router-dom';
import { notify } from '@/lib/notify'; import { notify } from '@/lib/notify';
import { api } from '../api/client'; import { api } from '../api/client';
import type { PostItem } from '../api/types'; import type { PostItem } from '../api/types';
import type { LayoutCtx } from '../layouts/MainLayout'; import type { LayoutCtx } from '../layouts/MainLayout';
import VirtualPostList from '../components/VirtualPostList'; import VirtualPostList from '../components/VirtualPostList';
import StaticFeedList from '../components/StaticFeedList';
import FeedHeader from '../components/FeedHeader'; import FeedHeader from '../components/FeedHeader';
import FeedSearchFilters from '../components/search/FeedSearchFilters'; import FeedSearchFilters from '../components/search/FeedSearchFilters';
import FeedPageSkeleton from '../components/FeedPageSkeleton';
import FeedSortBar, { parseFeedSort, buildHomeUrl, type FeedSort } from '../components/FeedSortBar'; import FeedSortBar, { parseFeedSort, buildHomeUrl, type FeedSort } from '../components/FeedSortBar';
import { useForumLimits } from '../hooks/useForumLimits'; import { useForumLimits } from '../hooks/useForumLimits';
import { parseSearchFromUrl, usePostSearch } from '../hooks/usePostSearch'; import { parseSearchFromUrl, usePostSearch } from '../hooks/usePostSearch';
import { import {
getFeedCache,
setFeedCache,
clearAllFeedCache,
navigateFeed, navigateFeed,
FEED_RESET_EVENT, FEED_RESET_EVENT,
FEED_PULL_REFRESH_EVENT,
type FeedNavState, type FeedNavState,
} from '../utils/feedCache'; } 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 { openForumPost } from '../utils/openPost';
import { startTransition, doneTransition } from '../utils/spaTransition';
import { isHomeHydrating } from '../utils/homeHydrate';
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO'; import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
import { siteMetaDescription, useSiteBranding } from '../hooks/useSiteBranding'; import { siteMetaDescription, useSiteBranding } from '../hooks/useSiteBranding';
import { boardPath, canonicalRedirectPath, parsePermalinkID } from '../utils/permalink'; import { boardPath, canonicalRedirectPath, parsePermalinkID } from '../utils/permalink';
@@ -35,9 +45,41 @@ function boardIdFromLocation(routeId: string | undefined, searchParams: URLSearc
return q > 0 ? q : 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() { export default function HomePage() {
const nav = useNavigate(); const nav = useNavigate();
const location = useLocation(); const location = useLocation();
const navType = useNavigationType();
const { id: boardRouteId } = useParams(); const { id: boardRouteId } = useParams();
const [params] = useSearchParams(); const [params] = useSearchParams();
const ctx = useOutletContext<LayoutCtx>(); const ctx = useOutletContext<LayoutCtx>();
@@ -56,7 +98,8 @@ export default function HomePage() {
const tag = params.get('tag') || ''; const tag = params.get('tag') || '';
const author = params.get('author') || ''; const author = params.get('author') || '';
const titleOnly = params.get('title_only') === '1'; 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 board = (ctx?.boards ?? []).find(b => b.id === boardId);
const isSiteHome = !boardId && !keyword && !tag && !author; const isSiteHome = !boardId && !keyword && !tag && !author;
const siteIntro = siteMetaDescription(branding); const siteIntro = siteMetaDescription(branding);
@@ -96,20 +139,117 @@ export default function HomePage() {
} }
}, [queryBoardId, boardId, boardRouteId, params, nav, limits, location.pathname, location.search]); }, [queryBoardId, boardId, boardRouteId, params, nav, limits, location.pathname, location.search]);
const [posts, setPosts] = useState<PostItem[]>([]); // URL 上的 sort 已被后台关闭时,纠正为默认排序
const [postTotal, setPostTotal] = useState(0); useEffect(() => {
const [page, setPage] = useState(1); if (limitsLoading) return;
const [loading, setLoading] = useState(true); if (rawSort !== 'latest' && rawSort !== 'hot' && rawSort !== 'reply') return;
const [restoreScrollTop, setRestoreScrollTop] = useState<number | null>(null); const stillOn = enabledFeedSortTabs(limits.feed_sort_tabs).some(t => t.id === rawSort);
const [listResetKey, setListResetKey] = useState(0); 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 scrollTopRef = useRef(0); const cacheKey = useMemo(
const skipCacheSaveRef = useRef(false); () => feedCacheKey({ boardId, keyword, sort, tag, author, titleOnly }),
const loadingRef = useRef(false); [boardId, keyword, sort, tag, author, titleOnly],
const pageRef = useRef(1); );
// 筛选键变化时同步水合(含首次挂载),保证第一帧就有列表数据
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; pageRef.current = page;
// 与当前筛选一致的列表快照(供卸载/切换筛选时写入缓存) cacheKeyRef.current = cacheKey;
const feedSnapRef = useRef({ boardId, keyword, tag, author, titleOnly, sort, posts, postTotal, page }); 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 totalPages = Math.max(1, Math.ceil(Math.max(postTotal, 0) / pageSize));
const showPagination = totalPages > 1 && posts.length > 0; const showPagination = totalPages > 1 && posts.length > 0;
@@ -121,16 +261,39 @@ export default function HomePage() {
setListResetKey(k => k + 1); setListResetKey(k => k + 1);
}, []); }, []);
/** 同筛选强制刷新:只复位滚动,保留旧列表直到 loadFirst 覆盖 */
const beginFeedRefresh = useCallback(() => { const beginFeedRefresh = useCallback(() => {
skipCacheSaveRef.current = true;
clearAllFeedCache();
resetFeedView(); resetFeedView();
}, [resetFeedView]); }, [resetFeedView]);
const fetchPage = useCallback(async (p: number) => { /** 把当前列表写入 Zustand滚动位置用 ref避免闭包过期 */
if (loadingRef.current) return; const persistFeed = useCallback((
loadingRef.current = true; nextPosts: PostItem[],
setLoading(true); 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 { try {
const data = await api.posts({ const data = await api.posts({
page: p, page: p,
@@ -140,144 +303,229 @@ export default function HomePage() {
tag: tag || '', tag: tag || '',
author: tag ? '' : author, author: tag ? '' : author,
title_only: !tag && titleOnly ? '1' : '', title_only: !tag && titleOnly ? '1' : '',
sort: sort === 'latest' ? '' : sort, sort,
}); });
if (seq !== fetchSeqRef.current) return;
const batch = Array.isArray(data.posts) ? data.posts : []; const batch = Array.isArray(data.posts) ? data.posts : [];
const total = data.total ?? 0; 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); setPosts(batch);
setPostTotal(total); setPostTotal(total);
setPage(p); setPage(p);
pageRef.current = 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) { } catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '加载失败'); if (seq !== fetchSeqRef.current) return;
setPosts([]); if (!silent) {
setPostTotal(0); notify.error(e instanceof Error ? e.message : '加载失败');
setPage(1); if (!keepView) {
pageRef.current = 1; setPosts([]);
setPostTotal(0);
setPage(1);
pageRef.current = 1;
}
}
} finally { } finally {
loadingRef.current = false; if (seq === fetchSeqRef.current) {
setLoading(false); setLoading(false);
setListPending(false);
}
} }
}, [boardId, keyword, tag, author, titleOnly, sort, pageSize]); }, [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) => { const goToPage = useCallback((p: number) => {
if (loadingRef.current) return;
const maxPage = Math.max(1, Math.ceil(Math.max(postTotal, 0) / pageSize)); const maxPage = Math.max(1, Math.ceil(Math.max(postTotal, 0) / pageSize));
if (p < 1 || p > maxPage) return; if (p < 1 || p > maxPage) return;
if (p === pageRef.current) return; if (p === pageRef.current) return;
resetFeedView(); void fetchPage(p, { resetScroll: true });
fetchPage(p); }, [fetchPage, postTotal, pageSize]);
}, [fetchPage, postTotal, pageSize, resetFeedView]);
const handleSelectPost = useCallback((id: number) => { const handleSelectPost = useCallback((id: number) => {
// 离开前再写一次滚动,确保详情页返回可还原
getHomeStoreState().patchScroll(viewKeyRef.current, scrollTopRef.current);
openForumPost(nav, id, limits.open_posts_in_new_tab); openForumPost(nav, id, limits.open_posts_in_new_tab);
}, [nav, limits.open_posts_in_new_tab]); }, [nav, limits.open_posts_in_new_tab]);
// 等限制就绪后再拉列表;筛选变化时重载 // 等限制就绪后再决定:强制刷新 / 用缓存 / 静默刷新 / 首拉
useEffect(() => { useEffect(() => {
if (limitsLoading || isInvalidBoardRoute || isMissingBoard) return; if (limitsLoading || isInvalidBoardRoute || isMissingBoard) return;
const forceRefresh = (location.state as FeedNavState | null)?.refreshFeed; const forceRefresh = (location.state as FeedNavState | null)?.refreshFeed;
if (forceRefresh) { // 浏览器后退/前进POP忽略 history 上残留的 refreshFeed避免误清空缓存
beginFeedRefresh(); if (forceRefresh && navType !== 'POP') {
loadFirst(); 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; 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) { if (cached && cached.posts.length > 0) {
setPosts(cached.posts); const needRestore = hydratedKeyRef.current !== cacheKey;
setPostTotal(cached.postTotal); hydratedKeyRef.current = cacheKey;
setPage(cached.page); if (needRestore) {
pageRef.current = cached.page; commitDisplayed({
setRestoreScrollTop(cached.scrollTop); posts: cached.posts,
scrollTopRef.current = cached.scrollTop; postTotal: cached.postTotal,
setLoading(false); 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;
setLoading(false);
setListPending(false);
setView({ cacheKey, sort, boardId, keyword, tag, author, titleOnly });
}
return; return;
} }
setRestoreScrollTop(null); hydratedKeyRef.current = cacheKey;
scrollTopRef.current = 0; if (postsRef.current.length === 0) {
setRestoreScrollTop(null);
scrollTopRef.current = 0;
}
loadFirst(); loadFirst();
}, [ }, [
limitsLoading, limitsLoading,
pageSize, pageSize,
cacheKey,
location.key,
location.state,
location.pathname,
location.search,
location.hash,
navType,
nav,
loadFirst,
commitDisplayed,
resetFeedView,
isInvalidBoardRoute,
isMissingBoard,
sort,
boardId, boardId,
keyword, keyword,
tag, tag,
author, author,
titleOnly, titleOnly,
sort,
location.key,
location.state,
loadFirst,
beginFeedRefresh,
isInvalidBoardRoute,
isMissingBoard,
]); ]);
// 筛选未变时同步列表快照;变筛选的那一帧先保留旧快照供 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(() => { useEffect(() => {
// cleanup 先保存上一档;再把快照重置为当前筛选的空占位 // Logo 等同 URL 强制刷新:仅复位滚动,不卸列表(数据由 transitionTo 预热)
feedSnapRef.current = { boardId, keyword, tag, author, titleOnly, sort, posts: [], postTotal: 0, page: 1 }; const onFeedReset = () => {
return () => { fetchSeqRef.current += 1;
if (skipCacheSaveRef.current) return; resetFeedView();
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);
}; };
}, [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); window.addEventListener(FEED_RESET_EVENT, onFeedReset);
return () => window.removeEventListener(FEED_RESET_EVENT, onFeedReset); return () => window.removeEventListener(FEED_RESET_EVENT, onFeedReset);
}, [beginFeedRefresh]); }, [resetFeedView]);
useEffect(() => { useEffect(() => {
const fn = () => { // 下拉 / posts-refresh / 软刷新 commit有预热则一次覆盖禁止先卸列表
beginFeedRefresh(); const applyWarmOrReload = () => {
loadFirst(); 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;
}
// 未命中:保留旧 posts静默重拉
if (postsRef.current.length > 0) {
setListPending(true);
setLoading(false);
void loadFirst();
return;
}
setLoading(true);
void loadFirst();
}; };
window.addEventListener('posts-refresh', fn); window.addEventListener('posts-refresh', applyWarmOrReload);
return () => window.removeEventListener('posts-refresh', fn); window.addEventListener(FEED_PULL_REFRESH_EVENT, applyWarmOrReload);
}, [beginFeedRefresh, loadFirst]); 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 handleSortChange = (next: FeedSort) => {
const url = buildHomeUrl(boardId, next, { keyword, tag, author, titleOnly, permalink: limits });
// 排序标签:一律强制刷新到第 1 页顶部,不恢复浏览进度
if (next === sort) { if (next === sort) {
const tid = startTransition();
getHomeStoreState().clearFeed(cacheKeyRef.current);
beginFeedRefresh(); beginFeedRefresh();
loadFirst(); void Promise.resolve(loadFirst({ resetScroll: true })).finally(() => doneTransition(tid));
return; return;
} }
navigateFeed(nav, buildHomeUrl(boardId, next, { keyword, tag, author, titleOnly, permalink: limits })); 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 searchFilters = parseSearchFromUrl(location.pathname, params);
const isSearchActive = !!(keyword || author); const isSearchActive = !!(view.keyword || view.author);
if (isInvalidBoardRoute || isMissingBoard) { if (isInvalidBoardRoute || isMissingBoard) {
return ( return (
@@ -288,9 +536,9 @@ export default function HomePage() {
); );
} }
// 首屏用同构骨架,避免标题/列表分区先后出现造成闪动 // 冷启动由门闩 / ensureColdBootReady 挡住;有旧列表时软刷新绝不卸空
if ((loading || limitsLoading || (isBoardRoute && boardsLoading)) && posts.length === 0) { if ((loading || limitsLoading || (isBoardRoute && boardsLoading)) && posts.length === 0) {
return <FeedPageSkeleton />; return null;
} }
return ( return (
@@ -298,15 +546,32 @@ export default function HomePage() {
<div className="feed-panel"> <div className="feed-panel">
<div className="feed-top"> <div className="feed-top">
<div className="feed-top__bar"> <div className="feed-top__bar">
<FeedHeader {!useVirtualList ? (
keyword={keyword} (view.keyword || view.tag || view.author) ? (
tag={tag} <h1 className="feed-header-title">
author={author} {view.tag
postTotal={postTotal} ? `#${view.tag}`
titleAs={isSiteHome ? 'h2' : 'h1'} : view.keyword
/> ? `搜索:${view.keyword}`
: `作者:${view.author}`}
</h1>
) : null
) : (
<FeedHeader
keyword={view.keyword}
tag={view.tag}
author={view.author}
postTotal={postTotal}
titleAs={isSiteHome ? 'h2' : 'h1'}
/>
)}
{showSortBar && ( {showSortBar && (
<FeedSortBar value={sort} onChange={handleSortChange} postTotal={postTotal} /> <FeedSortBar
value={view.sort}
pendingValue={listPending ? sort : null}
onChange={handleSortChange}
postTotal={postTotal}
/>
)} )}
</div> </div>
{isSearchActive && ( {isSearchActive && (
@@ -318,32 +583,36 @@ export default function HomePage() {
/> />
)} )}
</div> </div>
<VirtualPostList {!useVirtualList ? (
posts={posts} <StaticFeedList posts={posts} sort={view.sort} boardId={view.boardId} />
sort={sort} ) : (
loading={loading || limitsLoading} <VirtualPostList
hasMore={hasMore} posts={posts}
showPagination={showPagination} sort={view.sort}
page={page} loading={listPending ? false : (loading || limitsLoading)}
totalPages={totalPages} hasMore={hasMore}
postTotal={postTotal} showPagination={showPagination}
onPageChange={goToPage} page={page}
onSelect={handleSelectPost} totalPages={totalPages}
restoreScrollTop={restoreScrollTop} postTotal={postTotal}
resetScrollKey={listResetKey} onPageChange={goToPage}
onScrollTopChange={(top) => { scrollTopRef.current = top; }} onSelect={handleSelectPost}
onScrollRestored={() => setRestoreScrollTop(null)} restoreScrollTop={restoreScrollTop}
keyword={keyword || tag || author} resetScrollKey={listResetKey}
isSearchMode={!!(keyword || author)} onScrollTopChange={handleScrollTopChange}
searchKeyword={keyword} onScrollRestored={() => setRestoreScrollTop(null)}
searchAuthor={author} keyword={view.keyword || view.tag || view.author}
searchTitleOnly={titleOnly} isSearchMode={!!(view.keyword || view.author)}
searchScopeBoardId={searchFilters.scopeBoardId} searchKeyword={view.keyword}
onClearSearch={postSearch.clearSearch} searchAuthor={view.author}
boardId={boardId} searchTitleOnly={view.titleOnly}
boardName={ctx?.boards?.find(b => b.id === boardId)?.name || ''} searchScopeBoardId={searchFilters.scopeBoardId}
noBoards={!ctx?.boardsLoading && (ctx?.boards?.length ?? 0) === 0} 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>
</div> </div>
); );

View File

@@ -15,6 +15,7 @@ import { loginPath } from '../utils/authRedirect';
import { resolveFriendLinkLogo, isReciprocalChecking, reciprocalStatusLabel } from '../utils/friendLink'; import { resolveFriendLinkLogo, isReciprocalChecking, reciprocalStatusLabel } from '../utils/friendLink';
import { InFlowSiteFooter } from '../components/SiteFooter'; import { InFlowSiteFooter } from '../components/SiteFooter';
import FriendLinkApplyDialog from '../components/FriendLinkApplyDialog'; import FriendLinkApplyDialog from '../components/FriendLinkApplyDialog';
import { useSessionResource } from '../hooks/useSessionResource';
const APPLY_STATUS_ORDER: Record<FriendLinkApply['status'], number> = { const APPLY_STATUS_ORDER: Record<FriendLinkApply['status'], number> = {
pending: 0, pending: 0,
@@ -48,8 +49,6 @@ export default function LinksPage() {
const { user } = useAuth(); const { user } = useAuth();
const [applyOpen, setApplyOpen] = useState(false); const [applyOpen, setApplyOpen] = useState(false);
const [editApply, setEditApply] = useState<FriendLinkApply | null>(null); const [editApply, setEditApply] = useState<FriendLinkApply | null>(null);
const [myApplies, setMyApplies] = useState<FriendLinkApply[]>([]);
const [myLoading, setMyLoading] = useState(false);
const [cancelingId, setCancelingId] = useState<number | null>(null); const [cancelingId, setCancelingId] = useState<number | null>(null);
usePageSEO({ usePageSEO({
@@ -63,6 +62,15 @@ export default function LinksPage() {
(l: FriendLink) => l.name?.trim() && l.url?.trim(), (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( const sortedApplies = useMemo(
() => [...myApplies].sort((a, b) => { () => [...myApplies].sort((a, b) => {
const byStatus = APPLY_STATUS_ORDER[a.status] - APPLY_STATUS_ORDER[b.status]; const byStatus = APPLY_STATUS_ORDER[a.status] - APPLY_STATUS_ORDER[b.status];
@@ -98,16 +106,10 @@ export default function LinksPage() {
setMyApplies([]); setMyApplies([]);
return; return;
} }
setMyLoading(true);
api.myFriendLinkApplies() api.myFriendLinkApplies()
.then(r => setMyApplies(r.applies ?? [])) .then(r => setMyApplies(r.applies ?? []))
.catch(e => notify.error(e instanceof Error ? e.message : '加载失败')) .catch(e => notify.error(e instanceof Error ? e.message : '加载失败'));
.finally(() => setMyLoading(false)); }, [user, setMyApplies]);
}, [user]);
useEffect(() => {
loadMyApplies();
}, [loadMyApplies]);
useEffect(() => { useEffect(() => {
if (!user || !myApplies.some(isReciprocalChecking)) return; if (!user || !myApplies.some(isReciprocalChecking)) return;

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 { useState, useEffect, useLayoutEffect, useRef, useCallback, useMemo } from 'react';
import { useParams, useNavigate, useOutletContext, useLocation } from 'react-router-dom'; import { useParams, useNavigate, useOutletContext, useLocation, useNavigationType } 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 { ArrowLeft, ThumbsUp, Star, Lock, MessageSquare, MessageSquareOff, Flag, MoreHorizontal } from 'lucide-react';
import FeaturedIcon from '@/components/FeaturedIcon'; import FeaturedIcon from '@/components/FeaturedIcon';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
@@ -16,7 +16,6 @@ import {
AlertDialogFooter, AlertDialogFooter,
AlertDialogHeader, AlertDialogHeader,
AlertDialogTitle, AlertDialogTitle,
AlertDialogTrigger,
} from '@/components/ui/alert-dialog'; } from '@/components/ui/alert-dialog';
import { import {
DropdownMenu, DropdownMenu,
@@ -44,6 +43,7 @@ import PostBountyBanner from '../components/PostBountyBanner';
import { findCommentFloor } from '../utils/bounty'; import { findCommentFloor } from '../utils/bounty';
import PostLotteryCard from '../components/PostLotteryCard'; import PostLotteryCard from '../components/PostLotteryCard';
import PostRevisionPanel from '../components/PostRevisionPanel'; import PostRevisionPanel from '../components/PostRevisionPanel';
import PostManageMenu from '../components/PostManageMenu';
import ArticleOutline from '../components/ArticleOutline'; import ArticleOutline from '../components/ArticleOutline';
import { useAuth } from '../hooks/useAuth'; import { useAuth } from '../hooks/useAuth';
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO'; import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
@@ -51,17 +51,41 @@ import { getCachedSiteBranding } from '../hooks/useSiteBranding';
import { formatDateTime, isTimeDiffSignificant } from '../utils/content'; import { formatDateTime, isTimeDiffSignificant } from '../utils/content';
import { collectCommentSubtreeIds } from '../utils/comment'; import { collectCommentSubtreeIds } from '../utils/comment';
import { loadMyCommentIds } from '../utils/guest'; 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 { useGlobalWheelScroll } from '../hooks/useGlobalWheelScroll';
import { loginPath } from '../utils/authRedirect'; import { loginPath } from '../utils/authRedirect';
import { excerptFromHTML, firstImageFromHTML } from '../utils/seoText'; import { excerptFromHTML, firstImageFromHTML } from '../utils/seoText';
import { canonicalRedirectPath, parsePermalinkID, postPath } from '../utils/permalink'; import { canonicalRedirectPath, parsePermalinkID, postPath } from '../utils/permalink';
import { useForumLimits } from '../hooks/useForumLimits'; import { useForumLimits } from '../hooks/useForumLimits';
import type { LayoutCtx } from '../layouts/MainLayout'; 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 { InFlowSiteFooter } from '../components/SiteFooter';
import NotFoundPage from './NotFoundPage'; 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 { function formatEditRemaining(createdAt: string, windowHours: number): string {
if (windowHours <= 0) return ''; if (windowHours <= 0) return '';
@@ -80,29 +104,35 @@ export default function PostDetailPage() {
const postId = parsePermalinkID(id); const postId = parsePermalinkID(id);
const nav = useNavigate(); const nav = useNavigate();
const location = useLocation(); const location = useLocation();
const navType = useNavigationType();
const { user, refresh } = useAuth(); const { user, refresh } = useAuth();
const { limits } = useForumLimits(); const { limits } = useForumLimits();
const { setPostOutline, isMobile } = useOutletContext<LayoutCtx>(); const { setPostOutline, isMobile } = useOutletContext<LayoutCtx>();
const [post, setPost] = useState<PostItem | null>(null); const initialSnap = (postId && !Number.isNaN(postId) && navType === 'POP')
const [poll, setPoll] = useState<PollView | null>(null); ? getSessionSnapshot<PostDetailSnapshot>(postDetailCacheKey(postId))
const [lottery, setLottery] = useState<PostLotteryView | null>(null); : undefined;
const [comments, setComments] = useState<Comment[]>([]);
const [liked, setLiked] = useState(false); const [post, setPost] = useState<PostItem | null>(initialSnap?.post ?? null);
const [favorited, setFavorited] = useState(false); 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 [replyTo, setReplyTo] = useState<Comment | null>(null);
const [editingCommentId, setEditingCommentId] = useState<number | null>(null); const [editingCommentId, setEditingCommentId] = useState<number | null>(null);
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(!initialSnap);
const [highlightFloor, setHighlightFloor] = useState<number | null>(null); const [highlightFloor, setHighlightFloor] = useState<number | null>(null);
const [submitCount, setSubmitCount] = useState(0); const [submitCount, setSubmitCount] = useState(0);
const [canEdit, setCanEdit] = useState(false); const [canEdit, setCanEdit] = useState(initialSnap?.canEdit ?? false);
const [isEdited, setIsEdited] = useState(false); const [isEdited, setIsEdited] = useState(initialSnap?.isEdited ?? false);
const [editBlockReason, setEditBlockReason] = useState(''); const [editBlockReason, setEditBlockReason] = useState(initialSnap?.editBlockReason ?? '');
const [editWindowHours, setEditWindowHours] = useState(0); const [editWindowHours, setEditWindowHours] = useState(initialSnap?.editWindowHours ?? 0);
const [showRevisions, setShowRevisions] = useState(false); const [showRevisions, setShowRevisions] = useState(false);
const [deletingPost, setDeletingPost] = 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 [reportOpen, setReportOpen] = useState(false);
const [reportReason, setReportReason] = useState<ReportReason>('spam'); const [reportReason, setReportReason] = useState<ReportReason>('spam');
const [reportDetail, setReportDetail] = useState(''); const [reportDetail, setReportDetail] = useState('');
@@ -112,14 +142,25 @@ export default function PostDetailPage() {
const [rejecting, setRejecting] = useState(false); const [rejecting, setRejecting] = useState(false);
const [bountyAwardTarget, setBountyAwardTarget] = useState<number | null>(null); const [bountyAwardTarget, setBountyAwardTarget] = useState<number | null>(null);
const [bountyAwarding, setBountyAwarding] = useState(false); const [bountyAwarding, setBountyAwarding] = useState(false);
const [bountyCanRefund, setBountyCanRefund] = useState(true); const [bountyCanRefund, setBountyCanRefund] = useState(initialSnap?.bountyCanRefund ?? true);
const [bountyRefundBlockReason, setBountyRefundBlockReason] = useState(''); const [bountyRefundBlockReason, setBountyRefundBlockReason] = useState(initialSnap?.bountyRefundBlockReason ?? '');
const [bountyEligibleReplyCount, setBountyEligibleReplyCount] = useState(0); 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 pageRef = useRef<HTMLDivElement>(null);
const commentSectionRef = useRef<HTMLDivElement>(null); const commentSectionRef = useRef<HTMLDivElement>(null);
const commentBoxRef = useRef<HTMLDivElement>(null); const commentBoxRef = useRef<HTMLDivElement>(null);
const highlightTimer = useRef<ReturnType<typeof setTimeout>>(); 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); useGlobalWheelScroll(pageRef, !loading && !!post);
@@ -132,6 +173,15 @@ export default function PostDetailPage() {
const brand = getCachedSiteBranding(); const brand = getCachedSiteBranding();
const postContent = post?.content ?? ''; 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 ? { const postSEO = post ? {
title: post.title, title: post.title,
description: excerptFromHTML(postContent), description: excerptFromHTML(postContent),
@@ -155,10 +205,6 @@ export default function PostDetailPage() {
} : null; } : null;
usePageSEO(postSEO); usePageSEO(postSEO);
const handleHeadingsChange = useCallback((next: PostHeading[]) => {
setHeadings(next);
}, []);
useEffect(() => { useEffect(() => {
if (loading || !post) { if (loading || !post) {
setPostOutline({ headings: [], scrollRoot: null, title: '文章目录' }); setPostOutline({ headings: [], scrollRoot: null, title: '文章目录' });
@@ -178,18 +224,62 @@ export default function PostDetailPage() {
const loadSeq = useRef(0); const loadSeq = useRef(0);
const detailPath = postPath(postId, limits); 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)) { if (!postId || Number.isNaN(postId)) {
setPost(null); setPost(null);
setLoading(false); setLoading(false);
return; return;
} }
if (mode === 'force') {
deleteSessionSnapshot(postDetailCacheKey(postId));
}
const cached = mode === 'force' || navType !== 'POP'
? undefined
: getSessionSnapshot<PostDetailSnapshot>(postDetailCacheKey(postId));
if (cached) {
loadSeq.current += 1;
applySnapshot(cached, { restoreScroll: navType === 'POP' && !location.hash });
setReplyTo(null);
setEditingCommentId(null);
setComposerOpen(false);
setLoading(false);
return;
}
const seq = ++loadSeq.current;
const keep = !!postRef.current;
setReplyTo(null); setReplyTo(null);
setEditingCommentId(null); setEditingCommentId(null);
setHeadings([]); setComposerOpen(false);
const seq = ++loadSeq.current; if (!keep) {
setLoading(true); setLoading(true);
setPost(null); setPost(null);
}
(async () => { (async () => {
try { try {
@@ -199,30 +289,108 @@ export default function PostDetailPage() {
api.comments(postId, myIds), api.comments(postId, myIds),
]); ]);
if (seq !== loadSeq.current) return; if (seq !== loadSeq.current) return;
setPost(detail.post); const commentsList = Array.isArray(comm.comments) ? comm.comments : [];
setPoll(detail.poll ?? null); const snap: PostDetailSnapshot = {
setLottery(detail.lottery ?? null); post: detail.post,
setLiked(detail.liked); comments: commentsList,
setFavorited(detail.favorited); poll: detail.poll ?? null,
setCanEdit(detail.can_edit ?? false); lottery: detail.lottery ?? null,
setIsEdited(detail.is_edited ?? isTimeDiffSignificant(detail.post.created_at, detail.post.updated_at ?? detail.post.created_at)); liked: detail.liked,
setEditBlockReason(detail.edit_block_reason ?? ''); favorited: detail.favorited,
setEditWindowHours(detail.post_edit_window_hours ?? 0); canEdit: detail.can_edit ?? false,
setBountyCanRefund(detail.bounty_can_refund ?? true); isEdited: detail.is_edited ?? isTimeDiffSignificant(detail.post.created_at, detail.post.updated_at ?? detail.post.created_at),
setBountyRefundBlockReason(detail.bounty_refund_block_reason ?? ''); editBlockReason: detail.edit_block_reason ?? '',
setBountyEligibleReplyCount(detail.bounty_eligible_reply_count ?? 0); editWindowHours: detail.post_edit_window_hours ?? 0,
setComments(Array.isArray(comm.comments) ? comm.comments : []); 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(); void refresh();
} catch { } catch {
if (seq !== loadSeq.current) return; if (seq !== loadSeq.current) return;
setPost(null); if (!keep) setPost(null);
} finally { } finally {
if (seq === loadSeq.current) setLoading(false); if (seq === loadSeq.current) setLoading(false);
} }
})(); })();
};
useEffect(() => {
loadPostRef.current('auto');
// eslint-disable-next-line react-hooks/exhaustive-deps -- 仅 postId 变化时加载 // eslint-disable-next-line react-hooks/exhaustive-deps -- 仅 postId 变化时加载
}, [postId]); }, [postId]);
useEffect(() => {
// 下拉/软刷新:始终强制重拉,确保拿到最新数据
const onForce = () => {
if (!postId || Number.isNaN(postId)) 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 reloadComments = useCallback(async () => {
const myIds = user ? [] : loadMyCommentIds(); const myIds = user ? [] : loadMyCommentIds();
const comm = await api.comments(postId, myIds); const comm = await api.comments(postId, myIds);
@@ -244,15 +412,54 @@ export default function PostDetailPage() {
} }
}, [postId]); }, [postId]);
const scrollToCommentBox = useCallback(() => { const focusCommentEditor = useCallback(() => {
const target = commentBoxRef.current || commentSectionRef.current; const root = commentBoxRef.current;
target?.scrollIntoView({ behavior: 'smooth', block: 'center' }); if (!root) return;
window.setTimeout(() => { const editable = root.querySelector<HTMLElement>('.ProseMirror, [contenteditable="true"]');
const ta = commentBoxRef.current?.querySelector('textarea'); editable?.focus({ preventScroll: true });
ta?.focus({ preventScroll: true });
}, 320);
}, []); }, []);
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 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 jumpToFloor = useCallback((floor: number) => {
const el = document.getElementById(`floor-${floor}`); const el = document.getElementById(`floor-${floor}`);
if (!el) return false; if (!el) return false;
@@ -468,6 +675,7 @@ export default function PostDetailPage() {
}); });
setReplyTo(null); setReplyTo(null);
setSubmitCount(c => c + 1); setSubmitCount(c => c + 1);
if (isMobile) setComposerOpen(false);
notify.success(r.message || (r.status === 'pending' ? '评论已提交审核' : '评论成功')); notify.success(r.message || (r.status === 'pending' ? '评论已提交审核' : '评论成功'));
await Promise.all([reloadComments(), reloadPostContent()]); await Promise.all([reloadComments(), reloadPostContent()]);
setTimeout(() => jumpToFloor(r.floor), 100); setTimeout(() => jumpToFloor(r.floor), 100);
@@ -530,6 +738,7 @@ export default function PostDetailPage() {
setDeletingPost(true); setDeletingPost(true);
try { try {
await api.deletePost(postId); await api.deletePost(postId);
deleteSessionSnapshot(postDetailCacheKey(postId));
clearAllFeedCache(); clearAllFeedCache();
window.dispatchEvent(new Event('posts-refresh')); window.dispatchEvent(new Event('posts-refresh'));
notify.success('帖子已删除'); notify.success('帖子已删除');
@@ -549,7 +758,7 @@ export default function PostDetailPage() {
onCancelReply: () => setReplyTo(null), 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) { if (!post) {
return ( return (
<NotFoundPage <NotFoundPage
@@ -738,12 +947,38 @@ export default function PostDetailPage() {
<article className="page-wrap post-detail-page" ref={pageRef}> <article className="page-wrap post-detail-page" ref={pageRef}>
<div className="post-detail-header"> <div className="post-detail-header">
<div className="post-detail-nav"> <div className="post-detail-nav">
<Button variant="ghost" size="sm" onClick={() => nav(-1)}> <div className="post-detail-nav-left">
<ArrowLeft /> <Button variant="ghost" size="sm" onClick={() => nav(-1)}>
<ArrowLeft />
</Button>
{post.board && ( </Button>
<BoardBadge board={post.board} className="post-detail-board-tag" /> {post.board && (
<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> </div>
@@ -882,9 +1117,8 @@ export default function PostDetailPage() {
<PostContent <PostContent
html={post.content || ''} html={post.content || ''}
isLoggedIn={!!user} isLoggedIn={isLoggedIn}
postId={post.id} postId={post.id}
onHeadingsChange={handleHeadingsChange}
onRequestReply={scrollToCommentBox} onRequestReply={scrollToCommentBox}
onUnlocked={() => { void reloadPostContent(); }} onUnlocked={() => { void reloadPostContent(); }}
/> />
@@ -943,101 +1177,32 @@ export default function PostDetailPage() {
</DropdownMenu> </DropdownMenu>
) : null} ) : null}
</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>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel></AlertDialogCancel>
<AlertDialogAction onClick={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>
</div> </div>
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle></AlertDialogTitle>
<AlertDialogDescription>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deletingPost}></AlertDialogCancel>
<AlertDialogAction
disabled={deletingPost}
onClick={(e) => {
e.preventDefault();
void handleDeletePost();
}}
>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Dialog open={reportOpen} onOpenChange={setReportOpen}> <Dialog open={reportOpen} onOpenChange={setReportOpen}>
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
@@ -1122,7 +1287,45 @@ export default function PostDetailPage() {
</div> </div>
) : !replyTo && ( ) : !replyTo && (
<div className="comment-box-wrap" ref={commentBoxRef}> <div className="comment-box-wrap" ref={commentBoxRef}>
<CommentBox {...commentBoxProps} /> {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>
)} )}

View File

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

View File

@@ -10,14 +10,13 @@ import ProjectListItem from '../components/ProjectListItem';
import { InFlowSiteFooter } from '../components/SiteFooter'; import { InFlowSiteFooter } from '../components/SiteFooter';
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO'; import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
import { getCachedSiteBranding } from '../hooks/useSiteBranding'; import { getCachedSiteBranding } from '../hooks/useSiteBranding';
import { useSessionResource } from '../hooks/useSessionResource';
type ProjectsSnap = { list: GiteaProject[]; total: number; totalPages: number };
export default function ProjectsPage() { export default function ProjectsPage() {
const nav = useNavigate(); const nav = useNavigate();
const [list, setList] = useState<GiteaProject[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(0);
const [loading, setLoading] = useState(true);
const [queryInput, setQueryInput] = useState(''); const [queryInput, setQueryInput] = useState('');
const [query, setQuery] = useState(''); const [query, setQuery] = useState('');
@@ -40,24 +39,20 @@ export default function ProjectsPage() {
return () => window.clearTimeout(t); return () => window.clearTimeout(t);
}, [queryInput]); }, [queryInput]);
useEffect(() => { const { data, loading } = useSessionResource<ProjectsSnap>(
let cancelled = false; `projects:${page}:${query}`,
setLoading(true); () => api.projects({ page, limit: 30, q: query || undefined }).then(d => ({
api.projects({ page, limit: 30, q: query || undefined }) list: Array.isArray(d.projects) ? d.projects : [],
.then(d => { total: d.total ?? 0,
if (cancelled) return; totalPages: d.total_pages ?? 0,
setList(Array.isArray(d.projects) ? d.projects : []); })),
setTotal(d.total ?? 0); {
setTotalPages(d.total_pages ?? 0); onError: (e) => notify.error(e instanceof Error ? e.message : '加载失败'),
}) },
.catch(e => { );
if (!cancelled) notify.error(e instanceof Error ? e.message : '加载失败'); const list = data?.list ?? [];
}) const total = data?.total ?? 0;
.finally(() => { const totalPages = data?.totalPages ?? 0;
if (!cancelled) setLoading(false);
});
return () => { cancelled = true; };
}, [page, query]);
return ( return (
<div className="page-wrap"> <div className="page-wrap">

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

@@ -1,14 +1,18 @@
import { useEffect, useState } from 'react'; import { useEffect, useMemo, useRef } from 'react';
import { useParams } from 'react-router-dom'; import { useOutletContext, useParams } from 'react-router-dom';
import NotFoundPage from './NotFoundPage'; import NotFoundPage from './NotFoundPage';
import { api } from '../api/client'; import { api } from '../api/client';
import type { SitePage } from '../api/types'; import type { SitePage } from '../api/types';
import ArticleOutline from '../components/ArticleOutline';
import PostContent from '../components/PostContent'; import PostContent from '../components/PostContent';
import PageLoader from '../components/PageLoader';
import { usePageSEO } from '../hooks/usePageSEO'; import { usePageSEO } from '../hooks/usePageSEO';
import { parsePermalinkSlug, pagePath } from '../utils/permalink'; import { parsePermalinkSlug, pagePath } from '../utils/permalink';
import { useForumLimits } from '../hooks/useForumLimits'; import { useForumLimits } from '../hooks/useForumLimits';
import { useAuth } from '../hooks/useAuth'; 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() { export default function SitePageView() {
@@ -16,22 +20,25 @@ export default function SitePageView() {
const slug = parsePermalinkSlug(rawSlug); const slug = parsePermalinkSlug(rawSlug);
const { limits } = useForumLimits(); const { limits } = useForumLimits();
const { user } = useAuth(); const { user } = useAuth();
const [page, setPage] = useState<SitePage | null>(null); const { setPostOutline, isMobile } = useOutletContext<LayoutCtx>();
const [loading, setLoading] = useState(true); const pageRef = useRef<HTMLDivElement>(null);
const [notFound, setNotFound] = useState(false); 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 ?? '';
useEffect(() => { // 同步从正文派生目录,与帖子详情共用右侧栏目录布局
if (!slug) { const headings = useMemo(() => {
setNotFound(true); if (!pageContent.trim()) return [];
setLoading(false); const rendered = renderPostContentHtml(pageContent, isLoggedIn, {
return; openLinksInNewTab: limits.open_content_links_in_new_tab,
} });
setLoading(true); return extractHeadingsFromHtml(rendered);
api.page(slug) }, [pageContent, isLoggedIn, limits.open_content_links_in_new_tab]);
.then(d => setPage(d.page))
.catch(() => setNotFound(true))
.finally(() => setLoading(false));
}, [slug]);
usePageSEO({ usePageSEO({
title: page?.title, title: page?.title,
@@ -40,19 +47,42 @@ export default function SitePageView() {
ogType: 'article', 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 (!slug) return <NotFoundPage title="页面不存在" />;
if (loading) return <PageLoader />; if (loading) return null;
if (notFound || !page) return <NotFoundPage title="页面不存在" description="该页面不存在或未发布" />; if (notFound || !page) return <NotFoundPage title="页面不存在" description="该页面不存在或未发布" />;
return ( return (
<div className="page-wrap"> <div className="page-wrap" ref={pageRef}>
<article className="site-page"> <article className="site-page">
<header className="site-page__head"> <header className="site-page__head">
<h1>{page.title}</h1> <h1>{page.title}</h1>
</header> </header>
{isMobile && headings.length > 0 && (
<details className="post-detail-toc-mobile">
<summary>{headings.length}</summary>
<ArticleOutline
headings={headings}
scrollRoot={pageRef.current}
title="目录"
/>
</details>
)}
<PostContent <PostContent
html={page.content} html={page.content}
isLoggedIn={!!user} isLoggedIn={isLoggedIn}
className="site-page__body post-detail-content" className="site-page__body post-detail-content"
/> />
</article> </article>

View File

@@ -20,9 +20,9 @@ import { api } from '../api/client';
import type { PostItem, UserActivityStats, UserPublic } from '../api/types'; import type { PostItem, UserActivityStats, UserPublic } from '../api/types';
import { useAuth } from '../hooks/useAuth'; import { useAuth } from '../hooks/useAuth';
import { useForumLimits } from '../hooks/useForumLimits'; import { useForumLimits } from '../hooks/useForumLimits';
import { useSessionResource } from '../hooks/useSessionResource';
import PostListItem from '../components/PostListItem'; import PostListItem from '../components/PostListItem';
import FeedPagination from '../components/FeedPagination'; import FeedPagination from '../components/FeedPagination';
import ComposeMessageDialog from '../components/ComposeMessageDialog';
import { openForumPost } from '../utils/openPost'; import { openForumPost } from '../utils/openPost';
import { formatDateTime } from '../utils/content'; import { formatDateTime } from '../utils/content';
import { usePageSEO } from '../hooks/usePageSEO'; import { usePageSEO } from '../hooks/usePageSEO';
@@ -31,6 +31,9 @@ import { canonicalRedirectPath, parsePermalinkID, userPath } from '../utils/perm
import NotFoundPage from './NotFoundPage'; import NotFoundPage from './NotFoundPage';
import { InFlowSiteFooter } from '../components/SiteFooter'; import { InFlowSiteFooter } from '../components/SiteFooter';
type ProfileSnap = { profile: UserPublic; stats: UserActivityStats | null };
type PostsSnap = { posts: PostItem[]; total: number };
export default function UserProfilePage() { export default function UserProfilePage() {
const { id: idParam } = useParams(); const { id: idParam } = useParams();
const userId = parsePermalinkID(idParam); const userId = parsePermalinkID(idParam);
@@ -40,15 +43,33 @@ export default function UserProfilePage() {
const { limits } = useForumLimits(); const { limits } = useForumLimits();
const pageSize = limits.page_size_default > 0 ? limits.page_size_default : 20; 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 [notFound, setNotFound] = useState(false);
const [posts, setPosts] = useState<PostItem[]>([]);
const [postsLoading, setPostsLoading] = useState(false);
const [postPage, setPostPage] = useState(1); 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 isSelf = !!me && me.id === userId;
const totalPages = Math.max(1, Math.ceil(postTotal / pageSize)); const totalPages = Math.max(1, Math.ceil(postTotal / pageSize));
@@ -56,43 +77,13 @@ export default function UserProfilePage() {
useEffect(() => { useEffect(() => {
if (!userId || Number.isNaN(userId)) { if (!userId || Number.isNaN(userId)) {
setNotFound(true); 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]); }, [userId]);
useEffect(() => { useEffect(() => {
if (!userId || Number.isNaN(userId) || !profile) return; setNotFound(false);
let cancelled = false; setPostPage(1);
setPostsLoading(true); }, [userId]);
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]);
useEffect(() => { useEffect(() => {
if (!userId || Number.isNaN(userId)) return; if (!userId || Number.isNaN(userId)) return;
@@ -190,7 +181,7 @@ export default function UserProfilePage() {
nav(loginPath(userPath(profile.id))); nav(loginPath(userPath(profile.id)));
return; return;
} }
setMsgOpen(true); nav(`/messages?peer=${profile.id}`);
}} }}
> >
<Mail size={14} /> <Mail size={14} />
@@ -272,16 +263,6 @@ export default function UserProfilePage() {
</div> </div>
</div> </div>
<InFlowSiteFooter /> <InFlowSiteFooter />
{!isSelf && profile && me && (
<ComposeMessageDialog
open={msgOpen}
onOpenChange={setMsgOpen}
toUserId={profile.id}
toNickname={profile.nickname}
onSent={() => nav(`/messages?peer=${profile.id}`)}
/>
)}
</div> </div>
); );
} }

View File

@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
import { Trash2, RotateCcw } from 'lucide-react'; import { Trash2, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
@@ -40,6 +40,8 @@ function formatAdminTime(iso: string) {
export default function AdminCommentsPage() { export default function AdminCommentsPage() {
const nav = useNavigate(); const nav = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const focusId = Number(searchParams.get('id') || 0) || 0;
const { ready } = useAdminGuard(); const { ready } = useAdminGuard();
const [tab, setTab] = useState<Tab>('pending'); const [tab, setTab] = useState<Tab>('pending');
const [comments, setComments] = useState<Comment[]>([]); const [comments, setComments] = useState<Comment[]>([]);
@@ -49,6 +51,9 @@ export default function AdminCommentsPage() {
const [totalPages, setTotalPages] = useState(1); const [totalPages, setTotalPages] = useState(1);
const [pendingCount, setPendingCount] = useState(0); const [pendingCount, setPendingCount] = useState(0);
const [revComment, setRevComment] = useState<Comment | null>(null); 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) => { const loadList = (p = page, st: Tab = tab) => {
setLoading(true); setLoading(true);
@@ -90,6 +95,45 @@ export default function AdminCommentsPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [ready, tab]); }, [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) => { const approve = async (id: number) => {
try { try {
const r = await api.adminApproveComment(id); const r = await api.adminApproveComment(id);
@@ -268,7 +312,11 @@ export default function AdminCommentsPage() {
</thead> </thead>
<tbody> <tbody>
{comments.map(c => ( {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.id}</td>
<td>#{c.floor}</td> <td>#{c.floor}</td>
<td> <td>

View File

@@ -0,0 +1,302 @@
import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { Globe2, ExternalLink, Star } from 'lucide-react';
import { Spinner } from '@/components/ui/spinner';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { notify } from '@/lib/notify';
import { cn } from '@/lib/utils';
import { api } from '../../api/client';
import type { CommunityInstance, ForumLimits } from '../../api/types';
import { useAdminGuard } from '../../layouts/AdminLayout';
import { formatTime } from '../../utils/content';
import { invalidateForumLimitsCache } from '../../hooks/useForumLimits';
import {
mergeForumLimitsWithAsideWidgets,
normalizeAsideWidgets,
resolveAsideWidgets,
} from '../../utils/asideWidgets';
type EntryFlags = {
nav: boolean;
footer: boolean;
aside: boolean;
};
/** 后台:公网实例列表 + 开源展柜入口位置 */
export default function AdminCommunityPage() {
const { ready } = useAdminGuard();
const [hubEnabled, setHubEnabled] = useState(false);
const [list, setList] = useState<CommunityInstance[]>([]);
const [loading, setLoading] = useState(true);
const [featuringId, setFeaturingId] = useState<string | null>(null);
const [forumLimits, setForumLimits] = useState<ForumLimits | null>(null);
const [entrySaving, setEntrySaving] = useState(false);
const entryFlags = useMemo<EntryFlags>(() => {
const widgets = resolveAsideWidgets({
aside_widgets: forumLimits?.aside_widgets,
aside_show_tag_cloud: forumLimits?.aside_show_tag_cloud ?? false,
aside_show_recent_comments: forumLimits?.aside_show_recent_comments ?? false,
aside_show_friend_links: forumLimits?.aside_show_friend_links ?? true,
aside_show_showcase: forumLimits?.aside_show_showcase ?? false,
});
return {
nav: !!forumLimits?.nav_show_showcase,
footer: !!forumLimits?.footer_show_showcase,
aside: widgets.find(w => w.id === 'showcase')?.enabled ?? false,
};
}, [forumLimits]);
useEffect(() => {
if (!ready) return;
setLoading(true);
Promise.all([
api.adminCommunityInstances(),
api.adminSettings().catch(() => null),
])
.then(([instancesRes, settings]) => {
setHubEnabled(!!instancesRes.hub_enabled);
setList(Array.isArray(instancesRes.instances) ? instancesRes.instances : []);
if (settings?.limits) {
const loaded = normalizeAsideWidgets(
resolveAsideWidgets({
aside_widgets: settings.limits.aside_widgets,
aside_show_tag_cloud: settings.limits.aside_show_tag_cloud ?? false,
aside_show_recent_comments: settings.limits.aside_show_recent_comments ?? false,
aside_show_friend_links: settings.limits.aside_show_friend_links ?? true,
aside_show_showcase: settings.limits.aside_show_showcase ?? false,
}),
);
setForumLimits(mergeForumLimitsWithAsideWidgets({
...settings.limits,
nav_show_showcase: !!settings.limits.nav_show_showcase,
footer_show_showcase: !!settings.limits.footer_show_showcase,
aside_show_showcase: !!settings.limits.aside_show_showcase,
}, loaded));
}
})
.catch(() => {
setList([]);
})
.finally(() => setLoading(false));
}, [ready]);
const patchEntryVisibility = async (patch: Partial<EntryFlags>) => {
if (entrySaving) return;
const prev = entryFlags;
const nextFlags = { ...prev, ...patch };
setForumLimits((fl) => {
if (!fl) return fl;
const widgets = normalizeAsideWidgets(fl.aside_widgets).map(w => (
w.id === 'showcase' ? { ...w, enabled: nextFlags.aside } : w
));
return mergeForumLimitsWithAsideWidgets({
...fl,
nav_show_showcase: nextFlags.nav,
footer_show_showcase: nextFlags.footer,
aside_show_showcase: nextFlags.aside,
}, widgets);
});
setEntrySaving(true);
try {
const body: {
nav_show_showcase?: boolean;
footer_show_showcase?: boolean;
aside_show_showcase?: boolean;
} = {};
if (patch.nav !== undefined) body.nav_show_showcase = patch.nav;
if (patch.footer !== undefined) body.footer_show_showcase = patch.footer;
if (patch.aside !== undefined) body.aside_show_showcase = patch.aside;
const r = await api.adminUpdateShowcaseEntry(body);
setForumLimits((base) => {
if (!base) return base;
const widgets = normalizeAsideWidgets(base.aside_widgets).map(w => (
w.id === 'showcase' ? { ...w, enabled: r.aside_show_showcase } : w
));
return mergeForumLimitsWithAsideWidgets({
...base,
nav_show_showcase: r.nav_show_showcase,
footer_show_showcase: r.footer_show_showcase,
aside_show_showcase: r.aside_show_showcase,
}, widgets);
});
invalidateForumLimitsCache();
notify.success(r.message);
} catch (e: unknown) {
setForumLimits((fl) => {
if (!fl) return fl;
const widgets = normalizeAsideWidgets(fl.aside_widgets).map(w => (
w.id === 'showcase' ? { ...w, enabled: prev.aside } : w
));
return mergeForumLimitsWithAsideWidgets({
...fl,
nav_show_showcase: prev.nav,
footer_show_showcase: prev.footer,
aside_show_showcase: prev.aside,
}, widgets);
});
notify.error(e instanceof Error ? e.message : '保存失败');
} finally {
setEntrySaving(false);
}
};
const handleToggleFeatured = async (row: CommunityInstance) => {
if (featuringId) return;
setFeaturingId(row.instance_id);
try {
const r = await api.adminFeatureCommunityInstance(row.instance_id, {
featured: !row.featured,
featured_note: row.featured_note || '',
});
setList((prev) => prev.map((item) => (
item.instance_id === row.instance_id ? { ...item, ...r.instance } : item
)));
notify.success(r.message);
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '操作失败');
} finally {
setFeaturingId(null);
}
};
if (!ready || loading) {
return <div className="flex justify-center py-16"><Spinner size="lg" /></div>;
}
return (
<div className="admin-page">
<div className="admin-page-head">
<div>
<h1 className="admin-page-title">
<Globe2 size={22} aria-hidden />
</h1>
<p className="admin-page-desc">
{' '}
<Link to="/showcase" className="admin-inline-link" target="_blank" rel="noopener noreferrer"></Link>
</p>
</div>
</div>
{!hubEnabled && (
<div className="admin-card admin-settings-card" style={{ marginBottom: 16 }}>
<div className="admin-card-body">
<p>
<code>app.ini</code> <code>[community] hub = true</code>
{' '} <code>JIANG13_COMMUNITY_HUB=1</code>
</p>
</div>
</div>
)}
{hubEnabled && (
<div className="admin-card admin-links-entry-card" style={{ marginBottom: 16 }}>
<div className="admin-card-head"></div>
<p className="admin-card-desc">
访 /showcase
</p>
<div className="admin-card-body admin-links-entry-body">
{(
[
{ key: 'nav' as const, label: '左侧栏(站点)', on: entryFlags.nav },
{ key: 'aside' as const, label: '右侧栏', on: entryFlags.aside },
{ key: 'footer' as const, label: '页脚', on: entryFlags.footer },
]
).map(item => (
<div key={item.key} className="admin-links-entry-row">
<span id={`admin-showcase-entry-${item.key}`}>{item.label}</span>
<button
type="button"
role="switch"
aria-checked={item.on}
aria-labelledby={`admin-showcase-entry-${item.key}`}
disabled={entrySaving}
className={cn('admin-settings-switch', item.on && 'is-on')}
onClick={() => void patchEntryVisibility({ [item.key]: !item.on })}
>
<span className="admin-settings-switch-ui" aria-hidden />
</button>
</div>
))}
</div>
</div>
)}
<div className="admin-card">
<div className="admin-card-head">
<span></span>
<span className="admin-settings-card-badge">{list.length} </span>
</div>
<div className="admin-card-body" style={{ padding: 0 }}>
{list.length === 0 ? (
<p className="admin-empty" style={{ padding: 24 }}></p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
{list.map((row) => (
<tr key={row.instance_id}>
<td>
<Badge variant={row.online ? 'default' : 'secondary'}>
{row.online ? '在线' : '离线'}
</Badge>
</td>
<td>
<div className="admin-community-site">
<strong>
{row.featured && <Star size={12} className="admin-community-star" aria-hidden />}
{row.site_name || '未命名站点'}
</strong>
<a
href={row.site_url}
target="_blank"
rel="noopener noreferrer"
className={cn('admin-inline-link', 'admin-community-url')}
>
{row.site_url}
<ExternalLink size={12} aria-hidden />
</a>
</div>
</td>
<td><code>{row.version || '—'}</code></td>
<td>{row.users}</td>
<td>{row.posts}</td>
<td title={row.last_seen_at}>{formatTime(row.last_seen_at)}</td>
<td>
<Button
variant="outline"
size="sm"
loading={featuringId === row.instance_id}
disabled={!!featuringId}
onClick={() => void handleToggleFeatured(row)}
>
{row.featured ? '取消精选' : '精选'}
</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
</div>
);
}

View File

@@ -1,12 +1,37 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate } from 'react-router-dom';
import { FileText, Flag, MessageSquare, Link2 } from 'lucide-react'; import { FileText, Flag, MessageSquare, Link2, Activity } from 'lucide-react';
import { Spinner } from '@/components/ui/spinner'; import { Spinner } from '@/components/ui/spinner';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { api } from '../../api/client'; import { api } from '../../api/client';
import { useAdminGuard } from '../../layouts/AdminLayout'; import { useAdminGuard } from '../../layouts/AdminLayout';
import type { AdminDashboard } from '../../api/types'; import type { AdminDashboard, AdminDashboardTraffic } from '../../api/types';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import CommunitySupportStrip from '../../components/admin/CommunitySupportStrip';
function formatDashNum(n: number) {
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
if (n >= 10_000) return `${(n / 1000).toFixed(1)}k`;
return String(n ?? 0);
}
function pvTrendLabel(today: number, yesterday: number) {
if (yesterday <= 0) {
return today > 0 ? '昨日无数据' : '较昨日 —';
}
const delta = ((today - yesterday) / yesterday) * 100;
if (Math.abs(delta) < 0.5) return '与昨日持平';
const abs = Math.abs(delta).toFixed(0);
return delta > 0 ? `较昨日 ↑ ${abs}%` : `较昨日 ↓ ${abs}%`;
}
function trendTone(today: number, yesterday: number): 'up' | 'down' | 'flat' {
if (yesterday <= 0) return 'flat';
const delta = today - yesterday;
if (delta > 0) return 'up';
if (delta < 0) return 'down';
return 'flat';
}
export default function AdminDashboardPage() { export default function AdminDashboardPage() {
const nav = useNavigate(); const nav = useNavigate();
@@ -31,20 +56,16 @@ export default function AdminDashboardPage() {
const pendingReports = data.pending_reports ?? 0; const pendingReports = data.pending_reports ?? 0;
const pendingFriendLinks = data.pending_friend_links ?? 0; const pendingFriendLinks = data.pending_friend_links ?? 0;
const pendingTotal = pendingPosts + pendingComments + pendingReports + pendingFriendLinks; const pendingTotal = pendingPosts + pendingComments + pendingReports + pendingFriendLinks;
const traffic: AdminDashboardTraffic = data.traffic ?? {
const stats = [ enabled: false, today_pv: 0, today_uv: 0, yesterday_pv: 0, total_pv: 0,
{ label: '注册用户', value: data.users }, };
{ label: '帖子总数', value: data.posts },
{ label: '板块数量', value: data.boards },
{ label: '评论总数', value: data.comments },
];
const queues = [ const queues = [
{ {
key: 'posts', key: 'posts',
label: '待审帖子', label: '待审帖子',
count: pendingPosts, count: pendingPosts,
hint: '新帖与修改待审核', hint: '新帖与修改',
to: '/admin/posts', to: '/admin/posts',
icon: FileText, icon: FileText,
}, },
@@ -52,7 +73,7 @@ export default function AdminDashboardPage() {
key: 'comments', key: 'comments',
label: '待审评论', label: '待审评论',
count: pendingComments, count: pendingComments,
hint: '评论与回复待审核', hint: '评论与回复',
to: '/admin/comments', to: '/admin/comments',
icon: MessageSquare, icon: MessageSquare,
}, },
@@ -60,7 +81,7 @@ export default function AdminDashboardPage() {
key: 'reports', key: 'reports',
label: '待处理举报', label: '待处理举报',
count: pendingReports, count: pendingReports,
hint: '用户举报需人工处理', hint: '用户举报',
to: '/admin/reports', to: '/admin/reports',
icon: Flag, icon: Flag,
}, },
@@ -68,65 +89,128 @@ export default function AdminDashboardPage() {
key: 'links', key: 'links',
label: '待审友链', label: '待审友链',
count: pendingFriendLinks, count: pendingFriendLinks,
hint: '用户提交的友情链接申请', hint: '友链申请',
to: '/admin/links', to: '/admin/links',
icon: Link2, icon: Link2,
}, },
]; ];
return ( const scale = [
<div className="admin-page"> { label: '注册用户', value: data.users },
<div className="admin-page-head"> { label: '帖子总数', value: data.posts },
<h1></h1> { label: '板块数量', value: data.boards },
<p></p> { label: '评论总数', value: data.comments },
</div> ];
<section className="admin-queue-section" aria-label="待处理事项"> const tone = trendTone(traffic.today_pv, traffic.yesterday_pv);
<div className="admin-section-label">
<span></span> return (
{pendingTotal > 0 ? ( <div className="admin-page admin-dash-page">
<Badge variant="orange">{pendingTotal} </Badge> <div className="admin-page-head admin-dash-head">
) : ( <div className="admin-dash-head-title">
<span className="admin-section-muted"></span> <h1></h1>
{pendingTotal > 0 && (
<Badge variant="orange">{pendingTotal} </Badge>
)} )}
</div> </div>
<div className="admin-queue-grid"> <p>访</p>
{queues.map(q => { </div>
const Icon = q.icon;
const hasWork = q.count > 0;
return (
<button
key={q.key}
type="button"
className={cn('admin-queue-card', hasWork && 'has-work')}
onClick={() => nav(q.to)}
>
<div className="admin-queue-card-top">
<Icon size={18} aria-hidden />
<span className="admin-queue-count">{q.count}</span>
</div>
<div className="admin-queue-label">{q.label}</div>
<div className="admin-queue-hint">{q.hint}</div>
</button>
);
})}
</div>
</section>
<section className="admin-stat-section" aria-label="运行概览"> <div className="admin-dash-bento">
<div className="admin-section-label"> <section className="admin-dash-traffic" aria-label="今日访问">
<span></span> <div className="admin-dash-traffic-top">
<div className="admin-dash-section-label">
<span className="admin-monitor-section-bar" aria-hidden />
<h2>访</h2>
</div>
<button
type="button"
className="admin-text-link admin-dash-link"
onClick={() => nav('/admin/monitor')}
>
<Activity size={14} aria-hidden />
</button>
</div>
{!traffic.enabled ? (
<div className="admin-dash-traffic-empty">
<p>访</p>
<button
type="button"
className="admin-text-link"
onClick={() => nav('/admin/monitor?tab=settings')}
>
</button>
</div>
) : (
<>
<div className="admin-dash-traffic-pv">{formatDashNum(traffic.today_pv)}</div>
<div className="admin-dash-traffic-meta">
<span>访 (PV)</span>
<span className="admin-dash-traffic-uv">访 (UV) {formatDashNum(traffic.today_uv)}</span>
</div>
<div className={cn('admin-dash-traffic-trend', `is-${tone}`)}>
{pvTrendLabel(traffic.today_pv, traffic.yesterday_pv)}
</div>
<p className="admin-dash-traffic-total">
访 {formatDashNum(traffic.total_pv)}
<span className="admin-dash-traffic-hint"></span>
</p>
</>
)}
</section>
<section className="admin-dash-queue" aria-label="待处理事项">
<div className="admin-dash-section-label admin-dash-queue-head">
<span className="admin-monitor-section-bar" aria-hidden />
<h2></h2>
{pendingTotal === 0 && (
<span className="admin-section-muted"></span>
)}
</div>
<div className="admin-dash-queue-grid">
{queues.map((q) => {
const Icon = q.icon;
const hasWork = q.count > 0;
return (
<button
key={q.key}
type="button"
className={cn('admin-dash-queue-card', hasWork && 'has-work')}
onClick={() => nav(q.to)}
>
<div className="admin-dash-queue-card-top">
<Icon size={16} aria-hidden />
<span className="admin-dash-queue-count">{q.count}</span>
</div>
<div className="admin-dash-queue-label">{q.label}</div>
<div className="admin-dash-queue-hint">{q.hint}</div>
</button>
);
})}
</div>
</section>
</div>
<section className="admin-dash-scale" aria-label="内容规模">
<div className="admin-dash-section-label">
<span className="admin-monitor-section-bar" aria-hidden />
<h2></h2>
</div> </div>
<div className="admin-stat-grid"> <div className="admin-dash-metric-grid">
{stats.map(s => ( {scale.map((s) => (
<div key={s.label} className="admin-stat-card"> <div key={s.label} className="admin-dash-metric-card">
<div className="admin-stat-value">{s.value}</div> <div className="admin-dash-metric-value">{formatDashNum(s.value)}</div>
<div className="admin-stat-label">{s.label}</div> <div className="admin-dash-metric-label">{s.label}</div>
</div> </div>
))} ))}
</div> </div>
</section> </section>
<CommunitySupportStrip />
<div className="admin-card"> <div className="admin-card">
<div className="admin-card-head"> <div className="admin-card-head">
<span></span> <span></span>
@@ -145,7 +229,7 @@ export default function AdminDashboardPage() {
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{data.recent_posts.map(p => ( {data.recent_posts.map((p) => (
<tr key={p.id}> <tr key={p.id}>
<td>{p.id}</td> <td>{p.id}</td>
<td> <td>
@@ -161,7 +245,7 @@ export default function AdminDashboardPage() {
) : '—'} ) : '—'}
</td> </td>
<td className="space-x-1"> <td className="space-x-1">
{p.featured ? <Badge variant="orange"></Badge> : null} {p.featured ? <Badge variant="orange"></Badge> : null}
{p.pinned ? <Badge variant="green"></Badge> : null} {p.pinned ? <Badge variant="green"></Badge> : null}
{p.board_pinned ? <Badge variant="green"></Badge> : null} {p.board_pinned ? <Badge variant="green"></Badge> : null}
{!p.featured && !p.pinned && !p.board_pinned ? '—' : null} {!p.featured && !p.pinned && !p.board_pinned ? '—' : null}

View File

@@ -22,6 +22,7 @@ import { cn } from '@/lib/utils';
import { api } from '../../api/client'; import { api } from '../../api/client';
import { useAdminGuard } from '../../layouts/AdminLayout'; import { useAdminGuard } from '../../layouts/AdminLayout';
import type { ForumLimits, FriendLink, FriendLinkApply, SiteBranding } from '../../api/types'; import type { ForumLimits, FriendLink, FriendLinkApply, SiteBranding } from '../../api/types';
import { DEFAULT_FEED_SORT_TABS } from '../../api/types';
import { useSiteBranding, seedSiteBrandingCache, invalidateSiteBrandingCache } from '../../hooks/useSiteBranding'; import { useSiteBranding, seedSiteBrandingCache, invalidateSiteBrandingCache } from '../../hooks/useSiteBranding';
import { invalidateForumLimitsCache } from '../../hooks/useForumLimits'; import { invalidateForumLimitsCache } from '../../hooks/useForumLimits';
import { formatTime } from '../../utils/content'; import { formatTime } from '../../utils/content';
@@ -178,10 +179,14 @@ export default function AdminLinksPage() {
aside_show_tag_cloud: false, aside_show_tag_cloud: false,
aside_show_recent_comments: false, aside_show_recent_comments: false,
aside_show_friend_links: true, aside_show_friend_links: true,
aside_show_showcase: false,
aside_widgets: loadedAsideWidgets, aside_widgets: loadedAsideWidgets,
nav_show_friend_links: true, nav_show_friend_links: true,
footer_show_friend_links: true, footer_show_friend_links: true,
nav_show_showcase: false,
footer_show_showcase: false,
feed_list_style: 'title', feed_list_style: 'title',
feed_sort_tabs: DEFAULT_FEED_SORT_TABS,
permalink_enabled: false, permalink_enabled: false,
permalink_ext: 'html', permalink_ext: 'html',
...s.limits, ...s.limits,
@@ -350,15 +355,20 @@ export default function AdminLinksPage() {
aside_show_tag_cloud: false, aside_show_tag_cloud: false,
aside_show_recent_comments: false, aside_show_recent_comments: false,
aside_show_friend_links: nextFlags.aside, aside_show_friend_links: nextFlags.aside,
aside_show_showcase: false,
aside_widgets: normalizeAsideWidgets([ aside_widgets: normalizeAsideWidgets([
{ id: 'tag_cloud', enabled: false }, { id: 'tag_cloud', enabled: false },
{ id: 'recent_comments', enabled: false }, { id: 'recent_comments', enabled: false },
{ id: 'recent_users', enabled: false }, { id: 'recent_users', enabled: false },
{ id: 'friend_links', enabled: nextFlags.aside }, { id: 'friend_links', enabled: nextFlags.aside },
{ id: 'showcase', enabled: false },
]), ]),
nav_show_friend_links: nextFlags.nav, nav_show_friend_links: nextFlags.nav,
footer_show_friend_links: nextFlags.footer, footer_show_friend_links: nextFlags.footer,
nav_show_showcase: false,
footer_show_showcase: false,
feed_list_style: 'title', feed_list_style: 'title',
feed_sort_tabs: DEFAULT_FEED_SORT_TABS,
permalink_enabled: false, permalink_enabled: false,
permalink_ext: 'html', permalink_ext: 'html',
post_edit_window_hours: 24, post_edit_window_hours: 24,

View File

@@ -0,0 +1,733 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Activity, AlertTriangle } from 'lucide-react';
import { Spinner } from '@/components/ui/spinner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { notify } from '@/lib/notify';
import { cn } from '@/lib/utils';
import { api } from '../../api/client';
import type {
MonitorASNItem,
MonitorCityItem,
MonitorConfig,
MonitorGeoResult,
MonitorLogItem,
MonitorOverview,
MonitorRealtime,
MonitorStatItem,
} from '../../api/types';
import { useAdminGuard } from '../../layouts/AdminLayout';
import { formatTime } from '../../utils/content';
import { invalidateForumLimitsCache } from '../../hooks/useForumLimits';
import MonitorWorldMap from '../../components/admin/MonitorWorldMap';
import MonitorChinaMap from '../../components/admin/MonitorChinaMap';
import { countryLabelZh } from '../../components/admin/monitorMapUtils';
type TabKey = 'overview' | 'stats' | 'logs' | 'settings';
type StatsDim = 'url' | 'referer' | 'browser' | 'os' | 'device' | 'status';
type StatsRange = '1d' | '7d' | '30d' | '90d';
type MapMode = 'world' | 'china';
type RankMode = 'city' | 'asn';
function countryLabel(code: string) {
return countryLabelZh(code);
}
function formatBytes(n: number) {
if (!n || n < 0) return '0 B';
const u = ['B', 'KB', 'MB', 'GB', 'TB'];
let v = n;
let i = 0;
while (v >= 1024 && i < u.length - 1) {
v /= 1024;
i++;
}
return `${v < 10 && i > 0 ? v.toFixed(1) : Math.round(v)} ${u[i]}`;
}
function formatNum(n: number) {
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
if (n >= 10_000) return `${(n / 1000).toFixed(1)}k`;
return String(n ?? 0);
}
function MiniSparkline({ series }: { series: { count: number }[] }) {
const max = Math.max(1, ...series.map((p) => p.count));
const w = 240;
const h = 48;
const pts = series.map((p, i) => {
const x = series.length <= 1 ? 0 : (i / (series.length - 1)) * w;
const y = h - (p.count / max) * (h - 4) - 2;
return `${x},${y}`;
}).join(' ');
return (
<svg className="admin-monitor-spark" viewBox={`0 0 ${w} ${h}`} width="100%" height={h} aria-hidden>
<polyline fill="none" stroke="var(--j13-green)" strokeWidth="2" points={pts} />
</svg>
);
}
const CHINA_CODES = new Set(['CN', 'HK', 'TW', 'MO']);
function geoCountries(geo: MonitorGeoResult | null) {
return geo?.countries || [];
}
function GeoRankTable({
cities,
asns,
mode,
rankMode,
onRankMode,
hasCountryHits,
}: {
cities: MonitorCityItem[];
asns: MonitorASNItem[];
mode: MapMode;
rankMode: RankMode;
onRankMode: (m: RankMode) => void;
/** 近 30 日是否已有国家级浏览量(用于区分「无 PV 地理」与缺库) */
hasCountryHits: boolean;
}) {
const cityRows = mode === 'china'
? cities.filter((i) => CHINA_CODES.has((i.country || '').toUpperCase()))
: cities;
const rows = rankMode === 'city' ? cityRows : asns;
const emptyHint = rankMode === 'city'
? (hasCountryHits
? '需前台路由产生带城市的浏览量;仅请求日志不会进入此排行。请确认已放置 IP2Location DB3 BIN。'
: '需前台路由产生浏览量后才会有城市排行;仅请求日志不会点亮此处。')
: (hasCountryHits
? '需浏览量写入 ASN请确认已放置 GeoLite2-ASN.mmdb。仅请求日志不会进入此排行。'
: '需前台路由产生浏览量后才会有运营商排行;仅请求日志不会点亮此处。');
return (
<div className="admin-monitor-rank">
<div className="admin-monitor-seg" role="group" aria-label="排行维度">
<button
type="button"
className={cn('admin-monitor-seg-btn', rankMode === 'city' && 'active')}
onClick={() => onRankMode('city')}
>
</button>
<button
type="button"
className={cn('admin-monitor-seg-btn', rankMode === 'asn' && 'active')}
onClick={() => onRankMode('asn')}
>
</button>
</div>
{rows.length === 0 ? (
<div className="admin-monitor-geo-empty">
<p></p>
<p className="admin-monitor-muted">{emptyHint}</p>
</div>
) : (
<table className="admin-monitor-geo-table">
<thead>
<tr>
<th>{rankMode === 'city' ? '城市' : '运营商'}</th>
<th></th>
</tr>
</thead>
<tbody>
{rankMode === 'city'
? cityRows.slice(0, 12).map((item, idx) => (
<tr key={`${item.country}-${item.city}-${idx}`}>
<td title={[item.region, item.city].filter(Boolean).join(' · ')}>
{item.city}
{item.region ? <span className="admin-monitor-muted"> · {item.region}</span> : null}
</td>
<td>{formatNum(item.count)}</td>
</tr>
))
: asns.slice(0, 12).map((item) => (
<tr key={item.asn}>
<td title={item.as_org || `AS${item.asn}`}>
{item.as_org || `AS${item.asn}`}
<span className="admin-monitor-muted"> · AS{item.asn}</span>
</td>
<td>{formatNum(item.count)}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
}
function parseMonitorTab(raw: string | null): TabKey {
if (raw === 'stats' || raw === 'logs' || raw === 'settings' || raw === 'overview') {
return raw;
}
return 'overview';
}
export default function AdminMonitorPage() {
const { ready } = useAdminGuard();
const [searchParams, setSearchParams] = useSearchParams();
const [tab, setTab] = useState<TabKey>(() => parseMonitorTab(searchParams.get('tab')));
const [overview, setOverview] = useState<MonitorOverview | null>(null);
const [geo, setGeo] = useState<MonitorGeoResult | null>(null);
const [realtime, setRealtime] = useState<MonitorRealtime | null>(null);
const [mapMode, setMapMode] = useState<MapMode>('world');
const [rankMode, setRankMode] = useState<RankMode>('city');
const [loading, setLoading] = useState(true);
const [statsDim, setStatsDim] = useState<StatsDim>('url');
const [statsRange, setStatsRange] = useState<StatsRange>('30d');
const [statsItems, setStatsItems] = useState<MonitorStatItem[]>([]);
const [statsLoading, setStatsLoading] = useState(false);
const [logs, setLogs] = useState<MonitorLogItem[]>([]);
const [logsTotal, setLogsTotal] = useState(0);
const [logsPage, setLogsPage] = useState(1);
const [logMethod, setLogMethod] = useState('');
const [logPath, setLogPath] = useState('');
const [logStatus, setLogStatus] = useState('');
const [logIP, setLogIP] = useState('');
const [logsLoading, setLogsLoading] = useState(false);
const [settings, setSettings] = useState<MonitorConfig | null>(null);
const [excludeText, setExcludeText] = useState('');
const [saving, setSaving] = useState(false);
useEffect(() => {
const next = parseMonitorTab(searchParams.get('tab'));
setTab((prev) => (prev === next ? prev : next));
}, [searchParams]);
const selectTab = (key: TabKey) => {
setTab(key);
const next = new URLSearchParams(searchParams);
if (key === 'overview') next.delete('tab');
else next.set('tab', key);
setSearchParams(next, { replace: true });
};
const loadOverview = useCallback(async () => {
const [ov, g, rt] = await Promise.all([
api.adminMonitorOverview(),
api.adminMonitorGeo('30d'),
api.adminMonitorRealtime(),
]);
setOverview(ov);
setGeo(g);
setRealtime(rt);
}, []);
useEffect(() => {
if (!ready) return;
setLoading(true);
loadOverview()
.catch(() => notify.error('加载监控概览失败'))
.finally(() => setLoading(false));
}, [ready, loadOverview]);
// 概览页实时轮询
useEffect(() => {
if (!ready || tab !== 'overview') return;
const id = window.setInterval(() => {
api.adminMonitorRealtime().then(setRealtime).catch(() => {});
api.adminMonitorOverview().then(setOverview).catch(() => {});
}, 5000);
return () => window.clearInterval(id);
}, [ready, tab]);
useEffect(() => {
if (!ready || tab !== 'stats') return;
setStatsLoading(true);
api.adminMonitorStats(statsDim, statsRange)
.then((r) => setStatsItems(r.items || []))
.catch(() => notify.error('加载统计失败'))
.finally(() => setStatsLoading(false));
}, [ready, tab, statsDim, statsRange]);
const loadLogs = useCallback(async (page = 1) => {
setLogsLoading(true);
try {
const r = await api.adminMonitorLogs({
page,
size: 20,
method: logMethod || undefined,
path: logPath || undefined,
status: logStatus || undefined,
ip: logIP || undefined,
});
setLogs(r.items || []);
setLogsTotal(r.total || 0);
setLogsPage(r.page || page);
} catch {
notify.error('加载请求日志失败');
} finally {
setLogsLoading(false);
}
}, [logMethod, logPath, logStatus, logIP]);
useEffect(() => {
if (!ready || tab !== 'logs') return;
loadLogs(1);
}, [ready, tab, loadLogs]);
useEffect(() => {
if (!ready || tab !== 'settings') return;
api.adminMonitorSettings()
.then((cfg) => {
setSettings(cfg);
setExcludeText((cfg.exclude_rules || []).join('\n'));
})
.catch(() => notify.error('加载设置失败'));
}, [ready, tab]);
const enabled = overview?.enabled ?? settings?.enabled ?? false;
const metrics = useMemo(() => {
if (!overview) return [];
const pvHint = '前台浏览';
const accessHintShort = '服务端请求';
const accessHintFull = '服务端请求(含 API重启后重计';
return [
{ label: '浏览量', hint: pvHint, title: pvHint, value: formatNum(overview.pageviews) },
{ label: '访客数', hint: pvHint, title: pvHint, value: formatNum(overview.visitors) },
{ label: '独立 IP', hint: accessHintShort, title: accessHintFull, value: formatNum(overview.unique_ips) },
{ label: '流量', hint: accessHintShort, title: accessHintFull, value: formatBytes(overview.traffic) },
{ label: '蜘蛛', hint: accessHintShort, title: accessHintFull, value: formatNum(overview.bots) },
{ label: '请求数', hint: accessHintShort, title: accessHintFull, value: formatNum(overview.requests) },
{ label: '4xx', hint: accessHintShort, title: accessHintFull, value: formatNum(overview.status_4xx) },
{ label: '5xx', hint: accessHintShort, title: accessHintFull, value: formatNum(overview.status_5xx) },
];
}, [overview]);
const hasCountryHits = (geo?.countries?.length || 0) > 0;
const hasRegionHits = (geo?.regions?.length || 0) > 0;
const saveSettings = async () => {
if (!settings) return;
setSaving(true);
try {
const rules = excludeText.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
const r = await api.adminUpdateMonitorSettings({
...settings,
exclude_rules: rules,
});
setSettings(r.monitor);
setExcludeText((r.monitor.exclude_rules || []).join('\n'));
invalidateForumLimitsCache();
notify.success(r.message);
const ov = await api.adminMonitorOverview();
setOverview(ov);
} catch (e: unknown) {
notify.error(e instanceof Error ? e.message : '保存失败');
} finally {
setSaving(false);
}
};
if (!ready || (loading && tab === 'overview')) {
return <div className="flex justify-center py-16"><Spinner size="lg" /></div>;
}
const tabs: { key: TabKey; label: string }[] = [
{ key: 'overview', label: '概览' },
{ key: 'stats', label: '访问统计' },
{ key: 'logs', label: '请求日志' },
{ key: 'settings', label: '设置' },
];
const dims: { key: StatsDim; label: string }[] = [
{ key: 'url', label: 'URL' },
{ key: 'referer', label: '来源' },
{ key: 'browser', label: '浏览器' },
{ key: 'os', label: '系统' },
{ key: 'device', label: '设备' },
{ key: 'status', label: '状态码' },
];
const ranges: { key: StatsRange; label: string }[] = [
{ key: '1d', label: '今日' },
{ key: '7d', label: '7 日' },
{ key: '30d', label: '30 日' },
{ key: '90d', label: '90 日' },
];
return (
<div className="admin-page admin-monitor-page">
<div className="admin-page-head">
<div>
<h1 className="admin-page-title">
<Activity size={22} aria-hidden />
</h1>
<p className="admin-page-desc">
/访访 pageview访 /api
</p>
</div>
</div>
<div className="admin-tabs" role="tablist" aria-label="监控分类">
{tabs.map((t) => (
<button
key={t.key}
type="button"
role="tab"
aria-selected={tab === t.key}
className={cn('admin-tab', tab === t.key && 'active')}
onClick={() => selectTab(t.key)}
>
{t.label}
</button>
))}
</div>
{!enabled && tab !== 'settings' && (
<div className="admin-monitor-banner" role="status">
<AlertTriangle size={16} aria-hidden />
<span>访</span>
<button type="button" className="admin-text-link" onClick={() => selectTab('settings')}>
</button>
</div>
)}
{tab === 'overview' && overview && (
<>
<section className="admin-card admin-monitor-today" aria-label="今日状态">
<div className="admin-monitor-today-head">
<span className="admin-monitor-section-bar" aria-hidden />
<h2 className="admin-monitor-section-title"></h2>
</div>
<div className="admin-monitor-today-grid">
{metrics.map((m) => (
<div key={m.label} className="admin-monitor-today-item" title={m.title}>
<div className="admin-monitor-today-label">
{m.label}
<span className="admin-monitor-today-hint">{m.hint}</span>
</div>
<div className="admin-monitor-today-value">{m.value}</div>
</div>
))}
</div>
</section>
<div className="admin-monitor-main">
<section className="admin-card admin-monitor-map-panel">
<div className="admin-card-head admin-monitor-map-head">
<div className="admin-monitor-today-head" style={{ marginBottom: 0 }}>
<span className="admin-monitor-section-bar" aria-hidden />
<div>
<h2 className="admin-monitor-section-title">访</h2>
<p className="admin-monitor-map-sub">
· 30
{mapMode === 'china' ? ' · 按省/区填色' : ' · 按国家填色'}
</p>
</div>
</div>
<div className="admin-monitor-seg" role="group" aria-label="地图范围">
<button
type="button"
className={cn('admin-monitor-seg-btn', mapMode === 'world' && 'active')}
onClick={() => setMapMode('world')}
>
</button>
<button
type="button"
className={cn('admin-monitor-seg-btn', mapMode === 'china' && 'active')}
onClick={() => setMapMode('china')}
>
</button>
</div>
</div>
<div className="admin-card-body admin-monitor-map-body">
<div className="admin-monitor-map-visual">
{mapMode === 'world' ? (
<MonitorWorldMap items={geoCountries(geo)} />
) : (
<MonitorChinaMap
regions={geo?.regions || []}
hasCountryHits={hasCountryHits}
hasRegionHits={hasRegionHits}
/>
)}
</div>
<div className="admin-monitor-map-side">
<GeoRankTable
cities={geo?.cities || []}
asns={geo?.asns || []}
mode={mapMode}
rankMode={rankMode}
onRankMode={setRankMode}
hasCountryHits={hasCountryHits}
/>
</div>
</div>
</section>
<div className="admin-monitor-rt-stack">
<section className="admin-card admin-monitor-rt-card">
<div className="admin-monitor-today-head">
<span className="admin-monitor-section-bar" aria-hidden />
<h2 className="admin-monitor-section-title">1 </h2>
</div>
<div className="admin-monitor-rt-value">{formatNum(realtime?.requests_1m || 0)}</div>
</section>
<section className="admin-card admin-monitor-rt-card">
<div className="admin-monitor-today-head">
<span className="admin-monitor-section-bar" aria-hidden />
<h2 className="admin-monitor-section-title">1 </h2>
</div>
<div className="admin-monitor-rt-value">{formatBytes(realtime?.traffic_1m || 0)}</div>
<p className="admin-monitor-muted admin-monitor-rt-spark-label"> 1 </p>
<MiniSparkline series={realtime?.hourly_series || []} />
</section>
</div>
</div>
</>
)}
{tab === 'stats' && (
<div className="admin-card">
<div className="admin-card-head">
<div className="admin-tabs" style={{ marginBottom: 0 }}>
{dims.map((d) => (
<button
key={d.key}
type="button"
className={cn('admin-tab', statsDim === d.key && 'active')}
onClick={() => setStatsDim(d.key)}
>
{d.label}
</button>
))}
</div>
<div className="admin-tabs" style={{ marginBottom: 0 }}>
{ranges.map((r) => (
<button
key={r.key}
type="button"
className={cn('admin-tab', statsRange === r.key && 'active')}
onClick={() => setStatsRange(r.key)}
>
{r.label}
</button>
))}
</div>
</div>
<div className="admin-card-body" style={{ padding: 0 }}>
{statsLoading ? (
<div className="flex justify-center py-12"><Spinner /></div>
) : statsItems.length === 0 ? (
<p className="admin-empty"></p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th style={{ width: 48 }}>#</th>
<th></th>
<th style={{ width: 100 }}></th>
</tr>
</thead>
<tbody>
{statsItems.map((item, idx) => (
<tr key={`${item.key}-${idx}`}>
<td>{idx + 1}</td>
<td className="admin-table-mono" title={item.key}>{item.key}</td>
<td>{formatNum(item.count)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
)}
{tab === 'logs' && (
<div className="admin-card">
<div className="admin-form-row admin-monitor-log-filters">
<Input value={logMethod} onChange={(e) => setLogMethod(e.target.value)} placeholder="方法 GET" aria-label="方法" style={{ width: 100 }} />
<Input value={logPath} onChange={(e) => setLogPath(e.target.value)} placeholder="路径包含…" aria-label="路径" />
<Input value={logStatus} onChange={(e) => setLogStatus(e.target.value)} placeholder="状态码" aria-label="状态码" style={{ width: 90 }} />
<Input value={logIP} onChange={(e) => setLogIP(e.target.value)} placeholder="IP 包含…" aria-label="IP" style={{ width: 140 }} />
<Button type="button" variant="outline" onClick={() => loadLogs(1)}></Button>
</div>
<div className="admin-card-body" style={{ padding: 0 }}>
{logsLoading ? (
<div className="flex justify-center py-12"><Spinner /></div>
) : logs.length === 0 ? (
<p className="admin-empty"></p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th>IP</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
{logs.map((row) => {
const placeBits = [row.region, row.city, row.as_org].filter(Boolean);
const geoBits = [
row.country ? countryLabel(row.country) : '',
...placeBits,
].filter(Boolean);
return (
<tr key={row.id}>
<td>{formatTime(row.created_at)}</td>
<td>{row.method}</td>
<td className="admin-table-mono" title={row.path}>{row.path}</td>
<td>{row.status}</td>
<td className="admin-table-mono">
{row.ip || '—'}
{row.is_bot ? ' · bot' : ''}
{placeBits.length > 0 ? (
<div className="admin-monitor-muted" style={{ fontSize: 12 }}>
{placeBits.join(' · ')}
</div>
) : null}
</td>
<td>{row.duration_ms}ms</td>
<td title={geoBits.join(' · ')}>{row.country ? countryLabel(row.country) : '—'}</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
{logsTotal > 20 && (
<div className="admin-form-row" style={{ justifyContent: 'flex-end' }}>
<Button type="button" variant="outline" disabled={logsPage <= 1} onClick={() => loadLogs(logsPage - 1)}></Button>
<span className="admin-monitor-muted"> {logsPage} / {logsTotal} </span>
<Button type="button" variant="outline" disabled={logsPage * 20 >= logsTotal} onClick={() => loadLogs(logsPage + 1)}></Button>
</div>
)}
</div>
</div>
)}
{tab === 'settings' && settings && (
<div className="admin-card admin-settings-card">
<div className="admin-card-head"></div>
<div className="admin-card-body admin-monitor-settings">
<label className="admin-monitor-switch-row">
<div>
<strong>访</strong>
<p className="admin-monitor-muted">
/访 API pageview
</p>
</div>
<Switch
checked={settings.enabled}
onCheckedChange={(v) => setSettings({ ...settings, enabled: v })}
/>
</label>
<label className="admin-monitor-field">
<span> monitor.db1365</span>
<Input
type="number"
min={1}
max={365}
value={settings.retention_days}
onChange={(e) => setSettings({ ...settings, retention_days: Number(e.target.value) || 30 })}
/>
</label>
<label className="admin-monitor-field">
<span>JSONL1365</span>
<Input
type="number"
min={1}
max={365}
value={settings.access_log_retention_days ?? 7}
onChange={(e) => setSettings({ ...settings, access_log_retention_days: Number(e.target.value) || 7 })}
/>
</label>
<label className="admin-monitor-switch-row">
<div>
<strong></strong>
<p className="admin-monitor-muted"> X-Forwarded-For / CF-Connecting-IP IP</p>
</div>
<Switch
checked={settings.trust_proxy}
onCheckedChange={(v) => setSettings({ ...settings, trust_proxy: v })}
/>
</label>
<label className="admin-monitor-field">
<span> .js</span>
<textarea
className="admin-monitor-textarea"
rows={8}
value={excludeText}
onChange={(e) => setExcludeText(e.target.value)}
/>
<Button
type="button"
variant="outline"
style={{ marginTop: 8 }}
onClick={() => setExcludeText((settings.default_exclude_rules || []).join('\n'))}
>
</Button>
</label>
<div className="admin-monitor-geo-note">
<strong>GeoIP</strong>
<p className="admin-monitor-muted">
// IP2Location DB3 BIN ASN GeoLite2-ASN.mmdb Docker
</p>
<ul className="admin-monitor-muted" style={{ margin: '8px 0 0', paddingLeft: 18 }}>
<li>
IPv4 BIN<code>{settings.ip2location_v4_path || 'data/IP2LOCATION-LITE-DB3.BIN'}</code>
{' · '}{settings.ip2location_v4_available ? '已加载' : '未检测到'}
</li>
<li>
IPv6 BIN<code>{settings.ip2location_v6_path || 'data/IP2LOCATION-LITE-DB3.IPV6.BIN'}</code>
{' · '}{settings.ip2location_v6_available ? '已加载' : '未检测到'}
</li>
<li>
ASN<code>{settings.geoip_asn_path || 'data/GeoLite2-ASN.mmdb'}</code>
{' · '}{settings.geoip_asn_available ? '已加载' : '未检测到'}
</li>
<li>
Country <code>{settings.geoip_country_path || 'data/GeoLite2-Country.mmdb'}</code>
{' · '}{settings.geoip_country_available ? '已加载' : '未检测到(可选)'}
</li>
</ul>
<p className="admin-monitor-muted" style={{ marginTop: 8 }}>
<code>{settings.access_log_dir || 'data/logs/access'}</code>
JSONL
</p>
<p className="admin-monitor-muted" style={{ marginTop: 8 }}>
CDN CF-IPCountry IP
</p>
</div>
<div style={{ marginTop: 16 }}>
<Button type="button" onClick={saveSettings} disabled={saving}>
{saving ? '保存中…' : '保存设置'}
</Button>
</div>
</div>
</div>
)}
</div>
);
}

View File

@@ -1,5 +1,5 @@
import { useEffect, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom'; import { useNavigate, useSearchParams } from 'react-router-dom';
import { Search, Lock, LockOpen, MessageSquareOff, Trash2, RotateCcw } from 'lucide-react'; import { Search, Lock, LockOpen, MessageSquareOff, Trash2, RotateCcw } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
@@ -32,6 +32,8 @@ function formatAdminTime(iso: string) {
export default function AdminPostsPage() { export default function AdminPostsPage() {
const nav = useNavigate(); const nav = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const focusId = Number(searchParams.get('id') || 0) || 0;
const { ready } = useAdminGuard(); const { ready } = useAdminGuard();
const [tab, setTab] = useState<Tab>('pending'); const [tab, setTab] = useState<Tab>('pending');
const [posts, setPosts] = useState<PostItem[]>([]); const [posts, setPosts] = useState<PostItem[]>([]);
@@ -42,6 +44,9 @@ export default function AdminPostsPage() {
const [pendingCount, setPendingCount] = useState(0); const [pendingCount, setPendingCount] = useState(0);
const [keyword, setKeyword] = useState(''); const [keyword, setKeyword] = useState('');
const [search, setSearch] = useState(''); const [search, setSearch] = useState('');
const [highlightId, setHighlightId] = useState<number | null>(focusId > 0 ? focusId : null);
const focusTriedRef = useRef(false);
const highlightTimer = useRef<ReturnType<typeof setTimeout>>();
const loadActive = (p = page, kw = search, status = tab === 'pending' ? 'pending' : 'all') => { const loadActive = (p = page, kw = search, status = tab === 'pending' ? 'pending' : 'all') => {
setLoading(true); setLoading(true);
@@ -92,6 +97,43 @@ export default function AdminPostsPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps -- 仅随 tab/search/ready 刷新 // eslint-disable-next-line react-hooks/exhaustive-deps -- 仅随 tab/search/ready 刷新
}, [ready, search, tab]); }, [ready, search, tab]);
// 从通知深链 ?id= 定位并高亮
useEffect(() => {
if (!ready || loading || focusId <= 0 || focusTriedRef.current) return;
if (tab === 'trash') return;
const found = posts.find((p) => p.id === focusId);
if (found) {
focusTriedRef.current = true;
setHighlightId(focusId);
requestAnimationFrame(() => {
document.getElementById(`admin-post-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;
}
if (tab === 'pending') {
setTab('active');
return;
}
focusTriedRef.current = true;
notify.warning('该帖子可能已审核或不在当前列表');
const next = new URLSearchParams(searchParams);
next.delete('id');
setSearchParams(next, { replace: true });
}, [ready, loading, posts, focusId, tab, searchParams, setSearchParams]);
useEffect(() => () => clearTimeout(highlightTimer.current), []);
const switchTab = (next: Tab) => { const switchTab = (next: Tab) => {
if (next === tab) return; if (next === tab) return;
setTab(next); setTab(next);
@@ -218,7 +260,7 @@ export default function AdminPostsPage() {
? '回收站中的帖子可恢复或永久删除;永久删除后不可撤销' ? '回收站中的帖子可恢复或永久删除;永久删除后不可撤销'
: tab === 'pending' : tab === 'pending'
? '审核普通用户提交的帖子;通过后公开,拒绝后仅作者可见并私信通知' ? '审核普通用户提交的帖子;通过后公开,拒绝后仅作者可见并私信通知'
: '精华、全局置顶、板块置顶、锁定编辑/讨论、删除(移入回收站);支持按标题、标签或正文搜索'} : '推荐、全局置顶、板块置顶、锁定编辑/讨论、删除(移入回收站);支持按标题、标签或正文搜索'}
</p> </p>
</div> </div>
@@ -337,7 +379,7 @@ export default function AdminPostsPage() {
<th></th> <th></th>
<th></th> <th></th>
<th></th> <th></th>
<th></th> <th></th>
<th></th> <th></th>
<th></th> <th></th>
<th></th> <th></th>
@@ -352,7 +394,11 @@ export default function AdminPostsPage() {
{posts.map(p => { {posts.map(p => {
const edited = p.updated_at && isTimeDiffSignificant(p.created_at, p.updated_at); const edited = p.updated_at && isTimeDiffSignificant(p.created_at, p.updated_at);
return ( return (
<tr key={p.id}> <tr
key={p.id}
id={`admin-post-row-${p.id}`}
className={cn(highlightId === p.id && 'admin-row-highlight')}
>
<td>{p.id}</td> <td>{p.id}</td>
<td className="max-w-[200px] truncate"> <td className="max-w-[200px] truncate">
<button type="button" className="admin-text-link" onClick={() => nav(`/post/${p.id}`)}> <button type="button" className="admin-text-link" onClick={() => nav(`/post/${p.id}`)}>
@@ -396,7 +442,7 @@ export default function AdminPostsPage() {
</Button> </Button>
)} )}
<Button size="sm" variant="outline" onClick={() => toggleFeature(p)}> <Button size="sm" variant="outline" onClick={() => toggleFeature(p)}>
{p.featured ? '取消精华' : '精华'} {p.featured ? '取消推荐' : '推荐'}
</Button> </Button>
<Button size="sm" variant="outline" onClick={() => togglePin(p)}> <Button size="sm" variant="outline" onClick={() => togglePin(p)}>
{p.pinned ? '取消全局置顶' : '全局置顶'} {p.pinned ? '取消全局置顶' : '全局置顶'}

View File

@@ -11,9 +11,11 @@ import { invalidateForumLimitsCache } from '../../hooks/useForumLimits';
import { DEFAULT_BRANDING, seedSiteBrandingCache } from '../../hooks/useSiteBranding'; import { DEFAULT_BRANDING, seedSiteBrandingCache } from '../../hooks/useSiteBranding';
import { clearAllFeedCache } from '../../utils/feedCache'; import { clearAllFeedCache } from '../../utils/feedCache';
import { normalizeAsideWidgets, resolveAsideWidgets, mergeForumLimitsWithAsideWidgets, resolveSavedAsideWidgets } from '../../utils/asideWidgets'; import { normalizeAsideWidgets, resolveAsideWidgets, mergeForumLimitsWithAsideWidgets, resolveSavedAsideWidgets } from '../../utils/asideWidgets';
import { normalizeFeedSortTabs } from '../../utils/feedSortTabs';
import AsideWidgetList from '../../components/admin/AsideWidgetList'; import AsideWidgetList from '../../components/admin/AsideWidgetList';
import FeedSortTabList from '../../components/admin/FeedSortTabList';
import type { AdminSettings, ForumLimits, MailConfig, OIDCConfig, OAuthClient, GiteaSyncConfig, StorageConfig, SiteBranding, AsideWidget } from '../../api/types'; import type { AdminSettings, ForumLimits, MailConfig, OIDCConfig, OAuthClient, GiteaSyncConfig, StorageConfig, SiteBranding, AsideWidget } from '../../api/types';
import { DEFAULT_ASIDE_WIDGETS } from '../../api/types'; import { DEFAULT_ASIDE_WIDGETS, DEFAULT_FEED_SORT_TABS } from '../../api/types';
type TabId = 'branding' | 'limits' | 'mail' | 'oidc' | 'gitea' | 'storage' | 'filter' | 'system'; type TabId = 'branding' | 'limits' | 'mail' | 'oidc' | 'gitea' | 'storage' | 'filter' | 'system';
@@ -298,10 +300,14 @@ export default function AdminSettingsPage() {
aside_show_tag_cloud: false, aside_show_tag_cloud: false,
aside_show_recent_comments: false, aside_show_recent_comments: false,
aside_show_friend_links: true, aside_show_friend_links: true,
aside_show_showcase: false,
aside_widgets: loadedAsideWidgets, aside_widgets: loadedAsideWidgets,
nav_show_friend_links: true, nav_show_friend_links: true,
footer_show_friend_links: true, footer_show_friend_links: true,
nav_show_showcase: false,
footer_show_showcase: false,
feed_list_style: 'title', feed_list_style: 'title',
feed_sort_tabs: normalizeFeedSortTabs(s.limits?.feed_sort_tabs ?? DEFAULT_FEED_SORT_TABS),
permalink_enabled: false, permalink_enabled: false,
permalink_ext: 'html', permalink_ext: 'html',
...s.limits, ...s.limits,
@@ -913,7 +919,7 @@ export default function AdminSettingsPage() {
<section className="admin-settings-section" id="settings-feed-list"> <section className="admin-settings-section" id="settings-feed-list">
<div className="admin-settings-section-head"> <div className="admin-settings-section-head">
<h3></h3> <h3></h3>
<p></p> <p></p>
</div> </div>
<div className="admin-settings-table" role="group" aria-label="列表呈现"> <div className="admin-settings-table" role="group" aria-label="列表呈现">
<div className="admin-settings-row"> <div className="admin-settings-row">
@@ -943,6 +949,16 @@ export default function AdminSettingsPage() {
</span> </span>
</div> </div>
</div> </div>
<div className="admin-settings-subsection">
<h4 className="admin-settings-subsection-title"></h4>
<p className="admin-settings-subsection-desc">
</p>
<FeedSortTabList
tabs={normalizeFeedSortTabs(limits.feed_sort_tabs ?? DEFAULT_FEED_SORT_TABS)}
onChange={tabs => setLimits(prev => prev ? { ...prev, feed_sort_tabs: tabs } : prev)}
/>
</div>
</section> </section>
<section className="admin-settings-section" id="settings-permalink"> <section className="admin-settings-section" id="settings-permalink">
@@ -1676,7 +1692,7 @@ export default function AdminSettingsPage() {
<div className="admin-card admin-settings-card"> <div className="admin-card admin-settings-card">
<div className="admin-card-head"></div> <div className="admin-card-head"></div>
<div className="admin-card-body admin-settings-backup-body"> <div className="admin-card-body admin-settings-backup-body">
<p> SQLite 便</p> <p> SQLite 便 <code>monitor.db</code> </p>
<p className="admin-settings-backup-name"> <p className="admin-settings-backup-name">
<code>jiang13_backup_YYYYMMDD_HHMMSS.db</code> <code>jiang13_backup_YYYYMMDD_HHMMSS.db</code>
</p> </p>

View File

@@ -0,0 +1,106 @@
import { create } from 'zustand';
import type { PostItem } from '../api/types';
import type { FeedSort } from '../components/FeedSortBar';
/** 列表缓存过期时间:超过后返回首页时静默刷新,仍先展示旧数据 */
export const FEED_STALE_MS = 5 * 60 * 1000;
/** 单条 Feed 筛选对应的缓存快照 */
export type FeedCacheEntry = {
posts: PostItem[];
postTotal: number;
page: number;
scrollTop: number;
/** 上次成功拉取 API 的时间戳ms */
lastFetchTime: number;
};
type FeedKeyParts = {
boardId: number;
keyword: string;
sort: FeedSort;
tag?: string;
author?: string;
titleOnly?: boolean;
};
/** 与筛选条件一一对应的缓存键 */
export function feedCacheKey(parts: FeedKeyParts): string {
const {
boardId,
keyword,
sort,
tag = '',
author = '',
titleOnly = false,
} = parts;
return `${boardId}:${keyword}:${tag}:${author}:${titleOnly ? 1 : 0}:${sort}`;
}
type HomeStoreState = {
/** 按筛选键存放多份列表,首页 / 板块 / 搜索互不覆盖 */
feeds: Record<string, FeedCacheEntry>;
getFeed: (key: string) => FeedCacheEntry | null;
setFeed: (key: string, data: Omit<FeedCacheEntry, 'lastFetchTime'> & { lastFetchTime?: number }) => void;
/** 滚动时只更新 scrollTop不改动列表数据 */
patchScroll: (key: string, scrollTop: number) => void;
isStale: (key: string, now?: number) => boolean;
clearFeed: (key: string) => void;
clearAll: () => void;
};
export const useHomeStore = create<HomeStoreState>((set, get) => ({
feeds: {},
getFeed: (key) => get().feeds[key] ?? null,
setFeed: (key, data) => {
set((state) => ({
feeds: {
...state.feeds,
[key]: {
posts: data.posts,
postTotal: data.postTotal,
page: data.page,
scrollTop: data.scrollTop,
lastFetchTime: data.lastFetchTime ?? Date.now(),
},
},
}));
},
patchScroll: (key, scrollTop) => {
const prev = get().feeds[key];
if (!prev) return;
// 数值未变则跳过,减少无意义的 store 更新
if (prev.scrollTop === scrollTop) return;
set((state) => ({
feeds: {
...state.feeds,
[key]: { ...prev, scrollTop },
},
}));
},
isStale: (key, now = Date.now()) => {
const entry = get().feeds[key];
if (!entry) return true;
return now - entry.lastFetchTime > FEED_STALE_MS;
},
clearFeed: (key) => {
set((state) => {
if (!(key in state.feeds)) return state;
const next = { ...state.feeds };
delete next[key];
return { feeds: next };
});
},
clearAll: () => set({ feeds: {} }),
}));
/** 非 React 路径(如 feedCache 封装)直接读写 */
export function getHomeStoreState() {
return useHomeStore.getState();
}

File diff suppressed because it is too large Load Diff

17
frontend/src/types/svg-maps.d.ts vendored Normal file
View File

@@ -0,0 +1,17 @@
declare module '@svg-maps/world' {
const map: {
label: string;
viewBox: string;
locations: Array<{ id: string; name: string; path: string }>;
};
export default map;
}
declare module '@svg-maps/china' {
const map: {
label: string;
viewBox: string;
locations: Array<{ id: string; name: string; path: string }>;
};
export default map;
}

View File

@@ -1,19 +1,29 @@
import type { AsideWidget, AsideWidgetId, ForumLimits, ForumLimitsPublic } from '../api/types'; import type { AsideWidget, AsideWidgetId, ForumLimits, ForumLimitsPublic } from '../api/types';
import { DEFAULT_ASIDE_WIDGETS } from '../api/types'; import { DEFAULT_ASIDE_WIDGETS } from '../api/types';
const ASIDE_WIDGET_IDS: AsideWidgetId[] = ['tag_cloud', 'recent_comments', 'recent_users', 'friend_links']; const ASIDE_WIDGET_IDS: AsideWidgetId[] = [
'tag_cloud',
'recent_comments',
'recent_users',
'friend_links',
'showcase',
];
/** 从 limits 解析右侧栏组件列表(兼容仅有布尔开关的旧数据) */ /** 从 limits 解析右侧栏组件列表(兼容仅有布尔开关的旧数据) */
export function resolveAsideWidgets( export function resolveAsideWidgets(
limits: Pick<ForumLimitsPublic, 'aside_widgets' | 'aside_show_tag_cloud' | 'aside_show_recent_comments' | 'aside_show_friend_links'>, limits: Partial<Pick<
ForumLimitsPublic,
'aside_widgets' | 'aside_show_tag_cloud' | 'aside_show_recent_comments' | 'aside_show_friend_links' | 'aside_show_showcase'
>>,
): AsideWidget[] { ): AsideWidget[] {
if (limits.aside_widgets?.length) { if (limits.aside_widgets?.length) {
return normalizeAsideWidgets(limits.aside_widgets); return normalizeAsideWidgets(limits.aside_widgets);
} }
return [ return [
{ id: 'tag_cloud', enabled: limits.aside_show_tag_cloud }, { id: 'tag_cloud', enabled: !!limits.aside_show_tag_cloud },
{ id: 'recent_comments', enabled: limits.aside_show_recent_comments }, { id: 'recent_comments', enabled: !!limits.aside_show_recent_comments },
{ id: 'friend_links', enabled: limits.aside_show_friend_links }, { id: 'friend_links', enabled: limits.aside_show_friend_links !== false },
{ id: 'showcase', enabled: !!limits.aside_show_showcase },
]; ];
} }
@@ -33,12 +43,16 @@ export function normalizeAsideWidgets(widgets: AsideWidget[]): AsideWidget[] {
} }
/** 将 aside_widgets 同步回 ForumLimits 布尔字段 */ /** 将 aside_widgets 同步回 ForumLimits 布尔字段 */
export function syncAsideBoolsFromWidgets(widgets: AsideWidget[]): Pick<ForumLimits, 'aside_show_tag_cloud' | 'aside_show_recent_comments' | 'aside_show_friend_links'> { export function syncAsideBoolsFromWidgets(widgets: AsideWidget[]): Pick<
ForumLimits,
'aside_show_tag_cloud' | 'aside_show_recent_comments' | 'aside_show_friend_links' | 'aside_show_showcase'
> {
const normalized = normalizeAsideWidgets(widgets); const normalized = normalizeAsideWidgets(widgets);
return { return {
aside_show_tag_cloud: normalized.find(w => w.id === 'tag_cloud')?.enabled ?? false, aside_show_tag_cloud: normalized.find(w => w.id === 'tag_cloud')?.enabled ?? false,
aside_show_recent_comments: normalized.find(w => w.id === 'recent_comments')?.enabled ?? false, aside_show_recent_comments: normalized.find(w => w.id === 'recent_comments')?.enabled ?? false,
aside_show_friend_links: normalized.find(w => w.id === 'friend_links')?.enabled ?? true, aside_show_friend_links: normalized.find(w => w.id === 'friend_links')?.enabled ?? true,
aside_show_showcase: normalized.find(w => w.id === 'showcase')?.enabled ?? false,
}; };
} }
@@ -64,6 +78,7 @@ export function isAsideWidgetEnabled(widgets: AsideWidget[], id: AsideWidgetId):
aside_show_tag_cloud: false, aside_show_tag_cloud: false,
aside_show_recent_comments: false, aside_show_recent_comments: false,
aside_show_friend_links: false, aside_show_friend_links: false,
aside_show_showcase: false,
}).find(w => w.id === id)?.enabled ?? false; }).find(w => w.id === id)?.enabled ?? false;
} }

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