Compare commits
61 Commits
536707f812
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| de2f5e8be8 | |||
| 5c774f9a83 | |||
| f3f50d7e90 | |||
| 67bef6dc08 | |||
| 23e304ac53 | |||
| cad53942e8 | |||
| 76be8926f2 | |||
| 4d93e455f9 | |||
| c958dcfd80 | |||
| 84bfbd9a3e | |||
| 500e452c2f | |||
| 1c0f7ede55 | |||
| 2e9c42a34c | |||
| dff60dde6a | |||
| ea9e0058d4 | |||
| d5aa36416c | |||
| 2159280af5 | |||
| bc9a031890 | |||
| 0d81787125 | |||
| 68713c053b | |||
| 94823c0821 | |||
| b608ec85ba | |||
| 6048d71759 | |||
| 37d14a22d5 | |||
| a02d103cfe | |||
| 21c6233fc0 | |||
| 4ca5c17e2e | |||
| cf7a37eccc | |||
| 44eed97fe0 | |||
| 9e134916a4 | |||
| ba60a9b1c4 | |||
| 132ca5c82c | |||
| 185649db7c | |||
| 9d926750b2 | |||
| a91d917fa9 | |||
| 34f3d088ad | |||
| c6ce44f8b4 | |||
| 429956c594 | |||
| 16b6a18096 | |||
| 95c2154087 | |||
| 0abfb32194 | |||
| bcfd306643 | |||
| 335b708b04 | |||
| a83f8bd670 | |||
| 4dc3bbb13f | |||
| 8cfe31da61 | |||
| 7965768f3d | |||
| 012cac23de | |||
| d929bf96aa | |||
| cce9fb9ed8 | |||
| 9eefe24a33 | |||
| f559fc4c4b | |||
| 55b1831da2 | |||
| c6df703b96 | |||
| 7cc574f9a1 | |||
| 2208af7070 | |||
| df19752a1e | |||
| c07d1fd2bd | |||
| 4f85a86077 | |||
| f0650a9c39 | |||
| 4f42a2faff |
25
.dockerignore
Normal file
25
.dockerignore
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
# Git 与编辑器
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
.idea
|
||||||
|
.vscode
|
||||||
|
.cursor
|
||||||
|
|
||||||
|
# 运行时数据与本地配置
|
||||||
|
data/
|
||||||
|
app.ini
|
||||||
|
tmp-cookie.txt
|
||||||
|
|
||||||
|
# 编译产物与前端缓存
|
||||||
|
dist/
|
||||||
|
frontend/node_modules/
|
||||||
|
frontend/dist/
|
||||||
|
embed_static/static/spa/
|
||||||
|
node_modules/
|
||||||
|
.vite/
|
||||||
|
|
||||||
|
# 文档与截图(不参与镜像构建)
|
||||||
|
docs/
|
||||||
|
|
||||||
|
# 计划文件
|
||||||
|
*.plan.md
|
||||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -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
|
||||||
|
|||||||
@@ -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 4px,padding 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 列密度更高
|
|
||||||
- 颜文字标签内字体清晰可读
|
|
||||||
@@ -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`
|
|
||||||
|
|
||||||
不直接复用 ArticleEditor(900 行,含全屏/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 E:CSS 样式
|
|
||||||
|
|
||||||
#### 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,移除 EmojiPicker,content 改为 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 个 chunk(hot/j13/text),`React.lazy()` 动态导入
|
|
||||||
- 首次打开选择器只加载"热门"chunk(8 个贴纸),切换分类时才加载其他 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 内容
|
|
||||||
- 保存后评论更新正确
|
|
||||||
@@ -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 return),pageRef.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 编译通过。
|
|
||||||
36
.trae/rules/build-scripts.mdc
Normal file
36
.trae/rules/build-scripts.mdc
Normal 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「快速开始」如需对外暴露再更新
|
||||||
55
Dockerfile
Normal file
55
Dockerfile
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
# 姜十三论坛 — 多阶段构建:Node 前端 → Go 单二进制 → Alpine 运行镜像
|
||||||
|
# 不使用 # syntax=docker/dockerfile:1,避免构建前额外拉取 docker.io/docker/dockerfile
|
||||||
|
#
|
||||||
|
# 国内网络:默认经 DaoCloud 拉取基础镜像,npm/go 走国内代理
|
||||||
|
# 海外或已配置 Docker registry-mirrors 时可传空前缀:
|
||||||
|
# docker build --build-arg IMAGE_PREFIX= ...
|
||||||
|
|
||||||
|
ARG IMAGE_PREFIX=docker.m.daocloud.io/library/
|
||||||
|
ARG VERSION=dev
|
||||||
|
|
||||||
|
# ── Stage 1: 前端构建(Vite → embed_static/static/spa)────────────────────
|
||||||
|
FROM ${IMAGE_PREFIX}node:22-bookworm-slim AS frontend
|
||||||
|
WORKDIR /src/frontend
|
||||||
|
COPY frontend/package.json frontend/package-lock.json ./
|
||||||
|
RUN npm config set registry https://registry.npmmirror.com \
|
||||||
|
&& npm ci
|
||||||
|
COPY frontend/ ./
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# ── Stage 2: Go 编译(纯 Go SQLite,CGO_ENABLED=0)────────────────────────
|
||||||
|
FROM ${IMAGE_PREFIX}golang:1.26-bookworm AS builder
|
||||||
|
ARG VERSION
|
||||||
|
ENV GOPROXY=https://goproxy.cn,direct
|
||||||
|
WORKDIR /src
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY . .
|
||||||
|
COPY --from=frontend /src/embed_static/static/spa ./embed_static/static/spa
|
||||||
|
RUN CGO_ENABLED=0 go build -trimpath \
|
||||||
|
-ldflags "-s -w -X main.version=${VERSION}" \
|
||||||
|
-o /out/jiang13 ./cmd/jiang13
|
||||||
|
|
||||||
|
# ── Stage 3: 运行镜像 ───────────────────────────────────────────────────────
|
||||||
|
FROM ${IMAGE_PREFIX}alpine:3.21
|
||||||
|
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
|
||||||
|
&& apk add --no-cache ca-certificates tzdata wget su-exec \
|
||||||
|
&& adduser -D -u 1000 -h /app jiang13
|
||||||
|
|
||||||
|
ENV TZ=Asia/Shanghai
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=builder /out/jiang13 /app/jiang13
|
||||||
|
COPY docker-entrypoint.sh /docker-entrypoint.sh
|
||||||
|
RUN chown jiang13:jiang13 /app/jiang13 \
|
||||||
|
&& chmod +x /app/jiang13 /docker-entrypoint.sh
|
||||||
|
|
||||||
|
# 以 root 启动,entrypoint 修正 /data 卷权限后 su-exec 降权为 jiang13
|
||||||
|
VOLUME ["/data"]
|
||||||
|
EXPOSE 3000
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||||
|
CMD wget -qO- http://127.0.0.1:3000/health || exit 1
|
||||||
|
|
||||||
|
ENTRYPOINT ["/docker-entrypoint.sh"]
|
||||||
|
CMD ["--work-path", "/app", "--data", "/data", "--port", "3000"]
|
||||||
32
Makefile
32
Makefile
@@ -4,13 +4,15 @@
|
|||||||
APP_NAME := jiang13
|
APP_NAME := jiang13
|
||||||
MAIN_PKG := ./cmd/jiang13
|
MAIN_PKG := ./cmd/jiang13
|
||||||
BUILD_DIR := dist
|
BUILD_DIR := dist
|
||||||
VERSION := 1.0.0
|
DEV_DATA_DIR := dist/data
|
||||||
|
VERSION := 1.1.8
|
||||||
LDFLAGS := -s -w -X main.version=$(VERSION)
|
LDFLAGS := -s -w -X main.version=$(VERSION)
|
||||||
|
REGISTRY_IMAGE := hangzhang714128/jiang13-forum
|
||||||
|
|
||||||
GO := go
|
GO := go
|
||||||
GOFLAGS := -trimpath
|
GOFLAGS := -trimpath
|
||||||
|
|
||||||
.PHONY: all build build-windows build-linux build-darwin clean run dev tidy help frontend frontend-build
|
.PHONY: all build build-windows build-linux build-darwin clean run dev tidy help frontend frontend-build docker compose-up compose-down
|
||||||
|
|
||||||
all: build
|
all: build
|
||||||
|
|
||||||
@@ -54,22 +56,37 @@ build-all: frontend-build
|
|||||||
tidy:
|
tidy:
|
||||||
$(GO) mod tidy
|
$(GO) mod tidy
|
||||||
|
|
||||||
## 本地运行(仅后端,使用已 embed 的前端)
|
## 本地运行(仅后端,使用已 embed 的前端;数据目录与 dist 二进制一致)
|
||||||
run:
|
run:
|
||||||
$(GO) run $(MAIN_PKG)
|
@mkdir -p $(DEV_DATA_DIR)
|
||||||
|
$(GO) run $(MAIN_PKG) --data $(DEV_DATA_DIR)
|
||||||
|
|
||||||
## 前端热更新开发(后端 :3000 + Vite :5173,Ctrl+C 同时退出)
|
## 前端热更新开发(后端 :3000 + Vite :5173,Ctrl+C 同时退出;数据目录与 dist 二进制一致)
|
||||||
dev:
|
dev:
|
||||||
@echo "前端热更新: http://localhost:5173"
|
@echo "前端热更新: http://localhost:5173"
|
||||||
@echo "后端 API : http://localhost:3000"
|
@echo "后端 API : http://localhost:3000"
|
||||||
|
@echo "数据目录 : $(DEV_DATA_DIR) (与 dist 二进制一致)"
|
||||||
|
@mkdir -p $(DEV_DATA_DIR)
|
||||||
@trap 'kill 0' INT; \
|
@trap 'kill 0' INT; \
|
||||||
$(GO) run $(MAIN_PKG) & \
|
$(GO) run $(MAIN_PKG) --dev --data $(DEV_DATA_DIR) & \
|
||||||
cd frontend && (test -d node_modules || npm install) && npm run dev
|
cd frontend && (test -d node_modules || npm install) && npm run dev
|
||||||
|
|
||||||
## 清理编译产物
|
## 清理编译产物
|
||||||
clean:
|
clean:
|
||||||
rm -rf $(BUILD_DIR)
|
rm -rf $(BUILD_DIR)
|
||||||
|
|
||||||
|
## 构建 Docker 镜像
|
||||||
|
docker:
|
||||||
|
docker build --build-arg VERSION=$(VERSION) -t $(REGISTRY_IMAGE):$(VERSION) -t $(REGISTRY_IMAGE):latest .
|
||||||
|
|
||||||
|
## Docker Compose 启动
|
||||||
|
compose-up:
|
||||||
|
docker compose up -d --build
|
||||||
|
|
||||||
|
## Docker Compose 停止
|
||||||
|
compose-down:
|
||||||
|
docker compose down
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "姜十三论坛编译命令:"
|
@echo "姜十三论坛编译命令:"
|
||||||
@echo " make build - 编译当前平台"
|
@echo " make build - 编译当前平台"
|
||||||
@@ -79,3 +96,6 @@ help:
|
|||||||
@echo " make build-all - 编译全部平台"
|
@echo " make build-all - 编译全部平台"
|
||||||
@echo " make run - 仅启动后端(:3000)"
|
@echo " make run - 仅启动后端(:3000)"
|
||||||
@echo " make dev - 前端热更新开发(:5173 + :3000)"
|
@echo " make dev - 前端热更新开发(:5173 + :3000)"
|
||||||
|
@echo " make docker - 构建 Docker 镜像"
|
||||||
|
@echo " make compose-up - Docker Compose 启动"
|
||||||
|
@echo " make compose-down - Docker Compose 停止"
|
||||||
|
|||||||
135
README.md
135
README.md
@@ -11,6 +11,7 @@
|
|||||||
|
|
||||||
[](https://bbs.iioio.com/)
|
[](https://bbs.iioio.com/)
|
||||||
[](LICENSE)
|
[](LICENSE)
|
||||||
|
[](https://hub.docker.com/r/hangzhang714128/jiang13-forum)
|
||||||
[](go.mod)
|
[](go.mod)
|
||||||
[](frontend/package.json)
|
[](frontend/package.json)
|
||||||
[](#)
|
[](#)
|
||||||
@@ -19,6 +20,7 @@
|
|||||||
[快速开始](#-快速开始) ·
|
[快速开始](#-快速开始) ·
|
||||||
[界面预览](#-界面预览) ·
|
[界面预览](#-界面预览) ·
|
||||||
[功能亮点](#-功能亮点) ·
|
[功能亮点](#-功能亮点) ·
|
||||||
|
[更新日志](docs/site-posts/changelog.md) ·
|
||||||
[路线图](ROADMAP.md) ·
|
[路线图](ROADMAP.md) ·
|
||||||
[参与贡献](CONTRIBUTING.md)
|
[参与贡献](CONTRIBUTING.md)
|
||||||
|
|
||||||
@@ -116,6 +118,7 @@
|
|||||||
- **零依赖数据库** — SQLite 内建,数据目录由 `app.ini` 统一管理
|
- **零依赖数据库** — SQLite 内建,数据目录由 `app.ini` 统一管理
|
||||||
- **跨平台** — Windows / Linux / macOS 一键编译
|
- **跨平台** — Windows / Linux / macOS 一键编译
|
||||||
- **系统服务** — 内置 Linux systemd / Windows Service 注册
|
- **系统服务** — 内置 Linux systemd / Windows Service 注册
|
||||||
|
- **Docker 单容器** — 多阶段镜像,挂载 `data/` 即可持久化
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -152,9 +155,119 @@ build.bat -Target build-linux
|
|||||||
build.bat -Target build-all
|
build.bat -Target build-all
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. 启动
|
### 2. Docker 部署(推荐)
|
||||||
|
|
||||||
把二进制放到目标目录后直接运行(首次会在同目录生成 `app.ini`):
|
**一键启动(本地构建):**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
```bat
|
||||||
|
.\build.bat -Target compose-up
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make compose-up
|
||||||
|
```
|
||||||
|
|
||||||
|
浏览器打开 `http://localhost:3000/register` 注册;**首个用户自动成为管理员**。
|
||||||
|
|
||||||
|
版本变更与升级说明见 **[更新日志](docs/site-posts/changelog.md)**。Docker 与 Windows / Linux 单文件共用同一版本号。
|
||||||
|
|
||||||
|
- Docker 标签:[hub.docker.com/r/hangzhang714128/jiang13-forum/tags](https://hub.docker.com/r/hangzhang714128/jiang13-forum/tags)
|
||||||
|
- 预编译包:[Gitea Releases](https://git.iioio.com/freefire/jiang13-forum/releases)
|
||||||
|
|
||||||
|
**拉取已构建镜像(Docker Hub):**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker pull hangzhang714128/jiang13-forum:latest
|
||||||
|
docker run -d --name jiang13 \
|
||||||
|
-p 3000:3000 \
|
||||||
|
-v jiang13-data:/data \
|
||||||
|
--restart unless-stopped \
|
||||||
|
hangzhang714128/jiang13-forum:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
**数据持久化:** 容器内 `/data` 对应 SQLite、上传、日志与 JWT 密钥,与下方「数据目录」结构一致。可用 Docker volume 或绑定宿主机目录。镜像启动时会自动将 `/data` 卷属主修正为 uid `1000`(`jiang13` 用户),适配 1Panel 等面板挂载的目录。
|
||||||
|
|
||||||
|
**若使用旧版镜像仍报 permission denied**,可在宿主机执行:`chown -R 1000:1000 /你的数据目录`
|
||||||
|
|
||||||
|
**可选环境变量(容器编排):**
|
||||||
|
|
||||||
|
| 变量 | 说明 |
|
||||||
|
|------|------|
|
||||||
|
| `JIANG13_HTTP_PORT` | HTTP 端口(默认 `3000`) |
|
||||||
|
| `JIANG13_DATA` | 数据目录(默认 `/data`) |
|
||||||
|
| `JIANG13_JWT_SECRET` | JWT 密钥(留空则自动生成并写入 `/data/.jwt_secret`) |
|
||||||
|
| `JIANG13_CONFIG` | 配置文件路径 |
|
||||||
|
| `JIANG13_WORK_PATH` | 工作目录 |
|
||||||
|
| `JIANG13_COMMUNITY_HUB` | 维护者选项:设为 `1` 时本站作为社区枢纽收报。官方站 `bbs.iioio.com` 会按域名自动成为枢纽,无需此变量;仅非官网的枢纽镜像 / 预发需要显式开启(见 `app.ini.example`) |
|
||||||
|
|
||||||
|
**健康检查:** `GET /health` 返回 `{"status":"ok"}`,供 Docker / 负载均衡探活。
|
||||||
|
|
||||||
|
**发布镜像到 Docker Hub(手动):**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker login
|
||||||
|
.\build.bat -Target docker # Windows
|
||||||
|
# make docker # Linux/macOS
|
||||||
|
docker push hangzhang714128/jiang13-forum:1.1.7
|
||||||
|
docker push hangzhang714128/jiang13-forum:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
或直接构建:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker build --build-arg VERSION=1.1.7 -t hangzhang714128/jiang13-forum:1.1.7 -t hangzhang714128/jiang13-forum:latest .
|
||||||
|
docker push hangzhang714128/jiang13-forum:1.1.7
|
||||||
|
docker push hangzhang714128/jiang13-forum:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
停止服务:`docker compose down` / `.\build.bat -Target compose-down` / `make compose-down`
|
||||||
|
|
||||||
|
**构建失败(无法连接 auth.docker.io)?** Dockerfile 已默认经 DaoCloud 拉取基础镜像。若仍超时,可在 Docker Desktop → Settings → Docker Engine 添加:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"registry-mirrors": ["https://docker.m.daocloud.io"]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
保存并重启 Docker 后重试 `.\build.bat -Target docker`。PowerShell 中请用 `.\build.bat`(带 `.\` 前缀)。
|
||||||
|
|
||||||
|
**1Panel 部署提示:**
|
||||||
|
|
||||||
|
1. 容器镜像填 `hangzhang714128/jiang13-forum:latest`
|
||||||
|
2. 端口映射 `3000:3000`
|
||||||
|
3. 挂载数据卷到容器内 `/data`(镜像会自动修正目录权限)
|
||||||
|
4. 首次访问 `http://服务器IP:3000/register` 注册管理员
|
||||||
|
|
||||||
|
### 3. 直接启动(二进制)
|
||||||
|
|
||||||
|
不想自己编译时,从 [Gitea Releases](https://git.iioio.com/freefire/jiang13-forum/releases) 下载与 Docker 同版本号的文件即可:
|
||||||
|
|
||||||
|
| 文件 | 平台 |
|
||||||
|
|------|------|
|
||||||
|
| `jiang13-*-windows-amd64.exe` | Windows x64 |
|
||||||
|
| `jiang13-*-linux-amd64` | Linux x64 |
|
||||||
|
|
||||||
|
当前 **1.1.7:** [Windows](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/jiang13-1.1.7-windows-amd64.exe) · [Linux](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/jiang13-1.1.7-linux-amd64)
|
||||||
|
|
||||||
|
把文件放到目标目录后直接运行(首次会在同目录生成 `app.ini`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Windows
|
||||||
|
.\jiang13-1.1.7-windows-amd64.exe
|
||||||
|
# 或改名为 jiang13.exe 后:
|
||||||
|
.\jiang13.exe
|
||||||
|
|
||||||
|
# Linux
|
||||||
|
chmod +x jiang13-1.1.7-linux-amd64
|
||||||
|
./jiang13-1.1.7-linux-amd64
|
||||||
|
```
|
||||||
|
|
||||||
|
本地刚编译的产物在 `dist/`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Windows
|
# Windows
|
||||||
@@ -172,7 +285,7 @@ cp app.ini.example /opt/jiang13/app.ini
|
|||||||
./jiang13
|
./jiang13
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. 首次使用
|
### 4. 首次使用
|
||||||
|
|
||||||
1. 浏览器打开 `http://localhost:3000/register` 注册账号
|
1. 浏览器打开 `http://localhost:3000/register` 注册账号
|
||||||
2. **第一个注册的用户自动成为管理员**
|
2. **第一个注册的用户自动成为管理员**
|
||||||
@@ -208,7 +321,9 @@ 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` |
|
||||||
|
|
||||||
### 4. 注册为系统服务(可选)
|
**环境变量(容器 / 编排,优先级低于命令行):** `JIANG13_HTTP_PORT`、`JIANG13_DATA`、`JIANG13_JWT_SECRET`、`JIANG13_CONFIG`、`JIANG13_WORK_PATH`、`JIANG13_COMMUNITY_HUB`(非官网枢纽镜像用;`bbs.iioio.com` 按域名自动为枢纽,见上表)
|
||||||
|
|
||||||
|
### 5. 注册为系统服务(可选)
|
||||||
|
|
||||||
将二进制与 `app.ini` 放到同一目录后注册即可。之后改端口或数据目录只需编辑 `app.ini` 并重启服务,不必重新安装。
|
将二进制与 `app.ini` 放到同一目录后注册即可。之后改端口或数据目录只需编辑 `app.ini` 并重启服务,不必重新安装。
|
||||||
|
|
||||||
@@ -260,6 +375,8 @@ make dev
|
|||||||
|
|
||||||
浏览器访问 `http://localhost:5173`,API 自动代理到 `http://localhost:3000`。
|
浏览器访问 `http://localhost:5173`,API 自动代理到 `http://localhost:3000`。
|
||||||
|
|
||||||
|
开发后端与 `dist/jiang13` 共用数据目录 `dist/data`(SQLite、上传、JWT 密钥等),避免 dev 与 dist 运行数据不一致。
|
||||||
|
|
||||||
**何时需要完整构建:**
|
**何时需要完整构建:**
|
||||||
|
|
||||||
- 修改 Go 代码或要发布单二进制 → `build.bat` / `make build`
|
- 修改 Go 代码或要发布单二进制 → `build.bat` / `make build`
|
||||||
@@ -295,6 +412,10 @@ jiang13-forum/
|
|||||||
├── cmd/jiang13/ # 程序入口(含系统服务注册)
|
├── cmd/jiang13/ # 程序入口(含系统服务注册)
|
||||||
├── config/ # app.ini 与命令行配置
|
├── config/ # app.ini 与命令行配置
|
||||||
├── app.ini.example # 配置文件示例
|
├── app.ini.example # 配置文件示例
|
||||||
|
├── Dockerfile # 多阶段 Docker 构建
|
||||||
|
├── docker-compose.yml # 单容器 Compose 部署
|
||||||
|
├── docker-entrypoint.sh # 容器启动脚本(修正 /data 卷权限)
|
||||||
|
├── .dockerignore
|
||||||
├── model/ # GORM 模型与数据库迁移
|
├── model/ # GORM 模型与数据库迁移
|
||||||
├── service/ # 业务逻辑
|
├── service/ # 业务逻辑
|
||||||
├── handler/ # HTTP 处理器(前台 + 后台)
|
├── handler/ # HTTP 处理器(前台 + 后台)
|
||||||
@@ -313,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 # 后台导出的主库备份
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
32
build.ps1
32
build.ps1
@@ -3,7 +3,7 @@
|
|||||||
# .\build.ps1 -Target build-windows
|
# .\build.ps1 -Target build-windows
|
||||||
|
|
||||||
param(
|
param(
|
||||||
[ValidateSet('build', 'build-windows', 'build-linux', 'build-darwin', 'build-all', 'frontend', 'tidy', 'run', 'dev', 'clean', 'help')]
|
[ValidateSet('build', 'build-windows', 'build-linux', 'build-darwin', 'build-all', 'frontend', 'tidy', 'run', 'dev', 'clean', 'docker', 'compose-up', 'compose-down', 'help')]
|
||||||
[string]$Target = 'build'
|
[string]$Target = 'build'
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -11,7 +11,9 @@ $ErrorActionPreference = 'Stop'
|
|||||||
$AppName = 'jiang13'
|
$AppName = 'jiang13'
|
||||||
$MainPkg = './cmd/jiang13'
|
$MainPkg = './cmd/jiang13'
|
||||||
$BuildDir = 'dist'
|
$BuildDir = 'dist'
|
||||||
$Version = '1.0.0'
|
$DevDataDir = 'dist/data'
|
||||||
|
$Version = '1.1.8'
|
||||||
|
$RegistryImage = 'hangzhang714128/jiang13-forum'
|
||||||
$Ldlags = "-s -w -X main.version=$Version"
|
$Ldlags = "-s -w -X main.version=$Version"
|
||||||
|
|
||||||
function Ensure-Dir($path) {
|
function Ensure-Dir($path) {
|
||||||
@@ -76,6 +78,9 @@ switch ($Target) {
|
|||||||
Write-Host '.\build.ps1 -Target dev backend + Vite HMR (recommended for frontend dev)'
|
Write-Host '.\build.ps1 -Target dev backend + Vite HMR (recommended for frontend dev)'
|
||||||
Write-Host '.\build.ps1 -Target tidy'
|
Write-Host '.\build.ps1 -Target tidy'
|
||||||
Write-Host '.\build.ps1 -Target clean'
|
Write-Host '.\build.ps1 -Target clean'
|
||||||
|
Write-Host '.\build.ps1 -Target docker build Docker image'
|
||||||
|
Write-Host '.\build.ps1 -Target compose-up docker compose up -d --build'
|
||||||
|
Write-Host '.\build.ps1 -Target compose-down docker compose down'
|
||||||
Write-Host ''
|
Write-Host ''
|
||||||
Write-Host 'Note: Windows "make" is often Embarcadero MAKE, not GNU Make.'
|
Write-Host 'Note: Windows "make" is often Embarcadero MAKE, not GNU Make.'
|
||||||
}
|
}
|
||||||
@@ -86,18 +91,21 @@ switch ($Target) {
|
|||||||
Write-Host '[ok] cleaned dist' -ForegroundColor Green
|
Write-Host '[ok] cleaned dist' -ForegroundColor Green
|
||||||
}
|
}
|
||||||
'run' {
|
'run' {
|
||||||
go run $MainPkg
|
Ensure-Dir $DevDataDir
|
||||||
|
go run $MainPkg --data $DevDataDir
|
||||||
}
|
}
|
||||||
'dev' {
|
'dev' {
|
||||||
$root = (Get-Location).Path
|
$root = (Get-Location).Path
|
||||||
|
Ensure-Dir $DevDataDir
|
||||||
Write-Host ''
|
Write-Host ''
|
||||||
Write-Host '[dev] 前端开发 : http://localhost:5173 (Vite HMR)' -ForegroundColor Green
|
Write-Host '[dev] 前端开发 : http://localhost:5173 (Vite HMR)' -ForegroundColor Green
|
||||||
Write-Host '[dev] 后端 API : http://localhost:3000 (Go)' -ForegroundColor Green
|
Write-Host '[dev] 后端 API : http://localhost:3000 (Go)' -ForegroundColor Green
|
||||||
|
Write-Host "[dev] 数据目录 : $DevDataDir (与 dist 二进制一致)" -ForegroundColor Green
|
||||||
Write-Host '[dev] 提示 : 请访问 5173 端口,Vite 会自动代理 API 到 3000' -ForegroundColor Yellow
|
Write-Host '[dev] 提示 : 请访问 5173 端口,Vite 会自动代理 API 到 3000' -ForegroundColor Yellow
|
||||||
Write-Host '[dev] 正在新窗口启动 Go 后端 (仅 API)...' -ForegroundColor Cyan
|
Write-Host '[dev] 正在新窗口启动 Go 后端 (仅 API)...' -ForegroundColor Cyan
|
||||||
Start-Process powershell -ArgumentList @(
|
Start-Process powershell -ArgumentList @(
|
||||||
'-NoExit', '-Command',
|
'-NoExit', '-Command',
|
||||||
"Set-Location '$root'; Write-Host '[backend] Go API on :3000' -ForegroundColor Cyan; go run $MainPkg --dev"
|
"Set-Location '$root'; Write-Host '[backend] Go API on :3000' -ForegroundColor Cyan; go run $MainPkg --dev --data '$DevDataDir'"
|
||||||
) | Out-Null
|
) | Out-Null
|
||||||
Start-Sleep -Seconds 2
|
Start-Sleep -Seconds 2
|
||||||
Push-Location frontend
|
Push-Location frontend
|
||||||
@@ -132,4 +140,20 @@ switch ($Target) {
|
|||||||
Build-Go -OutFile "$AppName-darwin-arm64" -GoOS 'darwin' -GoArch 'arm64'
|
Build-Go -OutFile "$AppName-darwin-arm64" -GoOS 'darwin' -GoArch 'arm64'
|
||||||
Write-Host '[ok] all platforms done' -ForegroundColor Green
|
Write-Host '[ok] all platforms done' -ForegroundColor Green
|
||||||
}
|
}
|
||||||
|
'docker' {
|
||||||
|
Write-Host "[docker] build $RegistryImage`:$Version and latest" -ForegroundColor Cyan
|
||||||
|
docker build --build-arg "VERSION=$Version" -t "${RegistryImage}:$Version" -t "${RegistryImage}:latest" .
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw 'docker build failed' }
|
||||||
|
Write-Host '[ok] docker image built' -ForegroundColor Green
|
||||||
|
}
|
||||||
|
'compose-up' {
|
||||||
|
docker compose up -d --build
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw 'docker compose up failed' }
|
||||||
|
Write-Host '[ok] compose started' -ForegroundColor Green
|
||||||
|
}
|
||||||
|
'compose-down' {
|
||||||
|
docker compose down
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw 'docker compose down failed' }
|
||||||
|
Write-Host '[ok] compose stopped' -ForegroundColor Green
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,9 +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=..." 注入
|
||||||
|
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)
|
||||||
|
|||||||
@@ -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"
|
||||||
)
|
)
|
||||||
@@ -72,11 +73,18 @@ func (p *program) setup() error {
|
|||||||
|
|
||||||
log.Println("========================================")
|
log.Println("========================================")
|
||||||
log.Println(" 姜十三论坛 Jiang13 Forum 启动中...")
|
log.Println(" 姜十三论坛 Jiang13 Forum 启动中...")
|
||||||
|
log.Printf(" 版本: %s", version)
|
||||||
log.Println("========================================")
|
log.Println("========================================")
|
||||||
|
|
||||||
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 {
|
||||||
|
|||||||
410
cmd/monitor-geo-check/main.go
Normal file
410
cmd/monitor-geo-check/main.go
Normal file
@@ -0,0 +1,410 @@
|
|||||||
|
// 只读诊断:检查 Geo 库与 page_views 地理字段,或对指定 IP 试查中文映射结果。
|
||||||
|
//
|
||||||
|
// go run ./cmd/monitor-geo-check -db data/monitor.db
|
||||||
|
// go run ./cmd/monitor-geo-check -db data/monitor.db -ip 14.109.35.246
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.iioio.com/freefire/jiang13-forum/service"
|
||||||
|
"github.com/glebarez/sqlite"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
dbPath := flag.String("db", filepath.Join("data", "monitor.db"), "含 page_views 的 SQLite(默认 data/monitor.db)")
|
||||||
|
ipLookup := flag.String("ip", "", "对指定 IP 试查 BIN+ASN(不写库)")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
abs, err := filepath.Abs(*dbPath)
|
||||||
|
if err != nil {
|
||||||
|
fatalf("解析路径失败: %v", err)
|
||||||
|
}
|
||||||
|
dataDir := filepath.Dir(abs)
|
||||||
|
|
||||||
|
if *ipLookup == "" {
|
||||||
|
if st, err := os.Stat(abs); err != nil || st.IsDir() {
|
||||||
|
fatalf("数据库不存在: %s", abs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("数据库: %s\n", abs)
|
||||||
|
fmt.Printf("数据目录: %s\n\n", dataDir)
|
||||||
|
|
||||||
|
suite := service.NewGeoIPService(dataDir)
|
||||||
|
defer suite.Close()
|
||||||
|
printGeoFiles(dataDir, suite)
|
||||||
|
|
||||||
|
if ip := strings.TrimSpace(*ipLookup); ip != "" {
|
||||||
|
lookupIP(suite, ip)
|
||||||
|
fmt.Println()
|
||||||
|
if _, err := os.Stat(abs); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := gorm.Open(sqlite.Open(abs), &gorm.Config{
|
||||||
|
Logger: logger.Default.LogMode(logger.Silent),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
fatalf("打开数据库失败: %v", err)
|
||||||
|
}
|
||||||
|
sqlDB, err := db.DB()
|
||||||
|
if err != nil {
|
||||||
|
fatalf("获取连接失败: %v", err)
|
||||||
|
}
|
||||||
|
defer sqlDB.Close()
|
||||||
|
sqlDB.SetMaxOpenConns(1)
|
||||||
|
|
||||||
|
if !tableExists(db, "page_views") {
|
||||||
|
fatalf("表 page_views 不存在(请确认指向 data/monitor.db,或尚未写入过浏览量)")
|
||||||
|
}
|
||||||
|
|
||||||
|
have := columnSet(db)
|
||||||
|
printColumnPresence(have)
|
||||||
|
|
||||||
|
since := time.Now().AddDate(0, 0, -30)
|
||||||
|
var total, recentNonBot, withCountry, withRegion, withCity, withASN int64
|
||||||
|
_ = db.Table("page_views").Count(&total).Error
|
||||||
|
_ = db.Table("page_views").Where("created_at >= ? AND is_bot = ?", since, false).Count(&recentNonBot).Error
|
||||||
|
|
||||||
|
fmt.Println("=== page_views 统计(近 30 日非 bot)===")
|
||||||
|
fmt.Printf("总量: %d\n", total)
|
||||||
|
fmt.Printf("近 30 日非 bot: %d\n", recentNonBot)
|
||||||
|
|
||||||
|
if have["country"] {
|
||||||
|
_ = db.Table("page_views").Where("created_at >= ? AND is_bot = ? AND country <> ''", since, false).Count(&withCountry).Error
|
||||||
|
fmt.Printf("有国家: %d\n", withCountry)
|
||||||
|
} else {
|
||||||
|
fmt.Println("有国家: (列缺失)")
|
||||||
|
}
|
||||||
|
if have["region"] || have["region_iso"] {
|
||||||
|
cond := "created_at >= ? AND is_bot = ?"
|
||||||
|
parts := []string{}
|
||||||
|
if have["region"] {
|
||||||
|
parts = append(parts, "region <> ''")
|
||||||
|
}
|
||||||
|
if have["region_iso"] {
|
||||||
|
parts = append(parts, "region_iso <> ''")
|
||||||
|
}
|
||||||
|
_ = db.Table("page_views").
|
||||||
|
Where(cond+" AND ("+strings.Join(parts, " OR ")+")", since, false).
|
||||||
|
Count(&withRegion).Error
|
||||||
|
fmt.Printf("有省字段: %d\n", withRegion)
|
||||||
|
} else {
|
||||||
|
fmt.Println("有省字段: (列缺失)")
|
||||||
|
}
|
||||||
|
if have["city"] {
|
||||||
|
_ = db.Table("page_views").Where("created_at >= ? AND is_bot = ? AND city <> ''", since, false).Count(&withCity).Error
|
||||||
|
fmt.Printf("有城市: %d\n", withCity)
|
||||||
|
} else {
|
||||||
|
fmt.Println("有城市: (列缺失)")
|
||||||
|
}
|
||||||
|
if have["asn"] {
|
||||||
|
_ = db.Table("page_views").Where("created_at >= ? AND is_bot = ? AND asn > 0", since, false).Count(&withASN).Error
|
||||||
|
fmt.Printf("有 ASN: %d\n", withASN)
|
||||||
|
} else {
|
||||||
|
fmt.Println("有 ASN: (列缺失)")
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
fmt.Println("=== 近 30 日省级 Top(country / region / region_iso)===")
|
||||||
|
if !(have["region"] || have["region_iso"]) {
|
||||||
|
fmt.Println("(省列尚未迁移,跳过)")
|
||||||
|
} else {
|
||||||
|
type regionRow struct {
|
||||||
|
Country string
|
||||||
|
Region string
|
||||||
|
RegionISO string `gorm:"column:region_iso"`
|
||||||
|
Count int64
|
||||||
|
}
|
||||||
|
parts := []string{}
|
||||||
|
if have["region"] {
|
||||||
|
parts = append(parts, "region <> ''")
|
||||||
|
}
|
||||||
|
if have["region_iso"] {
|
||||||
|
parts = append(parts, "region_iso <> ''")
|
||||||
|
}
|
||||||
|
selParts := []string{}
|
||||||
|
groupParts := []string{}
|
||||||
|
if have["country"] {
|
||||||
|
selParts = append(selParts, "country")
|
||||||
|
groupParts = append(groupParts, "country")
|
||||||
|
} else {
|
||||||
|
selParts = append(selParts, "'' as country")
|
||||||
|
}
|
||||||
|
if have["region"] {
|
||||||
|
selParts = append(selParts, "region")
|
||||||
|
groupParts = append(groupParts, "region")
|
||||||
|
} else {
|
||||||
|
selParts = append(selParts, "'' as region")
|
||||||
|
}
|
||||||
|
if have["region_iso"] {
|
||||||
|
selParts = append(selParts, "region_iso")
|
||||||
|
groupParts = append(groupParts, "region_iso")
|
||||||
|
} else {
|
||||||
|
selParts = append(selParts, "'' as region_iso")
|
||||||
|
}
|
||||||
|
selParts = append(selParts, "COUNT(*) as count")
|
||||||
|
var regions []regionRow
|
||||||
|
_ = db.Table("page_views").
|
||||||
|
Select(strings.Join(selParts, ", ")).
|
||||||
|
Where("created_at >= ? AND is_bot = ? AND ("+strings.Join(parts, " OR ")+")", since, false).
|
||||||
|
Group(strings.Join(groupParts, ", ")).
|
||||||
|
Order("count DESC").
|
||||||
|
Limit(20).
|
||||||
|
Scan(®ions).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)
|
||||||
|
}
|
||||||
@@ -32,11 +32,14 @@ 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,并初始化数据目录
|
||||||
//
|
//
|
||||||
// 优先级(高 → 低):命令行显式参数 > app.ini > 内置默认值
|
// 优先级(高 → 低):命令行显式参数 > 环境变量 > app.ini > 内置默认值
|
||||||
func Parse() (*Config, error) {
|
func Parse() (*Config, error) {
|
||||||
configFlag := flag.String("config", "", "配置文件路径(默认:工作目录/app.ini)")
|
configFlag := flag.String("config", "", "配置文件路径(默认:工作目录/app.ini)")
|
||||||
workFlag := flag.String("work-path", "", "工作目录(默认:可执行文件所在目录)")
|
workFlag := flag.String("work-path", "", "工作目录(默认:可执行文件所在目录)")
|
||||||
@@ -52,12 +55,20 @@ func Parse() (*Config, error) {
|
|||||||
return nil, fmt.Errorf("无效的 -service 动作 %q,可选:install|uninstall|start|stop|restart|status", *serviceFlag)
|
return nil, fmt.Errorf("无效的 -service 动作 %q,可选:install|uninstall|start|stop|restart|status", *serviceFlag)
|
||||||
}
|
}
|
||||||
|
|
||||||
workPath, err := resolveWorkPath(*workFlag)
|
workPathInput := strings.TrimSpace(*workFlag)
|
||||||
|
if workPathInput == "" {
|
||||||
|
workPathInput = envOrDefault(envWorkPath)
|
||||||
|
}
|
||||||
|
workPath, err := resolveWorkPath(workPathInput)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
configFile, err := resolveConfigPath(workPath, *configFlag)
|
configInput := strings.TrimSpace(*configFlag)
|
||||||
|
if configInput == "" {
|
||||||
|
configInput = envOrDefault(envConfig)
|
||||||
|
}
|
||||||
|
configFile, err := resolveConfigPath(workPath, configInput)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -73,11 +84,17 @@ func Parse() (*Config, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
port := fileCfg.Port
|
port := fileCfg.Port
|
||||||
|
if p := envIntOrZero(envHTTPPort); p > 0 {
|
||||||
|
port = p
|
||||||
|
}
|
||||||
if *portFlag > 0 {
|
if *portFlag > 0 {
|
||||||
port = *portFlag
|
port = *portFlag
|
||||||
}
|
}
|
||||||
|
|
||||||
dataInput := fileCfg.DataRel
|
dataInput := fileCfg.DataRel
|
||||||
|
if v := envOrDefault(envData); v != "" {
|
||||||
|
dataInput = v
|
||||||
|
}
|
||||||
if strings.TrimSpace(*dataFlag) != "" {
|
if strings.TrimSpace(*dataFlag) != "" {
|
||||||
dataInput = *dataFlag
|
dataInput = *dataFlag
|
||||||
}
|
}
|
||||||
@@ -86,9 +103,17 @@ func Parse() (*Config, error) {
|
|||||||
return nil, fmt.Errorf("解析数据目录失败: %w", err)
|
return nil, fmt.Errorf("解析数据目录失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
jwtSecret := strings.TrimSpace(*jwtFlag)
|
jwtSecret := fileCfg.JWTSecret
|
||||||
if jwtSecret == "" {
|
if v := envOrDefault(envJWTSecret); v != "" {
|
||||||
jwtSecret = fileCfg.JWTSecret
|
jwtSecret = v
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(*jwtFlag) != "" {
|
||||||
|
jwtSecret = strings.TrimSpace(*jwtFlag)
|
||||||
|
}
|
||||||
|
|
||||||
|
communityHub := fileCfg.CommunityHub
|
||||||
|
if v := envBoolOrNil(envCommunityHub); v != nil {
|
||||||
|
communityHub = *v
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg := &Config{
|
cfg := &Config{
|
||||||
@@ -100,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"
|
||||||
@@ -167,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)
|
||||||
@@ -201,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")
|
||||||
|
|||||||
51
config/env.go
Normal file
51
config/env.go
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 容器 / 编排常用环境变量(优先级:命令行 > 环境变量 > app.ini > 内置默认)
|
||||||
|
const (
|
||||||
|
envWorkPath = "JIANG13_WORK_PATH"
|
||||||
|
envConfig = "JIANG13_CONFIG"
|
||||||
|
envHTTPPort = "JIANG13_HTTP_PORT"
|
||||||
|
envData = "JIANG13_DATA"
|
||||||
|
envJWTSecret = "JIANG13_JWT_SECRET"
|
||||||
|
envCommunityHub = "JIANG13_COMMUNITY_HUB"
|
||||||
|
)
|
||||||
|
|
||||||
|
func envOrDefault(key string) string {
|
||||||
|
return strings.TrimSpace(os.Getenv(key))
|
||||||
|
}
|
||||||
|
|
||||||
|
func envIntOrZero(key string) int {
|
||||||
|
v := envOrDefault(key)
|
||||||
|
if v == "" {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
n, err := strconv.Atoi(v)
|
||||||
|
if err != nil || n <= 0 || n > 65535 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// envBoolOrNil 解析布尔环境变量;未设置返回 nil
|
||||||
|
func envBoolOrNil(key string) *bool {
|
||||||
|
v := strings.ToLower(envOrDefault(key))
|
||||||
|
if v == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
switch v {
|
||||||
|
case "1", "true", "yes", "on":
|
||||||
|
t := true
|
||||||
|
return &t
|
||||||
|
case "0", "false", "no", "off":
|
||||||
|
f := false
|
||||||
|
return &f
|
||||||
|
default:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,7 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
33
docker-compose.yml
Normal file
33
docker-compose.yml
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
# 姜十三论坛 — Docker Compose 单服务部署
|
||||||
|
# 启动:docker compose up -d --build
|
||||||
|
# 或:make compose-up / build.bat -Target compose-up
|
||||||
|
|
||||||
|
services:
|
||||||
|
jiang13:
|
||||||
|
image: hangzhang714128/jiang13-forum:latest
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
args:
|
||||||
|
VERSION: dev
|
||||||
|
ports:
|
||||||
|
- "3000:3000"
|
||||||
|
volumes:
|
||||||
|
- jiang13-data:/data
|
||||||
|
# 可选:挂载自定义 app.ini(只读)
|
||||||
|
# - ./app.ini:/app/app.ini:ro
|
||||||
|
environment:
|
||||||
|
TZ: Asia/Shanghai
|
||||||
|
# 可选:固定 JWT 密钥(留空则自动生成并持久化到 /data/.jwt_secret)
|
||||||
|
# JIANG13_JWT_SECRET: your-secret-here
|
||||||
|
restart: unless-stopped
|
||||||
|
stop_grace_period: 15s
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:3000/health"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
start_period: 15s
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
jiang13-data:
|
||||||
15
docker-entrypoint.sh
Normal file
15
docker-entrypoint.sh
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# 宿主机 / 1Panel 挂载的 volume 常为 root 所有(uid 0),
|
||||||
|
# 而应用以 jiang13(uid 1000)运行,需在启动时修正 /data 权限后降权。
|
||||||
|
|
||||||
|
DATA_DIR="/data"
|
||||||
|
|
||||||
|
if [ "$(id -u)" = '0' ]; then
|
||||||
|
mkdir -p "$DATA_DIR"
|
||||||
|
chown -R jiang13:jiang13 "$DATA_DIR"
|
||||||
|
exec su-exec jiang13 /app/jiang13 "$@"
|
||||||
|
fi
|
||||||
|
|
||||||
|
exec /app/jiang13 "$@"
|
||||||
105
docs/docker-data.md
Normal file
105
docs/docker-data.md
Normal 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
79
docs/monitor.md
Normal 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
|
||||||
@@ -18,6 +18,16 @@
|
|||||||
|
|
||||||
把原先分篇的「上手 / 功能 / 部署」三帖 **删除**,避免与长文重复。
|
把原先分篇的「上手 / 功能 / 部署」三帖 **删除**,避免与长文重复。
|
||||||
|
|
||||||
|
## 自定义单页(推荐)
|
||||||
|
|
||||||
|
站务帖之外,建议在后台 **单页管理** 发一篇更新日志,方便 Docker / Windows 用户对照版本:
|
||||||
|
|
||||||
|
| 文件 | 标题 | slug | 操作 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| [changelog.md](./changelog.md) | 更新日志 | `changelog` | 发布;页脚展示(可选侧栏导航) |
|
||||||
|
|
||||||
|
访问路径:`/page/changelog`。
|
||||||
|
|
||||||
## 可选短文
|
## 可选短文
|
||||||
|
|
||||||
若站务区希望不止一篇,见 [optional.md](./optional.md):
|
若站务区希望不止一篇,见 [optional.md](./optional.md):
|
||||||
|
|||||||
193
docs/site-posts/changelog.md
Normal file
193
docs/site-posts/changelog.md
Normal file
@@ -0,0 +1,193 @@
|
|||||||
|
# 更新日志
|
||||||
|
|
||||||
|
> 建议标题:更新日志
|
||||||
|
> 建议 slug:`changelog`
|
||||||
|
> 建议路径:`/page/changelog`
|
||||||
|
> 建议操作:后台「单页管理」新建并发布;勾选「页脚展示」(可选「侧栏导航」)
|
||||||
|
> 复制正文时:从下方第一个 `---` **之后**开始粘贴(Markdown 模式)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Docker 镜像、Windows exe、Linux 单文件 **共用同一版本号**。有新版本时,以本页为准。
|
||||||
|
|
||||||
|
**当前版本:1.1.8**(2026-09-02)
|
||||||
|
|
||||||
|
## 去哪看新版本
|
||||||
|
|
||||||
|
| 渠道 | 看什么 | 地址 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 本页 | 版本号、变更说明、升级注意 | 本站 `/page/changelog` |
|
||||||
|
| Docker | 镜像标签(`latest` 与 `1.1.x`) | [Docker Hub · Tags](https://hub.docker.com/r/hangzhang714128/jiang13-forum/tags) |
|
||||||
|
| Windows / Linux / macOS | 预编译单文件(与 Docker 同版本) | [Gitea Releases](https://git.iioio.com/freefire/jiang13-forum/releases) |
|
||||||
|
| 源码 | 提交记录与自行编译 | [Gitea 仓库](https://git.iioio.com/freefire/jiang13-forum) |
|
||||||
|
|
||||||
|
**1.1.8 直接下载:**
|
||||||
|
|
||||||
|
- Windows x64:[jiang13_v1.1.8_windows-amd64.exe](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.8/jiang13_v1.1.8_windows-amd64.exe)
|
||||||
|
- Linux x64:[jiang13_v1.1.8_linux-amd64](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.8/jiang13_v1.1.8_linux-amd64)
|
||||||
|
- macOS arm64:[jiang13_v1.1.8_darwin-arm64](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.8/jiang13_v1.1.8_darwin-arm64)
|
||||||
|
|
||||||
|
拉取指定版本镜像:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker pull hangzhang714128/jiang13-forum:1.1.8
|
||||||
|
# 或始终跟随最新
|
||||||
|
docker pull hangzhang714128/jiang13-forum:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
Windows:停掉正在跑的进程或服务,用新下载的 exe 覆盖原文件(可改名为 `jiang13.exe`),**不要动**旁边的 `data/` 与 `app.ini`,再启动即可。
|
||||||
|
|
||||||
|
Linux:赋予执行权限后放到原目录覆盖,同样保留 `data/` 与 `app.ini`。
|
||||||
|
|
||||||
|
## 升级注意
|
||||||
|
|
||||||
|
- 一般只需换镜像或换 exe,数据目录向后兼容。
|
||||||
|
- Docker 请继续挂载原来的 `/data` 卷,切勿新建空目录当「升级」。
|
||||||
|
- 升级后若页面样式异常,强制刷新浏览器(Ctrl+F5)。程序也会在前端资源失效时自动硬刷新。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📦 v1.1.8 · 2026-09-02
|
||||||
|
|
||||||
|
表情选择与评论富文本展示完善,私信表情不再发成图片附件。
|
||||||
|
|
||||||
|
**新增 / 调整**
|
||||||
|
|
||||||
|
- 表情选择器在评论富文本中可直接插入,与文章编辑器一致
|
||||||
|
- 私信页支持表情选择器,点击表情直接插入文本框
|
||||||
|
|
||||||
|
**修复**
|
||||||
|
|
||||||
|
- 私信中插入的表情改为文本内容发送,不再作为图片附件
|
||||||
|
- 消息未读数在多端间同步更及时
|
||||||
|
- 帖子详情快照逻辑修复,避免打开旧缓存页
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📦 v1.1.7 · 2026-09-02
|
||||||
|
|
||||||
|
私信与开源展柜体验升级,待审通知的审核态更及时。
|
||||||
|
|
||||||
|
**新增 / 调整**
|
||||||
|
|
||||||
|
- 私信改为飞书风布局:缩略图表情/图片、按会话草稿、用户搜索发起会话
|
||||||
|
- 主页「发私信」直达消息页对应会话
|
||||||
|
- 开源展柜改为目录式 UI,空列表不再粘滞
|
||||||
|
- 消息页体验重构;待审通知打开后实时回填审核态
|
||||||
|
|
||||||
|
**修复**
|
||||||
|
|
||||||
|
- 帖子详情右栏默认头像改为深绿底白字,与列表默认头像配色一致
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📦 v1.1.6 · 2026-09-01
|
||||||
|
|
||||||
|
编辑器插入体验与首页默认 Feed 排序更合理。
|
||||||
|
|
||||||
|
**新增 / 调整**
|
||||||
|
|
||||||
|
- 链接对话框支持网址、链接文字与站内帖子/单页搜索;站内搜索收进「高级选项」,点选同步链接文字
|
||||||
|
- 文章与评论共用统一图片插入选择器(上传 / 链接 / 已上传)
|
||||||
|
- 链接是否新标签打开交由全站设置,对话框不再单独开关
|
||||||
|
- 首页默认「最新」按发帖与最后评论的较晚时间混排,零回复新帖不再沉底
|
||||||
|
- 单页详情右侧栏与帖子共用目录布局;三栏主滚动区统一细绿色滚动条
|
||||||
|
|
||||||
|
**修复**
|
||||||
|
|
||||||
|
- 帖子目录从正文同步派生,避免预取缓存竞态导致空树
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📦 v1.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 一致,减少闪动
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📦 v1.1.4 · 2026-08-31
|
||||||
|
|
||||||
|
网站监控的地理信息与口径更准确。
|
||||||
|
|
||||||
|
- 补全 IP2Location(IP 地理位置库)中国城市中文名,同名城市按省消歧
|
||||||
|
- 对齐监控概览「双通道」口径文案与诊断抽样说明
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📦 v1.1.3 · 2026-08-31
|
||||||
|
|
||||||
|
管理后台可看站点访问情况。
|
||||||
|
|
||||||
|
- 新增管理端 **网站监控**:浏览量写入独立 `monitor.db`,与主库分开
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📦 v1.1.2 · 2026-08-31
|
||||||
|
|
||||||
|
可选接入官方社区展柜。
|
||||||
|
|
||||||
|
- 可选社区上报,以及官方精选展柜(自建站可出现在官方社区列表中)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📦 v1.1.1 · 2026-08-31
|
||||||
|
|
||||||
|
- 评论管理操作收进「更多」菜单,管理员界面更干净
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📦 v1.1.0 · 2026-08-30
|
||||||
|
|
||||||
|
一批社区功能与界面整理,版本号从 1.0 跨到 1.1。
|
||||||
|
|
||||||
|
**新增**
|
||||||
|
|
||||||
|
- 友链申请、独立友链页;页脚左右区域可分别开关
|
||||||
|
- 自定义单页(后台「单页管理」,如本页)
|
||||||
|
- 投票帖、悬赏帖、抽奖帖
|
||||||
|
- 侧栏签到;右侧栏「最新注册」
|
||||||
|
- 搜索重设计:筛选面板、结果页 chips(筛选标签)
|
||||||
|
- 帖子管理收进右上角菜单;手机端评论输入默认折叠
|
||||||
|
|
||||||
|
**优化**
|
||||||
|
|
||||||
|
- 首页帖子列表密度与标题样式
|
||||||
|
- 开源码桶展示加强,去掉 Feed 顶栏统计
|
||||||
|
- 单页编辑、列表留白与友链申请体验
|
||||||
|
- 开发与发行版共用 `dist/data` 数据目录,避免两套数据打架
|
||||||
|
|
||||||
|
**修复**
|
||||||
|
|
||||||
|
- 手机端搜索入口与底部 Sheet(抽屉面板)
|
||||||
|
- 占位头像对比度;无头像用户不再误用游客灰底
|
||||||
|
- 页面双指缩放锁死,正文原图与灯箱仍可 pinch(捏合)放大
|
||||||
|
- 单页正文排版与帖子详情对齐
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📦 v1.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 文件,再把新版本写到本页最上方。
|
||||||
@@ -17,6 +17,7 @@ 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,19 +30,58 @@ 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)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if sub, err := fs.Sub(staticFS, "static/spa/stickers"); err == nil {
|
||||||
|
fileServer := http.StripPrefix("/stickers", http.FileServer(http.FS(sub)))
|
||||||
|
r.GET("/stickers/*filepath", func(c *gin.Context) {
|
||||||
|
// stickers 不含哈希指纹,设置适中的缓存
|
||||||
|
c.Header("Cache-Control", "public, max-age=86400")
|
||||||
fileServer.ServeHTTP(c.Writer, c.Request)
|
fileServer.ServeHTTP(c.Writer, c.Request)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
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)
|
||||||
@@ -61,7 +101,7 @@ func ServeSPANoIndex(c *gin.Context) {
|
|||||||
|
|
||||||
// IsSPARoute 判断是否应由 SPA 处理
|
// IsSPARoute 判断是否应由 SPA 处理
|
||||||
func IsSPARoute(path string) bool {
|
func IsSPARoute(path string) bool {
|
||||||
if path == "/robots.txt" || path == "/sitemap.xml" {
|
if path == "/health" || path == "/robots.txt" || path == "/sitemap.xml" {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if strings.HasPrefix(path, "/api") ||
|
if strings.HasPrefix(path, "/api") ||
|
||||||
@@ -69,6 +109,7 @@ func IsSPARoute(path string) bool {
|
|||||||
strings.HasPrefix(path, "/uploads") ||
|
strings.HasPrefix(path, "/uploads") ||
|
||||||
strings.HasPrefix(path, "/media") ||
|
strings.HasPrefix(path, "/media") ||
|
||||||
strings.HasPrefix(path, "/assets") ||
|
strings.HasPrefix(path, "/assets") ||
|
||||||
|
strings.HasPrefix(path, "/stickers") ||
|
||||||
strings.HasPrefix(path, "/oauth") ||
|
strings.HasPrefix(path, "/oauth") ||
|
||||||
strings.HasPrefix(path, "/.well-known") {
|
strings.HasPrefix(path, "/.well-known") {
|
||||||
return false
|
return false
|
||||||
|
|||||||
@@ -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 HTML(meta / 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())
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,26 +2,10 @@
|
|||||||
<html lang="zh-CN">
|
<html lang="zh-CN">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||||
<meta name="description" content="拾三一隅,自在交流" />
|
<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; }
|
|
||||||
body { overflow: hidden; font-size: 14px; line-height: 1.5; }
|
|
||||||
.app-shell { height: 100%; max-height: 100dvh; display: flex; flex-direction: column; overflow: hidden; }
|
|
||||||
.app-frame { flex: 1; min-height: 0; height: 100%; max-width: 1400px; width: 100%; margin: 0 auto; display: flex; flex-direction: column; overflow: hidden; }
|
|
||||||
.app-header { height: 56px; flex-shrink: 0; }
|
|
||||||
.site-footer { flex-shrink: 0; }
|
|
||||||
.app-body { flex: 1; display: flex; min-height: 0; width: 100%; overflow: hidden; }
|
|
||||||
.content-workspace { flex: 1; display: flex; min-width: 0; min-height: 0; overflow: hidden; }
|
|
||||||
.sidebar { width: 210px; flex-shrink: 0; }
|
|
||||||
.main-content { flex: 1; min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
|
|
||||||
.aside-panel { width: 280px; flex-shrink: 0; }
|
|
||||||
@media (max-width: 1100px) { .aside-panel { display: none; } }
|
|
||||||
@media (max-width: 768px) { .sidebar { display: none; } }
|
|
||||||
</style>
|
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
var theme = localStorage.getItem('j13-theme') || 'light';
|
var theme = localStorage.getItem('j13-theme') || 'light';
|
||||||
@@ -29,6 +13,33 @@
|
|||||||
document.documentElement.style.colorScheme = theme;
|
document.documentElement.style.colorScheme = theme;
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
|
<script>
|
||||||
|
/* 锁死手机/平板双指与手势缩放;头像裁剪 / 图片灯箱放行 pinch */
|
||||||
|
(function () {
|
||||||
|
function inZoomAllowArea(target) {
|
||||||
|
return !!(
|
||||||
|
target &&
|
||||||
|
target.closest &&
|
||||||
|
target.closest('.avatar-crop-stage, .image-lightbox')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function blockGesture(e) {
|
||||||
|
if (inZoomAllowArea(e.target)) return;
|
||||||
|
if (e.cancelable) e.preventDefault();
|
||||||
|
}
|
||||||
|
function blockMultiTouch(e) {
|
||||||
|
if (e.touches && e.touches.length > 1) {
|
||||||
|
if (inZoomAllowArea(e.target)) return;
|
||||||
|
if (e.cancelable) e.preventDefault();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.addEventListener('gesturestart', blockGesture, { passive: false });
|
||||||
|
document.addEventListener('gesturechange', blockGesture, { passive: false });
|
||||||
|
document.addEventListener('gestureend', blockGesture, { passive: false });
|
||||||
|
document.addEventListener('touchstart', blockMultiTouch, { passive: false });
|
||||||
|
document.addEventListener('touchmove', blockMultiTouch, { passive: false });
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
101
frontend/package-lock.json
generated
101
frontend/package-lock.json
generated
@@ -8,6 +8,9 @@
|
|||||||
"name": "jiang13-forum-web",
|
"name": "jiang13-forum-web",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@dnd-kit/core": "^6.3.1",
|
||||||
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
"@hookform/resolvers": "^5.4.0",
|
"@hookform/resolvers": "^5.4.0",
|
||||||
"@radix-ui/react-alert-dialog": "^1.1.16",
|
"@radix-ui/react-alert-dialog": "^1.1.16",
|
||||||
"@radix-ui/react-dialog": "^1.1.16",
|
"@radix-ui/react-dialog": "^1.1.16",
|
||||||
@@ -15,6 +18,8 @@
|
|||||||
"@radix-ui/react-label": "^2.1.9",
|
"@radix-ui/react-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",
|
||||||
@@ -46,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",
|
||||||
@@ -352,6 +358,59 @@
|
|||||||
"node": ">=6.9.0"
|
"node": ">=6.9.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@dnd-kit/accessibility": {
|
||||||
|
"version": "3.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
|
||||||
|
"integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">=16.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@dnd-kit/core": {
|
||||||
|
"version": "6.3.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
|
||||||
|
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@dnd-kit/accessibility": "^3.1.1",
|
||||||
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
|
"tslib": "^2.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">=16.8.0",
|
||||||
|
"react-dom": ">=16.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@dnd-kit/sortable": {
|
||||||
|
"version": "10.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz",
|
||||||
|
"integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
|
"tslib": "^2.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@dnd-kit/core": "^6.3.0",
|
||||||
|
"react": ">=16.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@dnd-kit/utilities": {
|
||||||
|
"version": "3.2.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
|
||||||
|
"integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": ">=16.8.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@esbuild/aix-ppc64": {
|
"node_modules/@esbuild/aix-ppc64": {
|
||||||
"version": "0.21.5",
|
"version": "0.21.5",
|
||||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
|
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
|
||||||
@@ -1915,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",
|
||||||
@@ -4410,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
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,9 @@
|
|||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@dnd-kit/core": "^6.3.1",
|
||||||
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
"@hookform/resolvers": "^5.4.0",
|
"@hookform/resolvers": "^5.4.0",
|
||||||
"@radix-ui/react-alert-dialog": "^1.1.16",
|
"@radix-ui/react-alert-dialog": "^1.1.16",
|
||||||
"@radix-ui/react-dialog": "^1.1.16",
|
"@radix-ui/react-dialog": "^1.1.16",
|
||||||
@@ -16,6 +19,8 @@
|
|||||||
"@radix-ui/react-label": "^2.1.9",
|
"@radix-ui/react-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",
|
||||||
@@ -47,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",
|
||||||
|
|||||||
60
frontend/scripts/extract-lucide-paths.mjs
Normal file
60
frontend/scripts/extract-lucide-paths.mjs
Normal 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');
|
||||||
168
frontend/scripts/gen-ssr-icons.mjs
Normal file
168
frontend/scripts/gen-ssr-icons.mjs
Normal file
@@ -0,0 +1,168 @@
|
|||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
|
const paths = JSON.parse(fs.readFileSync('tmp-lucide-paths.json', 'utf8'));
|
||||||
|
|
||||||
|
function splitInner(inner) {
|
||||||
|
const tags = [];
|
||||||
|
const re = /<([a-z]+)([^>]*)\/>/g;
|
||||||
|
let m;
|
||||||
|
while ((m = re.exec(inner))) {
|
||||||
|
tags.push(`<${m[1]}${m[2]}/>`);
|
||||||
|
}
|
||||||
|
return tags;
|
||||||
|
}
|
||||||
|
|
||||||
|
function goFunc(name, size, key, className = '') {
|
||||||
|
const tags = splitInner(paths[key]);
|
||||||
|
const lines = tags.map((t) => `\t\t\`${t}\`,`).join('\n');
|
||||||
|
if (className) {
|
||||||
|
return `func ${name}() string {\n\treturn ssrSVGWithClass(${size}, "${className}",\n${lines}\n\t)\n}\n\n`;
|
||||||
|
}
|
||||||
|
return `func ${name}() string {\n\treturn ssrSVG(${size},\n${lines}\n\t)\n}\n\n`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const boardKeys = [
|
||||||
|
'code-2', 'coffee', 'help-circle', 'message-square', 'lightbulb', 'book-open',
|
||||||
|
'gamepad-2', 'palette', 'music', 'camera', 'heart', 'zap', 'globe', 'users',
|
||||||
|
'briefcase', 'graduation-cap', 'shopping-bag', 'map-pin', 'megaphone', 'flame',
|
||||||
|
'star', 'folder', 'wrench', 'cpu',
|
||||||
|
];
|
||||||
|
const defaults = [
|
||||||
|
'code-2', 'coffee', 'help-circle', 'message-square',
|
||||||
|
'lightbulb', 'book-open', 'gamepad-2', 'palette',
|
||||||
|
];
|
||||||
|
|
||||||
|
let out = `package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
\t"strconv"
|
||||||
|
\t"strings"
|
||||||
|
\t"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 内联 SVG:path 对齐 lucide-react@1.18(由 scripts/extract-lucide-paths.mjs 抽取)
|
||||||
|
|
||||||
|
func ssrSVG(size int, paths ...string) string {
|
||||||
|
\treturn ssrSVGWithClass(size, "", paths...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ssrSVGWithClass(size int, className string, paths ...string) string {
|
||||||
|
\tvar b strings.Builder
|
||||||
|
\tb.WriteString(\`<svg xmlns="http://www.w3.org/2000/svg" width="\`)
|
||||||
|
\tb.WriteString(strconv.Itoa(size))
|
||||||
|
\tb.WriteString(\`" height="\`)
|
||||||
|
\tb.WriteString(strconv.Itoa(size))
|
||||||
|
\tb.WriteString(\`" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"\`)
|
||||||
|
\tif className != "" {
|
||||||
|
\t\tb.WriteString(\` class="\`)
|
||||||
|
\t\tb.WriteString(className)
|
||||||
|
\t\tb.WriteString(\`"\`)
|
||||||
|
\t}
|
||||||
|
\tb.WriteString(\` aria-hidden="true">\`)
|
||||||
|
\tfor _, p := range paths {
|
||||||
|
\t\tb.WriteString(p)
|
||||||
|
\t}
|
||||||
|
\tb.WriteString(\`</svg>\`)
|
||||||
|
\treturn b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
`;
|
||||||
|
|
||||||
|
out += goFunc('ssrIconSearch', 16, 'search', 'header-search-icon');
|
||||||
|
out += goFunc('ssrIconSliders', 15, 'sliders-horizontal');
|
||||||
|
out += goFunc('ssrIconPlus', 16, 'plus');
|
||||||
|
out += goFunc('ssrIconMoon', 18, 'moon');
|
||||||
|
out += goFunc('ssrIconSun', 18, 'sun');
|
||||||
|
out += goFunc('ssrIconMail', 18, 'mail');
|
||||||
|
out += goFunc('ssrIconHome', 18, 'house');
|
||||||
|
out += goFunc('ssrIconStar', 18, 'star');
|
||||||
|
out += goFunc('ssrIconFolderGit', 18, 'folder-git-2');
|
||||||
|
out += goFunc('ssrIconLink2', 18, 'link-2');
|
||||||
|
out += goFunc('ssrIconEarth', 18, 'earth');
|
||||||
|
out += goFunc('ssrIconFileText', 18, 'file-text');
|
||||||
|
out += goFunc('ssrIconLayoutDashboard', 18, 'layout-dashboard');
|
||||||
|
out += goFunc('ssrIconMessageCircle', 16, 'message-circle');
|
||||||
|
out += goFunc('ssrIconClock', 16, 'clock');
|
||||||
|
out += goFunc('ssrIconBadgeCheck', 16, 'badge-check');
|
||||||
|
out += goFunc('ssrIconTags', 16, 'tags');
|
||||||
|
out += goFunc('ssrIconUserPlus', 16, 'user-plus');
|
||||||
|
out += goFunc('ssrIconCalendarCheck', 18, 'calendar-check');
|
||||||
|
out += goFunc('ssrIconCheck', 18, 'check');
|
||||||
|
out += goFunc('ssrIconGift', 15, 'gift');
|
||||||
|
out += goFunc('ssrIconPanelRight', 18, 'panel-right');
|
||||||
|
|
||||||
|
out += '// 板块图标 path(key 对齐 BOARD_ICON_OPTIONS / AllowedBoardIcons)\nvar ssrBoardIconInner = map[string]string{\n';
|
||||||
|
for (const k of boardKeys) {
|
||||||
|
out += `\t"${k}": \`${paths[k]}\`,\n`;
|
||||||
|
}
|
||||||
|
out += '}\n\n';
|
||||||
|
|
||||||
|
out += '// 与前端 DEFAULT_ICONS 顺序一致(按 themeIndex 回退)\nvar ssrBoardDefaultIcons = []string{\n';
|
||||||
|
for (const k of defaults) {
|
||||||
|
out += `\t"${k}",\n`;
|
||||||
|
}
|
||||||
|
out += '}\n\n';
|
||||||
|
|
||||||
|
out += `// ssrBoardIconSVG 输出板块 Lucide 图标;class 打在 svg 上(与 React BoardIconDisplay 一致)
|
||||||
|
func ssrBoardIconSVG(icon string, themeIndex int, className string) string {
|
||||||
|
\tkey := strings.TrimSpace(strings.ToLower(icon))
|
||||||
|
\tinner, ok := ssrBoardIconInner[key]
|
||||||
|
\tif !ok || inner == "" {
|
||||||
|
\t\tif themeIndex < 0 {
|
||||||
|
\t\t\tthemeIndex = 0
|
||||||
|
\t\t}
|
||||||
|
\t\tkey = ssrBoardDefaultIcons[themeIndex%len(ssrBoardDefaultIcons)]
|
||||||
|
\t\tinner = ssrBoardIconInner[key]
|
||||||
|
\t}
|
||||||
|
\treturn ssrSVGWithClass(18, className, inner)
|
||||||
|
}
|
||||||
|
|
||||||
|
// formatSSRRelativeTime 与前端 formatTime 同规则
|
||||||
|
func formatSSRRelativeTime(t time.Time) string {
|
||||||
|
\tif t.IsZero() {
|
||||||
|
\t\treturn ""
|
||||||
|
\t}
|
||||||
|
\tnow := time.Now()
|
||||||
|
\tdiffSec := now.Sub(t).Seconds()
|
||||||
|
\tif diffSec < 0 {
|
||||||
|
\t\tdiffSec = 0
|
||||||
|
\t}
|
||||||
|
\tif diffSec < 60 {
|
||||||
|
\t\treturn "刚刚"
|
||||||
|
\t}
|
||||||
|
\tif diffSec < 3600 {
|
||||||
|
\t\treturn strconv.Itoa(int(diffSec/60)) + "分钟前"
|
||||||
|
\t}
|
||||||
|
\tif diffSec < 86400 {
|
||||||
|
\t\treturn strconv.Itoa(int(diffSec/3600)) + "小时前"
|
||||||
|
\t}
|
||||||
|
\tdiffDay := int(diffSec / 86400)
|
||||||
|
\tif diffDay < 30 {
|
||||||
|
\t\treturn strconv.Itoa(diffDay) + "天前"
|
||||||
|
\t}
|
||||||
|
\tif t.Year() == now.Year() {
|
||||||
|
\t\treturn strconv.Itoa(int(t.Month())) + "月" + strconv.Itoa(t.Day()) + "日"
|
||||||
|
\t}
|
||||||
|
\treturn strconv.Itoa(t.Year()) + "年" + strconv.Itoa(int(t.Month())) + "月" + strconv.Itoa(t.Day()) + "日"
|
||||||
|
}
|
||||||
|
|
||||||
|
// formatSSRShortDateTime 与前端 formatShortDateTime 同规则(MM-DD HH:mm)
|
||||||
|
func formatSSRShortDateTime(t time.Time) string {
|
||||||
|
\tif t.IsZero() {
|
||||||
|
\t\treturn ""
|
||||||
|
\t}
|
||||||
|
\tlocal := t.Local()
|
||||||
|
\tpad := func(n int) string {
|
||||||
|
\t\tif n < 10 {
|
||||||
|
\t\t\treturn "0" + strconv.Itoa(n)
|
||||||
|
\t\t}
|
||||||
|
\t\treturn strconv.Itoa(n)
|
||||||
|
\t}
|
||||||
|
\treturn pad(int(local.Month())) + "-" + pad(local.Day()) + " " + pad(local.Hour()) + ":" + pad(local.Minute())
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
const outPath = path.join('..', 'handler', 'ssr_icons.go');
|
||||||
|
fs.writeFileSync(outPath, out);
|
||||||
|
console.log('wrote', outPath, Object.keys(paths).length, 'icons');
|
||||||
@@ -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'));
|
||||||
@@ -31,6 +32,8 @@ const UserProfilePage = lazyWithRetry(() => import('./pages/UserProfilePage'));
|
|||||||
const FavoritesPage = lazyWithRetry(() => import('./pages/FavoritesPage'));
|
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 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'));
|
||||||
@@ -38,7 +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 AdminSitePageEditPage = lazyWithRetry(() => import('./pages/admin/AdminSitePageEditPage'));
|
||||||
|
const AdminLinksPage = lazyWithRetry(() => import('./pages/admin/AdminLinksPage'));
|
||||||
|
const SitePageView = lazyWithRetry(() => import('./pages/SitePageView'));
|
||||||
const AdminSettingsPage = lazyWithRetry(() => import('./pages/admin/AdminSettingsPage'));
|
const 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(
|
||||||
@@ -52,17 +61,24 @@ const router = createBrowserRouter(
|
|||||||
<Route index element={<Navigate to="/admin/dashboard" replace />} />
|
<Route index element={<Navigate to="/admin/dashboard" replace />} />
|
||||||
<Route path="dashboard" element={<Suspense fallback={<PageLoader />}><AdminDashboardPage /></Suspense>} />
|
<Route path="dashboard" element={<Suspense fallback={<PageLoader />}><AdminDashboardPage /></Suspense>} />
|
||||||
<Route path="boards" element={<Suspense fallback={<PageLoader />}><BoardsManagePage /></Suspense>} />
|
<Route path="boards" element={<Suspense fallback={<PageLoader />}><BoardsManagePage /></Suspense>} />
|
||||||
|
<Route path="pages/new" element={<Suspense fallback={<PageLoader />}><AdminSitePageEditPage /></Suspense>} />
|
||||||
|
<Route path="pages/:id/edit" element={<Suspense fallback={<PageLoader />}><AdminSitePageEditPage /></Suspense>} />
|
||||||
|
<Route path="pages" element={<Suspense fallback={<PageLoader />}><AdminPagesPage /></Suspense>} />
|
||||||
|
<Route path="links" element={<Suspense fallback={<PageLoader />}><AdminLinksPage /></Suspense>} />
|
||||||
|
<Route path="community" element={<Suspense fallback={<PageLoader />}><AdminCommunityPage /></Suspense>} />
|
||||||
<Route path="posts" element={<Suspense fallback={<PageLoader />}><AdminPostsPage /></Suspense>} />
|
<Route path="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>
|
||||||
<Route element={<MainLayout />}>
|
<Route element={<MainLayout />}>
|
||||||
<Route path="/" element={<HomePage />} />
|
<Route path="/" element={<HomePage />} />
|
||||||
|
<Route path="/board/:id" element={<HomePage />} />
|
||||||
{/* :id 可为 123 或 123.html(伪静态后缀由后台配置) */}
|
{/* :id 可为 123 或 123.html(伪静态后缀由后台配置) */}
|
||||||
<Route path="/post/:id" element={<PostDetailPage />} />
|
<Route path="/post/:id" element={<PostDetailPage />} />
|
||||||
<Route path="/compose" element={<ComposePage />} />
|
<Route path="/compose" element={<ComposePage />} />
|
||||||
@@ -71,8 +87,11 @@ const router = createBrowserRouter(
|
|||||||
<Route path="/user/:id" element={<UserProfilePage />} />
|
<Route path="/user/:id" element={<UserProfilePage />} />
|
||||||
<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="/showcase" element={<Suspense fallback={null}><ShowcasePage /></Suspense>} />
|
||||||
<Route path="/messages" element={<MessagesPage />} />
|
<Route path="/messages" element={<MessagesPage />} />
|
||||||
<Route path="*" element={<Suspense fallback={<PageLoader />}><NotFoundPage /></Suspense>} />
|
<Route path="/page/:slug" element={<Suspense fallback={null}><SitePageView /></Suspense>} />
|
||||||
|
<Route path="*" element={<Suspense fallback={null}><NotFoundPage /></Suspense>} />
|
||||||
</Route>
|
</Route>
|
||||||
<Route path="*" element={<Suspense fallback={<PageLoader fullScreen />}><NotFoundPage standalone /></Suspense>} />
|
<Route path="*" element={<Suspense fallback={<PageLoader fullScreen />}><NotFoundPage standalone /></Suspense>} />
|
||||||
</Route>,
|
</Route>,
|
||||||
@@ -85,6 +104,7 @@ export default function App() {
|
|||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<ErrorBoundary>
|
<ErrorBoundary>
|
||||||
<RouterProvider router={router} />
|
<RouterProvider router={router} />
|
||||||
|
<TopProgressBar />
|
||||||
<PullToRefresh />
|
<PullToRefresh />
|
||||||
<Toaster />
|
<Toaster />
|
||||||
</ErrorBoundary>
|
</ErrorBoundary>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { User, UserPublic, UserActivityStats, Board, PostItem, Comment, RecentComment, ForumStats, TagCount, AdminDashboard, AdminSettings, ForumLimits, ForumLimitsPublic, PostDetailResponse, PostRevision, CommentRevision, MailConfig, OIDCConfig, OAuthClient, OAuthClientInput, GiteaProject, GiteaSyncConfig, StorageConfig, MediaListResult, SiteBranding, RegisterConfig, PrivateMessage, MessageConversation, PostReport, ReportReason, ReportStatus, BadgeDef, PointLedger, CheckInStatus, LotteryStatus } from './types';
|
import type { User, UserPublic, UserActivityStats, Board, PostItem, Comment, RecentComment, RecentUser, ForumStats, TagCount, AdminDashboard, AdminSettings, ForumLimits, ForumLimitsPublic, PostDetailResponse, PostRevision, CommentRevision, MailConfig, OIDCConfig, OAuthClient, OAuthClientInput, GiteaProject, GiteaSyncConfig, StorageConfig, MediaListResult, SiteBranding, RegisterConfig, PrivateMessage, MessageConversation, PostReport, ReportReason, ReportStatus, BadgeDef, PointLedger, CheckInStatus, LotteryStatus, SitePage, SitePageSummary, PollView, PostLotteryView, FriendLinkApply, CommunityConfig, CommunityInstance, CommunityShowcaseItem, MonitorConfig, MonitorOverview, MonitorGeoResult, MonitorStatItem, MonitorRealtime, MonitorLogItem } from './types';
|
||||||
|
|
||||||
const BASE = '';
|
const BASE = '';
|
||||||
|
|
||||||
@@ -25,12 +25,36 @@ 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'),
|
||||||
|
page: (slug: string) => request<{ page: SitePage }>(`/api/pages/${encodeURIComponent(slug)}`),
|
||||||
boards: () => request<{ boards: Board[] }>('/api/boards'),
|
boards: () => request<{ boards: Board[] }>('/api/boards'),
|
||||||
projects: (params?: { page?: number; limit?: number }) => {
|
projects: (params?: { page?: number; limit?: number; q?: 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));
|
||||||
if (params?.limit) q.set('limit', String(params.limit));
|
if (params?.limit) q.set('limit', String(params.limit));
|
||||||
|
if (params?.q?.trim()) q.set('q', params.q.trim());
|
||||||
const qs = q.toString();
|
const qs = q.toString();
|
||||||
return request<{ projects: GiteaProject[]; total: number; page: number; total_pages: number }>(
|
return request<{ projects: GiteaProject[]; total: number; page: number; total_pages: number }>(
|
||||||
`/api/projects${qs ? `?${qs}` : ''}`,
|
`/api/projects${qs ? `?${qs}` : ''}`,
|
||||||
@@ -40,7 +64,6 @@ export const api = {
|
|||||||
const q = new URLSearchParams(params as Record<string, string>).toString();
|
const q = new URLSearchParams(params as Record<string, string>).toString();
|
||||||
return request<{ posts: PostItem[]; total: number; page: number; has_more: boolean }>(`/api/posts?${q}`);
|
return request<{ posts: PostItem[]; total: number; page: number; has_more: boolean }>(`/api/posts?${q}`);
|
||||||
},
|
},
|
||||||
hotPosts: () => request<{ posts: PostItem[] }>('/api/posts/hot'),
|
|
||||||
tags: (limit = 40) => request<{ tags: TagCount[] }>(`/api/tags?limit=${limit}`),
|
tags: (limit = 40) => request<{ tags: TagCount[] }>(`/api/tags?limit=${limit}`),
|
||||||
post: (id: number, opts?: { skipView?: boolean }) => {
|
post: (id: number, opts?: { skipView?: boolean }) => {
|
||||||
const q = opts?.skipView ? '?skip_view=1' : '';
|
const q = opts?.skipView ? '?skip_view=1' : '';
|
||||||
@@ -51,6 +74,7 @@ export const api = {
|
|||||||
return request<{ comments: Comment[]; total: number }>(`/api/posts/${id}/comments${q}`);
|
return request<{ comments: Comment[]; total: number }>(`/api/posts/${id}/comments${q}`);
|
||||||
},
|
},
|
||||||
recentComments: () => request<{ comments: RecentComment[] }>('/api/comments/recent'),
|
recentComments: () => request<{ comments: RecentComment[] }>('/api/comments/recent'),
|
||||||
|
recentUsers: () => request<{ users: RecentUser[] }>('/api/users/recent'),
|
||||||
favorites: () => request<{ favorites: unknown[]; total: number }>('/api/favorites'),
|
favorites: () => request<{ favorites: unknown[]; total: number }>('/api/favorites'),
|
||||||
createBoard: (body: { name: string; description: string; sort_order: number; icon?: string; color_index?: number }) =>
|
createBoard: (body: { name: string; description: string; sort_order: number; icon?: string; color_index?: number }) =>
|
||||||
request<{ board: Board }>('/api/admin/boards', { method: 'POST', body: JSON.stringify(body) }),
|
request<{ board: Board }>('/api/admin/boards', { method: 'POST', body: JSON.stringify(body) }),
|
||||||
@@ -60,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));
|
||||||
@@ -285,6 +362,7 @@ export const api = {
|
|||||||
check_in: CheckInStatus;
|
check_in: CheckInStatus;
|
||||||
lottery: LotteryStatus;
|
lottery: LotteryStatus;
|
||||||
}>(`/api/me/points?page=${page}`),
|
}>(`/api/me/points?page=${page}`),
|
||||||
|
checkInStatus: () => request<{ check_in: CheckInStatus }>('/api/me/check-in'),
|
||||||
checkIn: () =>
|
checkIn: () =>
|
||||||
request<{ message: string; check_in: CheckInStatus; points: number }>('/api/me/check-in', { method: 'POST' }),
|
request<{ message: string; check_in: CheckInStatus; points: number }>('/api/me/check-in', { method: 'POST' }),
|
||||||
lotteryStatus: () => request<{ lottery: LotteryStatus }>('/api/me/lottery'),
|
lotteryStatus: () => request<{ lottery: LotteryStatus }>('/api/me/lottery'),
|
||||||
@@ -341,13 +419,27 @@ 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: {} });
|
||||||
},
|
},
|
||||||
createPost: (data: { board_id: string; title: string; content: string; tags?: string; post_type?: string }) => {
|
/** 当前用户历史上传的帖子图片 */
|
||||||
|
myPostImages: (params?: { page?: number; size?: number }) => {
|
||||||
|
const q = new URLSearchParams();
|
||||||
|
if (params?.page) q.set('page', String(params.page));
|
||||||
|
if (params?.size) q.set('size', String(params.size));
|
||||||
|
const qs = q.toString();
|
||||||
|
return request<MediaListResult>(`/api/uploads/images${qs ? `?${qs}` : ''}`);
|
||||||
|
},
|
||||||
|
createPost: (data: {
|
||||||
|
board_id: string; title: string; content: string; tags?: string; post_type?: string;
|
||||||
|
poll_options?: string; bounty_points?: number; lottery_winner_count?: number;
|
||||||
|
}) => {
|
||||||
const fd = new FormData();
|
const fd = new FormData();
|
||||||
fd.append('board_id', data.board_id);
|
fd.append('board_id', data.board_id);
|
||||||
fd.append('title', data.title);
|
fd.append('title', data.title);
|
||||||
fd.append('content', data.content);
|
fd.append('content', data.content);
|
||||||
fd.append('tags', data.tags || '');
|
fd.append('tags', data.tags || '');
|
||||||
fd.append('post_type', data.post_type || 'normal');
|
fd.append('post_type', data.post_type || 'normal');
|
||||||
|
if (data.poll_options) fd.append('poll_options', data.poll_options);
|
||||||
|
if (data.bounty_points != null) fd.append('bounty_points', String(data.bounty_points));
|
||||||
|
if (data.lottery_winner_count != null) fd.append('lottery_winner_count', String(data.lottery_winner_count));
|
||||||
return request<{ post_id: number; message?: string; status?: string }>('/api/posts', { method: 'POST', body: fd, headers: {} });
|
return request<{ post_id: number; message?: string; status?: string }>('/api/posts', { method: 'POST', body: fd, headers: {} });
|
||||||
},
|
},
|
||||||
updatePost: (id: number, data: { title: string; content: string; tags?: string; board_id?: string | number; post_type?: string }) => {
|
updatePost: (id: number, data: { title: string; content: string; tags?: string; board_id?: string | number; post_type?: string }) => {
|
||||||
@@ -372,6 +464,76 @@ export const api = {
|
|||||||
headers: {},
|
headers: {},
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
pollVote: (id: number, optionIds: number[]) =>
|
||||||
|
request<{ message: string; poll: PollView }>(`/api/posts/${id}/poll/vote`, {
|
||||||
|
method: 'POST', body: JSON.stringify({ option_ids: optionIds }),
|
||||||
|
}),
|
||||||
|
pollClose: (id: number) =>
|
||||||
|
request<{ message: string; poll: PollView }>(`/api/posts/${id}/poll/close`, { method: 'POST', body: '{}' }),
|
||||||
|
bountyAward: (id: number, commentId: number) => {
|
||||||
|
const fd = new FormData();
|
||||||
|
fd.append('comment_id', String(commentId));
|
||||||
|
return request<{ message: string }>(`/api/posts/${id}/bounty/award`, { method: 'POST', body: fd, headers: {} });
|
||||||
|
},
|
||||||
|
bountyRefund: (id: number) =>
|
||||||
|
request<{ message: string }>(`/api/posts/${id}/bounty/refund`, { method: 'POST', body: '{}' }),
|
||||||
|
postLotteryDraw: (id: number) =>
|
||||||
|
request<{ message: string; lottery: PostLotteryView }>(`/api/posts/${id}/lottery/draw`, { method: 'POST', body: '{}' }),
|
||||||
|
adminPages: () => request<{ pages: SitePage[] }>('/api/admin/pages'),
|
||||||
|
adminPage: (id: number) => request<{ page: SitePage }>(`/api/admin/pages/${id}`),
|
||||||
|
adminCreatePage: (data: Partial<SitePage>) =>
|
||||||
|
request<{ message: string; page: SitePage }>('/api/admin/pages', { method: 'POST', body: JSON.stringify(data) }),
|
||||||
|
adminUpdatePage: (id: number, data: Partial<SitePage>) =>
|
||||||
|
request<{ message: string }>(`/api/admin/pages/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
|
||||||
|
adminSetPagePublished: (id: number, published: boolean) =>
|
||||||
|
request<{ message: string; published: boolean }>(`/api/admin/pages/${id}/published`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({ published }),
|
||||||
|
}),
|
||||||
|
adminDeletePage: (id: number) =>
|
||||||
|
request<{ message: string }>(`/api/admin/pages/${id}`, { method: 'DELETE' }),
|
||||||
|
adminFriendLinkApplies: (params?: { page?: number; size?: number; status?: string }) => {
|
||||||
|
const q = new URLSearchParams();
|
||||||
|
if (params?.page) q.set('page', String(params.page));
|
||||||
|
if (params?.size) q.set('size', String(params.size));
|
||||||
|
if (params?.status) q.set('status', params.status);
|
||||||
|
const qs = q.toString();
|
||||||
|
return request<{
|
||||||
|
applies: FriendLinkApply[];
|
||||||
|
total: number;
|
||||||
|
page: number;
|
||||||
|
pending_count: number;
|
||||||
|
reciprocal_check_enabled?: boolean;
|
||||||
|
}>(`/api/admin/friend-link-applies${qs ? `?${qs}` : ''}`);
|
||||||
|
},
|
||||||
|
adminUpdateFriendLinkSettings: (body: {
|
||||||
|
reciprocal_check_enabled?: boolean;
|
||||||
|
nav_show_friend_links?: boolean;
|
||||||
|
footer_show_friend_links?: boolean;
|
||||||
|
aside_show_friend_links?: boolean;
|
||||||
|
}) =>
|
||||||
|
request<{
|
||||||
|
message: string;
|
||||||
|
reciprocal_check_enabled: boolean;
|
||||||
|
nav_show_friend_links: boolean;
|
||||||
|
footer_show_friend_links: boolean;
|
||||||
|
aside_show_friend_links: boolean;
|
||||||
|
}>('/api/admin/friend-link-settings', {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
}),
|
||||||
|
adminApproveFriendLinkApply: (id: number) =>
|
||||||
|
request<{ message: string; apply: FriendLinkApply }>(`/api/admin/friend-link-applies/${id}/approve`, {
|
||||||
|
method: 'POST', body: '{}',
|
||||||
|
}),
|
||||||
|
adminRejectFriendLinkApply: (id: number, body?: { note?: string }) =>
|
||||||
|
request<{ message: string; apply: FriendLinkApply }>(`/api/admin/friend-link-applies/${id}/reject`, {
|
||||||
|
method: 'POST', body: JSON.stringify(body ?? {}),
|
||||||
|
}),
|
||||||
|
adminRecheckFriendLinkApply: (id: number) =>
|
||||||
|
request<{ message: string; apply: FriendLinkApply }>(`/api/admin/friend-link-applies/${id}/recheck`, {
|
||||||
|
method: 'POST',
|
||||||
|
}),
|
||||||
deletePost: (id: number) => request<{ message: string }>(`/api/posts/${id}`, { method: 'DELETE' }),
|
deletePost: (id: number) => request<{ message: string }>(`/api/posts/${id}`, { method: 'DELETE' }),
|
||||||
login: (username: string, password: string) => {
|
login: (username: string, password: string) => {
|
||||||
const fd = new FormData();
|
const fd = new FormData();
|
||||||
@@ -425,6 +587,37 @@ export const api = {
|
|||||||
like: (id: number) => request<{ liked: boolean; like_count: number }>(`/api/posts/${id}/like`, { method: 'POST' }),
|
like: (id: number) => request<{ liked: boolean; like_count: number }>(`/api/posts/${id}/like`, { method: 'POST' }),
|
||||||
likeComment: (id: number) => request<{ liked: boolean; like_count: number }>(`/api/comments/${id}/like`, { method: 'POST' }),
|
likeComment: (id: number) => request<{ liked: boolean; like_count: number }>(`/api/comments/${id}/like`, { method: 'POST' }),
|
||||||
favorite: (id: number) => request<{ favorited: boolean }>(`/api/posts/${id}/favorite`, { method: 'POST' }),
|
favorite: (id: number) => request<{ favorited: boolean }>(`/api/posts/${id}/favorite`, { method: 'POST' }),
|
||||||
|
applyFriendLink: (body: {
|
||||||
|
name: string;
|
||||||
|
url: string;
|
||||||
|
logo: string;
|
||||||
|
link_on_homepage: boolean;
|
||||||
|
reciprocal_page_url?: string;
|
||||||
|
}) =>
|
||||||
|
request<{ message: string; apply: FriendLinkApply; warning?: string }>('/api/friend-links/apply', {
|
||||||
|
method: 'POST', body: JSON.stringify(body),
|
||||||
|
}),
|
||||||
|
uploadFriendLinkLogo: (file: File) => {
|
||||||
|
const fd = new FormData();
|
||||||
|
fd.append('logo', file);
|
||||||
|
return request<{ message: string; url: string }>('/api/friend-links/logo', {
|
||||||
|
method: 'POST', body: fd, headers: {},
|
||||||
|
});
|
||||||
|
},
|
||||||
|
myFriendLinkApplies: () =>
|
||||||
|
request<{ applies: FriendLinkApply[] }>('/api/friend-links/my-applies'),
|
||||||
|
updateFriendLinkApply: (id: number, body: {
|
||||||
|
name: string;
|
||||||
|
url: string;
|
||||||
|
logo: string;
|
||||||
|
link_on_homepage: boolean;
|
||||||
|
reciprocal_page_url?: string;
|
||||||
|
}) =>
|
||||||
|
request<{ message: string; apply: FriendLinkApply; warning?: string }>(`/api/friend-links/applies/${id}`, {
|
||||||
|
method: 'PUT', body: JSON.stringify(body),
|
||||||
|
}),
|
||||||
|
cancelFriendLinkApply: (id: number) =>
|
||||||
|
request<{ message: string }>(`/api/friend-links/applies/${id}`, { method: 'DELETE' }),
|
||||||
reportPost: (id: number, body: { reason: ReportReason; detail?: string }) =>
|
reportPost: (id: number, body: { reason: ReportReason; detail?: string }) =>
|
||||||
request<{ message: string; report: PostReport }>(`/api/posts/${id}/report`, {
|
request<{ message: string; report: PostReport }>(`/api/posts/${id}/report`, {
|
||||||
method: 'POST', body: JSON.stringify(body),
|
method: 'POST', body: JSON.stringify(body),
|
||||||
@@ -471,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),
|
||||||
|
|||||||
@@ -69,6 +69,7 @@ export interface ForumStats {
|
|||||||
users: number;
|
users: number;
|
||||||
posts: number;
|
posts: number;
|
||||||
boards: number;
|
boards: number;
|
||||||
|
comments: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 标签云单项 */
|
/** 标签云单项 */
|
||||||
@@ -84,10 +85,15 @@ export interface PostItem {
|
|||||||
title: string;
|
title: string;
|
||||||
content?: string;
|
content?: string;
|
||||||
tags: string;
|
tags: string;
|
||||||
/** normal=讨论 | question=问答 */
|
/** normal=讨论 | question=问答 | poll=投票 | bounty=悬赏 | lottery=抽奖 */
|
||||||
post_type?: 'normal' | 'question' | string;
|
post_type?: 'normal' | 'question' | 'poll' | 'bounty' | 'lottery' | string;
|
||||||
/** 仅问答帖有意义 */
|
/** 仅问答帖有意义 */
|
||||||
question_resolved?: boolean;
|
question_resolved?: boolean;
|
||||||
|
bounty_points?: number;
|
||||||
|
bounty_status?: 'open' | 'awarded' | 'refunded' | string;
|
||||||
|
bounty_comment_id?: number;
|
||||||
|
lottery_winner_count?: number;
|
||||||
|
lottery_status?: 'open' | 'drawn' | string;
|
||||||
pinned: boolean;
|
pinned: boolean;
|
||||||
/** 板块内置顶(仅板块列表抬升,首页不抬升) */
|
/** 板块内置顶(仅板块列表抬升,首页不抬升) */
|
||||||
board_pinned?: boolean;
|
board_pinned?: boolean;
|
||||||
@@ -100,6 +106,10 @@ export interface PostItem {
|
|||||||
view_count: number;
|
view_count: number;
|
||||||
comment_count: number;
|
comment_count: number;
|
||||||
last_reply_at?: string;
|
last_reply_at?: string;
|
||||||
|
/** 最后回复用户(登录用户);与 last_reply_guest_nick 二选一 */
|
||||||
|
last_reply_user?: User;
|
||||||
|
/** 最后回复游客昵称 */
|
||||||
|
last_reply_guest_nick?: string;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
updated_at?: string;
|
updated_at?: string;
|
||||||
board?: Board;
|
board?: Board;
|
||||||
@@ -131,12 +141,18 @@ export interface PostDetailResponse {
|
|||||||
comment_count: number;
|
comment_count: number;
|
||||||
liked: boolean;
|
liked: boolean;
|
||||||
favorited: boolean;
|
favorited: boolean;
|
||||||
/** 当前用户是否已在本帖发表过评论(含审核中) */
|
|
||||||
has_replied?: boolean;
|
has_replied?: boolean;
|
||||||
can_edit?: boolean;
|
can_edit?: boolean;
|
||||||
edit_block_reason?: string;
|
edit_block_reason?: string;
|
||||||
is_edited?: boolean;
|
is_edited?: boolean;
|
||||||
post_edit_window_hours?: number;
|
post_edit_window_hours?: number;
|
||||||
|
poll?: PollView;
|
||||||
|
lottery?: PostLotteryView;
|
||||||
|
/** 悬赏进行中:当前用户是否可取消悬赏 */
|
||||||
|
bounty_can_refund?: boolean;
|
||||||
|
bounty_refund_block_reason?: string;
|
||||||
|
/** 他人已发布有效回复数 */
|
||||||
|
bounty_eligible_reply_count?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Comment {
|
export interface Comment {
|
||||||
@@ -163,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;
|
||||||
@@ -171,9 +195,40 @@ export interface AdminDashboard {
|
|||||||
pending_posts?: number;
|
pending_posts?: number;
|
||||||
pending_comments?: number;
|
pending_comments?: number;
|
||||||
pending_reports?: number;
|
pending_reports?: number;
|
||||||
|
pending_friend_links?: number;
|
||||||
recent_posts: PostItem[];
|
recent_posts: PostItem[];
|
||||||
|
traffic?: AdminDashboardTraffic;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type AsideWidgetId = 'tag_cloud' | 'recent_comments' | 'recent_users' | 'friend_links' | 'showcase';
|
||||||
|
|
||||||
|
export interface AsideWidget {
|
||||||
|
id: AsideWidgetId;
|
||||||
|
enabled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_ASIDE_WIDGETS: AsideWidget[] = [
|
||||||
|
{ id: 'tag_cloud', enabled: false },
|
||||||
|
{ id: 'recent_comments', enabled: false },
|
||||||
|
{ id: 'recent_users', enabled: false },
|
||||||
|
{ id: 'friend_links', enabled: true },
|
||||||
|
{ id: 'showcase', enabled: false },
|
||||||
|
];
|
||||||
|
|
||||||
|
export type FeedSortId = 'reply' | 'latest' | 'hot';
|
||||||
|
|
||||||
|
export interface FeedSortTab {
|
||||||
|
id: FeedSortId;
|
||||||
|
label: string;
|
||||||
|
enabled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_FEED_SORT_TABS: FeedSortTab[] = [
|
||||||
|
{ id: 'reply', label: '最新', enabled: true },
|
||||||
|
{ id: 'latest', label: '新帖子', enabled: true },
|
||||||
|
{ id: 'hot', label: '推荐帖', enabled: true },
|
||||||
|
];
|
||||||
|
|
||||||
export interface ForumLimits {
|
export interface ForumLimits {
|
||||||
post_edit_window_hours: number;
|
post_edit_window_hours: number;
|
||||||
comment_edit_window_minutes: number;
|
comment_edit_window_minutes: number;
|
||||||
@@ -194,6 +249,28 @@ export interface ForumLimits {
|
|||||||
signature_max: number;
|
signature_max: number;
|
||||||
open_posts_in_new_tab: boolean;
|
open_posts_in_new_tab: boolean;
|
||||||
open_content_links_in_new_tab: boolean;
|
open_content_links_in_new_tab: boolean;
|
||||||
|
/** 右侧栏标签云 */
|
||||||
|
aside_show_tag_cloud: boolean;
|
||||||
|
/** 右侧栏最新评论 */
|
||||||
|
aside_show_recent_comments: boolean;
|
||||||
|
/** 右侧栏友情链接 */
|
||||||
|
aside_show_friend_links: boolean;
|
||||||
|
/** 右侧栏开源展柜 */
|
||||||
|
aside_show_showcase: boolean;
|
||||||
|
/** 右侧栏可选组件顺序与开关 */
|
||||||
|
aside_widgets: AsideWidget[];
|
||||||
|
/** 左侧栏「站点」展示友情链接入口 */
|
||||||
|
nav_show_friend_links: boolean;
|
||||||
|
/** 页脚展示友情链接入口 */
|
||||||
|
footer_show_friend_links: boolean;
|
||||||
|
/** 左侧栏「站点」展示开源展柜入口 */
|
||||||
|
nav_show_showcase: boolean;
|
||||||
|
/** 页脚展示开源展柜入口 */
|
||||||
|
footer_show_showcase: boolean;
|
||||||
|
/** 首页列表样式:title 仅标题 / thumbnail 缩略图 */
|
||||||
|
feed_list_style: 'title' | 'excerpt' | 'thumbnail';
|
||||||
|
/** 首页排序标签:名称、顺序、启停 */
|
||||||
|
feed_sort_tabs: FeedSortTab[];
|
||||||
/** 伪静态(固定链接)开关 */
|
/** 伪静态(固定链接)开关 */
|
||||||
permalink_enabled: boolean;
|
permalink_enabled: boolean;
|
||||||
/** 伪静态后缀,不含点,如 html / htm */
|
/** 伪静态后缀,不含点,如 html / htm */
|
||||||
@@ -214,19 +291,99 @@ export interface ForumLimitsPublic {
|
|||||||
signature_max: number;
|
signature_max: number;
|
||||||
open_posts_in_new_tab: boolean;
|
open_posts_in_new_tab: boolean;
|
||||||
open_content_links_in_new_tab: boolean;
|
open_content_links_in_new_tab: boolean;
|
||||||
|
aside_show_tag_cloud: boolean;
|
||||||
|
aside_show_recent_comments: boolean;
|
||||||
|
aside_show_friend_links: boolean;
|
||||||
|
aside_show_showcase: boolean;
|
||||||
|
aside_widgets: AsideWidget[];
|
||||||
|
nav_show_friend_links: boolean;
|
||||||
|
footer_show_friend_links: boolean;
|
||||||
|
nav_show_showcase: boolean;
|
||||||
|
footer_show_showcase: boolean;
|
||||||
|
feed_list_style: 'title' | 'excerpt' | 'thumbnail';
|
||||||
|
feed_sort_tabs: FeedSortTab[];
|
||||||
permalink_enabled: boolean;
|
permalink_enabled: boolean;
|
||||||
permalink_ext: string;
|
permalink_ext: string;
|
||||||
|
/** 是否上报前台路由 pageview(与后台监控采集开关同步) */
|
||||||
|
monitor_pageview: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface FriendLink {
|
export interface FriendLink {
|
||||||
name: string;
|
name: string;
|
||||||
url: string;
|
url: string;
|
||||||
|
logo?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FriendLinkApply {
|
||||||
|
id: number;
|
||||||
|
user_id: number;
|
||||||
|
name: string;
|
||||||
|
url: string;
|
||||||
|
description?: string;
|
||||||
|
logo?: string;
|
||||||
|
reciprocal_page_url?: string;
|
||||||
|
link_on_homepage?: boolean;
|
||||||
|
reciprocal_verified?: boolean;
|
||||||
|
reciprocal_check_note?: string;
|
||||||
|
reciprocal_checked_at?: string;
|
||||||
|
status: 'pending' | 'approved' | 'rejected';
|
||||||
|
review_note?: string;
|
||||||
|
reviewed_at?: string;
|
||||||
|
created_at: string;
|
||||||
|
user?: User;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SitePageSummary {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
slug: string;
|
||||||
|
show_in_footer?: boolean;
|
||||||
|
show_in_nav?: boolean;
|
||||||
|
sort_order?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SitePage extends SitePageSummary {
|
||||||
|
content: string;
|
||||||
|
published: boolean;
|
||||||
|
created_at?: string;
|
||||||
|
updated_at?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PollOptionView {
|
||||||
|
id: number;
|
||||||
|
text: string;
|
||||||
|
vote_count: number;
|
||||||
|
percent?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PollView {
|
||||||
|
multi: boolean;
|
||||||
|
max_choices: number;
|
||||||
|
closed: boolean;
|
||||||
|
ends_at?: string;
|
||||||
|
options: PollOptionView[];
|
||||||
|
my_option_ids?: number[];
|
||||||
|
total_votes: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PostLotteryWinnerView {
|
||||||
|
user_id: number;
|
||||||
|
username: string;
|
||||||
|
nickname: string;
|
||||||
|
comment_id: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PostLotteryView {
|
||||||
|
winner_count: number;
|
||||||
|
status: string;
|
||||||
|
participant_count: number;
|
||||||
|
winners?: PostLotteryWinnerView[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SiteBranding {
|
export interface SiteBranding {
|
||||||
name: string;
|
name: string;
|
||||||
slogan: string;
|
slogan: string;
|
||||||
/** 站点简介(首页可见 + SEO description) */
|
/** 站点简介(右侧栏顶部 + SEO description) */
|
||||||
description?: string;
|
description?: string;
|
||||||
/** SEO keywords,逗号分隔 */
|
/** SEO keywords,逗号分隔 */
|
||||||
keywords?: string;
|
keywords?: string;
|
||||||
@@ -241,6 +398,8 @@ export interface SiteBranding {
|
|||||||
icp_beian_url?: string;
|
icp_beian_url?: string;
|
||||||
/** 页脚友情链接 */
|
/** 页脚友情链接 */
|
||||||
friend_links?: FriendLink[];
|
friend_links?: FriendLink[];
|
||||||
|
/** 公开站点根 URL(API 动态填充) */
|
||||||
|
site_url?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AdminSettings {
|
export interface AdminSettings {
|
||||||
@@ -255,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;
|
||||||
@@ -349,8 +646,21 @@ export interface GiteaProject {
|
|||||||
full_name: string;
|
full_name: string;
|
||||||
description: string;
|
description: string;
|
||||||
html_url: string;
|
html_url: string;
|
||||||
|
language?: string;
|
||||||
|
stars_count?: number;
|
||||||
|
forks_count?: number;
|
||||||
updated_at_remote?: string | null;
|
updated_at_remote?: string | null;
|
||||||
forum_user_id?: number;
|
forum_user_id?: number;
|
||||||
|
owner?: {
|
||||||
|
id: number;
|
||||||
|
nickname: string;
|
||||||
|
avatar: string;
|
||||||
|
role: 'user' | 'admin';
|
||||||
|
verified?: boolean;
|
||||||
|
exp?: number;
|
||||||
|
level?: number;
|
||||||
|
badges?: UserBadge[];
|
||||||
|
};
|
||||||
synced_at: string;
|
synced_at: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -392,6 +702,14 @@ export interface RecentComment {
|
|||||||
created_at: string;
|
created_at: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 右栏「最新注册」用户 */
|
||||||
|
export interface RecentUser {
|
||||||
|
id: number;
|
||||||
|
nickname: string;
|
||||||
|
avatar: string;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
/** 站内私信 */
|
/** 站内私信 */
|
||||||
export interface PrivateMessage {
|
export interface PrivateMessage {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -399,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;
|
||||||
|
|||||||
@@ -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';
|
||||||
@@ -27,19 +28,23 @@ import {
|
|||||||
cycleMarkdownHeading,
|
cycleMarkdownHeading,
|
||||||
insertMarkdownMembersOnly,
|
insertMarkdownMembersOnly,
|
||||||
insertMarkdownReplyOnly,
|
insertMarkdownReplyOnly,
|
||||||
|
insertMarkdownPointsOnly,
|
||||||
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 {
|
||||||
@@ -63,10 +68,16 @@ interface Props {
|
|||||||
value: string;
|
value: string;
|
||||||
onChange: (v: string) => void;
|
onChange: (v: string) => void;
|
||||||
placeholder?: string;
|
placeholder?: string;
|
||||||
|
/**
|
||||||
|
* 是否启用登录/回复/积分可见区块。
|
||||||
|
* 发帖默认 true;自定义单页等场景应关闭。
|
||||||
|
*/
|
||||||
|
enableContentGates?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
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';
|
||||||
|
|
||||||
@@ -77,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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -161,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) => (
|
||||||
@@ -198,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>
|
||||||
@@ -211,7 +205,7 @@ function renderToolButtons(tools: ToolBtn[]) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEditor(
|
const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEditor(
|
||||||
{ value, onChange, placeholder = '在此撰写正文…' },
|
{ value, onChange, placeholder = '在此撰写正文…', enableContentGates = true },
|
||||||
ref,
|
ref,
|
||||||
) {
|
) {
|
||||||
const isInternalUpdate = useRef(false);
|
const isInternalUpdate = useRef(false);
|
||||||
@@ -222,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);
|
||||||
@@ -230,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: [
|
||||||
@@ -256,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 }) => {
|
||||||
@@ -274,9 +281,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
},
|
},
|
||||||
includeChildren: true,
|
includeChildren: true,
|
||||||
}),
|
}),
|
||||||
MembersOnly,
|
...(enableContentGates ? [MembersOnly, ReplyOnly, PointsOnly] : []),
|
||||||
ReplyOnly,
|
|
||||||
PointsOnly,
|
|
||||||
TabIndent,
|
TabIndent,
|
||||||
],
|
],
|
||||||
content: sanitizeHtml(value) || '',
|
content: sanitizeHtml(value) || '',
|
||||||
@@ -336,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: () => {
|
||||||
@@ -389,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);
|
||||||
@@ -473,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;
|
||||||
@@ -485,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(() => {
|
||||||
@@ -493,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 ? `` : '');
|
||||||
|
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\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;
|
||||||
@@ -567,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]);
|
||||||
|
|
||||||
@@ -579,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]);
|
||||||
|
|
||||||
@@ -592,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\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],
|
||||||
@@ -633,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} />,
|
||||||
@@ -644,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')) {
|
||||||
@@ -698,6 +803,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (enableContentGates) {
|
||||||
tools.push(
|
tools.push(
|
||||||
{
|
{
|
||||||
icon: <LockKeyhole size={15} />,
|
icon: <LockKeyhole size={15} />,
|
||||||
@@ -724,11 +830,13 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
action: wrapPointsOnly,
|
action: wrapPointsOnly,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return tools;
|
return tools;
|
||||||
}, [editor, 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[] = [
|
||||||
{ icon: <strong>H</strong>, title: '标题', hint: 'H2 → H6 循环', action: withMarkdown(cycleMarkdownHeading) },
|
{ icon: <strong>H</strong>, title: '标题', hint: 'H2 → H6 循环', action: withMarkdown(cycleMarkdownHeading) },
|
||||||
{ icon: <Bold size={15} />, title: '加粗', action: withMarkdown((ta, v, ch) => wrapMarkdownSelection(ta, v, '**', '**', '加粗文字', ch)) },
|
{ icon: <Bold size={15} />, title: '加粗', action: withMarkdown((ta, v, ch) => wrapMarkdownSelection(ta, v, '**', '**', '加粗文字', ch)) },
|
||||||
{ icon: <Italic size={15} />, title: '斜体', action: withMarkdown((ta, v, ch) => wrapMarkdownSelection(ta, v, '*', '*', '斜体文字', ch)) },
|
{ icon: <Italic size={15} />, title: '斜体', action: withMarkdown((ta, v, ch) => wrapMarkdownSelection(ta, v, '*', '*', '斜体文字', ch)) },
|
||||||
@@ -741,7 +849,24 @@ 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) {
|
||||||
|
tools.push(
|
||||||
{
|
{
|
||||||
icon: <LockKeyhole size={15} />,
|
icon: <LockKeyhole size={15} />,
|
||||||
title: '登录可见',
|
title: '登录可见',
|
||||||
@@ -756,7 +881,17 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
className: 'article-tool-btn--reply',
|
className: 'article-tool-btn--reply',
|
||||||
action: withMarkdown(insertMarkdownReplyOnly),
|
action: withMarkdown(insertMarkdownReplyOnly),
|
||||||
},
|
},
|
||||||
], [withMarkdown, openLinkDialog, openCodeBlockDialog, openTableDialog, insertMarkdownImage]);
|
{
|
||||||
|
icon: <Coins size={15} />,
|
||||||
|
title: '积分可见',
|
||||||
|
hint: '插入 <points-only> 区块',
|
||||||
|
className: 'article-tool-btn--points',
|
||||||
|
action: withMarkdown(insertMarkdownPointsOnly),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return tools;
|
||||||
|
}, [enableContentGates, 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'
|
||||||
@@ -764,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' ? (
|
||||||
@@ -877,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}
|
||||||
|
|||||||
106
frontend/src/components/AsideCheckInStrip.tsx
Normal file
106
frontend/src/components/AsideCheckInStrip.tsx
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
import { CalendarCheck, Check, Gift, Loader2 } from 'lucide-react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { useCheckIn } from '../hooks/useCheckIn';
|
||||||
|
import { useAuth } from '../hooks/useAuth';
|
||||||
|
import { loginPath } from '../utils/authRedirect';
|
||||||
|
|
||||||
|
/** 右侧栏首块底部:每日签到 */
|
||||||
|
export default function AsideCheckInStrip() {
|
||||||
|
const nav = useNavigate();
|
||||||
|
const { user, loading: authLoading } = useAuth();
|
||||||
|
const { status, loading, busy, doCheckIn } = useCheckIn(!!user && !authLoading);
|
||||||
|
|
||||||
|
// 鉴权未完成且无种子:空白,避免访客签到卡闪一下再消失
|
||||||
|
// 有 SSR boot 时 loading 一开始就是 false
|
||||||
|
if (authLoading) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return (
|
||||||
|
<div className="widget-checkin">
|
||||||
|
<div className="widget-checkin-panel widget-checkin-panel--guest">
|
||||||
|
<div className="widget-checkin-main">
|
||||||
|
<div className="widget-checkin-icon" aria-hidden>
|
||||||
|
<CalendarCheck size={18} strokeWidth={2.25} />
|
||||||
|
</div>
|
||||||
|
<div className="widget-checkin-info">
|
||||||
|
<span className="widget-checkin-title">每日签到</span>
|
||||||
|
<span className="widget-checkin-meta">登录后每日可得 5–15 积分</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="widget-checkin-action"
|
||||||
|
onClick={() => nav(loginPath())}
|
||||||
|
>
|
||||||
|
<Gift size={15} aria-hidden />
|
||||||
|
登录签到
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 登录用户:status 未到齐前不渲染最终态
|
||||||
|
if (loading || !status) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkedIn = !!status.checked_in;
|
||||||
|
const streak = status.streak ?? 0;
|
||||||
|
const todayPoints = status.today_points ?? 5;
|
||||||
|
|
||||||
|
const meta = checkedIn
|
||||||
|
? (streak > 0 ? `连续 ${streak} 天 · 今日已获得 ${todayPoints} 积分` : `今日已获得 ${todayPoints} 积分`)
|
||||||
|
: (streak > 0 ? `连续 ${streak} 天 · 今日可得 ${todayPoints} 积分` : `今日签到可得 ${todayPoints} 积分`);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="widget-checkin">
|
||||||
|
<div
|
||||||
|
className={`widget-checkin-panel${checkedIn ? ' widget-checkin-panel--done' : ''}`}
|
||||||
|
>
|
||||||
|
<div className="widget-checkin-main">
|
||||||
|
<div className="widget-checkin-icon" aria-hidden>
|
||||||
|
{checkedIn ? (
|
||||||
|
<Check size={18} strokeWidth={2.5} />
|
||||||
|
) : (
|
||||||
|
<CalendarCheck size={18} strokeWidth={2.25} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="widget-checkin-info">
|
||||||
|
<span className="widget-checkin-title">
|
||||||
|
{checkedIn ? '今日已签到' : '每日签到'}
|
||||||
|
</span>
|
||||||
|
<span className="widget-checkin-meta">{meta}</span>
|
||||||
|
</div>
|
||||||
|
{!checkedIn && (
|
||||||
|
<span className="widget-checkin-reward" aria-hidden>
|
||||||
|
{todayPoints}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{!checkedIn && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="widget-checkin-action"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={doCheckIn}
|
||||||
|
>
|
||||||
|
{busy ? (
|
||||||
|
<>
|
||||||
|
<Loader2 size={15} className="widget-checkin-action-spinner animate-spin" aria-hidden />
|
||||||
|
签到中…
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Gift size={15} aria-hidden />
|
||||||
|
立即签到
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -30,6 +30,7 @@ export default function CommentBox({ user, replyTo, inline, submitting, submitCo
|
|||||||
const [content, setContent] = useState('');
|
const [content, setContent] = useState('');
|
||||||
const [isPrivate, setIsPrivate] = useState(false);
|
const [isPrivate, setIsPrivate] = useState(false);
|
||||||
const editorRef = useRef<CommentEditorHandle>(null);
|
const editorRef = useRef<CommentEditorHandle>(null);
|
||||||
|
const prevSubmitCountRef = useRef<number>(submitCount);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (inline && replyTo) {
|
if (inline && replyTo) {
|
||||||
@@ -38,6 +39,9 @@ export default function CommentBox({ user, replyTo, inline, submitting, submitCo
|
|||||||
}, [replyTo?.id, inline]);
|
}, [replyTo?.id, inline]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
// 跳过首次挂载,仅在 submitCount 真正变化(评论成功提交)时清空并聚焦
|
||||||
|
if (prevSubmitCountRef.current === submitCount) return;
|
||||||
|
prevSubmitCountRef.current = submitCount;
|
||||||
setContent('');
|
setContent('');
|
||||||
setIsPrivate(false);
|
setIsPrivate(false);
|
||||||
editorRef.current?.focus();
|
editorRef.current?.focus();
|
||||||
|
|||||||
@@ -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) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
const onClick = useCallback(async (e: React.MouseEvent) => {
|
||||||
<div
|
try {
|
||||||
className="floor-body"
|
if (await handleMdCodeBlockUiClick(e.target)) {
|
||||||
onClick={(e) => {
|
e.preventDefault();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
notify.error('复制失败');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const el = (e.target as HTMLElement).closest('.mention') as HTMLElement | null;
|
const el = (e.target as HTMLElement).closest('.mention') as HTMLElement | null;
|
||||||
if (!el) return;
|
if (!el) return;
|
||||||
const name = el.getAttribute('data-name');
|
const name = el.getAttribute('data-name');
|
||||||
if (!name) return;
|
if (!name) return;
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
void openMention(name);
|
void openMention(name);
|
||||||
}}
|
}, [nav]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="floor-body post-detail-content"
|
||||||
|
onClick={(e) => { void onClick(e); }}
|
||||||
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),
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,15 +8,15 @@ import Placeholder from '@tiptap/extension-placeholder';
|
|||||||
import Underline from '@tiptap/extension-underline';
|
import Underline from '@tiptap/extension-underline';
|
||||||
import DOMPurify from 'dompurify';
|
import DOMPurify from 'dompurify';
|
||||||
import {
|
import {
|
||||||
Bold, Italic, Underline as UnderlineIcon, Strikethrough, Quote,
|
Bold, Italic, Underline as UnderlineIcon, Strikethrough,
|
||||||
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';
|
||||||
@@ -26,7 +26,7 @@ import type { Sticker } from '../data/stickers';
|
|||||||
export interface CommentEditorHandle {
|
export interface CommentEditorHandle {
|
||||||
getHTML: () => string;
|
getHTML: () => string;
|
||||||
isEmpty: () => boolean;
|
isEmpty: () => boolean;
|
||||||
focus: () => void;
|
focus: (options?: { preventScroll?: boolean }) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -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 }),
|
||||||
@@ -160,7 +148,7 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
|||||||
useImperativeHandle(ref, () => ({
|
useImperativeHandle(ref, () => ({
|
||||||
getHTML: () => editor ? sanitizeHtml(editor.getHTML()) : value,
|
getHTML: () => editor ? sanitizeHtml(editor.getHTML()) : value,
|
||||||
isEmpty: () => editor ? isEditorEmpty(editor) : !value.trim(),
|
isEmpty: () => editor ? isEditorEmpty(editor) : !value.trim(),
|
||||||
focus: () => { editor?.commands.focus(); },
|
focus: (options?: { preventScroll?: boolean }) => { editor?.commands.focus(options); },
|
||||||
}), [editor, value]);
|
}), [editor, value]);
|
||||||
|
|
||||||
const insertSticker = useCallback((sticker: Sticker) => {
|
const insertSticker = useCallback((sticker: Sticker) => {
|
||||||
@@ -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,44 +204,85 @@ 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 }[] = [
|
const tools: { icon: React.ReactNode; title: string; hint?: string; active?: boolean; action: () => void; className?: string }[] = [
|
||||||
{ icon: <strong>H</strong>, title: '标题', active: editor.isActive('heading'), action: () => {
|
|
||||||
for (let l = 2; l <= 4; l++) {
|
|
||||||
if (editor.isActive('heading', { level: l })) {
|
|
||||||
if (l === 4) editor.chain().focus().setParagraph().run();
|
|
||||||
else editor.chain().focus().toggleHeading({ level: (l + 1) as 2 | 3 | 4 }).run();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
editor.chain().focus().toggleHeading({ level: 2 }).run();
|
|
||||||
}},
|
|
||||||
{ 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() },
|
||||||
{ icon: <Strikethrough size={15} />, title: '删除线', active: editor.isActive('strike'), action: () => editor.chain().focus().toggleStrike().run() },
|
{ icon: <Strikethrough size={15} />, title: '删除线', active: editor.isActive('strike'), action: () => editor.chain().focus().toggleStrike().run() },
|
||||||
{ icon: <Quote size={15} />, title: '引用', active: editor.isActive('blockquote'), action: () => editor.chain().focus().toggleBlockquote().run() },
|
|
||||||
{ icon: <List size={15} />, title: '无序列表', active: editor.isActive('bulletList'), action: () => editor.chain().focus().toggleBulletList().run() },
|
{ icon: <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: <span className="article-tool-btn__owo">OwO</span>, title: '表情 OwO', active: showSticker, action: () => setShowSticker(v => !v) },
|
icon: <ImageIcon size={15} />,
|
||||||
|
title: '图片',
|
||||||
|
hint: '上传、链接或从已上传中选择',
|
||||||
|
action: () => setImagePickerOpen(true),
|
||||||
|
},
|
||||||
|
{ icon: <span className="article-tool-btn__owo">OwO</span>, title: '表情 OwO', active: showSticker, action: () => setShowSticker(v => !v), className: 'article-tool-btn--owo' },
|
||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -258,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' : ''}`}
|
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>
|
||||||
@@ -279,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}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import {
|
import {
|
||||||
Check, Clock, History, MessageSquare, X, Pencil, Trash2,
|
Check, Award, Clock, History, MessageSquare, X, Pencil, Trash2,
|
||||||
ThumbsUp, MoreHorizontal, Flag,
|
ThumbsUp, MoreHorizontal, Flag,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import type { ReactNode } from 'react';
|
import type { ReactNode } from 'react';
|
||||||
@@ -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';
|
||||||
@@ -51,6 +52,7 @@ import { isHtmlEmpty } from '../utils/postContent';
|
|||||||
import { Tooltip } from './ui/Tooltip';
|
import { Tooltip } from './ui/Tooltip';
|
||||||
import UserLink from './UserLink';
|
import UserLink from './UserLink';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
import { pinAwardedCommentTree } from '../utils/bounty';
|
||||||
|
|
||||||
function isCommentAuthor(c: Comment, user?: User | null): boolean {
|
function isCommentAuthor(c: Comment, user?: User | null): boolean {
|
||||||
return !!user && c.user_id > 0 && c.user_id === user.id;
|
return !!user && c.user_id > 0 && c.user_id === user.id;
|
||||||
@@ -83,6 +85,13 @@ interface ItemProps {
|
|||||||
onRequireLogin?: (actionLabel: string) => void;
|
onRequireLogin?: (actionLabel: string) => void;
|
||||||
onLikeUpdate?: (commentId: number, liked: boolean, likeCount: number) => void;
|
onLikeUpdate?: (commentId: number, liked: boolean, likeCount: number) => void;
|
||||||
renderReplyBox?: (comment: Comment) => ReactNode;
|
renderReplyBox?: (comment: Comment) => ReactNode;
|
||||||
|
bountyAward?: {
|
||||||
|
open: boolean;
|
||||||
|
awardedCommentId?: number;
|
||||||
|
postAuthorId: number;
|
||||||
|
canAward: boolean;
|
||||||
|
onAward: (commentId: number) => void;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 单条评论(支持嵌套子回复 + 内联回复框 + 编辑/删除) */
|
/** 单条评论(支持嵌套子回复 + 内联回复框 + 编辑/删除) */
|
||||||
@@ -103,12 +112,14 @@ function CommentItem({
|
|||||||
onRequireLogin,
|
onRequireLogin,
|
||||||
onLikeUpdate,
|
onLikeUpdate,
|
||||||
renderReplyBox,
|
renderReplyBox,
|
||||||
|
bountyAward,
|
||||||
}: ItemProps) {
|
}: ItemProps) {
|
||||||
const { limits } = useForumLimits();
|
const { limits } = useForumLimits();
|
||||||
const c = node.comment;
|
const c = node.comment;
|
||||||
const nick = commentNick(c);
|
const nick = commentNick(c);
|
||||||
const guest = isGuestComment(c);
|
const guest = isGuestComment(c);
|
||||||
const isHighlighted = highlightFloor === c.floor;
|
const isHighlighted = highlightFloor === c.floor;
|
||||||
|
const isBountyAwarded = bountyAward?.awardedCommentId === c.id;
|
||||||
const hidden = !!c.content_hidden;
|
const hidden = !!c.content_hidden;
|
||||||
const isReplying = replyToId === c.id;
|
const isReplying = replyToId === c.id;
|
||||||
const isEditing = editingId === c.id;
|
const isEditing = editingId === c.id;
|
||||||
@@ -134,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);
|
||||||
@@ -142,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('');
|
||||||
@@ -215,14 +232,19 @@ function CommentItem({
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
id={`floor-${c.floor}`}
|
id={`floor-${c.floor}`}
|
||||||
className={`waline-comment ${nested ? 'nested' : ''} ${isHighlighted ? 'highlight' : ''}`}
|
className={cn(
|
||||||
|
'waline-comment',
|
||||||
|
nested && 'nested',
|
||||||
|
isHighlighted && 'highlight',
|
||||||
|
isBountyAwarded && 'waline-comment--bounty-awarded',
|
||||||
|
)}
|
||||||
>
|
>
|
||||||
{!guest && c.user_id ? (
|
{!guest && c.user_id ? (
|
||||||
<UserLink
|
<UserLink
|
||||||
user={c.user ?? { id: c.user_id, nickname: nick }}
|
user={c.user ?? { id: c.user_id, nickname: nick }}
|
||||||
showAvatar={false}
|
showAvatar={false}
|
||||||
showName={false}
|
showName={false}
|
||||||
className={`waline-comment-avatar user-link--avatar-only${!c.user?.avatar ? ' guest' : ''}`}
|
className="waline-comment-avatar user-link--avatar-only"
|
||||||
>
|
>
|
||||||
{c.user?.avatar ? (
|
{c.user?.avatar ? (
|
||||||
<img src={c.user.avatar} alt="" loading="lazy" decoding="async" />
|
<img src={c.user.avatar} alt="" loading="lazy" decoding="async" />
|
||||||
@@ -231,7 +253,7 @@ function CommentItem({
|
|||||||
)}
|
)}
|
||||||
</UserLink>
|
</UserLink>
|
||||||
) : (
|
) : (
|
||||||
<div className={`waline-comment-avatar ${!c.user?.avatar ? 'guest' : ''}`}>
|
<div className={`waline-comment-avatar${!c.user?.avatar ? ' guest' : ''}`}>
|
||||||
{c.user?.avatar ? (
|
{c.user?.avatar ? (
|
||||||
<img src={c.user.avatar} alt="" loading="lazy" decoding="async" />
|
<img src={c.user.avatar} alt="" loading="lazy" decoding="async" />
|
||||||
) : (
|
) : (
|
||||||
@@ -255,6 +277,12 @@ function CommentItem({
|
|||||||
) : (
|
) : (
|
||||||
<span className="waline-comment-author">{nick}</span>
|
<span className="waline-comment-author">{nick}</span>
|
||||||
)}
|
)}
|
||||||
|
{isBountyAwarded && (
|
||||||
|
<span className="waline-comment-bounty-badge" title="悬赏已采纳">
|
||||||
|
<Check size={12} aria-hidden />
|
||||||
|
已采纳
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
{!hidden && (
|
{!hidden && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -312,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}>
|
||||||
@@ -345,52 +355,18 @@ function CommentItem({
|
|||||||
</Tooltip>
|
</Tooltip>
|
||||||
)
|
)
|
||||||
)}
|
)}
|
||||||
{!hidden && !isEditing && canEdit && (
|
{bountyAward?.open && bountyAward.canAward && c.user_id !== bountyAward.postAuthorId
|
||||||
<button type="button" className="waline-comment-reply-btn" onClick={() => onStartEdit(c)}>
|
&& c.status === 'published' && !hidden && (
|
||||||
<Pencil size={14} />
|
<button
|
||||||
编辑
|
type="button"
|
||||||
</button>
|
className="bounty-award-btn"
|
||||||
)}
|
onClick={() => bountyAward.onAward(c.id)}
|
||||||
{!hidden && !isEditing && isAdmin && showEdited && (
|
|
||||||
<button type="button" className="waline-comment-reply-btn" onClick={() => setRevOpen(true)}>
|
|
||||||
<History size={14} />
|
|
||||||
编辑记录
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
{!hidden && !isEditing && canDelete && (
|
|
||||||
<AlertDialog>
|
|
||||||
<AlertDialogTrigger asChild>
|
|
||||||
<button type="button" className="waline-comment-reply-btn cancel" disabled={deleting}>
|
|
||||||
<Trash2 size={14} />
|
|
||||||
删除
|
|
||||||
</button>
|
|
||||||
</AlertDialogTrigger>
|
|
||||||
<AlertDialogContent>
|
|
||||||
<AlertDialogHeader>
|
|
||||||
<AlertDialogTitle>确定删除该评论?</AlertDialogTitle>
|
|
||||||
<AlertDialogDescription>
|
|
||||||
将同时移入回收站其下所有回复,可在后台恢复或永久删除。
|
|
||||||
</AlertDialogDescription>
|
|
||||||
</AlertDialogHeader>
|
|
||||||
<AlertDialogFooter>
|
|
||||||
<AlertDialogCancel>取消</AlertDialogCancel>
|
|
||||||
<AlertDialogAction
|
|
||||||
onClick={async () => {
|
|
||||||
setDeleting(true);
|
|
||||||
try {
|
|
||||||
await onDelete(c);
|
|
||||||
} finally {
|
|
||||||
setDeleting(false);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
删除
|
<Award size={14} aria-hidden />
|
||||||
</AlertDialogAction>
|
采纳
|
||||||
</AlertDialogFooter>
|
</button>
|
||||||
</AlertDialogContent>
|
|
||||||
</AlertDialog>
|
|
||||||
)}
|
)}
|
||||||
{canReport && (
|
{showManageMenu && (
|
||||||
<DropdownMenu>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<button
|
<button
|
||||||
@@ -401,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">
|
||||||
|
{showManageGroup && (
|
||||||
|
<>
|
||||||
|
<DropdownMenuLabel>管理</DropdownMenuLabel>
|
||||||
|
{canApprove && (
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
className="report-more-menu__item"
|
disabled={approving}
|
||||||
|
onSelect={() => {
|
||||||
|
void (async () => {
|
||||||
|
setApproving(true);
|
||||||
|
try {
|
||||||
|
await onApprove?.(c);
|
||||||
|
} finally {
|
||||||
|
setApproving(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Check size={14} aria-hidden />
|
||||||
|
{approving ? '通过中…' : '通过审核'}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
)}
|
||||||
|
{canEdit && (
|
||||||
|
<DropdownMenuItem onSelect={() => onStartEdit(c)}>
|
||||||
|
<Pencil size={14} aria-hidden />
|
||||||
|
编辑
|
||||||
|
</DropdownMenuItem>
|
||||||
|
)}
|
||||||
|
{showHistory && (
|
||||||
|
<DropdownMenuItem onSelect={() => setRevOpen(true)}>
|
||||||
|
<History size={14} aria-hidden />
|
||||||
|
编辑记录
|
||||||
|
</DropdownMenuItem>
|
||||||
|
)}
|
||||||
|
{canDelete && (
|
||||||
|
<DropdownMenuItem
|
||||||
|
className="text-destructive focus:text-destructive"
|
||||||
|
disabled={deleting}
|
||||||
|
onSelect={() => setDeleteOpen(true)}
|
||||||
|
>
|
||||||
|
<Trash2 size={14} aria-hidden />
|
||||||
|
删除
|
||||||
|
</DropdownMenuItem>
|
||||||
|
)}
|
||||||
|
{canReport && <DropdownMenuSeparator />}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{canReport && (
|
||||||
|
<DropdownMenuItem
|
||||||
|
className="text-destructive focus:text-destructive"
|
||||||
onSelect={openReport}
|
onSelect={openReport}
|
||||||
>
|
>
|
||||||
<Flag size={14} />
|
<Flag size={14} aria-hidden />
|
||||||
举报
|
举报
|
||||||
</DropdownMenuItem>
|
</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} />
|
||||||
)}
|
)}
|
||||||
@@ -481,6 +536,7 @@ function CommentItem({
|
|||||||
onRequireLogin={onRequireLogin}
|
onRequireLogin={onRequireLogin}
|
||||||
onLikeUpdate={onLikeUpdate}
|
onLikeUpdate={onLikeUpdate}
|
||||||
renderReplyBox={renderReplyBox}
|
renderReplyBox={renderReplyBox}
|
||||||
|
bountyAward={bountyAward}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -506,6 +562,7 @@ interface Props {
|
|||||||
onRequireLogin?: (actionLabel: string) => void;
|
onRequireLogin?: (actionLabel: string) => void;
|
||||||
onLikeUpdate?: (commentId: number, liked: boolean, likeCount: number) => void;
|
onLikeUpdate?: (commentId: number, liked: boolean, likeCount: number) => void;
|
||||||
renderReplyBox?: (comment: Comment) => ReactNode;
|
renderReplyBox?: (comment: Comment) => ReactNode;
|
||||||
|
bountyAward?: ItemProps['bountyAward'];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Waline 嵌套楼层评论列表 */
|
/** Waline 嵌套楼层评论列表 */
|
||||||
@@ -525,8 +582,12 @@ export default function CommentThreadList({
|
|||||||
onRequireLogin,
|
onRequireLogin,
|
||||||
onLikeUpdate,
|
onLikeUpdate,
|
||||||
renderReplyBox,
|
renderReplyBox,
|
||||||
|
bountyAward,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const tree = buildCommentTree(comments);
|
const tree = pinAwardedCommentTree(
|
||||||
|
buildCommentTree(comments),
|
||||||
|
bountyAward?.awardedCommentId,
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="comment-thread-list">
|
<div className="comment-thread-list">
|
||||||
@@ -548,6 +609,7 @@ export default function CommentThreadList({
|
|||||||
onRequireLogin={onRequireLogin}
|
onRequireLogin={onRequireLogin}
|
||||||
onLikeUpdate={onLikeUpdate}
|
onLikeUpdate={onLikeUpdate}
|
||||||
renderReplyBox={renderReplyBox}
|
renderReplyBox={renderReplyBox}
|
||||||
|
bountyAward={bountyAward}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -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"
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,94 +1,51 @@
|
|||||||
import { Users, FileText, LayoutGrid } from 'lucide-react';
|
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import type { Board, ForumStats } from '../api/types';
|
import { navigateFeed } from '../utils/feedCache';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
boardId: number;
|
|
||||||
keyword: string;
|
keyword: string;
|
||||||
tag?: string;
|
tag?: string;
|
||||||
author?: string;
|
author?: string;
|
||||||
titleOnly?: boolean;
|
|
||||||
boards: Board[];
|
|
||||||
stats: ForumStats | null;
|
|
||||||
postTotal: number;
|
postTotal: number;
|
||||||
/** 搜索页用 h1;首页/板块页中间栏不再展示标题 */
|
/** 搜索页用 h1;首页/板块页中间栏不再展示标题 */
|
||||||
titleAs?: 'h1' | 'h2';
|
titleAs?: 'h1' | 'h2';
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function FeedHeader({
|
export default function FeedHeader({
|
||||||
boardId,
|
|
||||||
keyword,
|
keyword,
|
||||||
tag = '',
|
tag = '',
|
||||||
author = '',
|
author = '',
|
||||||
titleOnly = false,
|
|
||||||
boards,
|
|
||||||
stats,
|
|
||||||
postTotal,
|
postTotal,
|
||||||
titleAs = 'h1',
|
titleAs = 'h1',
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const nav = useNavigate();
|
const nav = useNavigate();
|
||||||
const board = boards.find(b => b.id === boardId);
|
|
||||||
|
|
||||||
const filtered = !!(keyword || tag || author);
|
const isSearch = !!(keyword || author);
|
||||||
const inBoard = !filtered && boardId > 0 && !!board;
|
const isTag = !!tag;
|
||||||
/** 侧栏已有「全部帖子 / 板块名」,中间栏不再重复;仅搜索/标签保留标题 */
|
const filtered = isSearch || isTag;
|
||||||
let title = '';
|
|
||||||
if (tag) title = `标签:${tag}`;
|
|
||||||
else if (keyword || author) {
|
|
||||||
const parts: string[] = [];
|
|
||||||
if (keyword) parts.push(titleOnly ? `标题含「${keyword}」` : `搜索:${keyword}`);
|
|
||||||
if (author) parts.push(`作者 ${author}`);
|
|
||||||
if (boardId && board) parts.push(`板块 ${board.name}`);
|
|
||||||
title = parts.join(' · ');
|
|
||||||
}
|
|
||||||
const TitleTag = titleAs;
|
const TitleTag = titleAs;
|
||||||
|
|
||||||
|
let title = '';
|
||||||
|
if (isTag) title = `标签:${tag}`;
|
||||||
|
else if (isSearch) title = '搜索结果';
|
||||||
|
|
||||||
|
// 无标题且无操作时不占位
|
||||||
|
if (!filtered) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`feed-head${filtered ? ' feed-head--solo' : ' feed-head--stats-only'}`}>
|
<div className="feed-head feed-head--solo">
|
||||||
<div className="feed-head__title">
|
<div className="feed-head__title">
|
||||||
{title ? <TitleTag>{title}</TitleTag> : null}
|
{title ? <TitleTag>{title}</TitleTag> : null}
|
||||||
{!filtered && inBoard && (
|
<span className="feed-head__meta feed-head__meta--count">共 {postTotal} 条</span>
|
||||||
<div className="feed-head__stats">
|
|
||||||
<span className="feed-stat-chip">
|
|
||||||
<FileText aria-hidden />
|
|
||||||
本板块 <strong>{postTotal}</strong> 帖
|
|
||||||
</span>
|
|
||||||
{stats && (
|
|
||||||
<span className="feed-stat-chip feed-stat-chip--muted" title="全站统计">
|
|
||||||
全站 {stats.posts} 帖 · {stats.users} 会员
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
{isTag && (
|
||||||
{!filtered && !inBoard && stats && (
|
|
||||||
<div className="feed-head__stats">
|
|
||||||
<span className="feed-stat-chip">
|
|
||||||
<Users aria-hidden />
|
|
||||||
会员 <strong>{stats.users}</strong>
|
|
||||||
</span>
|
|
||||||
<span className="feed-stat-chip">
|
|
||||||
<FileText aria-hidden />
|
|
||||||
帖子 <strong>{stats.posts}</strong>
|
|
||||||
</span>
|
|
||||||
<span className="feed-stat-chip">
|
|
||||||
<LayoutGrid aria-hidden />
|
|
||||||
板块 <strong>{stats.boards}</strong>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{filtered && (
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="feed-head__clear"
|
className="feed-head__clear"
|
||||||
onClick={() => nav('/')}
|
onClick={() => navigateFeed(nav, '/')}
|
||||||
>
|
>
|
||||||
{tag ? '清除标签' : '清除搜索'}
|
清除标签
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
{filtered && (
|
|
||||||
<span className="feed-toolbar__count">共 {postTotal} 条</span>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
import { Skeleton } from '@/components/ui/skeleton';
|
|
||||||
import PostListSkeleton from './PostListSkeleton';
|
|
||||||
|
|
||||||
/** 首页 Feed 初始骨架(标题区 + 排序栏 + 列表) */
|
|
||||||
export default function FeedPageSkeleton() {
|
|
||||||
return (
|
|
||||||
<div className="page-wrap page-wrap--feed" aria-busy="true" aria-label="内容加载中">
|
|
||||||
<div className="feed-panel">
|
|
||||||
<div className="feed-top">
|
|
||||||
<div className="feed-top__bar">
|
|
||||||
<div className="feed-head feed-head--stats-only">
|
|
||||||
<div className="feed-head__title">
|
|
||||||
<div className="feed-head__stats">
|
|
||||||
<Skeleton className="skeleton--stat-chip" />
|
|
||||||
<Skeleton className="skeleton--stat-chip" />
|
|
||||||
<Skeleton className="skeleton--stat-chip" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="feed-toolbar feed-toolbar--skeleton" aria-hidden>
|
|
||||||
<Skeleton className="skeleton--sort-tab" />
|
|
||||||
<Skeleton className="skeleton--sort-tab" />
|
|
||||||
<Skeleton className="skeleton--sort-tab" />
|
|
||||||
<span className="feed-toolbar__spacer" />
|
|
||||||
<Skeleton className="skeleton--count" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="post-list-scroll">
|
|
||||||
<PostListSkeleton />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,39 +1,57 @@
|
|||||||
import { useRef } from 'react';
|
import { useMemo, useRef } from 'react';
|
||||||
import { Clock, MessageCircle, Flame } from 'lucide-react';
|
import { useParams, useSearchParams } from 'react-router-dom';
|
||||||
|
import { boardPath, parsePermalinkID, type PermalinkOpts } from '../utils/permalink';
|
||||||
|
import { getCachedForumLimits, useForumLimits } from '../hooks/useForumLimits';
|
||||||
|
import { Clock, MessageCircle, BadgeCheck, Loader2 } from 'lucide-react';
|
||||||
import { cn } from '@/lib/utils';
|
import { 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 },
|
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();
|
||||||
if (boardId) p.set('board', String(boardId));
|
|
||||||
const tag = opts?.tag?.trim();
|
const tag = opts?.tag?.trim();
|
||||||
const keyword = opts?.keyword?.trim();
|
const keyword = opts?.keyword?.trim();
|
||||||
const author = opts?.author?.trim();
|
const author = opts?.author?.trim();
|
||||||
@@ -46,30 +64,76 @@ 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) {
|
||||||
|
const base = boardPath(boardId, opts?.permalink ?? getCachedForumLimits());
|
||||||
|
return qs ? `${base}?${qs}` : base;
|
||||||
|
}
|
||||||
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
|
||||||
@@ -79,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;
|
||||||
|
return (
|
||||||
|
<a
|
||||||
key={key}
|
key={key}
|
||||||
type="button"
|
href={href}
|
||||||
role="tab"
|
role="tab"
|
||||||
tabIndex={activeIndex === i ? 0 : -1}
|
tabIndex={activeIndex === i ? 0 : -1}
|
||||||
aria-selected={value === key}
|
aria-selected={value === key}
|
||||||
|
aria-busy={pending || undefined}
|
||||||
title={`${label} · ${hint}`}
|
title={`${label} · ${hint}`}
|
||||||
className={cn('feed-sort-tab', value === key && 'active')}
|
className={cn('feed-sort-tab', value === key && 'active', pending && 'is-pending')}
|
||||||
onClick={() => onChange(key)}
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
onChange(key);
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<Icon aria-hidden />
|
{pending
|
||||||
|
? <Loader2 className="feed-sort-tab__spin" aria-hidden />
|
||||||
|
: <Icon aria-hidden />}
|
||||||
<span className="feed-sort-tab__label">{label}</span>
|
<span className="feed-sort-tab__label">{label}</span>
|
||||||
</button>
|
</a>
|
||||||
))}
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
{postTotal != null && (
|
{postTotal != null && (
|
||||||
<span className="feed-toolbar__count">共 {postTotal} 条</span>
|
<span className="feed-toolbar__count">共 {postTotal} 条</span>
|
||||||
|
|||||||
284
frontend/src/components/FriendLinkApplyDialog.tsx
Normal file
284
frontend/src/components/FriendLinkApplyDialog.tsx
Normal file
@@ -0,0 +1,284 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import { Link2, Upload } from 'lucide-react';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Spinner } from '@/components/ui/spinner';
|
||||||
|
import { notify } from '@/lib/notify';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import { api } from '../api/client';
|
||||||
|
import type { FriendLinkApply } from '../api/types';
|
||||||
|
import { getCachedSiteBranding } from '../hooks/useSiteBranding';
|
||||||
|
import { resolveFriendLinkLogo } from '../utils/friendLink';
|
||||||
|
import FriendLinkSiteInfo from './FriendLinkSiteInfo';
|
||||||
|
|
||||||
|
type LinkPlacement = 'homepage' | 'custom';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
editApply?: FriendLinkApply | null;
|
||||||
|
onSubmitted?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 友链申请 / 修改弹窗 */
|
||||||
|
export default function FriendLinkApplyDialog({ open, onOpenChange, editApply, onSubmitted }: Props) {
|
||||||
|
const [name, setName] = useState('');
|
||||||
|
const [url, setUrl] = useState('');
|
||||||
|
const [logo, setLogo] = useState('');
|
||||||
|
const [linkPlacement, setLinkPlacement] = useState<LinkPlacement>('homepage');
|
||||||
|
const [reciprocalPageURL, setReciprocalPageURL] = useState('');
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [uploadingLogo, setUploadingLogo] = useState(false);
|
||||||
|
const fileRef = useRef<HTMLInputElement>(null);
|
||||||
|
const isEdit = !!editApply?.id;
|
||||||
|
|
||||||
|
const reset = () => {
|
||||||
|
setName('');
|
||||||
|
setUrl('');
|
||||||
|
setLogo('');
|
||||||
|
setLinkPlacement('homepage');
|
||||||
|
setReciprocalPageURL('');
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
if (editApply) {
|
||||||
|
setName(editApply.name ?? '');
|
||||||
|
setUrl(editApply.url ?? '');
|
||||||
|
setLogo(editApply.logo ?? '');
|
||||||
|
const onHomepage = editApply.link_on_homepage !== false;
|
||||||
|
setLinkPlacement(onHomepage ? 'homepage' : 'custom');
|
||||||
|
setReciprocalPageURL(onHomepage ? '' : (editApply.reciprocal_page_url ?? ''));
|
||||||
|
} else {
|
||||||
|
reset();
|
||||||
|
}
|
||||||
|
}, [open, editApply]);
|
||||||
|
|
||||||
|
const handleOpenChange = (next: boolean) => {
|
||||||
|
if (!next) reset();
|
||||||
|
onOpenChange(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
const uploadLogo = async (file: File | undefined) => {
|
||||||
|
if (!file) return;
|
||||||
|
setUploadingLogo(true);
|
||||||
|
try {
|
||||||
|
const r = await api.uploadFriendLinkLogo(file);
|
||||||
|
setLogo(r.url);
|
||||||
|
notify.success('LOGO 已上传');
|
||||||
|
} catch (e: unknown) {
|
||||||
|
notify.error(e instanceof Error ? e.message : '上传失败');
|
||||||
|
} finally {
|
||||||
|
setUploadingLogo(false);
|
||||||
|
if (fileRef.current) fileRef.current.value = '';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const submit = async () => {
|
||||||
|
const trimmedName = name.trim();
|
||||||
|
const trimmedURL = url.trim();
|
||||||
|
const trimmedLogo = logo.trim();
|
||||||
|
const trimmedReciprocal = reciprocalPageURL.trim();
|
||||||
|
if (!trimmedName || !trimmedURL) {
|
||||||
|
notify.warning('请填写网站名称与网站链接');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!/^https?:\/\//i.test(trimmedURL)) {
|
||||||
|
notify.warning('网站链接需以 http:// 或 https:// 开头');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!trimmedLogo) {
|
||||||
|
notify.warning('请填写或上传网站 LOGO');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (linkPlacement === 'custom') {
|
||||||
|
if (!trimmedReciprocal) {
|
||||||
|
notify.warning('请填写添加本站链接的页面地址');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!/^https?:\/\//i.test(trimmedReciprocal)) {
|
||||||
|
notify.warning('回链页地址需以 http:// 或 https:// 开头');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const linkOnHomepage = linkPlacement === 'homepage';
|
||||||
|
const body = {
|
||||||
|
name: trimmedName,
|
||||||
|
url: trimmedURL,
|
||||||
|
logo: trimmedLogo,
|
||||||
|
link_on_homepage: linkOnHomepage,
|
||||||
|
reciprocal_page_url: linkOnHomepage ? trimmedURL : trimmedReciprocal,
|
||||||
|
};
|
||||||
|
|
||||||
|
setSubmitting(true);
|
||||||
|
try {
|
||||||
|
if (isEdit) {
|
||||||
|
const r = await api.updateFriendLinkApply(editApply!.id, body);
|
||||||
|
notify.success(
|
||||||
|
editApply?.status === 'approved'
|
||||||
|
? `已更新并重新提交审核,友链已暂时从列表移除${r.message.includes('回链检测') ? ',回链检测将在后台进行' : ''}`
|
||||||
|
: r.message,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
const r = await api.applyFriendLink(body);
|
||||||
|
notify.success(r.message);
|
||||||
|
}
|
||||||
|
onSubmitted?.();
|
||||||
|
handleOpenChange(false);
|
||||||
|
} catch (e: unknown) {
|
||||||
|
notify.error(e instanceof Error ? e.message : '提交失败');
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const logoPreview = resolveFriendLinkLogo(logo.trim(), getCachedSiteBranding().site_url);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||||
|
<DialogContent className="friend-link-apply-dialog sm:max-w-[560px]">
|
||||||
|
<DialogHeader className="friend-link-apply-dialog__header">
|
||||||
|
<DialogTitle>{isEdit ? '修改友链申请' : '申请本页友情链接'}</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<FriendLinkSiteInfo />
|
||||||
|
|
||||||
|
<div className="friend-link-apply-form">
|
||||||
|
<div className="friend-link-apply-field">
|
||||||
|
<Label htmlFor="friend-link-name">网站名称</Label>
|
||||||
|
<Input
|
||||||
|
id="friend-link-name"
|
||||||
|
value={name}
|
||||||
|
onChange={e => setName(e.target.value)}
|
||||||
|
placeholder="请输入您的网站名称"
|
||||||
|
maxLength={32}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="friend-link-apply-field">
|
||||||
|
<Label htmlFor="friend-link-url">网站链接</Label>
|
||||||
|
<Input
|
||||||
|
id="friend-link-url"
|
||||||
|
value={url}
|
||||||
|
onChange={e => setUrl(e.target.value)}
|
||||||
|
placeholder="请输入您的网站地址(以 http 开头)"
|
||||||
|
maxLength={512}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="friend-link-apply-field">
|
||||||
|
<Label>本站链接放置位置</Label>
|
||||||
|
<div className="friend-link-apply-placement" role="radiogroup" aria-label="本站链接放置位置">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
aria-checked={linkPlacement === 'homepage'}
|
||||||
|
className={cn(
|
||||||
|
'friend-link-apply-placement__option',
|
||||||
|
linkPlacement === 'homepage' && 'friend-link-apply-placement__option--active',
|
||||||
|
)}
|
||||||
|
onClick={() => setLinkPlacement('homepage')}
|
||||||
|
>
|
||||||
|
友链在我的网站首页
|
||||||
|
</button>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
'friend-link-apply-placement__custom',
|
||||||
|
linkPlacement === 'custom' && 'friend-link-apply-placement__custom--open',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
aria-checked={linkPlacement === 'custom'}
|
||||||
|
className={cn(
|
||||||
|
'friend-link-apply-placement__option',
|
||||||
|
linkPlacement === 'custom' && 'friend-link-apply-placement__option--active',
|
||||||
|
)}
|
||||||
|
onClick={() => setLinkPlacement('custom')}
|
||||||
|
>
|
||||||
|
友链在其它页面
|
||||||
|
</button>
|
||||||
|
<div className="friend-link-apply-placement__custom-panel" aria-hidden={linkPlacement !== 'custom'}>
|
||||||
|
<div className="friend-link-apply-placement__custom-inner">
|
||||||
|
<Label htmlFor="friend-link-reciprocal">添加我方链接的页面地址</Label>
|
||||||
|
<Input
|
||||||
|
id="friend-link-reciprocal"
|
||||||
|
value={reciprocalPageURL}
|
||||||
|
onChange={e => setReciprocalPageURL(e.target.value)}
|
||||||
|
placeholder="如:https://您的域名/link.htm"
|
||||||
|
maxLength={512}
|
||||||
|
tabIndex={linkPlacement === 'custom' ? 0 : -1}
|
||||||
|
/>
|
||||||
|
<p className="friend-link-apply-field__hint">
|
||||||
|
请填写实际放置本站友链的页面,提交后将在后台检测该页面
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="friend-link-apply-field">
|
||||||
|
<Label htmlFor="friend-link-logo">填写或上传网站 LOGO</Label>
|
||||||
|
<div className="friend-link-apply-logo-row">
|
||||||
|
<div className="friend-link-apply-logo-preview" aria-label="LOGO 预览">
|
||||||
|
{logoPreview ? (
|
||||||
|
<img src={logoPreview} alt="" loading="lazy" decoding="async" />
|
||||||
|
) : (
|
||||||
|
<span>预览</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Input
|
||||||
|
id="friend-link-logo"
|
||||||
|
className="friend-link-apply-logo-input"
|
||||||
|
value={logo}
|
||||||
|
onChange={e => setLogo(e.target.value)}
|
||||||
|
placeholder="LOGO 图片地址"
|
||||||
|
maxLength={512}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
ref={fileRef}
|
||||||
|
type="file"
|
||||||
|
accept="image/jpeg,image/png,image/gif,image/webp"
|
||||||
|
className="sr-only"
|
||||||
|
onChange={e => uploadLogo(e.target.files?.[0])}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="friend-link-apply-logo-upload"
|
||||||
|
disabled={uploadingLogo}
|
||||||
|
onClick={() => fileRef.current?.click()}
|
||||||
|
>
|
||||||
|
{uploadingLogo ? <Spinner size="sm" /> : <Upload size={15} aria-hidden />}
|
||||||
|
上传
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter className="friend-link-apply-dialog__footer">
|
||||||
|
<p className="friend-link-apply-dialog__note">
|
||||||
|
<Link2 size={14} aria-hidden />
|
||||||
|
提交后立即返回,回链检测在后台进行,结果供管理员参考
|
||||||
|
</p>
|
||||||
|
<div className="friend-link-apply-dialog__actions">
|
||||||
|
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)}>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button type="button" disabled={submitting || uploadingLogo} onClick={submit}>
|
||||||
|
{submitting ? '提交中…' : isEdit ? '保存并提交' : '提交申请'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
44
frontend/src/components/FriendLinkSiteInfo.tsx
Normal file
44
frontend/src/components/FriendLinkSiteInfo.tsx
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { useSiteBranding } from '../hooks/useSiteBranding';
|
||||||
|
|
||||||
|
function resolveSiteURL(siteURL?: string): string {
|
||||||
|
const fromApi = siteURL?.trim();
|
||||||
|
if (fromApi) return fromApi;
|
||||||
|
if (typeof window !== 'undefined') return window.location.origin;
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveSiteLogoURL(logo?: string, favicon?: string, siteURL?: string): string {
|
||||||
|
const raw = logo?.trim() || favicon?.trim() || '';
|
||||||
|
if (!raw) return '';
|
||||||
|
if (/^https?:\/\//i.test(raw)) return raw;
|
||||||
|
const base = resolveSiteURL(siteURL);
|
||||||
|
if (!base) return raw;
|
||||||
|
return raw.startsWith('/') ? `${base}${raw}` : `${base}/${raw}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 申请弹窗内:本站友链信息(名称 / 地址 / LOGO 链接) */
|
||||||
|
export default function FriendLinkSiteInfo() {
|
||||||
|
const { branding } = useSiteBranding();
|
||||||
|
const siteURL = resolveSiteURL(branding.site_url);
|
||||||
|
const siteLogoURL = resolveSiteLogoURL(branding.logo, branding.favicon, branding.site_url);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="friend-link-site-info" aria-label="本站友链信息">
|
||||||
|
<h3 className="friend-link-site-info__title">本站信息(请添加本站链接后再申请)</h3>
|
||||||
|
<dl className="friend-link-site-info__list">
|
||||||
|
<div className="friend-link-site-info__item">
|
||||||
|
<dt>名称</dt>
|
||||||
|
<dd>{branding.name}</dd>
|
||||||
|
</div>
|
||||||
|
<div className="friend-link-site-info__item">
|
||||||
|
<dt>地址</dt>
|
||||||
|
<dd>{siteURL || '—'}</dd>
|
||||||
|
</div>
|
||||||
|
<div className="friend-link-site-info__item">
|
||||||
|
<dt>LOGO</dt>
|
||||||
|
<dd>{siteLogoURL || '—'}</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useEffect } from 'react';
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
import { X } from 'lucide-react';
|
import { X } from 'lucide-react';
|
||||||
import { createPortal } from 'react-dom';
|
import { createPortal } from 'react-dom';
|
||||||
|
|
||||||
@@ -9,8 +9,72 @@ interface Props {
|
|||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 帖子正文图片灯箱:展示原图,点击遮罩 / Esc / 关闭按钮退出 */
|
const MIN_SCALE = 1;
|
||||||
|
const MAX_SCALE = 4;
|
||||||
|
|
||||||
|
function touchDistance(a: Touch, b: Touch) {
|
||||||
|
const dx = a.clientX - b.clientX;
|
||||||
|
const dy = a.clientY - b.clientY;
|
||||||
|
return Math.hypot(dx, dy);
|
||||||
|
}
|
||||||
|
|
||||||
|
function touchMidpoint(a: Touch, b: Touch) {
|
||||||
|
return {
|
||||||
|
x: (a.clientX + b.clientX) / 2,
|
||||||
|
y: (a.clientY + b.clientY) / 2,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function clampScale(s: number) {
|
||||||
|
return Math.min(MAX_SCALE, Math.max(MIN_SCALE, s));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 帖子正文图片灯箱:展示原图,支持双指缩放 / 拖动,点击遮罩 / Esc / 关闭按钮退出 */
|
||||||
export default function ImageLightbox({ src, alt = '', open, onClose }: Props) {
|
export default function ImageLightbox({ src, alt = '', open, onClose }: Props) {
|
||||||
|
const [scale, setScale] = useState(1);
|
||||||
|
const [tx, setTx] = useState(0);
|
||||||
|
const [ty, setTy] = useState(0);
|
||||||
|
const [settling, setSettling] = useState(false);
|
||||||
|
|
||||||
|
const scaleRef = useRef(1);
|
||||||
|
const txRef = useRef(0);
|
||||||
|
const tyRef = useRef(0);
|
||||||
|
const pinchRef = useRef<{
|
||||||
|
startDist: number;
|
||||||
|
startScale: number;
|
||||||
|
startTx: number;
|
||||||
|
startTy: number;
|
||||||
|
midX: number;
|
||||||
|
midY: number;
|
||||||
|
} | null>(null);
|
||||||
|
const panRef = useRef<{
|
||||||
|
startX: number;
|
||||||
|
startY: number;
|
||||||
|
startTx: number;
|
||||||
|
startTy: number;
|
||||||
|
} | null>(null);
|
||||||
|
const stageRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
const applyTransform = useCallback((nextScale: number, nextTx: number, nextTy: number) => {
|
||||||
|
scaleRef.current = nextScale;
|
||||||
|
txRef.current = nextTx;
|
||||||
|
tyRef.current = nextTy;
|
||||||
|
setScale(nextScale);
|
||||||
|
setTx(nextTx);
|
||||||
|
setTy(nextTy);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const resetTransform = useCallback((animate = false) => {
|
||||||
|
if (animate) setSettling(true);
|
||||||
|
applyTransform(1, 0, 0);
|
||||||
|
}, [applyTransform]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
resetTransform(false);
|
||||||
|
setSettling(false);
|
||||||
|
}, [open, src, resetTransform]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
const onKey = (e: KeyboardEvent) => {
|
const onKey = (e: KeyboardEvent) => {
|
||||||
@@ -25,6 +89,111 @@ export default function ImageLightbox({ src, alt = '', open, onClose }: Props) {
|
|||||||
};
|
};
|
||||||
}, [open, onClose]);
|
}, [open, onClose]);
|
||||||
|
|
||||||
|
// 原生非 passive 监听,才能在 pinch/pan 时 preventDefault
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const el = stageRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
|
||||||
|
const onTouchStart = (e: TouchEvent) => {
|
||||||
|
setSettling(false);
|
||||||
|
if (e.touches.length === 2) {
|
||||||
|
const a = e.touches[0];
|
||||||
|
const b = e.touches[1];
|
||||||
|
const mid = touchMidpoint(a, b);
|
||||||
|
pinchRef.current = {
|
||||||
|
startDist: touchDistance(a, b) || 1,
|
||||||
|
startScale: scaleRef.current,
|
||||||
|
startTx: txRef.current,
|
||||||
|
startTy: tyRef.current,
|
||||||
|
midX: mid.x,
|
||||||
|
midY: mid.y,
|
||||||
|
};
|
||||||
|
panRef.current = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (e.touches.length === 1 && scaleRef.current > 1.01) {
|
||||||
|
panRef.current = {
|
||||||
|
startX: e.touches[0].clientX,
|
||||||
|
startY: e.touches[0].clientY,
|
||||||
|
startTx: txRef.current,
|
||||||
|
startTy: tyRef.current,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onTouchMove = (e: TouchEvent) => {
|
||||||
|
if (e.touches.length === 2 && pinchRef.current) {
|
||||||
|
if (e.cancelable) e.preventDefault();
|
||||||
|
const a = e.touches[0];
|
||||||
|
const b = e.touches[1];
|
||||||
|
const dist = touchDistance(a, b) || 1;
|
||||||
|
const nextScale = clampScale(
|
||||||
|
pinchRef.current.startScale * (dist / pinchRef.current.startDist),
|
||||||
|
);
|
||||||
|
const mid = touchMidpoint(a, b);
|
||||||
|
applyTransform(
|
||||||
|
nextScale,
|
||||||
|
pinchRef.current.startTx + (mid.x - pinchRef.current.midX),
|
||||||
|
pinchRef.current.startTy + (mid.y - pinchRef.current.midY),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (e.touches.length === 1 && panRef.current && scaleRef.current > 1.01) {
|
||||||
|
if (e.cancelable) e.preventDefault();
|
||||||
|
const dx = e.touches[0].clientX - panRef.current.startX;
|
||||||
|
const dy = e.touches[0].clientY - panRef.current.startY;
|
||||||
|
applyTransform(
|
||||||
|
scaleRef.current,
|
||||||
|
panRef.current.startTx + dx,
|
||||||
|
panRef.current.startTy + dy,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onTouchEnd = (e: TouchEvent) => {
|
||||||
|
if (e.touches.length < 2) pinchRef.current = null;
|
||||||
|
if (e.touches.length === 0) {
|
||||||
|
panRef.current = null;
|
||||||
|
if (scaleRef.current <= 1.05) resetTransform(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onWheel = (e: WheelEvent) => {
|
||||||
|
if (!(e.ctrlKey || e.metaKey)) return;
|
||||||
|
e.preventDefault();
|
||||||
|
setSettling(false);
|
||||||
|
const delta = -e.deltaY * 0.01;
|
||||||
|
const next = clampScale(scaleRef.current * (1 + delta));
|
||||||
|
if (next <= 1.01) {
|
||||||
|
resetTransform(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
applyTransform(next, txRef.current, tyRef.current);
|
||||||
|
};
|
||||||
|
|
||||||
|
el.addEventListener('touchstart', onTouchStart, { passive: false });
|
||||||
|
el.addEventListener('touchmove', onTouchMove, { passive: false });
|
||||||
|
el.addEventListener('touchend', onTouchEnd);
|
||||||
|
el.addEventListener('touchcancel', onTouchEnd);
|
||||||
|
el.addEventListener('wheel', onWheel, { passive: false });
|
||||||
|
return () => {
|
||||||
|
el.removeEventListener('touchstart', onTouchStart);
|
||||||
|
el.removeEventListener('touchmove', onTouchMove);
|
||||||
|
el.removeEventListener('touchend', onTouchEnd);
|
||||||
|
el.removeEventListener('touchcancel', onTouchEnd);
|
||||||
|
el.removeEventListener('wheel', onWheel);
|
||||||
|
};
|
||||||
|
}, [open, applyTransform, resetTransform]);
|
||||||
|
|
||||||
|
const handleBackdropClick = useCallback(() => {
|
||||||
|
if (scaleRef.current > 1.01) {
|
||||||
|
resetTransform(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onClose();
|
||||||
|
}, [onClose, resetTransform]);
|
||||||
|
|
||||||
if (!open || !src) return null;
|
if (!open || !src) return null;
|
||||||
|
|
||||||
return createPortal(
|
return createPortal(
|
||||||
@@ -33,7 +202,7 @@ export default function ImageLightbox({ src, alt = '', open, onClose }: Props) {
|
|||||||
type="button"
|
type="button"
|
||||||
className="image-lightbox-backdrop"
|
className="image-lightbox-backdrop"
|
||||||
aria-label="关闭"
|
aria-label="关闭"
|
||||||
onClick={onClose}
|
onClick={handleBackdropClick}
|
||||||
/>
|
/>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -43,15 +212,20 @@ export default function ImageLightbox({ src, alt = '', open, onClose }: Props) {
|
|||||||
>
|
>
|
||||||
<X size={20} aria-hidden />
|
<X size={20} aria-hidden />
|
||||||
</button>
|
</button>
|
||||||
<div className="image-lightbox-stage">
|
<div ref={stageRef} className="image-lightbox-stage">
|
||||||
<img
|
<img
|
||||||
src={src}
|
src={src}
|
||||||
alt={alt || '原图'}
|
alt={alt || '原图'}
|
||||||
className="image-lightbox-img"
|
className={`image-lightbox-img${settling ? ' image-lightbox-img--settling' : ''}`}
|
||||||
decoding="async"
|
decoding="async"
|
||||||
|
draggable={false}
|
||||||
|
style={{ transform: `translate3d(${tx}px, ${ty}px, 0) scale(${scale})` }}
|
||||||
|
onTransitionEnd={() => setSettling(false)}
|
||||||
|
onClick={e => e.stopPropagation()}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<p className="image-lightbox-hint">点击空白处关闭</p>
|
<p className="image-lightbox-hint image-lightbox-hint--desktop">点击空白处关闭</p>
|
||||||
|
<p className="image-lightbox-hint image-lightbox-hint--mobile">双指缩放 · 点击空白关闭</p>
|
||||||
</div>,
|
</div>,
|
||||||
document.body,
|
document.body,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
227
frontend/src/components/PmComposerInput.tsx
Normal file
227
frontend/src/components/PmComposerInput.tsx
Normal 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, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"');
|
||||||
|
}
|
||||||
|
|
||||||
|
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 += ``;
|
||||||
|
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;
|
||||||
@@ -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>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
182
frontend/src/components/PostBountyBanner.tsx
Normal file
182
frontend/src/components/PostBountyBanner.tsx
Normal file
@@ -0,0 +1,182 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { CheckCircle2, Coins } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
} from '@/components/ui/alert-dialog';
|
||||||
|
import { notify } from '@/lib/notify';
|
||||||
|
import { api } from '../api/client';
|
||||||
|
import type { PostItem } from '../api/types';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
post: PostItem;
|
||||||
|
isOwnerOrAdmin: boolean;
|
||||||
|
isAdmin?: boolean;
|
||||||
|
/** 是否可取消悬赏(楼主有他人回复时为 false;管理员为 true) */
|
||||||
|
canRefund?: boolean;
|
||||||
|
refundBlockReason?: string;
|
||||||
|
eligibleReplyCount?: number;
|
||||||
|
onUpdate?: () => void;
|
||||||
|
/** 跳转到被采纳的评论楼层 */
|
||||||
|
onJumpToAwarded?: () => void;
|
||||||
|
/** 被采纳评论是否仍在当前评论列表中 */
|
||||||
|
canJumpToAwarded?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 悬赏帖状态卡 */
|
||||||
|
export default function PostBountyBanner({
|
||||||
|
post,
|
||||||
|
isOwnerOrAdmin,
|
||||||
|
isAdmin = false,
|
||||||
|
canRefund = true,
|
||||||
|
refundBlockReason,
|
||||||
|
eligibleReplyCount = 0,
|
||||||
|
onUpdate,
|
||||||
|
onJumpToAwarded,
|
||||||
|
canJumpToAwarded,
|
||||||
|
}: Props) {
|
||||||
|
const [refundOpen, setRefundOpen] = useState(false);
|
||||||
|
const [refunding, setRefunding] = useState(false);
|
||||||
|
|
||||||
|
if (post.post_type !== 'bounty') return null;
|
||||||
|
|
||||||
|
const points = post.bounty_points ?? 0;
|
||||||
|
const open = post.bounty_status === 'open' && points > 0;
|
||||||
|
const awarded = post.bounty_status === 'awarded';
|
||||||
|
const refunded = post.bounty_status === 'refunded';
|
||||||
|
|
||||||
|
if (refunded && !isOwnerOrAdmin) return null;
|
||||||
|
|
||||||
|
const showRefundButton = isOwnerOrAdmin && canRefund;
|
||||||
|
const ownerRefundBlocked = isOwnerOrAdmin && !isAdmin && !canRefund;
|
||||||
|
|
||||||
|
const confirmRefund = async () => {
|
||||||
|
setRefunding(true);
|
||||||
|
try {
|
||||||
|
await api.bountyRefund(post.id);
|
||||||
|
notify.success('悬赏已退回');
|
||||||
|
setRefundOpen(false);
|
||||||
|
onUpdate?.();
|
||||||
|
} catch (e: unknown) {
|
||||||
|
notify.error(e instanceof Error ? e.message : '操作失败');
|
||||||
|
} finally {
|
||||||
|
setRefunding(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const refundDialogDescription = isAdmin && eligibleReplyCount > 0
|
||||||
|
? `将强制取消悬赏并把 ${points} 积分退回楼主账户。当前已有 ${eligibleReplyCount} 条他人回复,请确认已审慎处理。`
|
||||||
|
: `确定取消悬赏并将 ${points} 积分退回你的账户?取消后他人将无法再参与本帖悬赏。`;
|
||||||
|
|
||||||
|
if (open) {
|
||||||
|
let ownerHint = '在评论上点击「采纳」发放积分';
|
||||||
|
if (ownerRefundBlocked) {
|
||||||
|
ownerHint = refundBlockReason || '已有用户回复,请从评论中采纳发放积分';
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<section className="post-bounty post-bounty--open" aria-label="悬赏">
|
||||||
|
<div className="post-bounty__head">
|
||||||
|
<div className="post-bounty__lead">
|
||||||
|
<Coins size={18} className="post-bounty__icon" aria-hidden />
|
||||||
|
<div className="post-bounty__titles">
|
||||||
|
<strong className="post-bounty__title">悬赏进行中</strong>
|
||||||
|
<span className="post-bounty__points">{points} 积分</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{showRefundButton && (
|
||||||
|
<div className="post-bounty__actions">
|
||||||
|
<Button type="button" variant="outline" size="sm" onClick={() => setRefundOpen(true)}>
|
||||||
|
取消悬赏
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="post-bounty__hint">
|
||||||
|
{isOwnerOrAdmin
|
||||||
|
? ownerHint
|
||||||
|
: `回复本帖,优质回答可获得这 ${points} 积分`}
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
{showRefundButton && (
|
||||||
|
<AlertDialog
|
||||||
|
open={refundOpen}
|
||||||
|
onOpenChange={(next) => { if (!next && !refunding) setRefundOpen(false); }}
|
||||||
|
>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>{isAdmin && eligibleReplyCount > 0 ? '强制取消悬赏?' : '取消悬赏?'}</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
{refundDialogDescription}
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel disabled={refunding}>返回</AlertDialogCancel>
|
||||||
|
<AlertDialogAction
|
||||||
|
disabled={refunding}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
void confirmRefund();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{refunding ? '退回中…' : '确认取消'}
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (awarded) {
|
||||||
|
return (
|
||||||
|
<section className="post-bounty post-bounty--awarded" aria-label="悬赏已采纳">
|
||||||
|
<div className="post-bounty__head">
|
||||||
|
<div className="post-bounty__lead">
|
||||||
|
<CheckCircle2 size={18} className="post-bounty__icon" aria-hidden />
|
||||||
|
<div className="post-bounty__titles">
|
||||||
|
<strong className="post-bounty__title">已采纳</strong>
|
||||||
|
<span className="post-bounty__subtitle">
|
||||||
|
{points} 积分已发放给被采纳的回复
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{canJumpToAwarded && onJumpToAwarded && (
|
||||||
|
<div className="post-bounty__actions post-bounty__actions--inline">
|
||||||
|
<button type="button" className="post-bounty__jump" onClick={onJumpToAwarded}>
|
||||||
|
查看被采纳的回复
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (refunded) {
|
||||||
|
return (
|
||||||
|
<section className="post-bounty post-bounty--refunded" aria-label="悬赏已退回">
|
||||||
|
<div className="post-bounty__head">
|
||||||
|
<div className="post-bounty__lead">
|
||||||
|
<Coins size={18} className="post-bounty__icon" aria-hidden />
|
||||||
|
<div className="post-bounty__titles">
|
||||||
|
<strong className="post-bounty__title">悬赏已取消</strong>
|
||||||
|
<span className="post-bounty__subtitle">积分已退回</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -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,41 +106,13 @@ export default function PostContent({
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const foldBtn = target.closest<HTMLElement>('[data-code-fold]');
|
|
||||||
if (foldBtn) {
|
|
||||||
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 {
|
try {
|
||||||
await navigator.clipboard.writeText(text);
|
if (await handleMdCodeBlockUiClick(target)) {
|
||||||
const prev = copyBtn.textContent;
|
e.preventDefault();
|
||||||
copyBtn.textContent = '已复制';
|
}
|
||||||
copyBtn.classList.add('is-copied');
|
|
||||||
window.setTimeout(() => {
|
|
||||||
copyBtn.textContent = prev || '复制';
|
|
||||||
copyBtn.classList.remove('is-copied');
|
|
||||||
}, 1600);
|
|
||||||
} catch {
|
} catch {
|
||||||
notify.error('复制失败');
|
notify.error('复制失败');
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}, [nav, openLightbox, onRequestReply, onUnlocked, postId, unlocking]);
|
}, [nav, openLightbox, onRequestReply, onUnlocked, postId, unlocking]);
|
||||||
|
|
||||||
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
|
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||||
@@ -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}
|
||||||
|
|||||||
@@ -1,37 +1,48 @@
|
|||||||
import { memo } from 'react';
|
import { memo } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { Eye, Image as ImageIcon, MessageCircle, ThumbsUp } from 'lucide-react';
|
import { MessageCircle } from 'lucide-react';
|
||||||
import BoardBadge from '@/components/BoardBadge';
|
import BoardBadge from '@/components/BoardBadge';
|
||||||
import FeaturedIcon from '@/components/FeaturedIcon';
|
import FeaturedIcon from '@/components/FeaturedIcon';
|
||||||
import UserLink from '@/components/UserLink';
|
import UserLink from '@/components/UserLink';
|
||||||
import type { PostItem } from '../api/types';
|
import type { PostItem } from '../api/types';
|
||||||
import type { FeedSort } from './FeedSortBar';
|
import type { FeedSort } from './FeedSortBar';
|
||||||
|
import { useForumLimits } from '../hooks/useForumLimits';
|
||||||
import { formatTime } from '../utils/content';
|
import { formatTime } from '../utils/content';
|
||||||
import { postPath } from '../utils/permalink';
|
import { boardPath, postPath } from '../utils/permalink';
|
||||||
|
import { toPostImageThumbSrc } from '../utils/postContent';
|
||||||
import { excerptFromHTML, firstImageFromHTML } from '../utils/seoText';
|
import { excerptFromHTML, firstImageFromHTML } from '../utils/seoText';
|
||||||
import { parseTags } from './TagInput';
|
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
post: PostItem;
|
post: PostItem;
|
||||||
sort?: FeedSort;
|
sort?: FeedSort;
|
||||||
|
/** 当前板块 id,>0 时隐藏行内板块色标(避免板块页重复) */
|
||||||
|
boardId?: number;
|
||||||
onSelect: (id: number) => void;
|
onSelect: (id: number) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
function PostListItem({ post, sort = 'latest', onSelect }: Props) {
|
function PostListItem({ post, sort = 'latest', boardId = 0, onSelect }: Props) {
|
||||||
const nav = useNavigate();
|
const nav = useNavigate();
|
||||||
|
const { limits } = useForumLimits();
|
||||||
|
const feedStyle = limits.feed_list_style ?? 'title';
|
||||||
|
const showExcerpt = feedStyle === 'excerpt' || feedStyle === 'thumbnail';
|
||||||
|
const showThumb = feedStyle === 'thumbnail';
|
||||||
|
const titleOnly = feedStyle === 'title';
|
||||||
|
|
||||||
const initial = post.user?.nickname?.[0] || '?';
|
const initial = post.user?.nickname?.[0] || '?';
|
||||||
const timeLabel = sort === 'reply'
|
const timeLabel = sort === 'reply' && !post.last_reply_at
|
||||||
? (post.last_reply_at
|
? '暂无回复'
|
||||||
? `${formatTime(post.last_reply_at)} 回复`
|
|
||||||
: '暂无回复')
|
|
||||||
: formatTime(post.created_at);
|
: formatTime(post.created_at);
|
||||||
|
const lastReplyName = post.last_reply_user?.nickname?.trim()
|
||||||
|
|| post.last_reply_user?.username?.trim()
|
||||||
|
|| post.last_reply_guest_nick?.trim()
|
||||||
|
|| '';
|
||||||
|
const showLastReply = !!post.last_reply_at && (!!post.last_reply_user || !!lastReplyName);
|
||||||
const commentCount = post.comment_count ?? 0;
|
const commentCount = post.comment_count ?? 0;
|
||||||
const likeCount = post.like_count ?? 0;
|
|
||||||
const viewCount = post.view_count ?? 0;
|
|
||||||
const href = postPath(post.id);
|
const href = postPath(post.id);
|
||||||
const excerpt = excerptFromHTML(post.content || '', 72);
|
const firstImage = firstImageFromHTML(post.content || '');
|
||||||
const hasImage = !!firstImageFromHTML(post.content || '');
|
const thumbSrc = showThumb && firstImage ? toPostImageThumbSrc(firstImage) : null;
|
||||||
const tagList = parseTags(post.tags || '').slice(0, 3);
|
const excerpt = showExcerpt ? excerptFromHTML(post.content || '', 60) : '';
|
||||||
|
const showBoardBadge = !!post.board && boardId !== post.board.id;
|
||||||
|
|
||||||
const openPost = () => onSelect(post.id);
|
const openPost = () => onSelect(post.id);
|
||||||
const onKeyDown = (e: React.KeyboardEvent) => {
|
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||||
@@ -41,7 +52,6 @@ function PostListItem({ post, sort = 'latest', onSelect }: Props) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
const onTitleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
|
const onTitleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
|
||||||
// 修饰键 / 非左键:交给浏览器(新标签等)
|
|
||||||
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
|
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
return;
|
return;
|
||||||
@@ -51,9 +61,116 @@ function PostListItem({ post, sort = 'latest', 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 = (
|
||||||
|
<div className="post-title-row">
|
||||||
|
{post.pinned && (
|
||||||
|
<span className="post-pin-badge" title="全局置顶">全局置顶</span>
|
||||||
|
)}
|
||||||
|
{post.board_pinned && (
|
||||||
|
<span className="post-pin-badge post-pin-badge--board" title="板块置顶">板块置顶</span>
|
||||||
|
)}
|
||||||
|
{post.featured && (
|
||||||
|
<span className="post-feature-badge" title="推荐">
|
||||||
|
<FeaturedIcon size={12} />
|
||||||
|
推荐
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{post.status === 'pending' && (
|
||||||
|
<span className="post-status-badge post-status-badge--pending" title="审核中">审核中</span>
|
||||||
|
)}
|
||||||
|
{post.status === 'rejected' && (
|
||||||
|
<span className="post-status-badge post-status-badge--rejected" title="未通过">未通过</span>
|
||||||
|
)}
|
||||||
|
<a href={href} className="post-title" onClick={onTitleClick}>
|
||||||
|
{post.title}
|
||||||
|
</a>
|
||||||
|
{/* 类型徽章放标题后:flex 自动扣宽,长标题省略号紧挨徽章左侧 */}
|
||||||
|
{hasTypeBadge && (
|
||||||
|
<span className="post-title-type-badges">
|
||||||
|
{post.post_type === 'question' && (
|
||||||
|
<span
|
||||||
|
className={`post-qa-badge${post.question_resolved ? ' post-qa-badge--resolved' : ' post-qa-badge--open'}`}
|
||||||
|
title={post.question_resolved ? '已解决' : '未解决'}
|
||||||
|
>
|
||||||
|
{post.question_resolved ? '已解决' : '未解决'}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{post.post_type === 'poll' && (
|
||||||
|
<span className="post-type-badge post-type-badge--poll" title="投票">投票</span>
|
||||||
|
)}
|
||||||
|
{post.post_type === 'bounty' && post.bounty_status === 'open' && (post.bounty_points ?? 0) > 0 && (
|
||||||
|
<span className="post-bounty-badge post-bounty-badge--open" title="悬赏">悬赏 {post.bounty_points}</span>
|
||||||
|
)}
|
||||||
|
{post.post_type === 'bounty' && post.bounty_status === 'awarded' && (
|
||||||
|
<span className="post-bounty-badge post-bounty-badge--awarded" title="已采纳">已采纳</span>
|
||||||
|
)}
|
||||||
|
{post.post_type === 'lottery' && (
|
||||||
|
<span className="post-type-badge post-type-badge--lottery" title="抽奖">
|
||||||
|
{post.lottery_status === 'drawn' ? '已开奖' : '抽奖'}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
const metaLeft = (
|
||||||
|
<div className="post-meta-left">
|
||||||
|
{showBoardBadge && post.board && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="post-list-board-btn"
|
||||||
|
title={`进入板块:${post.board.name}`}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
nav(boardPath(post.board!.id, limits));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<BoardBadge board={post.board} className="post-list-board-badge" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<UserLink user={post.user} stopPropagation className="post-meta-author" showBadges={false} />
|
||||||
|
<span className="post-meta-sep post-meta-sep--before-time" aria-hidden>·</span>
|
||||||
|
<span className="post-meta-time post-meta-time--created">{timeLabel}</span>
|
||||||
|
{showLastReply && (
|
||||||
|
<span className="post-meta-last-reply">
|
||||||
|
<span className="post-meta-last-reply-arrow" aria-hidden>←</span>
|
||||||
|
{post.last_reply_user ? (
|
||||||
|
<UserLink
|
||||||
|
user={post.last_reply_user}
|
||||||
|
stopPropagation
|
||||||
|
className="post-meta-last-reply-user"
|
||||||
|
showBadges={false}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<span className="post-meta-last-reply-user">{lastReplyName}</span>
|
||||||
|
)}
|
||||||
|
<span className="post-meta-last-reply-time">{formatTime(post.last_reply_at!)}</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
const stats = (
|
||||||
|
<div className="post-stats">
|
||||||
|
<span className={`post-stat${commentCount === 0 ? ' post-stat--zero' : ''}`} title="评论">
|
||||||
|
<MessageCircle aria-hidden />
|
||||||
|
{commentCount}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="post-row"
|
className={`post-row post-row--v2${titleOnly ? ' post-row--title-only' : ''}${thumbSrc ? ' post-row--has-thumb' : ''}`}
|
||||||
role="link"
|
role="link"
|
||||||
tabIndex={0}
|
tabIndex={0}
|
||||||
onClick={openPost}
|
onClick={openPost}
|
||||||
@@ -71,88 +188,32 @@ function PostListItem({ post, sort = 'latest', onSelect }: Props) {
|
|||||||
: initial}
|
: initial}
|
||||||
</UserLink>
|
</UserLink>
|
||||||
|
|
||||||
<div className="post-body">
|
{thumbSrc ? (
|
||||||
<div className="post-head">
|
<div className="post-main post-main--with-thumb">
|
||||||
<div className="post-head-meta">
|
<div className="post-content">
|
||||||
<UserLink user={post.user} stopPropagation className="post-author" showBadges />
|
{titleRow}
|
||||||
<span className="post-head-dot" aria-hidden>·</span>
|
|
||||||
<span className="post-time">{timeLabel}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="post-title-row">
|
|
||||||
{post.pinned && (
|
|
||||||
<span className="post-pin-badge" title="全局置顶">全局置顶</span>
|
|
||||||
)}
|
|
||||||
{post.board_pinned && (
|
|
||||||
<span className="post-pin-badge post-pin-badge--board" title="板块置顶">板块置顶</span>
|
|
||||||
)}
|
|
||||||
{post.featured && (
|
|
||||||
<span className="post-feature-badge" title="精华">
|
|
||||||
<FeaturedIcon size={12} />
|
|
||||||
精华
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
{post.status === 'pending' && (
|
|
||||||
<span className="post-status-badge post-status-badge--pending" title="审核中">审核中</span>
|
|
||||||
)}
|
|
||||||
{post.status === 'rejected' && (
|
|
||||||
<span className="post-status-badge post-status-badge--rejected" title="未通过">未通过</span>
|
|
||||||
)}
|
|
||||||
{post.post_type === 'question' && (
|
|
||||||
<span
|
|
||||||
className={`post-qa-badge${post.question_resolved ? ' post-qa-badge--resolved' : ' post-qa-badge--open'}`}
|
|
||||||
title={post.question_resolved ? '已解决' : '未解决'}
|
|
||||||
>
|
|
||||||
{post.question_resolved ? '已解决' : '未解决'}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
<a href={href} className="post-title" onClick={onTitleClick}>
|
|
||||||
{post.title}
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{excerpt && <p className="post-excerpt">{excerpt}</p>}
|
{excerpt && <p className="post-excerpt">{excerpt}</p>}
|
||||||
|
<div className="post-meta post-meta--inline">{metaLeft}</div>
|
||||||
<div className="post-foot">
|
</div>
|
||||||
<div className="post-foot-left">
|
<div className="post-aside">
|
||||||
{post.board && <BoardBadge board={post.board} />}
|
<div className="post-thumb" aria-hidden>
|
||||||
{tagList.map(t => (
|
<img src={thumbSrc} alt="" loading="lazy" decoding="async" />
|
||||||
<button
|
</div>
|
||||||
key={t}
|
{stats}
|
||||||
type="button"
|
</div>
|
||||||
className="post-list-tag"
|
</div>
|
||||||
title={`筛选标签:${t}`}
|
) : (
|
||||||
onClick={(e) => {
|
<div className="post-main">
|
||||||
e.stopPropagation();
|
<div className="post-text">
|
||||||
nav(`/?tag=${encodeURIComponent(t)}`);
|
{titleRow}
|
||||||
}}
|
{excerpt && <p className="post-excerpt">{excerpt}</p>}
|
||||||
>
|
</div>
|
||||||
{t}
|
<div className="post-meta">
|
||||||
</button>
|
{metaLeft}
|
||||||
))}
|
{stats}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="post-stats">
|
|
||||||
{hasImage && (
|
|
||||||
<span className="post-stat post-stat--media" title="含图片">
|
|
||||||
<ImageIcon aria-hidden />
|
|
||||||
</span>
|
|
||||||
)}
|
)}
|
||||||
<span className={`post-stat${commentCount === 0 ? ' post-stat--zero' : ''}`} title="评论">
|
|
||||||
<MessageCircle aria-hidden />
|
|
||||||
{commentCount}
|
|
||||||
</span>
|
|
||||||
<span className={`post-stat${likeCount === 0 ? ' post-stat--zero' : ''}`} title="点赞">
|
|
||||||
<ThumbsUp aria-hidden />
|
|
||||||
{likeCount}
|
|
||||||
</span>
|
|
||||||
<span className={`post-stat${viewCount === 0 ? ' post-stat--zero' : ''}`} title="浏览">
|
|
||||||
<Eye aria-hidden />
|
|
||||||
{viewCount}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,37 +1,12 @@
|
|||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import type { ForumLimitsPublic } from '../api/types';
|
||||||
|
|
||||||
interface Props {
|
export type FeedListStyle = ForumLimitsPublic['feed_list_style'];
|
||||||
count?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 帖子列表加载骨架屏(对齐卡片式列表) */
|
/** 虚拟列表行高预估值 */
|
||||||
export default function PostListSkeleton({ count = 8 }: Props) {
|
export function feedListRowEstimate(style: FeedListStyle): number {
|
||||||
return (
|
switch (style) {
|
||||||
<div className="post-list-skeleton" aria-busy="true" aria-label="加载中">
|
case 'excerpt': return 68;
|
||||||
{Array.from({ length: count }, (_, i) => (
|
case 'thumbnail': return 72;
|
||||||
<div key={i} className="post-row post-row--skeleton">
|
default: return 64;
|
||||||
<Skeleton className="skeleton--avatar" />
|
}
|
||||||
<div className="post-body">
|
|
||||||
<div className="post-head">
|
|
||||||
<div className="skeleton-meta-row">
|
|
||||||
<Skeleton className="skeleton--meta" />
|
|
||||||
<Skeleton className="skeleton--meta skeleton--meta-short" />
|
|
||||||
</div>
|
|
||||||
{i % 4 === 0 && <Skeleton className="skeleton--badge" />}
|
|
||||||
</div>
|
|
||||||
<Skeleton className="skeleton--title" style={{ width: `${58 + (i % 4) * 9}%` }} />
|
|
||||||
<Skeleton className="skeleton--excerpt" style={{ width: `${72 + (i % 3) * 8}%` }} />
|
|
||||||
<div className="post-foot">
|
|
||||||
<Skeleton className="skeleton--badge" />
|
|
||||||
<div className="post-stats">
|
|
||||||
<Skeleton className="skeleton--stat" />
|
|
||||||
<Skeleton className="skeleton--stat" />
|
|
||||||
<Skeleton className="skeleton--stat" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
98
frontend/src/components/PostLotteryCard.tsx
Normal file
98
frontend/src/components/PostLotteryCard.tsx
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { Gift } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
} from '@/components/ui/alert-dialog';
|
||||||
|
import { notify } from '@/lib/notify';
|
||||||
|
import { api } from '../api/client';
|
||||||
|
import type { PostLotteryView } from '../api/types';
|
||||||
|
import { userPath } from '../utils/userPath';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
postId: number;
|
||||||
|
lottery: PostLotteryView;
|
||||||
|
isOwnerOrAdmin: boolean;
|
||||||
|
onUpdate: (lottery: PostLotteryView) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 抽奖帖信息卡 */
|
||||||
|
export default function PostLotteryCard({ postId, lottery, isOwnerOrAdmin, onUpdate }: Props) {
|
||||||
|
const [drawOpen, setDrawOpen] = useState(false);
|
||||||
|
const [drawing, setDrawing] = useState(false);
|
||||||
|
const drawn = lottery.status === 'drawn';
|
||||||
|
const canDraw = !drawn && isOwnerOrAdmin && lottery.participant_count >= lottery.winner_count;
|
||||||
|
|
||||||
|
const confirmDraw = async () => {
|
||||||
|
setDrawing(true);
|
||||||
|
try {
|
||||||
|
const r = await api.postLotteryDraw(postId);
|
||||||
|
onUpdate(r.lottery);
|
||||||
|
notify.success('开奖完成');
|
||||||
|
setDrawOpen(false);
|
||||||
|
} catch (e: unknown) {
|
||||||
|
notify.error(e instanceof Error ? e.message : '开奖失败');
|
||||||
|
} finally {
|
||||||
|
setDrawing(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<section className="post-lottery" aria-label="抽奖">
|
||||||
|
<div className="post-lottery__head">
|
||||||
|
<Gift size={18} aria-hidden />
|
||||||
|
<strong>{drawn ? '已开奖' : '抽奖进行中'}</strong>
|
||||||
|
<span>抽取 {lottery.winner_count} 人 · 当前 {lottery.participant_count} 人参与</span>
|
||||||
|
</div>
|
||||||
|
{!drawn && (
|
||||||
|
<p className="post-lottery__hint">回帖即可参与(楼主除外),由作者或管理员手动开奖</p>
|
||||||
|
)}
|
||||||
|
{drawn && lottery.winners && lottery.winners.length > 0 && (
|
||||||
|
<ul className="post-lottery__winners">
|
||||||
|
{lottery.winners.map(w => (
|
||||||
|
<li key={`${w.user_id}-${w.comment_id}`}>
|
||||||
|
<a href={userPath(w.user_id)}>{w.nickname || w.username}</a>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
{canDraw && (
|
||||||
|
<Button type="button" size="sm" onClick={() => setDrawOpen(true)}>立即开奖</Button>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
<AlertDialog
|
||||||
|
open={drawOpen}
|
||||||
|
onOpenChange={(next) => { if (!next && !drawing) setDrawOpen(false); }}
|
||||||
|
>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>立即开奖?</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
将从 {lottery.participant_count} 位参与者中抽取 {lottery.winner_count} 名中奖者。此操作不可撤销。
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel disabled={drawing}>取消</AlertDialogCancel>
|
||||||
|
<AlertDialogAction
|
||||||
|
disabled={drawing}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
void confirmDraw();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{drawing ? '开奖中…' : '确认开奖'}
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
189
frontend/src/components/PostManageMenu.tsx
Normal file
189
frontend/src/components/PostManageMenu.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
175
frontend/src/components/PostPollCard.tsx
Normal file
175
frontend/src/components/PostPollCard.tsx
Normal file
@@ -0,0 +1,175 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { BarChart3 } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { notify } from '@/lib/notify';
|
||||||
|
import { api } from '../api/client';
|
||||||
|
import type { PollView } from '../api/types';
|
||||||
|
import { useAuth } from '../hooks/useAuth';
|
||||||
|
import { formatDateTime } from '../utils/content';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
postId: number;
|
||||||
|
poll: PollView;
|
||||||
|
isOwnerOrAdmin: boolean;
|
||||||
|
onUpdate: (poll: PollView) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 投票帖投票卡 */
|
||||||
|
export default function PostPollCard({ postId, poll, isOwnerOrAdmin, onUpdate }: Props) {
|
||||||
|
const { user } = useAuth();
|
||||||
|
const [selected, setSelected] = useState<number[]>(poll.my_option_ids ?? []);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const voted = (poll.my_option_ids?.length ?? 0) > 0;
|
||||||
|
const showResults = poll.closed || voted;
|
||||||
|
const canVote = !voted && !poll.closed;
|
||||||
|
|
||||||
|
const headTitle = poll.closed
|
||||||
|
? '投票已结束'
|
||||||
|
: poll.multi
|
||||||
|
? `多选(最多 ${poll.max_choices} 项)`
|
||||||
|
: '单选投票';
|
||||||
|
|
||||||
|
const endsAtMs = poll.ends_at ? new Date(poll.ends_at).getTime() : NaN;
|
||||||
|
const expiredByDeadline = poll.closed && poll.ends_at && !Number.isNaN(endsAtMs) && endsAtMs <= Date.now();
|
||||||
|
|
||||||
|
const deadlineHint = poll.ends_at && !Number.isNaN(endsAtMs)
|
||||||
|
? poll.closed
|
||||||
|
? (expiredByDeadline ? `已于 ${formatDateTime(poll.ends_at)} 截止` : undefined)
|
||||||
|
: `截止于 ${formatDateTime(poll.ends_at)}`
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
const toggle = (id: number) => {
|
||||||
|
if (!canVote) return;
|
||||||
|
if (!user) {
|
||||||
|
notify.warning('请先登录');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (poll.multi) {
|
||||||
|
setSelected(prev => (
|
||||||
|
prev.includes(id)
|
||||||
|
? prev.filter(x => x !== id)
|
||||||
|
: [...prev, id].slice(0, poll.max_choices)
|
||||||
|
));
|
||||||
|
} else {
|
||||||
|
setSelected([id]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const submit = async () => {
|
||||||
|
if (!user) {
|
||||||
|
notify.warning('请先登录');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (selected.length === 0) {
|
||||||
|
notify.warning('请选择选项');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const r = await api.pollVote(postId, selected);
|
||||||
|
onUpdate(r.poll);
|
||||||
|
notify.success('投票成功');
|
||||||
|
} catch (e: unknown) {
|
||||||
|
notify.error(e instanceof Error ? e.message : '投票失败');
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const closePoll = async () => {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const r = await api.pollClose(postId);
|
||||||
|
onUpdate(r.poll);
|
||||||
|
notify.success('投票已结束');
|
||||||
|
} catch (e: unknown) {
|
||||||
|
notify.error(e instanceof Error ? e.message : '操作失败');
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="post-poll" aria-label="投票">
|
||||||
|
<div className="post-poll__head">
|
||||||
|
<BarChart3 size={18} aria-hidden />
|
||||||
|
<strong>{headTitle}</strong>
|
||||||
|
{deadlineHint && (
|
||||||
|
<span className="post-poll__deadline">{deadlineHint}</span>
|
||||||
|
)}
|
||||||
|
<span className="post-poll__meta">{poll.total_votes} 票</span>
|
||||||
|
</div>
|
||||||
|
<ul
|
||||||
|
className="post-poll__options"
|
||||||
|
role={poll.multi ? 'group' : 'radiogroup'}
|
||||||
|
aria-label="投票选项"
|
||||||
|
>
|
||||||
|
{poll.options.map(opt => {
|
||||||
|
const isActive = selected.includes(opt.id);
|
||||||
|
const isMine = poll.my_option_ids?.includes(opt.id);
|
||||||
|
return (
|
||||||
|
<li key={opt.id}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={[
|
||||||
|
'post-poll__option',
|
||||||
|
poll.multi ? 'post-poll__option--multi' : 'post-poll__option--single',
|
||||||
|
isActive ? 'active' : '',
|
||||||
|
showResults ? 'results' : '',
|
||||||
|
isMine ? 'mine' : '',
|
||||||
|
].filter(Boolean).join(' ')}
|
||||||
|
disabled={!canVote}
|
||||||
|
onClick={() => toggle(opt.id)}
|
||||||
|
role={poll.multi ? 'checkbox' : 'radio'}
|
||||||
|
aria-checked={isActive}
|
||||||
|
>
|
||||||
|
<span className="post-poll__option-main">
|
||||||
|
<span className="post-poll__option-indicator" aria-hidden />
|
||||||
|
<span className="post-poll__option-text">{opt.text}</span>
|
||||||
|
{showResults && (
|
||||||
|
<span className="post-poll__option-stat">
|
||||||
|
{opt.percent ?? 0}% · {opt.vote_count} 票
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
{showResults && (
|
||||||
|
<span className="post-poll__option-bar" aria-hidden>
|
||||||
|
<span
|
||||||
|
className="post-poll__option-fill"
|
||||||
|
style={{ width: `${opt.percent ?? 0}%` }}
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
<div className="post-poll__actions">
|
||||||
|
{canVote && user && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
disabled={busy || selected.length === 0}
|
||||||
|
onClick={submit}
|
||||||
|
>
|
||||||
|
提交投票
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{canVote && user && selected.length === 0 && (
|
||||||
|
<p className="post-poll__select-hint">
|
||||||
|
{poll.multi ? '请选择后提交' : '请选择一项后提交'}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{!user && canVote && (
|
||||||
|
<p className="post-poll__login-hint">登录后可参与投票</p>
|
||||||
|
)}
|
||||||
|
{isOwnerOrAdmin && !poll.closed && (
|
||||||
|
<Button type="button" variant="outline" size="sm" disabled={busy} onClick={closePoll}>
|
||||||
|
结束投票
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
121
frontend/src/components/ProjectListItem.tsx
Normal file
121
frontend/src/components/ProjectListItem.tsx
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
import { memo } from 'react';
|
||||||
|
import { GitFork, Star } from 'lucide-react';
|
||||||
|
import UserBadges from './UserBadges';
|
||||||
|
import UserLink from './UserLink';
|
||||||
|
import type { GiteaProject } from '../api/types';
|
||||||
|
import { formatTime } from '../utils/content';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
project: GiteaProject;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 开源码桶列表行:结构对齐帖子列表;作者一律用论坛用户,不展示 Gitea login */
|
||||||
|
function ProjectListItem({ project }: Props) {
|
||||||
|
const owner = project.owner;
|
||||||
|
// 未绑定论坛用户的仓库不应出现在列表;兜底不渲染
|
||||||
|
if (!owner?.id) return null;
|
||||||
|
|
||||||
|
const title = project.name || project.full_name;
|
||||||
|
const initial = owner.nickname?.[0] || '?';
|
||||||
|
const remoteIso = project.updated_at_remote ?? undefined;
|
||||||
|
const timeLabel = remoteIso ? formatTime(remoteIso) : '';
|
||||||
|
const stars = project.stars_count ?? 0;
|
||||||
|
const forks = project.forks_count ?? 0;
|
||||||
|
|
||||||
|
const open = () => {
|
||||||
|
if (!project.html_url) return;
|
||||||
|
window.open(project.html_url, '_blank', 'noopener,noreferrer');
|
||||||
|
};
|
||||||
|
|
||||||
|
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||||
|
if (e.key === 'Enter' || e.key === ' ') {
|
||||||
|
e.preventDefault();
|
||||||
|
open();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onTitleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
|
||||||
|
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
|
||||||
|
e.stopPropagation();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
open();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="post-row post-row--v2 project-list-item"
|
||||||
|
role="link"
|
||||||
|
tabIndex={0}
|
||||||
|
onClick={open}
|
||||||
|
onKeyDown={onKeyDown}
|
||||||
|
>
|
||||||
|
<UserLink
|
||||||
|
user={owner}
|
||||||
|
showAvatar={false}
|
||||||
|
showName={false}
|
||||||
|
stopPropagation
|
||||||
|
className="post-avatar user-link--avatar-only"
|
||||||
|
>
|
||||||
|
{owner.avatar
|
||||||
|
? <img src={owner.avatar} alt="" loading="lazy" decoding="async" />
|
||||||
|
: initial}
|
||||||
|
</UserLink>
|
||||||
|
|
||||||
|
<div className="post-main">
|
||||||
|
<div className="post-text">
|
||||||
|
<div className="post-title-row">
|
||||||
|
{project.language ? (
|
||||||
|
<span className="project-lang-badge" title="主要语言">{project.language}</span>
|
||||||
|
) : null}
|
||||||
|
<a
|
||||||
|
href={project.html_url}
|
||||||
|
className="post-title"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
onClick={onTitleClick}
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
{project.description ? (
|
||||||
|
<p className="post-excerpt">{project.description}</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div className="post-meta">
|
||||||
|
<div className="post-meta-left">
|
||||||
|
<UserLink
|
||||||
|
user={owner}
|
||||||
|
stopPropagation
|
||||||
|
className="post-meta-author"
|
||||||
|
showBadges={false}
|
||||||
|
/>
|
||||||
|
<UserBadges user={owner} compact maxAchievement={3} className="project-list-badges" />
|
||||||
|
{timeLabel ? (
|
||||||
|
<>
|
||||||
|
<span className="post-meta-sep post-meta-sep--before-time" aria-hidden>·</span>
|
||||||
|
<span className="post-meta-time post-meta-time--created" title={remoteIso}>
|
||||||
|
{timeLabel}
|
||||||
|
</span>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div className="post-stats">
|
||||||
|
<span className={`post-stat${stars === 0 ? ' post-stat--zero' : ''}`} title="Stars">
|
||||||
|
<Star aria-hidden />
|
||||||
|
{stars}
|
||||||
|
</span>
|
||||||
|
<span className={`post-stat${forks === 0 ? ' post-stat--zero' : ''}`} title="Forks">
|
||||||
|
<GitFork aria-hidden />
|
||||||
|
{forks}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default memo(ProjectListItem);
|
||||||
@@ -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(() => {
|
||||||
|
// 后台 / 登录页:整页 reload;前台:静默软刷新(无进度条,齐套后一次覆盖)
|
||||||
|
const isAdminOrAuth = !!(
|
||||||
|
document.querySelector('.admin-main')
|
||||||
|
|| document.querySelector('.auth-page')
|
||||||
|
);
|
||||||
|
if (isAdminOrAuth) {
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void softRefreshCurrentPage()
|
||||||
|
.catch(() => undefined)
|
||||||
|
.finally(() => {
|
||||||
|
setRefreshing(false);
|
||||||
|
setSettling(true);
|
||||||
|
setPull(0);
|
||||||
|
});
|
||||||
}, 180);
|
}, 180);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,17 @@
|
|||||||
import { ListTree, MessageCircle, MessagesSquare, Tags, Sparkles } from 'lucide-react';
|
import { useMemo } from 'react';
|
||||||
import { useLocation, useSearchParams } from 'react-router-dom';
|
import { ListTree, MessageCircle, Tags, Link2, UserPlus } from 'lucide-react';
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { useLocation, useSearchParams, useNavigate } from 'react-router-dom';
|
||||||
import type { PostItem, RecentComment, TagCount, User } 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';
|
||||||
import { formatShortDateTime, formatTime } from '../utils/content';
|
import { formatShortDateTime, formatTime } from '../utils/content';
|
||||||
|
import { resolveAsideWidgets } from '../utils/asideWidgets';
|
||||||
import TagCloud from './TagCloud';
|
import TagCloud from './TagCloud';
|
||||||
import UserLink from './UserLink';
|
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 ShowcaseAsideWidget from './ShowcaseAsideWidget';
|
||||||
|
|
||||||
export type PostDetailAside = {
|
export type PostDetailAside = {
|
||||||
author?: User | null;
|
author?: User | null;
|
||||||
@@ -20,60 +23,41 @@ export type PostDetailAside = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
hot: PostItem[];
|
|
||||||
recentComments: RecentComment[];
|
recentComments: RecentComment[];
|
||||||
|
recentUsers: RecentUser[];
|
||||||
tags?: TagCount[];
|
tags?: TagCount[];
|
||||||
tagsLoading?: boolean;
|
tagsLoading?: boolean;
|
||||||
|
stats?: ForumStats | null;
|
||||||
onPostClick: (id: number, opts?: { floor?: number }) => void;
|
onPostClick: (id: number, opts?: { floor?: number }) => void;
|
||||||
/** 首次拉取中,显示骨架避免空态闪烁 */
|
/** 首次拉取中:不渲染该块内容(由冷启动门闩保证首屏已齐或空白) */
|
||||||
loading?: boolean;
|
loading?: boolean;
|
||||||
|
/** 右侧栏可选组件顺序与开关 */
|
||||||
|
asideWidgets: AsideWidget[];
|
||||||
/** 帖子详情:右侧顶部展示作者与目录 */
|
/** 帖子详情:右侧顶部展示作者与目录 */
|
||||||
postDetail?: PostDetailAside | null;
|
postDetail?: PostDetailAside | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function ActiveSkeleton() {
|
|
||||||
return (
|
|
||||||
<div className="widget-skeleton" aria-busy="true" aria-label="正在聊加载中">
|
|
||||||
{Array.from({ length: 6 }, (_, i) => (
|
|
||||||
<div key={i} className="widget-item widget-item--active widget-item--skeleton">
|
|
||||||
<Skeleton className="skeleton--widget-title" style={{ width: `${62 + (i % 4) * 8}%` }} />
|
|
||||||
<Skeleton className="skeleton--widget-time" />
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function CommentSkeleton() {
|
|
||||||
return (
|
|
||||||
<div className="widget-skeleton" aria-busy="true" aria-label="评论加载中">
|
|
||||||
{Array.from({ length: 5 }, (_, i) => (
|
|
||||||
<div key={i} className="widget-item widget-item--comment widget-item--skeleton">
|
|
||||||
<Skeleton className="skeleton--widget-avatar" />
|
|
||||||
<Skeleton className="skeleton--widget-title" style={{ width: `${55 + (i % 3) * 12}%` }} />
|
|
||||||
<Skeleton className="skeleton--widget-time" />
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function RightPanel({
|
export default function RightPanel({
|
||||||
hot,
|
|
||||||
recentComments,
|
recentComments,
|
||||||
|
recentUsers,
|
||||||
tags = [],
|
tags = [],
|
||||||
tagsLoading = false,
|
tagsLoading = false,
|
||||||
|
stats = null,
|
||||||
onPostClick,
|
onPostClick,
|
||||||
loading = false,
|
loading = false,
|
||||||
|
asideWidgets,
|
||||||
postDetail = null,
|
postDetail = null,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const { branding } = useSiteBranding();
|
const { branding } = useSiteBranding();
|
||||||
|
const nav = useNavigate();
|
||||||
const loc = useLocation();
|
const loc = useLocation();
|
||||||
const [params] = useSearchParams();
|
const [params] = useSearchParams();
|
||||||
const activeTag = params.get('tag') || '';
|
const activeTag = params.get('tag') || '';
|
||||||
const hotList = hot?.slice(0, 8) ?? [];
|
|
||||||
const commentList = recentComments?.slice(0, 6) ?? [];
|
const commentList = recentComments?.slice(0, 6) ?? [];
|
||||||
// 站点首页:右侧品牌块承担唯一 h1;板块/搜索等页面由 Feed 标题作 h1
|
const userList = recentUsers?.slice(0, 8) ?? [];
|
||||||
|
const friendLinks = (branding.friend_links ?? []).filter(
|
||||||
|
(l: FriendLink) => l.name?.trim() && l.url?.trim(),
|
||||||
|
);
|
||||||
const isSiteHome = loc.pathname === '/'
|
const isSiteHome = loc.pathname === '/'
|
||||||
&& !params.get('board')
|
&& !params.get('board')
|
||||||
&& !params.get('keyword')
|
&& !params.get('keyword')
|
||||||
@@ -81,94 +65,64 @@ export default function RightPanel({
|
|||||||
&& !params.get('author');
|
&& !params.get('author');
|
||||||
const description = branding.description?.trim() || '';
|
const description = branding.description?.trim() || '';
|
||||||
const slogan = branding.slogan?.trim() || '';
|
const slogan = branding.slogan?.trim() || '';
|
||||||
// 有独立简介时展示简介;否则用欢迎语,避免与页脚 slogan 三连重复
|
const introText = description || slogan;
|
||||||
const aboutText = description || '欢迎参与讨论,发帖、评论,一起把小圈子聊热。';
|
|
||||||
// 有近期讨论则展示「正在聊」;否则显示欢迎引导
|
|
||||||
const showActive = loading || hotList.length > 0;
|
|
||||||
const showWelcome = !loading && hotList.length === 0;
|
|
||||||
const isPostDetail = !!postDetail;
|
const isPostDetail = !!postDetail;
|
||||||
|
|
||||||
|
const enabledWidgets = useMemo(
|
||||||
|
() => resolveAsideWidgets({
|
||||||
|
aside_widgets: asideWidgets,
|
||||||
|
aside_show_tag_cloud: false,
|
||||||
|
aside_show_recent_comments: false,
|
||||||
|
aside_show_friend_links: false,
|
||||||
|
}).filter(w => w.enabled),
|
||||||
|
[asideWidgets],
|
||||||
|
);
|
||||||
|
|
||||||
|
const renderWidget = (widget: AsideWidget) => {
|
||||||
|
switch (widget.id) {
|
||||||
|
case 'showcase':
|
||||||
|
return <ShowcaseAsideWidget key="showcase" />;
|
||||||
|
case 'friend_links':
|
||||||
return (
|
return (
|
||||||
<div className={`aside-panel-inner${isPostDetail ? ' aside-panel-inner--post-detail' : ''}`}>
|
<div key="friend_links" className="widget-card widget-card--friend-links">
|
||||||
{isPostDetail && (
|
<div className="widget-card-head widget-card-head--split">
|
||||||
|
<span className="widget-card-head-main">
|
||||||
|
<Link2 className="widget-card-icon widget-card-icon--links" aria-hidden />
|
||||||
|
<button type="button" className="widget-friend-links-title" onClick={() => nav('/links')}>
|
||||||
|
友情链接
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
<a href="/links?apply=1" className="widget-friend-links-apply">
|
||||||
|
申请
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
<div className="widget-card-body widget-card-body--friend-links">
|
||||||
|
{friendLinks.length === 0 ? (
|
||||||
|
<div className="widget-empty">暂无友情链接</div>
|
||||||
|
) : (
|
||||||
<>
|
<>
|
||||||
<PostAuthorCard
|
<ul className="widget-friend-links-list">
|
||||||
author={postDetail.author}
|
{friendLinks.slice(0, 8).map((link: FriendLink) => (
|
||||||
publishedAt={postDetail.publishedAt}
|
<li key={`${link.name}-${link.url}`}>
|
||||||
viewCount={postDetail.viewCount}
|
<a href={link.url} target="_blank" rel="noopener noreferrer" title={link.name}>
|
||||||
/>
|
{link.name}
|
||||||
<div className="widget-card widget-card--outline">
|
</a>
|
||||||
<div className="widget-card-head">
|
</li>
|
||||||
<ListTree className="widget-card-icon widget-card-icon--outline" aria-hidden />
|
))}
|
||||||
{postDetail.outlineTitle || '文章目录'}
|
</ul>
|
||||||
</div>
|
{friendLinks.length > 8 && (
|
||||||
<div className="widget-card-body widget-outline-body">
|
<button type="button" className="widget-friend-links-more" onClick={() => nav('/links')}>
|
||||||
<ArticleOutline
|
查看全部 {friendLinks.length} 个
|
||||||
headings={postDetail.headings}
|
</button>
|
||||||
scrollRoot={postDetail.scrollRoot}
|
)}
|
||||||
title={postDetail.outlineTitle || '文章目录'}
|
|
||||||
className="article-outline--aside"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!isPostDetail && showWelcome && (
|
|
||||||
<div className="widget-card widget-card--welcome">
|
|
||||||
<div className="widget-card-head">
|
|
||||||
<Sparkles className="widget-card-icon widget-card-icon--welcome" aria-hidden />
|
|
||||||
加入讨论
|
|
||||||
</div>
|
|
||||||
<div className="widget-card-body widget-welcome-body">
|
|
||||||
<p>社区还在起步,每条回复都很珍贵。</p>
|
|
||||||
<ul>
|
|
||||||
<li>逛逛板块,找到感兴趣的话题</li>
|
|
||||||
<li>游客也能评论,登录可点赞收藏</li>
|
|
||||||
<li>发一篇帖,留下你的痕迹</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
|
|
||||||
{!isPostDetail && showActive && (
|
|
||||||
<div className="widget-card">
|
|
||||||
<div className="widget-card-head">
|
|
||||||
<MessagesSquare className="widget-card-icon widget-card-icon--hot" aria-hidden />
|
|
||||||
正在聊
|
|
||||||
</div>
|
|
||||||
<div className="widget-card-body">
|
|
||||||
{loading && hotList.length === 0 ? (
|
|
||||||
<ActiveSkeleton />
|
|
||||||
) : hotList.length === 0 ? (
|
|
||||||
<div className="widget-empty">近 7 日暂无新回复</div>
|
|
||||||
) : hotList.map((item) => {
|
|
||||||
const replyLabel = item.last_reply_at
|
|
||||||
? `${formatTime(item.last_reply_at)}有人回`
|
|
||||||
: '近期有讨论';
|
|
||||||
const count = item.comment_count ?? 0;
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
key={item.id}
|
|
||||||
type="button"
|
|
||||||
className="widget-item widget-item--active"
|
|
||||||
onClick={() => onPostClick(item.id)}
|
|
||||||
title={item.title}
|
|
||||||
>
|
|
||||||
<span className="widget-item-title">{item.title}</span>
|
|
||||||
<span className="widget-item-meta">
|
|
||||||
<span className="widget-item-time">{replyLabel}</span>
|
|
||||||
{count > 0 && <span className="widget-item-count">{count} 评</span>}
|
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
);
|
);
|
||||||
})}
|
case 'tag_cloud':
|
||||||
</div>
|
return (
|
||||||
</div>
|
<div key="tag_cloud" className="widget-card widget-card--tags">
|
||||||
)}
|
|
||||||
|
|
||||||
{!isPostDetail && (
|
|
||||||
<div className="widget-card widget-card--tags">
|
|
||||||
<div className="widget-card-head">
|
<div className="widget-card-head">
|
||||||
<Tags className="widget-card-icon widget-card-icon--tags" aria-hidden />
|
<Tags className="widget-card-icon widget-card-icon--tags" aria-hidden />
|
||||||
标签云
|
标签云
|
||||||
@@ -177,18 +131,16 @@ export default function RightPanel({
|
|||||||
<TagCloud tags={tags} loading={tagsLoading} activeTag={activeTag} />
|
<TagCloud tags={tags} loading={tagsLoading} activeTag={activeTag} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
);
|
||||||
|
case 'recent_comments':
|
||||||
{!isPostDetail && (
|
return (
|
||||||
<div className="widget-card">
|
<div key="recent_comments" className="widget-card">
|
||||||
<div className="widget-card-head">
|
<div className="widget-card-head">
|
||||||
<MessageCircle className="widget-card-icon widget-card-icon--notice" aria-hidden />
|
<MessageCircle className="widget-card-icon widget-card-icon--notice" aria-hidden />
|
||||||
最新评论
|
最新评论
|
||||||
</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
|
||||||
@@ -221,12 +173,87 @@ export default function RightPanel({
|
|||||||
onClick={() => onPostClick(item.post_id, item.floor > 0 ? { floor: item.floor } : undefined)}
|
onClick={() => onPostClick(item.post_id, item.floor > 0 ? { floor: item.floor } : undefined)}
|
||||||
>
|
>
|
||||||
<span className="widget-item-title">{item.excerpt}</span>
|
<span className="widget-item-title">{item.excerpt}</span>
|
||||||
<span className="widget-item-time">{formatShortDateTime(item.created_at)}</span>
|
<span className="widget-item-meta">
|
||||||
|
<span
|
||||||
|
className="widget-item-time"
|
||||||
|
title={formatShortDateTime(item.created_at)}
|
||||||
|
>
|
||||||
|
{formatTime(item.created_at)}
|
||||||
|
</span>
|
||||||
|
{item.post_title && (
|
||||||
|
<span className="widget-item-post-title">{item.post_title}</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
);
|
||||||
|
case 'recent_users':
|
||||||
|
return (
|
||||||
|
<div key="recent_users" className="widget-card widget-card--users">
|
||||||
|
<div className="widget-card-head">
|
||||||
|
<UserPlus className="widget-card-icon widget-card-icon--users" aria-hidden />
|
||||||
|
最新注册
|
||||||
|
</div>
|
||||||
|
<div className="widget-card-body widget-card-body--users">
|
||||||
|
{loading && userList.length === 0 ? null : userList.length === 0 ? (
|
||||||
|
<div className="widget-empty">暂无用户</div>
|
||||||
|
) : (
|
||||||
|
<div className="widget-recent-users-grid">
|
||||||
|
{userList.map(item => (
|
||||||
|
<UserLink
|
||||||
|
key={item.id}
|
||||||
|
user={{ id: item.id, nickname: item.nickname, avatar: item.avatar }}
|
||||||
|
className="widget-recent-user-cell"
|
||||||
|
showBadges={false}
|
||||||
|
title={item.nickname}
|
||||||
|
>
|
||||||
|
<span className="widget-recent-user-avatar" aria-hidden>
|
||||||
|
{item.avatar
|
||||||
|
? <img src={item.avatar} alt="" loading="lazy" decoding="async" />
|
||||||
|
: (item.nickname?.[0] || '?')}
|
||||||
|
</span>
|
||||||
|
<span className="widget-recent-user-name">{item.nickname}</span>
|
||||||
|
</UserLink>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`aside-panel-inner${isPostDetail ? ' aside-panel-inner--post-detail' : ''}`}>
|
||||||
|
{isPostDetail && (
|
||||||
|
<>
|
||||||
|
{postDetail.author?.id ? (
|
||||||
|
<PostAuthorCard
|
||||||
|
author={postDetail.author}
|
||||||
|
publishedAt={postDetail.publishedAt}
|
||||||
|
viewCount={postDetail.viewCount}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
<div className="widget-card widget-card--outline">
|
||||||
|
<div className="widget-card-head">
|
||||||
|
<ListTree className="widget-card-icon widget-card-icon--outline" aria-hidden />
|
||||||
|
{postDetail.outlineTitle || '文章目录'}
|
||||||
|
</div>
|
||||||
|
<div className="widget-card-body widget-outline-body">
|
||||||
|
<ArticleOutline
|
||||||
|
headings={postDetail.headings}
|
||||||
|
scrollRoot={postDetail.scrollRoot}
|
||||||
|
title={postDetail.outlineTitle || '文章目录'}
|
||||||
|
className="article-outline--aside"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!isPostDetail && (
|
{!isPostDetail && (
|
||||||
@@ -238,14 +265,32 @@ export default function RightPanel({
|
|||||||
) : (
|
) : (
|
||||||
<p className="widget-about-title">{branding.name}</p>
|
<p className="widget-about-title">{branding.name}</p>
|
||||||
)}
|
)}
|
||||||
<p className="widget-about-desc">{aboutText}</p>
|
{introText && (
|
||||||
{description && slogan && slogan !== description && (
|
<p className="widget-about-desc">{introText}</p>
|
||||||
<p className="widget-about-slogan">{slogan}</p>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
{stats && (
|
||||||
|
<div className="widget-stats" aria-label="论坛统计">
|
||||||
|
<div className="widget-stat">
|
||||||
|
<span className="widget-stat-value">{stats.posts}</span>
|
||||||
|
<span className="widget-stat-label">帖子</span>
|
||||||
|
</div>
|
||||||
|
<div className="widget-stat">
|
||||||
|
<span className="widget-stat-value">{stats.comments}</span>
|
||||||
|
<span className="widget-stat-label">回复</span>
|
||||||
|
</div>
|
||||||
|
<div className="widget-stat">
|
||||||
|
<span className="widget-stat-value">{stats.users}</span>
|
||||||
|
<span className="widget-stat-label">用户</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
<AsideCheckInStrip />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isPostDetail && enabledWidgets.map(renderWidget)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
124
frontend/src/components/ShowcaseAsideWidget.tsx
Normal file
124
frontend/src/components/ShowcaseAsideWidget.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,20 +1,23 @@
|
|||||||
import {
|
import {
|
||||||
Home, Star, LayoutDashboard, FolderGit2, FolderKanban, ArrowLeft,
|
Home, Star, LayoutDashboard, FolderGit2, FolderKanban, ArrowLeft, FileText, Link2, Globe2,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { useNavigate, useLocation, useSearchParams } from 'react-router-dom';
|
import { useNavigate, useLocation, useSearchParams, Link } from 'react-router-dom';
|
||||||
import type { Board } from '../api/types';
|
import type { 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';
|
||||||
|
import { useSitePages } from '../hooks/useSitePages';
|
||||||
|
import { pagePath } from '../utils/permalink';
|
||||||
|
import { useForumLimits } from '../hooks/useForumLimits';
|
||||||
|
|
||||||
// 内容页不参与左侧栏高亮(非 feed 浏览上下文)
|
// 内容页不参与左侧栏高亮(非 feed 浏览上下文)
|
||||||
const NEUTRAL_SIDEBAR_PREFIXES = ['/post/', '/profile', '/user/'];
|
const NEUTRAL_SIDEBAR_PREFIXES = ['/post/', '/profile', '/user/', '/page/'];
|
||||||
|
|
||||||
export function isNeutralSidebarRoute(pathname: string): boolean {
|
export function isNeutralSidebarRoute(pathname: string): boolean {
|
||||||
return NEUTRAL_SIDEBAR_PREFIXES.some(prefix => pathname.startsWith(prefix));
|
return NEUTRAL_SIDEBAR_PREFIXES.some(prefix => pathname.startsWith(prefix));
|
||||||
@@ -26,6 +29,9 @@ function resolveMenuKey(pathname: string, activeBoard: number, keyword = ''): st
|
|||||||
if (keyword.trim()) return null;
|
if (keyword.trim()) return null;
|
||||||
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('/showcase')) return 'showcase';
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
@@ -56,12 +62,43 @@ 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 { limits } = useForumLimits();
|
||||||
|
const sort = parseFeedSort(params.get('sort'), limits.feed_sort_tabs);
|
||||||
|
const showFriendLinksNav = limits.nav_show_friend_links !== false;
|
||||||
|
const showShowcaseNav = !!limits.nav_show_showcase;
|
||||||
|
const showSiteSection = navPages.length > 0 || showFriendLinksNav || showShowcaseNav;
|
||||||
|
|
||||||
const keyword = params.get('keyword') || '';
|
const keyword = params.get('keyword') || '';
|
||||||
const menuKey = resolveMenuKey(loc.pathname, activeBoard, keyword);
|
const menuKey = resolveMenuKey(loc.pathname, activeBoard, keyword);
|
||||||
|
const permalinkOpts = { permalink: limits };
|
||||||
|
|
||||||
|
const feedNavLink = (
|
||||||
|
key: string,
|
||||||
|
to: string,
|
||||||
|
label: React.ReactNode,
|
||||||
|
icon: React.ReactNode,
|
||||||
|
selectId: number,
|
||||||
|
className?: string,
|
||||||
|
trailing?: React.ReactNode,
|
||||||
|
) => (
|
||||||
|
<Link
|
||||||
|
key={key}
|
||||||
|
to={to}
|
||||||
|
className={cn('sidebar-nav-item', className, menuKey != null && menuKey === key && 'active')}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
onSelectBoard(selectId);
|
||||||
|
navigateFeed(nav, to);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{icon}
|
||||||
|
<span className="flex-1 truncate">{label}</span>
|
||||||
|
{trailing}
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
|
||||||
const navItem = (key: string, label: React.ReactNode, icon?: React.ReactNode, onClick?: () => void) => (
|
const navItem = (key: string, label: React.ReactNode, icon?: React.ReactNode, onClick?: () => void) => (
|
||||||
<button
|
<button
|
||||||
@@ -99,23 +136,13 @@ export default function Sidebar({
|
|||||||
<aside className="sidebar">
|
<aside className="sidebar">
|
||||||
<div className="sidebar-section">浏览</div>
|
<div className="sidebar-section">浏览</div>
|
||||||
<nav className="sidebar-nav">
|
<nav className="sidebar-nav">
|
||||||
{navItem('all', '全部帖子', <Home aria-hidden />, () => { onSelectBoard(0); navigateFeed(nav, buildHomeUrl(0, sort)); })}
|
{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>
|
||||||
@@ -123,29 +150,27 @@ export default function Sidebar({
|
|||||||
{boards.map(b => {
|
{boards.map(b => {
|
||||||
const isActive = menuKey != null && menuKey === String(b.id);
|
const isActive = menuKey != null && menuKey === String(b.id);
|
||||||
const themeIdx = getBoardThemeIndex(b);
|
const themeIdx = getBoardThemeIndex(b);
|
||||||
return (
|
const boardUrl = buildHomeUrl(b.id, sort, permalinkOpts);
|
||||||
<button
|
const postMeta = (b.post_count ?? 0) > 0 ? (
|
||||||
type="button"
|
|
||||||
key={b.id}
|
|
||||||
className={cn(
|
|
||||||
'sidebar-nav-item',
|
|
||||||
'sidebar-nav-item--board',
|
|
||||||
isActive && 'active',
|
|
||||||
isActive && `sidebar-nav-item--board-${themeIdx}`,
|
|
||||||
)}
|
|
||||||
onClick={() => { onSelectBoard(b.id); navigateFeed(nav, buildHomeUrl(b.id, sort)); }}
|
|
||||||
>
|
|
||||||
<BoardIconDisplay
|
|
||||||
board={b}
|
|
||||||
className={cn('sidebar-board-icon', `sidebar-board-icon--${themeIdx}`)}
|
|
||||||
/>
|
|
||||||
<span className="flex-1 truncate">{b.name}</span>
|
|
||||||
{(b.post_count ?? 0) > 0 && (
|
|
||||||
<span className="sidebar-nav-item__meta" title={`${b.post_count} 篇帖子`}>
|
<span className="sidebar-nav-item__meta" title={`${b.post_count} 篇帖子`}>
|
||||||
{b.post_count} 帖
|
{b.post_count} 帖
|
||||||
</span>
|
</span>
|
||||||
)}
|
) : null;
|
||||||
</button>
|
return feedNavLink(
|
||||||
|
String(b.id),
|
||||||
|
boardUrl,
|
||||||
|
b.name,
|
||||||
|
<BoardIconDisplay
|
||||||
|
board={b}
|
||||||
|
className={cn('sidebar-board-icon', `sidebar-board-icon--${themeIdx}`)}
|
||||||
|
/>,
|
||||||
|
b.id,
|
||||||
|
cn(
|
||||||
|
'sidebar-nav-item--board',
|
||||||
|
isActive && 'active',
|
||||||
|
isActive && `sidebar-nav-item--board-${themeIdx}`,
|
||||||
|
),
|
||||||
|
postMeta,
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</nav>
|
</nav>
|
||||||
@@ -159,6 +184,19 @@ export default function Sidebar({
|
|||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
{showSiteSection && (
|
||||||
|
<>
|
||||||
|
<div className="sidebar-section sidebar-section--spaced">站点</div>
|
||||||
|
<nav className="sidebar-nav">
|
||||||
|
{showFriendLinksNav && navItem('links', '友情链接', <Link2 aria-hidden />, () => void transitionTo(nav, '/links'))}
|
||||||
|
{showShowcaseNav && navItem('showcase', '开源展柜', <Globe2 aria-hidden />, () => void transitionTo(nav, '/showcase'))}
|
||||||
|
{navPages.map(p => (
|
||||||
|
navItem(`page-${p.slug}`, p.title, <FileText aria-hidden />, () => void transitionTo(nav, pagePath(p.slug, limits)))
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
{isAdmin && (
|
{isAdmin && (
|
||||||
<>
|
<>
|
||||||
<div className="sidebar-section sidebar-section--spaced">管理</div>
|
<div className="sidebar-section sidebar-section--spaced">管理</div>
|
||||||
|
|||||||
@@ -1,18 +1,60 @@
|
|||||||
import { useSiteBranding } from '../hooks/useSiteBranding';
|
import { useSiteBranding } from '../hooks/useSiteBranding';
|
||||||
import { useMediaQuery } from '../hooks/useTheme';
|
import { useMediaQuery } from '../hooks/useTheme';
|
||||||
import type { FriendLink } from '../api/types';
|
import { Link } from 'react-router-dom';
|
||||||
|
import { useSitePages } from '../hooks/useSitePages';
|
||||||
|
import { pagePath } from '../utils/permalink';
|
||||||
|
import { useForumLimits } from '../hooks/useForumLimits';
|
||||||
|
|
||||||
function FooterSep() {
|
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 { limits } = useForumLimits();
|
||||||
const year = new Date().getFullYear();
|
const year = new Date().getFullYear();
|
||||||
const links = Array.isArray(branding.friend_links) ? branding.friend_links : [];
|
|
||||||
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">
|
||||||
@@ -29,31 +71,11 @@ export default function SiteFooter() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{(links.length > 0 || icp) && (
|
|
||||||
<nav className="site-footer__nav" aria-label="站点链接">
|
<nav className="site-footer__nav" aria-label="站点链接">
|
||||||
{links.map((link: FriendLink, i) => (
|
{navItems.flatMap((node, i) =>
|
||||||
<span key={`${link.name}-${link.url}`} className="site-footer__friend">
|
i === 0 ? [node] : [<FooterSep key={`sep-${i}`} />, node],
|
||||||
{i > 0 && <FooterSep />}
|
|
||||||
<a href={link.url} target="_blank" rel="noopener noreferrer">
|
|
||||||
{link.name}
|
|
||||||
</a>
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
{icp && (
|
|
||||||
<>
|
|
||||||
{links.length > 0 && <FooterSep />}
|
|
||||||
<a
|
|
||||||
href={icpURL}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener noreferrer"
|
|
||||||
className="site-footer__icp"
|
|
||||||
>
|
|
||||||
{icp}
|
|
||||||
</a>
|
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
</nav>
|
</nav>
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
);
|
);
|
||||||
|
|||||||
227
frontend/src/components/StaticFeedList.tsx
Normal file
227
frontend/src/components/StaticFeedList.tsx
Normal 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(/ /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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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) {
|
||||||
|
|||||||
75
frontend/src/components/TopProgressBar.tsx
Normal file
75
frontend/src/components/TopProgressBar.tsx
Normal 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
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -4,14 +4,17 @@ 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 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';
|
||||||
|
import { useForumLimits } from '../hooks/useForumLimits';
|
||||||
import { useMediaQuery } from '../hooks/useTheme';
|
import { useMediaQuery } from '../hooks/useTheme';
|
||||||
import { loginPath } from '../utils/authRedirect';
|
import { loginPath } from '../utils/authRedirect';
|
||||||
|
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[];
|
||||||
@@ -32,6 +35,13 @@ interface Props {
|
|||||||
onScrollRestored?: () => void;
|
onScrollRestored?: () => void;
|
||||||
/** 搜索关键词(用于空态文案) */
|
/** 搜索关键词(用于空态文案) */
|
||||||
keyword?: string;
|
keyword?: string;
|
||||||
|
/** 是否为帖子搜索(区别于标签筛选) */
|
||||||
|
isSearchMode?: boolean;
|
||||||
|
searchKeyword?: string;
|
||||||
|
searchAuthor?: string;
|
||||||
|
searchTitleOnly?: boolean;
|
||||||
|
searchScopeBoardId?: number;
|
||||||
|
onClearSearch?: () => void;
|
||||||
/** 当前板块 id,0 表示全部 */
|
/** 当前板块 id,0 表示全部 */
|
||||||
boardId?: number;
|
boardId?: number;
|
||||||
/** 当前板块名 */
|
/** 当前板块名 */
|
||||||
@@ -47,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,
|
||||||
@@ -61,13 +71,22 @@ export default function VirtualPostList({
|
|||||||
onScrollTopChange,
|
onScrollTopChange,
|
||||||
onScrollRestored,
|
onScrollRestored,
|
||||||
keyword = '',
|
keyword = '',
|
||||||
|
isSearchMode = false,
|
||||||
|
searchKeyword = '',
|
||||||
|
searchAuthor = '',
|
||||||
|
searchTitleOnly = false,
|
||||||
|
searchScopeBoardId = 0,
|
||||||
|
onClearSearch,
|
||||||
boardId = 0,
|
boardId = 0,
|
||||||
boardName = '',
|
boardName = '',
|
||||||
noBoards = false,
|
noBoards = false,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const nav = useNavigate();
|
const nav = useNavigate();
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
|
const { limits } = useForumLimits();
|
||||||
const isMobile = useMediaQuery('(max-width: 768px)');
|
const isMobile = useMediaQuery('(max-width: 768px)');
|
||||||
|
const feedStyle = limits.feed_list_style ?? 'title';
|
||||||
|
const rowEstimate = feedListRowEstimate(feedStyle);
|
||||||
const parentRef = useRef<HTMLDivElement>(null);
|
const parentRef = useRef<HTMLDivElement>(null);
|
||||||
const restoredRef = useRef(false);
|
const restoredRef = useRef(false);
|
||||||
const onScrollTopChangeRef = useRef(onScrollTopChange);
|
const onScrollTopChangeRef = useRef(onScrollTopChange);
|
||||||
@@ -116,7 +135,7 @@ export default function VirtualPostList({
|
|||||||
const virtualizer = useVirtualizer({
|
const virtualizer = useVirtualizer({
|
||||||
count: posts.length,
|
count: posts.length,
|
||||||
getScrollElement,
|
getScrollElement,
|
||||||
estimateSize: () => 108,
|
estimateSize: () => rowEstimate,
|
||||||
overscan: 8,
|
overscan: 8,
|
||||||
scrollMargin: isMobile ? scrollMargin : 0,
|
scrollMargin: isMobile ? scrollMargin : 0,
|
||||||
measureElement:
|
measureElement:
|
||||||
@@ -128,7 +147,7 @@ export default function VirtualPostList({
|
|||||||
const showEnd = !hasMore && !showPagination && posts.length > 0 && !loading;
|
const showEnd = !hasMore && !showPagination && posts.length > 0 && !loading;
|
||||||
const isInitialLoad = loading && posts.length === 0;
|
const isInitialLoad = loading && posts.length === 0;
|
||||||
const isEmpty = !loading && posts.length === 0;
|
const isEmpty = !loading && posts.length === 0;
|
||||||
const isSearchEmpty = isEmpty && !!keyword.trim();
|
const isSearchEmpty = isEmpty && (isSearchMode || !!keyword.trim());
|
||||||
const composeTarget = boardId > 0 ? `/compose?board=${boardId}` : '/compose';
|
const composeTarget = boardId > 0 ? `/compose?board=${boardId}` : '/compose';
|
||||||
const isAdmin = user?.role === 'admin';
|
const isAdmin = user?.role === 'admin';
|
||||||
|
|
||||||
@@ -143,6 +162,12 @@ export default function VirtualPostList({
|
|||||||
onScrollTopChangeRef.current?.(0);
|
onScrollTopChangeRef.current?.(0);
|
||||||
}, [resetScrollKey, virtualizer, getScrollElement]);
|
}, [resetScrollKey, virtualizer, getScrollElement]);
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
// 收到新的恢复目标时允许再次 restore;null 表示已消费,勿动标记
|
||||||
|
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();
|
||||||
@@ -155,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;
|
||||||
@@ -169,6 +190,12 @@ export default function VirtualPostList({
|
|||||||
return () => el.removeEventListener('scroll', onScroll);
|
return () => el.removeEventListener('scroll', onScroll);
|
||||||
}, [getScrollElement, isMobile]);
|
}, [getScrollElement, isMobile]);
|
||||||
|
|
||||||
|
const searchSummaryParts: string[] = [];
|
||||||
|
if (searchKeyword.trim()) searchSummaryParts.push(`关键词「${searchKeyword.trim()}」`);
|
||||||
|
if (searchAuthor.trim()) searchSummaryParts.push(`作者 ${searchAuthor.trim()}`);
|
||||||
|
if (searchTitleOnly && searchKeyword.trim()) searchSummaryParts.push('仅标题');
|
||||||
|
if (searchScopeBoardId > 0 && boardName) searchSummaryParts.push(`板块 ${boardName}`);
|
||||||
|
|
||||||
const emptyActions = (
|
const emptyActions = (
|
||||||
<div className="empty-feed-actions">
|
<div className="empty-feed-actions">
|
||||||
{noBoards ? (
|
{noBoards ? (
|
||||||
@@ -183,12 +210,15 @@ export default function VirtualPostList({
|
|||||||
)
|
)
|
||||||
) : isSearchEmpty ? (
|
) : isSearchEmpty ? (
|
||||||
<>
|
<>
|
||||||
|
<Button type="button" size="sm" variant="outline" onClick={dispatchOpenPostSearch}>
|
||||||
|
修改搜索
|
||||||
|
</Button>
|
||||||
|
<Button type="button" size="sm" variant="outline" onClick={() => (onClearSearch ? onClearSearch() : nav('/'))}>
|
||||||
|
清除筛选
|
||||||
|
</Button>
|
||||||
<Button type="button" size="sm" variant="outline" onClick={() => nav('/')}>
|
<Button type="button" size="sm" variant="outline" onClick={() => nav('/')}>
|
||||||
返回全部帖子
|
返回全部帖子
|
||||||
</Button>
|
</Button>
|
||||||
<Button type="button" size="sm" onClick={() => nav(user ? composeTarget : loginPath(composeTarget))}>
|
|
||||||
{user ? '发帖' : '登录后发帖'}
|
|
||||||
</Button>
|
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
@@ -213,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 />
|
|
||||||
) : 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} />
|
||||||
@@ -231,7 +259,9 @@ export default function VirtualPostList({
|
|||||||
{noBoards
|
{noBoards
|
||||||
? (isAdmin ? '创建第一个板块后即可开始发帖' : '管理员创建板块后即可参与讨论')
|
? (isAdmin ? '创建第一个板块后即可开始发帖' : '管理员创建板块后即可参与讨论')
|
||||||
: isSearchEmpty
|
: isSearchEmpty
|
||||||
? '试试更短的关键词,或浏览标签云 / 板块'
|
? (searchSummaryParts.length > 0
|
||||||
|
? `当前筛选:${searchSummaryParts.join(' · ')}。试试更短的关键词或放宽条件。`
|
||||||
|
: '试试更短的关键词,或浏览标签云 / 板块')
|
||||||
: boardName
|
: boardName
|
||||||
? `「${boardName}」还没有内容,来发第一篇吧`
|
? `「${boardName}」还没有内容,来发第一篇吧`
|
||||||
: '换个板块看看,或发第一篇内容'}
|
: '换个板块看看,或发第一篇内容'}
|
||||||
@@ -259,7 +289,7 @@ export default function VirtualPostList({
|
|||||||
transform: `translateY(${offsetY}px)`,
|
transform: `translateY(${offsetY}px)`,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<PostListItem post={post} sort={sort} onSelect={onSelect} />
|
<PostListItem post={post} sort={sort} boardId={boardId} onSelect={onSelect} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
215
frontend/src/components/admin/AdminSortableList.tsx
Normal file
215
frontend/src/components/admin/AdminSortableList.tsx
Normal file
@@ -0,0 +1,215 @@
|
|||||||
|
import {
|
||||||
|
type CSSProperties,
|
||||||
|
type ElementType,
|
||||||
|
type HTMLAttributes,
|
||||||
|
type ReactNode,
|
||||||
|
} from 'react';
|
||||||
|
import {
|
||||||
|
DndContext,
|
||||||
|
closestCenter,
|
||||||
|
KeyboardSensor,
|
||||||
|
PointerSensor,
|
||||||
|
useSensor,
|
||||||
|
useSensors,
|
||||||
|
type DragEndEvent,
|
||||||
|
} from '@dnd-kit/core';
|
||||||
|
import {
|
||||||
|
SortableContext,
|
||||||
|
rectSortingStrategy,
|
||||||
|
sortableKeyboardCoordinates,
|
||||||
|
useSortable,
|
||||||
|
verticalListSortingStrategy,
|
||||||
|
type SortingStrategy,
|
||||||
|
} from '@dnd-kit/sortable';
|
||||||
|
import { CSS } from '@dnd-kit/utilities';
|
||||||
|
import { ArrowDown, ArrowUp, GripVertical } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { reorderItems, shouldShowSortableMoveButtons } from '../../utils/sortOrder';
|
||||||
|
|
||||||
|
export type SortableItemControls = {
|
||||||
|
setNodeRef: (node: HTMLElement | null) => void;
|
||||||
|
style: CSSProperties;
|
||||||
|
isDragging: boolean;
|
||||||
|
dragHandleProps: HTMLAttributes<HTMLButtonElement>;
|
||||||
|
moveUp: () => void;
|
||||||
|
moveDown: () => void;
|
||||||
|
canMoveUp: boolean;
|
||||||
|
canMoveDown: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
type AdminSortableListProps<T> = {
|
||||||
|
items: T[];
|
||||||
|
getId: (item: T) => string | number;
|
||||||
|
onReorder: (items: T[]) => void;
|
||||||
|
renderItem: (item: T, index: number, controls: SortableItemControls) => ReactNode;
|
||||||
|
showMoveButtons?: boolean | 'auto';
|
||||||
|
strategy?: 'vertical' | 'grid';
|
||||||
|
as?: ElementType;
|
||||||
|
className?: string;
|
||||||
|
ariaLabel?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function resolveStrategy(mode: 'vertical' | 'grid'): SortingStrategy {
|
||||||
|
return mode === 'grid' ? rectSortingStrategy : verticalListSortingStrategy;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SortableItem<T>({
|
||||||
|
item,
|
||||||
|
index,
|
||||||
|
items,
|
||||||
|
getId,
|
||||||
|
onReorder,
|
||||||
|
showMoveButtons,
|
||||||
|
renderItem,
|
||||||
|
}: {
|
||||||
|
item: T;
|
||||||
|
index: number;
|
||||||
|
items: T[];
|
||||||
|
getId: (item: T) => string | number;
|
||||||
|
onReorder: (items: T[]) => void;
|
||||||
|
showMoveButtons: boolean;
|
||||||
|
renderItem: AdminSortableListProps<T>['renderItem'];
|
||||||
|
}) {
|
||||||
|
const id = getId(item);
|
||||||
|
const {
|
||||||
|
attributes,
|
||||||
|
listeners,
|
||||||
|
setNodeRef,
|
||||||
|
transform,
|
||||||
|
transition,
|
||||||
|
isDragging,
|
||||||
|
} = useSortable({ id });
|
||||||
|
|
||||||
|
const style: CSSProperties = {
|
||||||
|
transform: CSS.Transform.toString(transform),
|
||||||
|
transition,
|
||||||
|
};
|
||||||
|
|
||||||
|
const moveUp = () => {
|
||||||
|
if (index > 0) onReorder(reorderItems(items, index, index - 1));
|
||||||
|
};
|
||||||
|
const moveDown = () => {
|
||||||
|
if (index < items.length - 1) onReorder(reorderItems(items, index, index + 1));
|
||||||
|
};
|
||||||
|
|
||||||
|
const controls: SortableItemControls = {
|
||||||
|
setNodeRef,
|
||||||
|
style,
|
||||||
|
isDragging,
|
||||||
|
dragHandleProps: { ...attributes, ...listeners },
|
||||||
|
moveUp,
|
||||||
|
moveDown,
|
||||||
|
canMoveUp: index > 0,
|
||||||
|
canMoveDown: index < items.length - 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{renderItem(item, index, controls)}
|
||||||
|
{showMoveButtons && (
|
||||||
|
<span className="sr-only" aria-live="polite">
|
||||||
|
{controls.canMoveUp ? '可上移' : ''}{controls.canMoveDown ? '可下移' : ''}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SortableDragHandle({
|
||||||
|
label = '拖拽调整顺序',
|
||||||
|
className = 'admin-sortable-row__handle',
|
||||||
|
...props
|
||||||
|
}: HTMLAttributes<HTMLButtonElement> & { label?: string }) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={className}
|
||||||
|
aria-label={label}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<GripVertical size={16} aria-hidden />
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SortableMoveButtons({
|
||||||
|
controls,
|
||||||
|
className = 'admin-sortable-row__order',
|
||||||
|
}: {
|
||||||
|
controls: Pick<SortableItemControls, 'moveUp' | 'moveDown' | 'canMoveUp' | 'canMoveDown'>;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className={className}>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
disabled={!controls.canMoveUp}
|
||||||
|
onClick={controls.moveUp}
|
||||||
|
aria-label="上移"
|
||||||
|
>
|
||||||
|
<ArrowUp size={14} />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
disabled={!controls.canMoveDown}
|
||||||
|
onClick={controls.moveDown}
|
||||||
|
aria-label="下移"
|
||||||
|
>
|
||||||
|
<ArrowDown size={14} />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AdminSortableList<T>({
|
||||||
|
items,
|
||||||
|
getId,
|
||||||
|
onReorder,
|
||||||
|
renderItem,
|
||||||
|
showMoveButtons = 'auto',
|
||||||
|
strategy = 'vertical',
|
||||||
|
as: Wrapper = 'div',
|
||||||
|
className,
|
||||||
|
ariaLabel,
|
||||||
|
}: AdminSortableListProps<T>) {
|
||||||
|
const sensors = useSensors(
|
||||||
|
useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
|
||||||
|
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
|
||||||
|
);
|
||||||
|
|
||||||
|
const moveButtons = shouldShowSortableMoveButtons(items.length, showMoveButtons);
|
||||||
|
|
||||||
|
const handleDragEnd = (event: DragEndEvent) => {
|
||||||
|
const { active, over } = event;
|
||||||
|
if (!over || active.id === over.id) return;
|
||||||
|
const oldIndex = items.findIndex(item => getId(item) === active.id);
|
||||||
|
const newIndex = items.findIndex(item => getId(item) === over.id);
|
||||||
|
if (oldIndex < 0 || newIndex < 0) return;
|
||||||
|
onReorder(reorderItems(items, oldIndex, newIndex));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
|
||||||
|
<SortableContext items={items.map(getId)} strategy={resolveStrategy(strategy)}>
|
||||||
|
<Wrapper className={className} role={ariaLabel ? 'group' : undefined} aria-label={ariaLabel}>
|
||||||
|
{items.map((item, index) => (
|
||||||
|
<SortableItem
|
||||||
|
key={String(getId(item))}
|
||||||
|
item={item}
|
||||||
|
index={index}
|
||||||
|
items={items}
|
||||||
|
getId={getId}
|
||||||
|
onReorder={onReorder}
|
||||||
|
showMoveButtons={moveButtons}
|
||||||
|
renderItem={renderItem}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</Wrapper>
|
||||||
|
</SortableContext>
|
||||||
|
</DndContext>
|
||||||
|
);
|
||||||
|
}
|
||||||
79
frontend/src/components/admin/AsideWidgetList.tsx
Normal file
79
frontend/src/components/admin/AsideWidgetList.tsx
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
import AdminSortableList, { SortableDragHandle } from './AdminSortableList';
|
||||||
|
import type { AsideWidget, AsideWidgetId } from '../../api/types';
|
||||||
|
|
||||||
|
const WIDGET_META: Record<AsideWidgetId, { label: string; hint: string }> = {
|
||||||
|
tag_cloud: {
|
||||||
|
label: '标签云',
|
||||||
|
hint: '在右侧栏展示热门标签',
|
||||||
|
},
|
||||||
|
recent_comments: {
|
||||||
|
label: '最新评论',
|
||||||
|
hint: '在右侧栏展示最近回复',
|
||||||
|
},
|
||||||
|
recent_users: {
|
||||||
|
label: '最新注册',
|
||||||
|
hint: '在右侧栏展示最近注册的用户',
|
||||||
|
},
|
||||||
|
friend_links: {
|
||||||
|
label: '友情链接',
|
||||||
|
hint: '关闭后不在右侧栏展示,友链仍可在「友情链接」页面查看与申请',
|
||||||
|
},
|
||||||
|
showcase: {
|
||||||
|
label: '开源展柜',
|
||||||
|
hint: '展示精选公网部署;关闭后仍可直接访问 /showcase',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
widgets: AsideWidget[];
|
||||||
|
onChange: (next: AsideWidget[]) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function AsideWidgetList({ widgets, onChange }: Props) {
|
||||||
|
const handleToggle = (id: AsideWidgetId, enabled: boolean) => {
|
||||||
|
onChange(widgets.map(w => (w.id === id ? { ...w, enabled } : w)));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AdminSortableList
|
||||||
|
items={widgets}
|
||||||
|
getId={widget => widget.id}
|
||||||
|
onReorder={onChange}
|
||||||
|
showMoveButtons={false}
|
||||||
|
className="admin-sortable-list admin-sortable-list--boxed"
|
||||||
|
ariaLabel="右侧栏组件"
|
||||||
|
renderItem={(widget, _index, controls) => {
|
||||||
|
const meta = WIDGET_META[widget.id];
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={controls.setNodeRef}
|
||||||
|
style={controls.style}
|
||||||
|
className={`admin-sortable-row admin-sortable-row--widget${controls.isDragging ? ' is-dragging' : ''}`}
|
||||||
|
>
|
||||||
|
<SortableDragHandle
|
||||||
|
label={`拖拽调整「${meta.label}」顺序`}
|
||||||
|
{...controls.dragHandleProps}
|
||||||
|
/>
|
||||||
|
<div className="admin-sortable-row__main">
|
||||||
|
<span className="admin-sortable-row__label" id={`aside-widget-label-${widget.id}`}>
|
||||||
|
{meta.label}
|
||||||
|
</span>
|
||||||
|
<span className="admin-sortable-row__hint">{meta.hint}</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
id={`aside-widget-${widget.id}`}
|
||||||
|
role="switch"
|
||||||
|
aria-checked={widget.enabled}
|
||||||
|
aria-labelledby={`aside-widget-label-${widget.id}`}
|
||||||
|
className={`admin-settings-switch${widget.enabled ? ' is-on' : ''}`}
|
||||||
|
onClick={() => handleToggle(widget.id, !widget.enabled)}
|
||||||
|
>
|
||||||
|
<span className="admin-settings-switch-ui" aria-hidden />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
90
frontend/src/components/admin/CommunitySupportStrip.tsx
Normal file
90
frontend/src/components/admin/CommunitySupportStrip.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
89
frontend/src/components/admin/FeedSortTabList.tsx
Normal file
89
frontend/src/components/admin/FeedSortTabList.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
91
frontend/src/components/admin/MonitorChinaMap.tsx
Normal file
91
frontend/src/components/admin/MonitorChinaMap.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
121
frontend/src/components/admin/MonitorWorldMap.tsx
Normal file
121
frontend/src/components/admin/MonitorWorldMap.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
130
frontend/src/components/admin/monitorMapUtils.ts
Normal file
130
frontend/src/components/admin/monitorMapUtils.ts
Normal 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;
|
||||||
|
}
|
||||||
@@ -3,7 +3,13 @@ import BoardIconDisplay from '../BoardIconDisplay';
|
|||||||
import { getBoardThemeIndex } from '../../utils/boardTheme';
|
import { getBoardThemeIndex } from '../../utils/boardTheme';
|
||||||
import type { Board, ForumLimitsPublic } from '../../api/types';
|
import type { Board, ForumLimitsPublic } from '../../api/types';
|
||||||
|
|
||||||
export type PostType = 'normal' | 'question';
|
export type PostType = 'normal' | 'question' | 'poll' | 'bounty' | 'lottery';
|
||||||
|
|
||||||
|
const SPECIAL_TYPE_LABELS: Record<'poll' | 'bounty' | 'lottery', string> = {
|
||||||
|
poll: '投票',
|
||||||
|
bounty: '悬赏',
|
||||||
|
lottery: '抽奖',
|
||||||
|
};
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
isEdit: boolean;
|
isEdit: boolean;
|
||||||
@@ -32,12 +38,26 @@ export default function ComposeContextBar({
|
|||||||
onTagsChange,
|
onTagsChange,
|
||||||
limits,
|
limits,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
|
const isSpecialEdit = isEdit && (postType === 'poll' || postType === 'bounty' || postType === 'lottery');
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="compose-context" aria-label="发布设置">
|
<section className="compose-context" aria-label="发布设置">
|
||||||
<div className="compose-context-row">
|
<div className="compose-context-row">
|
||||||
<span className="compose-context-label">类型</span>
|
<span className="compose-context-label">类型</span>
|
||||||
<div className="compose-type-field">
|
<div className="compose-type-field">
|
||||||
<div className="compose-type-pills" role="radiogroup" aria-label="帖子类型">
|
<div className="compose-type-pills" role="radiogroup" aria-label="帖子类型">
|
||||||
|
{isSpecialEdit ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
aria-checked
|
||||||
|
className="compose-type-pill active"
|
||||||
|
disabled
|
||||||
|
>
|
||||||
|
{SPECIAL_TYPE_LABELS[postType]}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
role="radio"
|
role="radio"
|
||||||
@@ -53,13 +73,58 @@ export default function ComposeContextBar({
|
|||||||
aria-checked={postType === 'question'}
|
aria-checked={postType === 'question'}
|
||||||
className={`compose-type-pill${postType === 'question' ? ' active' : ''}`}
|
className={`compose-type-pill${postType === 'question' ? ' active' : ''}`}
|
||||||
onClick={() => onPostTypeChange('question')}
|
onClick={() => onPostTypeChange('question')}
|
||||||
|
disabled={isEdit}
|
||||||
>
|
>
|
||||||
问答
|
问答
|
||||||
</button>
|
</button>
|
||||||
|
{!isEdit && (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
aria-checked={postType === 'poll'}
|
||||||
|
className={`compose-type-pill${postType === 'poll' ? ' active' : ''}`}
|
||||||
|
onClick={() => onPostTypeChange('poll')}
|
||||||
|
>
|
||||||
|
投票
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
aria-checked={postType === 'bounty'}
|
||||||
|
className={`compose-type-pill${postType === 'bounty' ? ' active' : ''}`}
|
||||||
|
onClick={() => onPostTypeChange('bounty')}
|
||||||
|
>
|
||||||
|
悬赏
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="radio"
|
||||||
|
aria-checked={postType === 'lottery'}
|
||||||
|
className={`compose-type-pill${postType === 'lottery' ? ' active' : ''}`}
|
||||||
|
onClick={() => onPostTypeChange('lottery')}
|
||||||
|
>
|
||||||
|
抽奖
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
{postType === 'question' && (
|
{postType === 'question' && (
|
||||||
<span className="compose-type-hint">问答可标记解决状态</span>
|
<span className="compose-type-hint">问答可标记解决状态</span>
|
||||||
)}
|
)}
|
||||||
|
{postType === 'poll' && (
|
||||||
|
<span className="compose-type-hint">
|
||||||
|
{isEdit ? '投票选项发布后不可修改' : '发布后选项不可修改'}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{postType === 'bounty' && (
|
||||||
|
<span className="compose-type-hint">发布成功即扣除积分;有人回复后不可自行取消,需采纳或联系管理员</span>
|
||||||
|
)}
|
||||||
|
{postType === 'lottery' && (
|
||||||
|
<span className="compose-type-hint">回帖参与,手动开奖</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="compose-context-row">
|
<div className="compose-context-row">
|
||||||
|
|||||||
259
frontend/src/components/compose/ComposeSpecialFields.tsx
Normal file
259
frontend/src/components/compose/ComposeSpecialFields.tsx
Normal file
@@ -0,0 +1,259 @@
|
|||||||
|
import { Plus, Trash2 } from 'lucide-react';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Switch } from '@/components/ui/switch';
|
||||||
|
import type { PostType } from './ComposeContextBar';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
postType: PostType;
|
||||||
|
pollOptions: string[];
|
||||||
|
onPollOptionsChange: (opts: string[]) => void;
|
||||||
|
pollMulti: boolean;
|
||||||
|
onPollMultiChange: (v: boolean) => void;
|
||||||
|
pollMaxChoices: number;
|
||||||
|
onPollMaxChoicesChange: (v: number) => void;
|
||||||
|
pollEndsAt: string;
|
||||||
|
onPollEndsAtChange: (v: string) => void;
|
||||||
|
pollNoEndTime: boolean;
|
||||||
|
onPollNoEndTimeChange: (v: boolean) => void;
|
||||||
|
bountyPoints: number;
|
||||||
|
onBountyPointsChange: (v: number) => void;
|
||||||
|
userPointsBalance?: number;
|
||||||
|
lotteryWinners: number;
|
||||||
|
onLotteryWinnersChange: (v: number) => void;
|
||||||
|
disabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 默认截止时间:7 天后,分钟进位到下一整点 */
|
||||||
|
export function defaultPollEndsAtLocal(): string {
|
||||||
|
const d = new Date(Date.now() + 7 * 24 * 3600_000);
|
||||||
|
d.setMinutes(0, 0, 0);
|
||||||
|
if (d.getTime() <= Date.now()) {
|
||||||
|
d.setHours(d.getHours() + 1);
|
||||||
|
}
|
||||||
|
const pad = (n: number) => String(n).padStart(2, '0');
|
||||||
|
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** datetime-local → ISO8601(UTC) */
|
||||||
|
export function pollEndsAtLocalToISO(local: string): string | undefined {
|
||||||
|
const trimmed = local.trim();
|
||||||
|
if (!trimmed) return undefined;
|
||||||
|
const d = new Date(trimmed);
|
||||||
|
if (Number.isNaN(d.getTime())) return undefined;
|
||||||
|
return d.toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ISO8601 → datetime-local */
|
||||||
|
export function pollEndsAtISOToLocal(iso: string): string {
|
||||||
|
const d = new Date(iso);
|
||||||
|
if (Number.isNaN(d.getTime())) return '';
|
||||||
|
const pad = (n: number) => String(n).padStart(2, '0');
|
||||||
|
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 特殊帖类型附加字段(投票/悬赏/抽奖) */
|
||||||
|
export default function ComposeSpecialFields({
|
||||||
|
postType,
|
||||||
|
pollOptions,
|
||||||
|
onPollOptionsChange,
|
||||||
|
pollMulti,
|
||||||
|
onPollMultiChange,
|
||||||
|
pollMaxChoices,
|
||||||
|
onPollMaxChoicesChange,
|
||||||
|
pollEndsAt,
|
||||||
|
onPollEndsAtChange,
|
||||||
|
pollNoEndTime,
|
||||||
|
onPollNoEndTimeChange,
|
||||||
|
bountyPoints,
|
||||||
|
onBountyPointsChange,
|
||||||
|
userPointsBalance,
|
||||||
|
lotteryWinners,
|
||||||
|
onLotteryWinnersChange,
|
||||||
|
disabled,
|
||||||
|
}: Props) {
|
||||||
|
if (postType === 'normal' || postType === 'question') return null;
|
||||||
|
|
||||||
|
if (postType === 'poll') {
|
||||||
|
return (
|
||||||
|
<section className="compose-special" aria-label="投票设置">
|
||||||
|
<Label>投票选项(2-10 项)</Label>
|
||||||
|
<div className="compose-special__poll-mode">
|
||||||
|
<Switch checked={pollMulti} onCheckedChange={onPollMultiChange} disabled={disabled} id="poll-multi" />
|
||||||
|
<label htmlFor="poll-multi">允许多选</label>
|
||||||
|
{pollMulti && (
|
||||||
|
<>
|
||||||
|
<span className="compose-special__max-choices-label">最多可选</span>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
max={pollOptions.length || 10}
|
||||||
|
value={pollMaxChoices}
|
||||||
|
onChange={e => onPollMaxChoicesChange(Number(e.target.value) || 1)}
|
||||||
|
disabled={disabled}
|
||||||
|
className="compose-special__max-choices"
|
||||||
|
aria-label="最多可选"
|
||||||
|
/>
|
||||||
|
<span className="compose-special__max-choices-suffix">项</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="compose-special__poll-deadline">
|
||||||
|
<div className="compose-special__poll-deadline-toggle">
|
||||||
|
<Switch
|
||||||
|
checked={pollNoEndTime}
|
||||||
|
onCheckedChange={onPollNoEndTimeChange}
|
||||||
|
disabled={disabled}
|
||||||
|
id="poll-no-end-time"
|
||||||
|
/>
|
||||||
|
<label htmlFor="poll-no-end-time">不限时</label>
|
||||||
|
</div>
|
||||||
|
{!pollNoEndTime && (
|
||||||
|
<div className="compose-special__poll-deadline-field">
|
||||||
|
<Label htmlFor="poll-ends-at" className="compose-special__poll-deadline-label">投票截止时间</Label>
|
||||||
|
<Input
|
||||||
|
id="poll-ends-at"
|
||||||
|
type="datetime-local"
|
||||||
|
value={pollEndsAt}
|
||||||
|
onChange={e => onPollEndsAtChange(e.target.value)}
|
||||||
|
disabled={disabled}
|
||||||
|
className="compose-special__poll-deadline-input w-auto"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="compose-special__options">
|
||||||
|
{pollOptions.map((opt, i) => (
|
||||||
|
<div key={i} className="compose-special__option-row">
|
||||||
|
<Input
|
||||||
|
value={opt}
|
||||||
|
placeholder={`选项 ${i + 1}`}
|
||||||
|
maxLength={64}
|
||||||
|
disabled={disabled}
|
||||||
|
onChange={e => {
|
||||||
|
const next = [...pollOptions];
|
||||||
|
next[i] = e.target.value;
|
||||||
|
onPollOptionsChange(next);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
disabled={disabled || pollOptions.length <= 2}
|
||||||
|
onClick={() => onPollOptionsChange(pollOptions.filter((_, j) => j !== i))}
|
||||||
|
aria-label="删除选项"
|
||||||
|
>
|
||||||
|
<Trash2 size={16} />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{pollOptions.length < 10 && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => onPollOptionsChange([...pollOptions, ''])}
|
||||||
|
>
|
||||||
|
<Plus size={14} /> 添加选项
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (postType === 'bounty') {
|
||||||
|
const showBalance = !disabled && typeof userPointsBalance === 'number';
|
||||||
|
const balance = userPointsBalance ?? 0;
|
||||||
|
const overBudget = showBalance && bountyPoints > balance;
|
||||||
|
const remaining = showBalance && bountyPoints > 0 && !overBudget
|
||||||
|
? balance - bountyPoints
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="compose-special" aria-label="悬赏设置">
|
||||||
|
<Label htmlFor="bounty-points">悬赏积分(发布即扣除)</Label>
|
||||||
|
<div className="compose-special__bounty-row">
|
||||||
|
<Input
|
||||||
|
id="bounty-points"
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
value={bountyPoints || ''}
|
||||||
|
disabled={disabled}
|
||||||
|
onChange={e => onBountyPointsChange(Math.max(0, Number(e.target.value) || 0))}
|
||||||
|
/>
|
||||||
|
{showBalance && (
|
||||||
|
<p className={cn(
|
||||||
|
'compose-special__balance',
|
||||||
|
overBudget && 'compose-special__balance--over',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{overBudget
|
||||||
|
? '积分不足'
|
||||||
|
: remaining != null
|
||||||
|
? `当前余额 ${balance} · 发布后剩余 ${remaining}`
|
||||||
|
: `当前余额 ${balance}`}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (postType === 'lottery') {
|
||||||
|
return (
|
||||||
|
<section className="compose-special" aria-label="抽奖设置">
|
||||||
|
<Label htmlFor="lottery-winners">中奖人数(1-20)</Label>
|
||||||
|
<Input
|
||||||
|
id="lottery-winners"
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
max={20}
|
||||||
|
value={lotteryWinners || 1}
|
||||||
|
disabled={disabled}
|
||||||
|
onChange={e => onLotteryWinnersChange(Math.min(20, Math.max(1, Number(e.target.value) || 1)))}
|
||||||
|
/>
|
||||||
|
<p className="compose-special__hint">参与者为已回帖用户(不含楼主),由作者或管理员开奖</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildPollOptionsPayload(
|
||||||
|
options: string[],
|
||||||
|
multi: boolean,
|
||||||
|
maxChoices: number,
|
||||||
|
endsAtISO?: string | null,
|
||||||
|
): string {
|
||||||
|
const payload: Record<string, unknown> = {
|
||||||
|
multi,
|
||||||
|
max_choices: maxChoices,
|
||||||
|
options: options.filter(o => o.trim()).map(text => ({ text: text.trim() })),
|
||||||
|
};
|
||||||
|
if (endsAtISO) payload.ends_at = endsAtISO;
|
||||||
|
return JSON.stringify(payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 统计有效(非空)投票选项数量 */
|
||||||
|
export function countValidPollOptions(options: string[]): number {
|
||||||
|
return options.filter(o => o.trim()).length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 前端校验投票截止时间(非不限时时) */
|
||||||
|
export function validatePollEndsAtLocal(local: string): string | null {
|
||||||
|
const iso = pollEndsAtLocalToISO(local);
|
||||||
|
if (!iso) return '请选择有效的投票截止时间';
|
||||||
|
if (new Date(iso).getTime() <= Date.now() + 5 * 60_000) {
|
||||||
|
return '投票截止时间须晚于当前时间至少 5 分钟';
|
||||||
|
}
|
||||||
|
if (new Date(iso).getTime() > Date.now() + 365 * 24 * 3600_000) {
|
||||||
|
return '投票截止时间不能超过 365 天';
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -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?.(),
|
||||||
|
|||||||
351
frontend/src/components/editor/ArticleImagePickerDialog.tsx
Normal file
351
frontend/src/components/editor/ArticleImagePickerDialog.tsx
Normal 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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,13 +174,17 @@ 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>
|
||||||
|
|
||||||
|
<section className="article-link-dialog__section">
|
||||||
|
<div className="article-link-dialog__field">
|
||||||
|
<Label htmlFor="article-link-url">网址</Label>
|
||||||
<Input
|
<Input
|
||||||
|
id="article-link-url"
|
||||||
type="url"
|
type="url"
|
||||||
value={url}
|
value={url}
|
||||||
placeholder="https://"
|
placeholder="https://… 或 /post/123"
|
||||||
onChange={e => setUrl(e.target.value)}
|
onChange={e => setUrl(e.target.value)}
|
||||||
onKeyDown={e => {
|
onKeyDown={e => {
|
||||||
if (e.key === 'Enter') {
|
if (e.key === 'Enter') {
|
||||||
@@ -57,9 +194,99 @@ export function ArticleLinkDialog({
|
|||||||
}}
|
}}
|
||||||
autoFocus
|
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>
|
||||||
|
|||||||
54
frontend/src/components/editor/ArticleStickerExtension.ts
Normal file
54
frontend/src/components/editor/ArticleStickerExtension.ts
Normal 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',
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -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,7 +124,9 @@ 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) => {
|
||||||
|
const isText = s.type === 'text' && !!s.text;
|
||||||
|
return (
|
||||||
<button
|
<button
|
||||||
key={s.id}
|
key={s.id}
|
||||||
id={`${autoId}-opt-${i}`}
|
id={`${autoId}-opt-${i}`}
|
||||||
@@ -91,11 +135,11 @@ export default function StickerPicker({ onSelect }: Props) {
|
|||||||
tabIndex={focusIndex === i ? 0 : -1}
|
tabIndex={focusIndex === i ? 0 : -1}
|
||||||
aria-selected={focusIndex === i}
|
aria-selected={focusIndex === i}
|
||||||
aria-label={s.name}
|
aria-label={s.name}
|
||||||
className="sticker-picker-item"
|
className={isText ? 'sticker-picker-item sticker-picker-item--text' : 'sticker-picker-item sticker-picker-item--image'}
|
||||||
onClick={() => onSelect(s)}
|
onClick={() => onSelect(s)}
|
||||||
onFocus={() => setFocusIndex(i)}
|
onFocus={() => setFocusIndex(i)}
|
||||||
>
|
>
|
||||||
{s.type === 'text' && s.text ? (
|
{isText ? (
|
||||||
<span className="sticker-picker-text">{s.text}</span>
|
<span className="sticker-picker-text">{s.text}</span>
|
||||||
) : (
|
) : (
|
||||||
<img
|
<img
|
||||||
@@ -103,12 +147,12 @@ export default function StickerPicker({ onSelect }: Props) {
|
|||||||
alt={s.name}
|
alt={s.name}
|
||||||
width={32}
|
width={32}
|
||||||
height={32}
|
height={32}
|
||||||
style={{ width: 32, height: 32, objectFit: 'contain' }}
|
|
||||||
loading="lazy"
|
loading="lazy"
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
))
|
);
|
||||||
|
})
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
87
frontend/src/components/search/FeedSearchFilters.tsx
Normal file
87
frontend/src/components/search/FeedSearchFilters.tsx
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
import { X } from 'lucide-react';
|
||||||
|
import type { Board } from '../../api/types';
|
||||||
|
import type { PostSearchState, SearchFilterKey } from '../../hooks/usePostSearch';
|
||||||
|
import { dispatchOpenPostSearch } from '../../hooks/usePostSearch';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
filters: PostSearchState;
|
||||||
|
boards: Board[];
|
||||||
|
onRemove: (key: SearchFilterKey) => void;
|
||||||
|
onClear: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function FeedSearchFilters({ filters, boards, onRemove, onClear }: Props) {
|
||||||
|
const { keyword, author, titleOnly, scopeBoardId } = filters;
|
||||||
|
if (!keyword && !author) return null;
|
||||||
|
|
||||||
|
const boardName = scopeBoardId > 0
|
||||||
|
? boards.find((b) => b.id === scopeBoardId)?.name || '当前板块'
|
||||||
|
: '';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="search-filter-bar">
|
||||||
|
<div className="search-filter-bar__chips" role="list">
|
||||||
|
{keyword && (
|
||||||
|
<span className="search-filter-chip" role="listitem">
|
||||||
|
<span className="search-filter-chip__text">关键词「{keyword}」</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="search-filter-chip__remove"
|
||||||
|
aria-label={`移除关键词 ${keyword}`}
|
||||||
|
onClick={() => onRemove('keyword')}
|
||||||
|
>
|
||||||
|
<X size={12} aria-hidden />
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{author && (
|
||||||
|
<span className="search-filter-chip" role="listitem">
|
||||||
|
<span className="search-filter-chip__text">作者 {author}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="search-filter-chip__remove"
|
||||||
|
aria-label={`移除作者 ${author}`}
|
||||||
|
onClick={() => onRemove('author')}
|
||||||
|
>
|
||||||
|
<X size={12} aria-hidden />
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{titleOnly && keyword && (
|
||||||
|
<span className="search-filter-chip" role="listitem">
|
||||||
|
<span className="search-filter-chip__text">仅标题</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="search-filter-chip__remove"
|
||||||
|
aria-label="取消仅标题"
|
||||||
|
onClick={() => onRemove('titleOnly')}
|
||||||
|
>
|
||||||
|
<X size={12} aria-hidden />
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{scopeBoardId > 0 && boardName && (
|
||||||
|
<span className="search-filter-chip" role="listitem">
|
||||||
|
<span className="search-filter-chip__text">板块:{boardName}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="search-filter-chip__remove"
|
||||||
|
aria-label={`移除板块 ${boardName}`}
|
||||||
|
onClick={() => onRemove('board')}
|
||||||
|
>
|
||||||
|
<X size={12} aria-hidden />
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="search-filter-bar__actions">
|
||||||
|
<button type="button" className="search-filter-bar__link" onClick={dispatchOpenPostSearch}>
|
||||||
|
修改搜索
|
||||||
|
</button>
|
||||||
|
<button type="button" className="search-filter-bar__link search-filter-bar__link--muted" onClick={onClear}>
|
||||||
|
清除全部
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
310
frontend/src/components/search/PostSearchPanel.tsx
Normal file
310
frontend/src/components/search/PostSearchPanel.tsx
Normal file
@@ -0,0 +1,310 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
import { Search, User } from 'lucide-react';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
DialogDescription,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Switch } from '@/components/ui/switch';
|
||||||
|
import { api } from '../../api/client';
|
||||||
|
import { useMediaQuery } from '../../hooks/useTheme';
|
||||||
|
import { useForumLimits } from '../../hooks/useForumLimits';
|
||||||
|
import {
|
||||||
|
getRecentSearches,
|
||||||
|
type PostSearchSubmitInput,
|
||||||
|
type RecentSearch,
|
||||||
|
} from '../../hooks/usePostSearch';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
export interface PostSearchDraft {
|
||||||
|
keyword: string;
|
||||||
|
author: string;
|
||||||
|
titleOnly: boolean;
|
||||||
|
scopeBoardId: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
draft: PostSearchDraft;
|
||||||
|
contextBoardId: number;
|
||||||
|
contextBoardName?: string;
|
||||||
|
onSubmit: (input: PostSearchSubmitInput) => boolean;
|
||||||
|
onClear: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserSuggest = { id: number; username: string; nickname: string; avatar?: string };
|
||||||
|
|
||||||
|
export default function PostSearchPanel({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
draft,
|
||||||
|
contextBoardId,
|
||||||
|
contextBoardName = '',
|
||||||
|
onSubmit,
|
||||||
|
onClear,
|
||||||
|
}: Props) {
|
||||||
|
const isMobile = useMediaQuery('(max-width: 768px)');
|
||||||
|
const { limits } = useForumLimits();
|
||||||
|
const keywordRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
const [keyword, setKeyword] = useState(draft.keyword);
|
||||||
|
const [author, setAuthor] = useState(draft.author);
|
||||||
|
const [titleOnly, setTitleOnly] = useState(draft.titleOnly);
|
||||||
|
const [scopeBoardId, setScopeBoardId] = useState(draft.scopeBoardId);
|
||||||
|
const [recent, setRecent] = useState<RecentSearch[]>([]);
|
||||||
|
const [suggestions, setSuggestions] = useState<UserSuggest[]>([]);
|
||||||
|
const [suggestOpen, setSuggestOpen] = useState(false);
|
||||||
|
const authorWrapRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
setKeyword(draft.keyword);
|
||||||
|
setAuthor(draft.author);
|
||||||
|
setTitleOnly(draft.titleOnly);
|
||||||
|
setScopeBoardId(draft.scopeBoardId);
|
||||||
|
setRecent(getRecentSearches());
|
||||||
|
setSuggestions([]);
|
||||||
|
setSuggestOpen(false);
|
||||||
|
const t = window.setTimeout(() => keywordRef.current?.focus(), 80);
|
||||||
|
return () => window.clearTimeout(t);
|
||||||
|
}, [open, draft]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const q = author.trim();
|
||||||
|
if (q.length < 1) {
|
||||||
|
setSuggestions([]);
|
||||||
|
setSuggestOpen(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let cancelled = false;
|
||||||
|
const timer = window.setTimeout(() => {
|
||||||
|
api.searchUsers(q, 8).then((r) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
const users = Array.isArray(r.users) ? r.users : [];
|
||||||
|
setSuggestions(users);
|
||||||
|
setSuggestOpen(users.length > 0);
|
||||||
|
}).catch(() => {
|
||||||
|
if (!cancelled) {
|
||||||
|
setSuggestions([]);
|
||||||
|
setSuggestOpen(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}, 300);
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
window.clearTimeout(timer);
|
||||||
|
};
|
||||||
|
}, [author, open]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!suggestOpen) return;
|
||||||
|
const onDoc = (e: MouseEvent) => {
|
||||||
|
if (authorWrapRef.current?.contains(e.target as Node)) return;
|
||||||
|
setSuggestOpen(false);
|
||||||
|
};
|
||||||
|
document.addEventListener('mousedown', onDoc);
|
||||||
|
return () => document.removeEventListener('mousedown', onDoc);
|
||||||
|
}, [suggestOpen]);
|
||||||
|
|
||||||
|
const handleSubmit = useCallback(() => {
|
||||||
|
const ok = onSubmit({
|
||||||
|
keyword,
|
||||||
|
author,
|
||||||
|
titleOnly: !!keyword.trim() && titleOnly,
|
||||||
|
scopeBoardId: scopeBoardId > 0 ? scopeBoardId : 0,
|
||||||
|
});
|
||||||
|
if (ok) onOpenChange(false);
|
||||||
|
}, [keyword, author, titleOnly, scopeBoardId, onSubmit, onOpenChange]);
|
||||||
|
|
||||||
|
const applyRecent = (item: RecentSearch) => {
|
||||||
|
setKeyword(item.keyword);
|
||||||
|
setAuthor(item.author);
|
||||||
|
setTitleOnly(item.titleOnly);
|
||||||
|
setScopeBoardId(item.scopeBoardId);
|
||||||
|
};
|
||||||
|
|
||||||
|
const pickAuthor = (u: UserSuggest) => {
|
||||||
|
setAuthor(u.nickname || u.username);
|
||||||
|
setSuggestOpen(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const showBoardScope = contextBoardId > 0;
|
||||||
|
const kwHint = limits.search_keyword_min > 1
|
||||||
|
? `关键词 ${limits.search_keyword_min}–${limits.search_keyword_max} 字`
|
||||||
|
: `关键词最多 ${limits.search_keyword_max} 字`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent
|
||||||
|
className={cn(
|
||||||
|
'post-search-panel',
|
||||||
|
isMobile && 'post-search-panel--mobile',
|
||||||
|
)}
|
||||||
|
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||||
|
>
|
||||||
|
{isMobile && <div className="post-search-panel__handle" aria-hidden />}
|
||||||
|
<DialogHeader className="post-search-panel__header">
|
||||||
|
<DialogTitle>搜索帖子</DialogTitle>
|
||||||
|
{!isMobile && (
|
||||||
|
<DialogDescription className="post-search-panel__desc">
|
||||||
|
按关键词、作者或板块范围查找帖子
|
||||||
|
</DialogDescription>
|
||||||
|
)}
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="post-search-panel__body">
|
||||||
|
<label className="post-search-field">
|
||||||
|
<span className="post-search-field__label">关键词</span>
|
||||||
|
<div className="post-search-field__input-wrap">
|
||||||
|
<Search size={16} aria-hidden className="post-search-field__icon" />
|
||||||
|
<input
|
||||||
|
ref={keywordRef}
|
||||||
|
type="search"
|
||||||
|
className="post-search-field__input"
|
||||||
|
placeholder="输入标题或正文关键词…"
|
||||||
|
value={keyword}
|
||||||
|
onChange={(e) => setKeyword(e.target.value)}
|
||||||
|
maxLength={limits.search_keyword_max > 0 ? limits.search_keyword_max : undefined}
|
||||||
|
enterKeyHint="search"
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
handleSubmit();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<span className="post-search-field__hint">{kwHint}</span>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label className="post-search-field">
|
||||||
|
<span className="post-search-field__label">作者</span>
|
||||||
|
<div className="post-search-field__input-wrap" ref={authorWrapRef}>
|
||||||
|
<User size={16} aria-hidden className="post-search-field__icon" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="post-search-field__input"
|
||||||
|
placeholder="用户名或昵称"
|
||||||
|
value={author}
|
||||||
|
onChange={(e) => setAuthor(e.target.value)}
|
||||||
|
onFocus={() => suggestions.length > 0 && setSuggestOpen(true)}
|
||||||
|
autoComplete="off"
|
||||||
|
/>
|
||||||
|
{suggestOpen && suggestions.length > 0 && (
|
||||||
|
<ul className="search-author-suggest" role="listbox">
|
||||||
|
{suggestions.map((u) => (
|
||||||
|
<li key={u.id}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="search-author-suggest__item"
|
||||||
|
role="option"
|
||||||
|
onClick={() => pickAuthor(u)}
|
||||||
|
>
|
||||||
|
{u.avatar
|
||||||
|
? <img src={u.avatar} alt="" className="search-author-suggest__avatar" loading="lazy" />
|
||||||
|
: <span className="search-author-suggest__avatar search-author-suggest__avatar--ph">{(u.nickname || u.username).charAt(0)}</span>}
|
||||||
|
<span className="search-author-suggest__name">{u.nickname || u.username}</span>
|
||||||
|
{u.nickname && u.username !== u.nickname && (
|
||||||
|
<span className="search-author-suggest__user">@{u.username}</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{showBoardScope && (
|
||||||
|
<div className="post-search-field">
|
||||||
|
<span className="post-search-field__label">范围</span>
|
||||||
|
<div className="search-scope-pills" role="group" aria-label="搜索范围">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={cn('search-scope-pill', scopeBoardId === 0 && 'active')}
|
||||||
|
aria-pressed={scopeBoardId === 0}
|
||||||
|
onClick={() => setScopeBoardId(0)}
|
||||||
|
>
|
||||||
|
全站
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={cn('search-scope-pill', scopeBoardId === contextBoardId && 'active')}
|
||||||
|
aria-pressed={scopeBoardId === contextBoardId}
|
||||||
|
onClick={() => setScopeBoardId(contextBoardId)}
|
||||||
|
>
|
||||||
|
{contextBoardName || '当前板块'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="post-search-field post-search-field--row">
|
||||||
|
<div>
|
||||||
|
<span className="post-search-field__label">仅搜标题</span>
|
||||||
|
<span className="post-search-field__hint">需填写关键词时生效</span>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={titleOnly}
|
||||||
|
onCheckedChange={setTitleOnly}
|
||||||
|
disabled={!keyword.trim()}
|
||||||
|
aria-label="仅搜索标题"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{recent.length > 0 && (
|
||||||
|
<div className="post-search-recent">
|
||||||
|
<span className="post-search-field__label">最近搜索</span>
|
||||||
|
<ul className="post-search-recent__list">
|
||||||
|
{recent.map((item) => {
|
||||||
|
const label = [
|
||||||
|
item.keyword && `「${item.keyword}」`,
|
||||||
|
item.author && `@${item.author}`,
|
||||||
|
item.titleOnly && '仅标题',
|
||||||
|
item.scopeBoardId > 0 && '本板块',
|
||||||
|
].filter(Boolean).join(' · ') || '搜索';
|
||||||
|
return (
|
||||||
|
<li key={`${item.keyword}-${item.author}-${item.at}`}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="post-search-recent__item"
|
||||||
|
onClick={() => applyRecent(item)}
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className={cn('post-search-panel__footer', isMobile && 'post-search-panel__footer--mobile')}>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className={isMobile ? 'post-search-panel__btn' : undefined}
|
||||||
|
onClick={() => {
|
||||||
|
setKeyword('');
|
||||||
|
setAuthor('');
|
||||||
|
setTitleOnly(false);
|
||||||
|
setScopeBoardId(0);
|
||||||
|
onClear();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
清除
|
||||||
|
</Button>
|
||||||
|
<Button type="button" className={isMobile ? 'post-search-panel__btn' : undefined} onClick={handleSubmit}>
|
||||||
|
搜索
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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 }));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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: ['怀疑', '思考'] },
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -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();
|
||||||
|
|||||||
130
frontend/src/hooks/useCheckIn.ts
Normal file
130
frontend/src/hooks/useCheckIn.ts
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
import { notify } from '@/lib/notify';
|
||||||
|
import { api } from '../api/client';
|
||||||
|
import type { CheckInStatus } from '../api/types';
|
||||||
|
import { getSessionSnapshot, setSessionSnapshot } from '../utils/sessionPageCache';
|
||||||
|
import { PAGE_FORCE_REFRESH_EVENT } from '../utils/feedCache';
|
||||||
|
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
|
||||||
|
import { useAuth } from './useAuth';
|
||||||
|
|
||||||
|
/** 签到会话快照键(与 prefetchRoute 共用) */
|
||||||
|
export function checkInCacheKey(userId: number) {
|
||||||
|
return `checkin:${userId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 每日签到状态与操作(侧栏、积分页等复用) */
|
||||||
|
export function useCheckIn(enabled = true) {
|
||||||
|
const { user, refresh } = useAuth();
|
||||||
|
const userId = user?.id;
|
||||||
|
|
||||||
|
const [status, setStatus] = useState<CheckInStatus | null>(() => {
|
||||||
|
if (!userId || !enabled) return null;
|
||||||
|
return getSessionSnapshot<CheckInStatus>(checkInCacheKey(userId)) ?? null;
|
||||||
|
});
|
||||||
|
const [loading, setLoading] = useState(() => {
|
||||||
|
if (!userId || !enabled) return false;
|
||||||
|
return getSessionSnapshot<CheckInStatus>(checkInCacheKey(userId)) === undefined;
|
||||||
|
});
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
|
const load = useCallback((opts?: { force?: boolean }) => {
|
||||||
|
if (!userId || !enabled) {
|
||||||
|
setStatus(null);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const key = checkInCacheKey(userId);
|
||||||
|
if (!opts?.force) {
|
||||||
|
const hit = getSessionSnapshot<CheckInStatus>(key);
|
||||||
|
if (hit !== undefined) {
|
||||||
|
setStatus(hit);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setLoading(true);
|
||||||
|
api.checkInStatus()
|
||||||
|
.then((d) => {
|
||||||
|
setSessionSnapshot(key, d.check_in);
|
||||||
|
setStatus(d.check_in);
|
||||||
|
})
|
||||||
|
.catch((e) => notify.error(e instanceof Error ? e.message : '加载签到状态失败'))
|
||||||
|
.finally(() => setLoading(false));
|
||||||
|
}, [userId, enabled]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!userId || !enabled) {
|
||||||
|
setStatus(null);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const key = checkInCacheKey(userId);
|
||||||
|
const hit = getSessionSnapshot<CheckInStatus>(key);
|
||||||
|
if (hit !== undefined) {
|
||||||
|
setStatus(hit);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setStatus(null);
|
||||||
|
setLoading(true);
|
||||||
|
load({ force: true });
|
||||||
|
}, [userId, enabled, load]);
|
||||||
|
|
||||||
|
// 软刷新 commit:仅快照命中才盖;未命中保持旧 UI,后台静默再拉
|
||||||
|
useEffect(() => {
|
||||||
|
const applyHitOrSilent = (forceLoading: boolean) => {
|
||||||
|
if (!userId || !enabled) return;
|
||||||
|
const key = checkInCacheKey(userId);
|
||||||
|
const hit = getSessionSnapshot<CheckInStatus>(key);
|
||||||
|
if (hit !== undefined) {
|
||||||
|
setStatus(hit);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (forceLoading) {
|
||||||
|
load({ force: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 软刷新未命中:不 setLoading,静默覆盖
|
||||||
|
api.checkInStatus()
|
||||||
|
.then((d) => {
|
||||||
|
setSessionSnapshot(key, d.check_in);
|
||||||
|
setStatus(d.check_in);
|
||||||
|
setLoading(false);
|
||||||
|
})
|
||||||
|
.catch(() => { /* 保持旧 UI */ });
|
||||||
|
};
|
||||||
|
const onForce = () => applyHitOrSilent(true);
|
||||||
|
const onCommit = () => applyHitOrSilent(false);
|
||||||
|
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||||
|
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||||
|
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||||
|
};
|
||||||
|
}, [userId, enabled, load]);
|
||||||
|
|
||||||
|
const doCheckIn = useCallback(async () => {
|
||||||
|
if (!userId) return;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const r = await api.checkIn();
|
||||||
|
notify.success(`签到成功,+${r.check_in.today_points} 积分`);
|
||||||
|
setSessionSnapshot(checkInCacheKey(userId), r.check_in);
|
||||||
|
setStatus(r.check_in);
|
||||||
|
await refresh();
|
||||||
|
} catch (e: unknown) {
|
||||||
|
notify.error(e instanceof Error ? e.message : '签到失败');
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}, [userId, refresh]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
status,
|
||||||
|
loading,
|
||||||
|
busy,
|
||||||
|
doCheckIn,
|
||||||
|
reload: () => load({ force: true }),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,6 +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, DEFAULT_FEED_SORT_TABS } from '../api/types';
|
||||||
|
|
||||||
const DEFAULT_LIMITS: ForumLimitsPublic = {
|
const DEFAULT_LIMITS: ForumLimitsPublic = {
|
||||||
post_title_max: 128,
|
post_title_max: 128,
|
||||||
@@ -16,8 +17,20 @@ const DEFAULT_LIMITS: ForumLimitsPublic = {
|
|||||||
signature_max: 200,
|
signature_max: 200,
|
||||||
open_posts_in_new_tab: true,
|
open_posts_in_new_tab: true,
|
||||||
open_content_links_in_new_tab: true,
|
open_content_links_in_new_tab: true,
|
||||||
|
aside_show_tag_cloud: false,
|
||||||
|
aside_show_recent_comments: false,
|
||||||
|
aside_show_friend_links: true,
|
||||||
|
aside_show_showcase: false,
|
||||||
|
aside_widgets: DEFAULT_ASIDE_WIDGETS,
|
||||||
|
nav_show_friend_links: true,
|
||||||
|
footer_show_friend_links: true,
|
||||||
|
nav_show_showcase: false,
|
||||||
|
footer_show_showcase: false,
|
||||||
|
feed_list_style: 'title',
|
||||||
|
feed_sort_tabs: DEFAULT_FEED_SORT_TABS,
|
||||||
permalink_enabled: false,
|
permalink_enabled: false,
|
||||||
permalink_ext: 'html',
|
permalink_ext: 'html',
|
||||||
|
monitor_pageview: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
let cached: ForumLimitsPublic | null = null;
|
let cached: ForumLimitsPublic | null = null;
|
||||||
@@ -67,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;
|
||||||
|
|||||||
41
frontend/src/hooks/useMonitorPageview.ts
Normal file
41
frontend/src/hooks/useMonitorPageview.ts
Normal 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]);
|
||||||
|
}
|
||||||
271
frontend/src/hooks/usePostSearch.ts
Normal file
271
frontend/src/hooks/usePostSearch.ts
Normal file
@@ -0,0 +1,271 @@
|
|||||||
|
import { useCallback, useMemo } from 'react';
|
||||||
|
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
|
||||||
|
import { buildHomeUrl } from '../components/FeedSortBar';
|
||||||
|
import { navigateFeed } from '../utils/feedCache';
|
||||||
|
import { transitionTo } from '../utils/spaTransition';
|
||||||
|
import { notify } from '@/lib/notify';
|
||||||
|
import { parsePermalinkID, type PermalinkOpts } from '../utils/permalink';
|
||||||
|
|
||||||
|
/** 打开搜索面板(全局事件) */
|
||||||
|
export const POST_SEARCH_OPEN_EVENT = 'post-search-open';
|
||||||
|
|
||||||
|
export type SearchFilterKey = 'keyword' | 'author' | 'titleOnly' | 'board';
|
||||||
|
|
||||||
|
export interface PostSearchSubmitInput {
|
||||||
|
keyword?: string;
|
||||||
|
author?: string;
|
||||||
|
titleOnly?: boolean;
|
||||||
|
/** 0 = 全站,>0 = 限定板块 */
|
||||||
|
scopeBoardId?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PostSearchState {
|
||||||
|
keyword: string;
|
||||||
|
author: string;
|
||||||
|
titleOnly: boolean;
|
||||||
|
scopeBoardId: number;
|
||||||
|
contextBoardId: number;
|
||||||
|
isFiltered: boolean;
|
||||||
|
hasAdvancedFilters: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RecentSearch {
|
||||||
|
keyword: string;
|
||||||
|
author: string;
|
||||||
|
titleOnly: boolean;
|
||||||
|
scopeBoardId: number;
|
||||||
|
at: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const RECENT_KEY = 'jiang13-recent-searches';
|
||||||
|
const RECENT_MAX = 5;
|
||||||
|
|
||||||
|
export function parseBoardIdFromLocation(pathname: string, params: URLSearchParams): number {
|
||||||
|
const m = pathname.match(/^\/board\/(\d+(?:\.[A-Za-z0-9]{1,16})?)$/);
|
||||||
|
if (m) return parsePermalinkID(m[1]) || 0;
|
||||||
|
const q = Number(params.get('board')) || 0;
|
||||||
|
return q > 0 ? q : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseSearchFromUrl(
|
||||||
|
pathname: string,
|
||||||
|
params: URLSearchParams,
|
||||||
|
): Pick<PostSearchState, 'keyword' | 'author' | 'titleOnly' | 'scopeBoardId'> {
|
||||||
|
const keyword = params.get('keyword') || '';
|
||||||
|
const author = params.get('author') || '';
|
||||||
|
const titleOnly = params.get('title_only') === '1';
|
||||||
|
const pathBoardId = parseBoardIdFromLocation(pathname, params);
|
||||||
|
const scopeBoardId = (keyword || author) && pathBoardId > 0 ? pathBoardId : 0;
|
||||||
|
return { keyword, author, titleOnly, scopeBoardId };
|
||||||
|
}
|
||||||
|
|
||||||
|
function readRecentSearches(): RecentSearch[] {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(RECENT_KEY);
|
||||||
|
if (!raw) return [];
|
||||||
|
const parsed = JSON.parse(raw) as RecentSearch[];
|
||||||
|
return Array.isArray(parsed) ? parsed.slice(0, RECENT_MAX) : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeRecentSearches(items: RecentSearch[]) {
|
||||||
|
try {
|
||||||
|
localStorage.setItem(RECENT_KEY, JSON.stringify(items.slice(0, RECENT_MAX)));
|
||||||
|
} catch {
|
||||||
|
/* 忽略存储失败 */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function saveRecentSearch(entry: Omit<RecentSearch, 'at'>) {
|
||||||
|
const kw = entry.keyword.trim();
|
||||||
|
const author = entry.author.trim();
|
||||||
|
if (!kw && !author) return;
|
||||||
|
const next: RecentSearch = { ...entry, keyword: kw, author, at: Date.now() };
|
||||||
|
const prev = readRecentSearches().filter(
|
||||||
|
(r) => !(r.keyword === next.keyword && r.author === next.author
|
||||||
|
&& r.titleOnly === next.titleOnly && r.scopeBoardId === next.scopeBoardId),
|
||||||
|
);
|
||||||
|
writeRecentSearches([next, ...prev]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRecentSearches(): RecentSearch[] {
|
||||||
|
return readRecentSearches();
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateKeyword(kw: string, limits: PermalinkOpts & { search_keyword_min: number; search_keyword_max: number }): boolean {
|
||||||
|
if (!kw) return true;
|
||||||
|
const len = [...kw].length;
|
||||||
|
if (limits.search_keyword_min > 0 && len < limits.search_keyword_min) {
|
||||||
|
notify.warning(`搜索关键词至少 ${limits.search_keyword_min} 个字`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (limits.search_keyword_max > 0 && len > limits.search_keyword_max) {
|
||||||
|
notify.warning(`搜索关键词最多 ${limits.search_keyword_max} 个字`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSameSearchTarget(
|
||||||
|
pathname: string,
|
||||||
|
params: URLSearchParams,
|
||||||
|
target: string,
|
||||||
|
input: Required<Pick<PostSearchSubmitInput, 'keyword' | 'author' | 'titleOnly' | 'scopeBoardId'>>,
|
||||||
|
): boolean {
|
||||||
|
const active = parseSearchFromUrl(pathname, params);
|
||||||
|
const activeBoard = parseBoardIdFromLocation(pathname, params);
|
||||||
|
const onFeed = pathname === '/' || /^\/board\/\d+/.test(pathname);
|
||||||
|
return onFeed
|
||||||
|
&& active.keyword === input.keyword
|
||||||
|
&& active.author === input.author
|
||||||
|
&& active.titleOnly === input.titleOnly
|
||||||
|
&& (input.scopeBoardId > 0 ? activeBoard === input.scopeBoardId : active.scopeBoardId === 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePostSearch(
|
||||||
|
limits: PermalinkOpts & { search_keyword_min: number; search_keyword_max: number },
|
||||||
|
) {
|
||||||
|
const nav = useNavigate();
|
||||||
|
const loc = useLocation();
|
||||||
|
const [params] = useSearchParams();
|
||||||
|
|
||||||
|
const contextBoardId = useMemo(
|
||||||
|
() => parseBoardIdFromLocation(loc.pathname, params),
|
||||||
|
[loc.pathname, params],
|
||||||
|
);
|
||||||
|
|
||||||
|
const filters = useMemo((): PostSearchState => {
|
||||||
|
const parsed = parseSearchFromUrl(loc.pathname, params);
|
||||||
|
const isFiltered = !!(parsed.keyword || parsed.author);
|
||||||
|
const hasAdvancedFilters = !!(
|
||||||
|
parsed.author
|
||||||
|
|| (parsed.titleOnly && parsed.keyword)
|
||||||
|
|| parsed.scopeBoardId > 0
|
||||||
|
);
|
||||||
|
return { ...parsed, contextBoardId, isFiltered, hasAdvancedFilters };
|
||||||
|
}, [loc.pathname, params, contextBoardId]);
|
||||||
|
|
||||||
|
const buildUrl = useCallback((input: PostSearchSubmitInput) => {
|
||||||
|
const kw = (input.keyword ?? '').trim();
|
||||||
|
const author = (input.author ?? '').trim();
|
||||||
|
const titleOnly = !!kw && (input.titleOnly ?? false);
|
||||||
|
const scopeBoard = input.scopeBoardId ?? 0;
|
||||||
|
return buildHomeUrl(scopeBoard, 'latest', {
|
||||||
|
keyword: kw,
|
||||||
|
author,
|
||||||
|
titleOnly,
|
||||||
|
permalink: limits,
|
||||||
|
});
|
||||||
|
}, [limits]);
|
||||||
|
|
||||||
|
const submitSearch = useCallback((
|
||||||
|
input: PostSearchSubmitInput,
|
||||||
|
opts?: { refreshIfSame?: boolean },
|
||||||
|
) => {
|
||||||
|
const kw = (input.keyword ?? '').trim();
|
||||||
|
const author = (input.author ?? '').trim();
|
||||||
|
const activeKw = (params.get('keyword') || '').trim();
|
||||||
|
const activeAuthor = (params.get('author') || '').trim();
|
||||||
|
|
||||||
|
if (!kw && !author) {
|
||||||
|
if (activeKw || activeAuthor) navigateFeed(nav, '/');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!validateKeyword(kw, limits)) return false;
|
||||||
|
|
||||||
|
const titleOnly = !!kw && (input.titleOnly ?? false);
|
||||||
|
const scopeBoardId = input.scopeBoardId ?? 0;
|
||||||
|
const target = buildUrl({ keyword: kw, author, titleOnly, scopeBoardId });
|
||||||
|
const normalized = {
|
||||||
|
keyword: kw,
|
||||||
|
author,
|
||||||
|
titleOnly,
|
||||||
|
scopeBoardId,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isSameSearchTarget(loc.pathname, params, target, normalized)) {
|
||||||
|
if (opts?.refreshIfSame) navigateFeed(nav, target);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
saveRecentSearch({ keyword: kw, author, titleOnly, scopeBoardId });
|
||||||
|
void transitionTo(nav, target);
|
||||||
|
return true;
|
||||||
|
}, [nav, params, loc.pathname, limits, buildUrl]);
|
||||||
|
|
||||||
|
const clearSearch = useCallback(() => {
|
||||||
|
navigateFeed(nav, '/');
|
||||||
|
}, [nav]);
|
||||||
|
|
||||||
|
const removeFilter = useCallback((key: SearchFilterKey) => {
|
||||||
|
const current = parseSearchFromUrl(loc.pathname, params);
|
||||||
|
if (!current.keyword && !current.author) return;
|
||||||
|
|
||||||
|
let next: PostSearchSubmitInput;
|
||||||
|
switch (key) {
|
||||||
|
case 'keyword':
|
||||||
|
next = {
|
||||||
|
keyword: '',
|
||||||
|
author: current.author,
|
||||||
|
titleOnly: false,
|
||||||
|
scopeBoardId: current.scopeBoardId,
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
case 'author':
|
||||||
|
next = {
|
||||||
|
keyword: current.keyword,
|
||||||
|
author: '',
|
||||||
|
titleOnly: current.titleOnly,
|
||||||
|
scopeBoardId: current.scopeBoardId,
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
case 'titleOnly':
|
||||||
|
next = {
|
||||||
|
keyword: current.keyword,
|
||||||
|
author: current.author,
|
||||||
|
titleOnly: false,
|
||||||
|
scopeBoardId: current.scopeBoardId,
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
case 'board':
|
||||||
|
next = {
|
||||||
|
keyword: current.keyword,
|
||||||
|
author: current.author,
|
||||||
|
titleOnly: current.titleOnly,
|
||||||
|
scopeBoardId: 0,
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const kw = (next.keyword ?? '').trim();
|
||||||
|
const author = (next.author ?? '').trim();
|
||||||
|
if (!kw && !author) {
|
||||||
|
clearSearch();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
nav(buildUrl({
|
||||||
|
keyword: kw,
|
||||||
|
author,
|
||||||
|
titleOnly: next.titleOnly,
|
||||||
|
scopeBoardId: next.scopeBoardId,
|
||||||
|
}));
|
||||||
|
}, [loc.pathname, params, nav, buildUrl, clearSearch]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
filters,
|
||||||
|
buildUrl,
|
||||||
|
submitSearch,
|
||||||
|
clearSearch,
|
||||||
|
removeFilter,
|
||||||
|
getRecentSearches,
|
||||||
|
saveRecentSearch,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function dispatchOpenPostSearch() {
|
||||||
|
window.dispatchEvent(new CustomEvent(POST_SEARCH_OPEN_EVENT));
|
||||||
|
}
|
||||||
161
frontend/src/hooks/useSessionResource.ts
Normal file
161
frontend/src/hooks/useSessionResource.ts
Normal 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 };
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
|||||||
75
frontend/src/hooks/useSitePages.ts
Normal file
75
frontend/src/hooks/useSitePages.ts
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { api } from '../api/client';
|
||||||
|
import type { SitePageSummary } from '../api/types';
|
||||||
|
import { PAGE_FORCE_REFRESH_EVENT } from '../utils/feedCache';
|
||||||
|
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
|
||||||
|
|
||||||
|
let cache: SitePageSummary[] | null = null;
|
||||||
|
let pending: Promise<SitePageSummary[]> | null = null;
|
||||||
|
|
||||||
|
/** 拉取或复用站点页摘要缓存(供冷启动门闩与 hook 共用) */
|
||||||
|
export function ensureSitePagesLoaded(opts?: { force?: boolean }): Promise<SitePageSummary[]> {
|
||||||
|
if (opts?.force) {
|
||||||
|
cache = null;
|
||||||
|
pending = null;
|
||||||
|
}
|
||||||
|
if (cache) return Promise.resolve(cache);
|
||||||
|
if (!pending) {
|
||||||
|
pending = api.pages()
|
||||||
|
.then(d => {
|
||||||
|
cache = d.pages ?? [];
|
||||||
|
return cache;
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
cache = [];
|
||||||
|
return cache;
|
||||||
|
})
|
||||||
|
.finally(() => { pending = null; });
|
||||||
|
}
|
||||||
|
return pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 已发布单页摘要(页脚/侧栏导航) */
|
||||||
|
export function useSitePages() {
|
||||||
|
const [pages, setPages] = useState<SitePageSummary[]>(cache ?? []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const load = () => {
|
||||||
|
void ensureSitePagesLoaded().then(setPages);
|
||||||
|
};
|
||||||
|
if (cache) setPages(cache);
|
||||||
|
else load();
|
||||||
|
|
||||||
|
const onForce = () => {
|
||||||
|
cache = null;
|
||||||
|
pending = null;
|
||||||
|
load();
|
||||||
|
};
|
||||||
|
const onCommit = () => {
|
||||||
|
// 软刷新:cache 已由 prefetch 写好,同步进 state
|
||||||
|
void ensureSitePagesLoaded().then(setPages);
|
||||||
|
};
|
||||||
|
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||||
|
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||||
|
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return {
|
||||||
|
pages,
|
||||||
|
footerPages: pages.filter(p => p.show_in_footer),
|
||||||
|
navPages: pages.filter(p => p.show_in_nav),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function invalidateSitePagesCache() {
|
||||||
|
cache = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 文档 SSR:同步写入站点页摘要缓存 */
|
||||||
|
export function seedSitePagesCache(pages: SitePageSummary[]) {
|
||||||
|
cache = Array.isArray(pages) ? pages : [];
|
||||||
|
pending = null;
|
||||||
|
}
|
||||||
@@ -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,
|
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';
|
||||||
@@ -16,13 +16,15 @@ import { useNoIndexSEO } from '../hooks/usePageSEO';
|
|||||||
import SiteBrandMark from '../components/SiteBrandMark';
|
import SiteBrandMark from '../components/SiteBrandMark';
|
||||||
import { api } from '../api/client';
|
import { api } from '../api/client';
|
||||||
|
|
||||||
type BadgeKey = 'posts' | 'comments' | 'reports';
|
type BadgeKey = 'posts' | 'comments' | 'reports' | 'links';
|
||||||
|
|
||||||
type NavItem = {
|
type NavItem = {
|
||||||
to: string;
|
to: string;
|
||||||
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 },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -50,8 +54,10 @@ const NAV_GROUPS: NavGroup[] = [
|
|||||||
label: '社区',
|
label: '社区',
|
||||||
items: [
|
items: [
|
||||||
{ to: '/admin/boards', label: '板块管理', icon: FolderKanban },
|
{ to: '/admin/boards', label: '板块管理', icon: FolderKanban },
|
||||||
|
{ to: '/admin/pages', label: '单页管理', icon: BookOpen },
|
||||||
{ to: '/admin/users', label: '用户管理', icon: Users },
|
{ to: '/admin/users', label: '用户管理', icon: Users },
|
||||||
{ to: '/admin/badges', label: '徽章管理', icon: Award },
|
{ to: '/admin/badges', label: '徽章管理', icon: Award },
|
||||||
|
{ to: '/admin/links', label: '友情链接', icon: Link2, badgeKey: 'links' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -67,6 +73,7 @@ type PendingCounts = {
|
|||||||
posts: number;
|
posts: number;
|
||||||
comments: number;
|
comments: number;
|
||||||
reports: number;
|
reports: number;
|
||||||
|
links: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
function formatNavBadge(n: number) {
|
function formatNavBadge(n: number) {
|
||||||
@@ -82,7 +89,8 @@ export default function AdminLayout() {
|
|||||||
useNoIndexSEO('管理后台');
|
useNoIndexSEO('管理后台');
|
||||||
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 });
|
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);
|
||||||
@@ -99,10 +107,30 @@ export default function AdminLayout() {
|
|||||||
posts: d.pending_posts ?? 0,
|
posts: d.pending_posts ?? 0,
|
||||||
comments: d.pending_comments ?? 0,
|
comments: d.pending_comments ?? 0,
|
||||||
reports: d.pending_reports ?? 0,
|
reports: d.pending_reports ?? 0,
|
||||||
|
links: d.pending_friend_links ?? 0,
|
||||||
}))
|
}))
|
||||||
.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(() => {
|
||||||
|
if (loading || !user || user.role !== 'admin') return;
|
||||||
|
refreshPending();
|
||||||
|
const onRefresh = () => refreshPending();
|
||||||
|
window.addEventListener('admin-pending-refresh', onRefresh);
|
||||||
|
const timer = window.setInterval(refreshPending, 60_000);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('admin-pending-refresh', onRefresh);
|
||||||
|
window.clearInterval(timer);
|
||||||
|
};
|
||||||
|
}, [loading, user, refreshPending]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (loading) return;
|
if (loading) return;
|
||||||
if (!user) {
|
if (!user) {
|
||||||
@@ -140,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
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
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 } from 'lucide-react';
|
import { Menu, Moon, Sun, Search, Plus, PanelRight, X, Mail, SlidersHorizontal } from 'lucide-react';
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
@@ -14,41 +12,68 @@ import { useAuth } from '../hooks/useAuth';
|
|||||||
import { useTheme, useMediaQuery } from '../hooks/useTheme';
|
import { useTheme, useMediaQuery } from '../hooks/useTheme';
|
||||||
import { useOverlayA11y, moveTabIndex } from '../hooks/useOverlayA11y';
|
import { useOverlayA11y, moveTabIndex } from '../hooks/useOverlayA11y';
|
||||||
import { api } from '../api/client';
|
import { api } from '../api/client';
|
||||||
import type { Board, PostItem, RecentComment, ForumStats, TagCount, User } from '../api/types';
|
import type { Board, RecentComment, RecentUser, ForumStats, TagCount, User } from '../api/types';
|
||||||
import type { PostHeading } from '../utils/postHeadings';
|
import type { PostHeading } from '../utils/postHeadings';
|
||||||
import { getCachedBoards, getCachedStats, getCachedHot, getCachedRecentComments, getCachedTags, hasCachedAside, setCachedBoards, setCachedStats, setCachedHot, setCachedRecentComments, setCachedTags } from '../utils/layoutCache';
|
import { getCachedBoards, getCachedStats, getCachedRecentComments, getCachedRecentUsers, getCachedTags, hasCachedAside, setCachedBoards, setCachedStats, setCachedRecentComments, setCachedRecentUsers, setCachedTags } from '../utils/layoutCache';
|
||||||
import Sidebar, { isNeutralSidebarRoute } from '../components/Sidebar';
|
import Sidebar, { isNeutralSidebarRoute } from '../components/Sidebar';
|
||||||
import RightPanel from '../components/RightPanel';
|
import RightPanel from '../components/RightPanel';
|
||||||
import BackToTop from '../components/BackToTop';
|
import BackToTop from '../components/BackToTop';
|
||||||
import { useForumLimits } from '../hooks/useForumLimits';
|
import { useForumLimits } from '../hooks/useForumLimits';
|
||||||
|
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 { notify } from '@/lib/notify';
|
import { PAGE_SOFT_REFRESH_COMMIT_EVENT } from '../utils/softRefresh';
|
||||||
|
import { prefetchRoute, wasColdBootEnsured } from '../utils/prefetchRoute';
|
||||||
|
import {
|
||||||
|
transitionTo,
|
||||||
|
} from '../utils/spaTransition';
|
||||||
|
import PostSearchPanel from '../components/search/PostSearchPanel';
|
||||||
|
import {
|
||||||
|
POST_SEARCH_OPEN_EVENT,
|
||||||
|
usePostSearch,
|
||||||
|
} from '../hooks/usePostSearch';
|
||||||
import { cn } from '@/lib/utils';
|
import { 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 { 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 [hot, setHot] = useState<PostItem[]>(() => getCachedHot());
|
|
||||||
const [recentComments, setRecentComments] = useState<RecentComment[]>(() => getCachedRecentComments());
|
const [recentComments, setRecentComments] = useState<RecentComment[]>(() => getCachedRecentComments());
|
||||||
const [unreadMessages, setUnreadMessages] = useState(0);
|
const [recentUsers, setRecentUsers] = useState<RecentUser[]>(() => getCachedRecentUsers());
|
||||||
|
const [unreadMessages, setUnreadMessages] = useState(() => getBootUnread());
|
||||||
|
const [dmUnread, setDmUnread] = useState(0);
|
||||||
|
const [notifyUnread, setNotifyUnread] = useState(0);
|
||||||
const [tags, setTags] = useState<TagCount[]>(() => getCachedTags());
|
const [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<{
|
||||||
@@ -61,19 +86,29 @@ export default function MainLayout() {
|
|||||||
} | null>(null);
|
} | null>(null);
|
||||||
const [asideOpen, setAsideOpen] = useState(false);
|
const [asideOpen, setAsideOpen] = useState(false);
|
||||||
const [sidebarOpen, setSidebarOpen] = useState(false);
|
const [sidebarOpen, setSidebarOpen] = useState(false);
|
||||||
const [searchExpanded, setSearchExpanded] = useState(false);
|
const [searchPanelOpen, setSearchPanelOpen] = useState(false);
|
||||||
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);
|
||||||
const [boardId, setBoardId] = useState(Number(params.get('board')) || 0);
|
/** 冷启动门闩:main.tsx 已预热则可同步放行;否则等齐再呈现 */
|
||||||
const [keyword, setKeyword] = useState(params.get('keyword') || '');
|
const [shellReady, setShellReady] = useState(() => isCompose || wasColdBootEnsured());
|
||||||
const [searchAuthor, setSearchAuthor] = useState(params.get('author') || '');
|
const coldBootDone = useRef(isCompose || wasColdBootEnsured());
|
||||||
const [searchTitleOnly, setSearchTitleOnly] = useState(params.get('title_only') === '1');
|
const bootGen = useRef(0);
|
||||||
const [searchInBoard, setSearchInBoard] = useState(!!params.get('board') && !!params.get('keyword'));
|
const [boardId, setBoardId] = useState(() => {
|
||||||
const [searchAdvanced, setSearchAdvanced] = useState(false);
|
const m = loc.pathname.match(/^\/board\/(\d+(?:\.[A-Za-z0-9]{1,16})?)$/);
|
||||||
const feedSort = parseFeedSort(params.get('sort'));
|
if (m) return parsePermalinkID(m[1]) || 0;
|
||||||
|
return Number(params.get('board')) || 0;
|
||||||
|
});
|
||||||
|
const [keywordDraft, setKeywordDraft] = useState(params.get('keyword') || '');
|
||||||
const { limits: forumLimits } = useForumLimits();
|
const { limits: forumLimits } = useForumLimits();
|
||||||
|
const feedSort = parseFeedSort(params.get('sort'), forumLimits.feed_sort_tabs);
|
||||||
|
const postSearch = usePostSearch(forumLimits);
|
||||||
|
const asideWidgets = useMemo(() => resolveAsideWidgets(forumLimits), [forumLimits]);
|
||||||
|
const showTagCloud = asideWidgets.some(w => w.id === 'tag_cloud' && w.enabled);
|
||||||
|
const showRecentComments = asideWidgets.some(w => w.id === 'recent_comments' && w.enabled);
|
||||||
|
const showRecentUsers = asideWidgets.some(w => w.id === 'recent_users' && w.enabled);
|
||||||
|
|
||||||
const asideDrawerRef = useRef<HTMLElement>(null);
|
const asideDrawerRef = useRef<HTMLElement>(null);
|
||||||
const asideCloseRef = useRef<HTMLButtonElement>(null);
|
const asideCloseRef = useRef<HTMLButtonElement>(null);
|
||||||
@@ -99,35 +134,60 @@ export default function MainLayout() {
|
|||||||
initialFocusRef: sidebarCloseRef,
|
initialFocusRef: sidebarCloseRef,
|
||||||
});
|
});
|
||||||
|
|
||||||
useEffect(() => { setBoardId(Number(params.get('board')) || 0); }, [params]);
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setKeyword(params.get('keyword') || '');
|
const m = loc.pathname.match(/^\/board\/(\d+(?:\.[A-Za-z0-9]{1,16})?)$/);
|
||||||
setSearchAuthor(params.get('author') || '');
|
if (m) {
|
||||||
setSearchTitleOnly(params.get('title_only') === '1');
|
setBoardId(parsePermalinkID(m[1]) || 0);
|
||||||
setSearchInBoard(!!params.get('board') && (!!params.get('keyword') || !!params.get('author')));
|
return;
|
||||||
|
}
|
||||||
|
setBoardId(Number(params.get('board')) || 0);
|
||||||
|
}, [loc.pathname, params]);
|
||||||
|
useEffect(() => {
|
||||||
|
setKeywordDraft(params.get('keyword') || '');
|
||||||
}, [params]);
|
}, [params]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setAsideOpen(false);
|
setAsideOpen(false);
|
||||||
setSidebarOpen(false);
|
setSidebarOpen(false);
|
||||||
setSearchExpanded(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);
|
||||||
}, [hideAside]);
|
}, [hideAside]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isMobile) {
|
if (!isMobile) setSidebarOpen(false);
|
||||||
setSidebarOpen(false);
|
|
||||||
setSearchExpanded(false);
|
|
||||||
}
|
|
||||||
}, [isMobile]);
|
}, [isMobile]);
|
||||||
|
|
||||||
|
const openSearchPanel = useCallback(() => setSearchPanelOpen(true), []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!searchExpanded) return;
|
const onOpen = () => setSearchPanelOpen(true);
|
||||||
const t = window.setTimeout(() => searchInputRef.current?.focus(), 50);
|
window.addEventListener(POST_SEARCH_OPEN_EVENT, onOpen);
|
||||||
return () => window.clearTimeout(t);
|
return () => window.removeEventListener(POST_SEARCH_OPEN_EVENT, onOpen);
|
||||||
}, [searchExpanded]);
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isCompose) return;
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if (!(e.ctrlKey || e.metaKey) || e.key.toLowerCase() !== 'k') return;
|
||||||
|
const tag = (e.target as HTMLElement | null)?.tagName;
|
||||||
|
const editable = (e.target as HTMLElement | null)?.isContentEditable;
|
||||||
|
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || editable) return;
|
||||||
|
e.preventDefault();
|
||||||
|
if (isMobile) {
|
||||||
|
setSearchPanelOpen(true);
|
||||||
|
} else {
|
||||||
|
searchInputRef.current?.focus();
|
||||||
|
searchInputRef.current?.select();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.addEventListener('keydown', onKey);
|
||||||
|
return () => window.removeEventListener('keydown', onKey);
|
||||||
|
}, [isCompose, isMobile]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!asideOpen && !sidebarOpen) return;
|
if (!asideOpen && !sidebarOpen) return;
|
||||||
const prev = document.body.style.overflow;
|
const prev = document.body.style.overflow;
|
||||||
@@ -160,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();
|
||||||
@@ -181,10 +345,49 @@ export default function MainLayout() {
|
|||||||
};
|
};
|
||||||
}, [refreshUnreadMessages]);
|
}, [refreshUnreadMessages]);
|
||||||
|
|
||||||
// 标签云:进页/离开发帖页时拉取;不跟 posts-refresh 联动(置顶/精华等不改标签)
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isCompose) return;
|
const syncFromCache = () => {
|
||||||
|
// 仅当 cache 有内容时覆盖,避免空数组盖住已渲染的非空 UI
|
||||||
|
const nextBoards = getCachedBoards();
|
||||||
|
if (nextBoards.length > 0) setBoards(nextBoards);
|
||||||
|
setBoardsLoading(false);
|
||||||
|
const nextStats = getCachedStats();
|
||||||
|
if (nextStats) setStats(nextStats);
|
||||||
|
const nextComments = getCachedRecentComments();
|
||||||
|
if (nextComments.length > 0 || hasCachedAside()) setRecentComments(nextComments);
|
||||||
|
const nextUsers = getCachedRecentUsers();
|
||||||
|
if (nextUsers.length > 0 || hasCachedAside()) setRecentUsers(nextUsers);
|
||||||
|
const nextTags = getCachedTags();
|
||||||
|
if (nextTags.length > 0) setTags(nextTags);
|
||||||
|
setTagsLoading(false);
|
||||||
|
setAsideLoading(false);
|
||||||
|
asideEverLoaded.current = true;
|
||||||
|
refreshUnreadMessages();
|
||||||
|
};
|
||||||
|
const onForce = () => {
|
||||||
|
// 旧路径:仍可能被别处派发;尽量静默刷新壳层
|
||||||
|
refreshBoards();
|
||||||
|
refreshUnreadMessages();
|
||||||
|
refetchSiteBranding();
|
||||||
|
setLayoutRefreshTick(n => n + 1);
|
||||||
|
};
|
||||||
|
const onCommit = () => {
|
||||||
|
// 软刷新:预热已写入 cache,同一拍同步进 state,不触发分批 loading
|
||||||
|
syncFromCache();
|
||||||
|
};
|
||||||
|
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||||
|
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||||
|
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||||
|
};
|
||||||
|
}, [refreshBoards, refreshUnreadMessages]);
|
||||||
|
|
||||||
|
// 标签云:进页/离开发帖页时拉取;不跟 posts-refresh 联动(置顶/推荐等不改标签)
|
||||||
|
useEffect(() => {
|
||||||
|
if (isCompose || !showTagCloud) return;
|
||||||
let cancelled = false;
|
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;
|
||||||
@@ -197,31 +400,24 @@ export default function MainLayout() {
|
|||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
};
|
};
|
||||||
}, [isCompose]);
|
}, [isCompose, showTagCloud, layoutRefreshTick]);
|
||||||
|
|
||||||
const needAsideData = !isCompose && (!hideAside || asideOpen);
|
const needAsideData = !isCompose && (!hideAside || asideOpen);
|
||||||
|
const needRecentComments = needAsideData && showRecentComments;
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!needAsideData) return;
|
if (!needRecentComments) return;
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
// 无缓存时才显示加载态,有缓存则静默刷新,避免抽屉高度跳动
|
// 无缓存时才显示加载态,有缓存则静默刷新,避免抽屉高度跳动
|
||||||
if (!asideEverLoaded.current && !hasCachedAside()) {
|
if (!asideEverLoaded.current && !hasCachedAside()) {
|
||||||
setAsideLoading(true);
|
setAsideLoading(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
Promise.all([
|
|
||||||
api.hotPosts().then(d => {
|
|
||||||
if (cancelled) return;
|
|
||||||
const next = Array.isArray(d.posts) ? d.posts : [];
|
|
||||||
setHot(next);
|
|
||||||
setCachedHot(next);
|
|
||||||
}).catch(() => {}),
|
|
||||||
api.recentComments().then(d => {
|
api.recentComments().then(d => {
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
const next = Array.isArray(d.comments) ? d.comments : [];
|
const next = Array.isArray(d.comments) ? d.comments : [];
|
||||||
setRecentComments(next);
|
setRecentComments(next);
|
||||||
setCachedRecentComments(next);
|
setCachedRecentComments(next);
|
||||||
}).catch(() => {}),
|
}).catch(() => {}).finally(() => {
|
||||||
]).finally(() => {
|
|
||||||
if (!cancelled) {
|
if (!cancelled) {
|
||||||
asideEverLoaded.current = true;
|
asideEverLoaded.current = true;
|
||||||
setAsideLoading(false);
|
setAsideLoading(false);
|
||||||
@@ -231,47 +427,55 @@ export default function MainLayout() {
|
|||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
};
|
};
|
||||||
}, [needAsideData]);
|
}, [needRecentComments, layoutRefreshTick]);
|
||||||
|
|
||||||
const doSearch = () => {
|
const needRecentUsers = needAsideData && showRecentUsers;
|
||||||
const kw = keyword.trim();
|
useEffect(() => {
|
||||||
const author = searchAuthor.trim();
|
if (!needRecentUsers) return;
|
||||||
const activeKw = (params.get('keyword') || '').trim();
|
let cancelled = false;
|
||||||
const activeAuthor = (params.get('author') || '').trim();
|
if (!asideEverLoaded.current && !hasCachedAside()) {
|
||||||
const activeTitleOnly = params.get('title_only') === '1';
|
setAsideLoading(true);
|
||||||
const activeBoard = Number(params.get('board')) || 0;
|
|
||||||
if (!kw && !author) {
|
|
||||||
if (activeKw || activeAuthor) navigateFeed(nav, '/');
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
if (kw) {
|
|
||||||
const len = [...kw].length;
|
api.recentUsers().then(d => {
|
||||||
if (forumLimits.search_keyword_min > 0 && len < forumLimits.search_keyword_min) {
|
if (cancelled) return;
|
||||||
notify.warning(`搜索关键词至少 ${forumLimits.search_keyword_min} 个字`);
|
const next = Array.isArray(d.users) ? d.users : [];
|
||||||
return;
|
setRecentUsers(next);
|
||||||
|
setCachedRecentUsers(next);
|
||||||
|
}).catch(() => {}).finally(() => {
|
||||||
|
if (!cancelled) {
|
||||||
|
asideEverLoaded.current = true;
|
||||||
|
setAsideLoading(false);
|
||||||
}
|
}
|
||||||
if (forumLimits.search_keyword_max > 0 && len > forumLimits.search_keyword_max) {
|
|
||||||
notify.warning(`搜索关键词最多 ${forumLimits.search_keyword_max} 个字`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const scopeBoard = searchInBoard && boardId > 0 ? boardId : 0;
|
|
||||||
const target = buildHomeUrl(scopeBoard, 'latest', {
|
|
||||||
keyword: kw,
|
|
||||||
author,
|
|
||||||
titleOnly: !!kw && searchTitleOnly,
|
|
||||||
});
|
});
|
||||||
const same =
|
|
||||||
loc.pathname === '/'
|
return () => {
|
||||||
&& activeKw === kw
|
cancelled = true;
|
||||||
&& activeAuthor === author
|
};
|
||||||
&& activeTitleOnly === (!!kw && searchTitleOnly)
|
}, [needRecentUsers, layoutRefreshTick]);
|
||||||
&& activeBoard === scopeBoard;
|
|
||||||
if (same) {
|
const doQuickSearch = () => {
|
||||||
navigateFeed(nav, target);
|
const { author, titleOnly, scopeBoardId } = postSearch.filters;
|
||||||
return;
|
postSearch.submitSearch({
|
||||||
}
|
keyword: keywordDraft,
|
||||||
nav(target);
|
author,
|
||||||
|
titleOnly,
|
||||||
|
scopeBoardId,
|
||||||
|
}, { refreshIfSame: true });
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleHeaderClear = () => {
|
||||||
|
const hasUrlSearch = postSearch.filters.isFiltered;
|
||||||
|
setKeywordDraft('');
|
||||||
|
if (hasUrlSearch) postSearch.clearSearch();
|
||||||
|
};
|
||||||
|
|
||||||
|
const contextBoard = boards.find((b) => b.id === boardId);
|
||||||
|
const searchPanelDraft = {
|
||||||
|
keyword: keywordDraft,
|
||||||
|
author: postSearch.filters.author,
|
||||||
|
titleOnly: postSearch.filters.titleOnly,
|
||||||
|
scopeBoardId: postSearch.filters.scopeBoardId,
|
||||||
};
|
};
|
||||||
|
|
||||||
const openPost = useCallback((id: number, opts?: { floor?: number }) => {
|
const openPost = useCallback((id: number, opts?: { floor?: number }) => {
|
||||||
@@ -280,7 +484,7 @@ export default function MainLayout() {
|
|||||||
}, [nav, forumLimits.open_posts_in_new_tab]);
|
}, [nav, forumLimits.open_posts_in_new_tab]);
|
||||||
|
|
||||||
const userInitial = user?.nickname?.charAt(0) || '?';
|
const userInitial = user?.nickname?.charAt(0) || '?';
|
||||||
const isFeedHome = loc.pathname === '/';
|
const isFeedHome = loc.pathname === '/' || /^\/board\/\d+/.test(loc.pathname);
|
||||||
const outletKeyword = params.get('keyword') || '';
|
const outletKeyword = params.get('keyword') || '';
|
||||||
const outletTag = params.get('tag') || '';
|
const outletTag = params.get('tag') || '';
|
||||||
const outletAuthor = params.get('author') || '';
|
const outletAuthor = params.get('author') || '';
|
||||||
@@ -294,6 +498,10 @@ export default function MainLayout() {
|
|||||||
const activeChipIndex = Math.max(0, boardChipIds.indexOf(mobileActiveBoard === -1 ? 0 : mobileActiveBoard));
|
const 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;
|
||||||
@@ -318,7 +526,7 @@ export default function MainLayout() {
|
|||||||
|
|
||||||
const selectBoardChip = (id: number) => {
|
const selectBoardChip = (id: number) => {
|
||||||
setBoardId(id);
|
setBoardId(id);
|
||||||
navigateFeed(nav, buildHomeUrl(id, feedSort));
|
navigateFeed(nav, buildHomeUrl(id, feedSort, { permalink: forumLimits }));
|
||||||
};
|
};
|
||||||
|
|
||||||
const onBoardBarKeyDown = (e: React.KeyboardEvent) => {
|
const onBoardBarKeyDown = (e: React.KeyboardEvent) => {
|
||||||
@@ -333,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${searchExpanded && isMobile ? ' app-header--search-open' : ''}`}>
|
<header className="app-header">
|
||||||
<div className="header-inner">
|
<div className="header-inner">
|
||||||
{isMobile && !isCompose && !searchExpanded && (
|
{!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}
|
||||||
@@ -350,33 +558,42 @@ export default function MainLayout() {
|
|||||||
<Menu size={18} aria-hidden />
|
<Menu size={18} aria-hidden />
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
{!(isMobile && searchExpanded) && (
|
{/* 任意页点 Logo:回首页并强制刷新,不展示会话缓存 */}
|
||||||
<button type="button" className="header-brand" onClick={() => navigateFeed(nav, '/')}>
|
<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 && !searchExpanded && (
|
{!isCompose && isMobile && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="header-icon-btn header-search-toggle"
|
className={cn(
|
||||||
onClick={() => setSearchExpanded(true)}
|
'header-search-mobile-pill',
|
||||||
|
(keywordDraft || postSearch.filters.isFiltered) && 'header-search-mobile-pill--active',
|
||||||
|
)}
|
||||||
|
onClick={openSearchPanel}
|
||||||
aria-label="搜索帖子"
|
aria-label="搜索帖子"
|
||||||
title="搜索"
|
|
||||||
>
|
>
|
||||||
<Search size={18} aria-hidden />
|
<Search size={15} aria-hidden className="header-search-mobile-pill__icon" />
|
||||||
|
<span className="header-search-mobile-pill__text">
|
||||||
|
{keywordDraft
|
||||||
|
|| postSearch.filters.keyword
|
||||||
|
|| postSearch.filters.author
|
||||||
|
|| '搜索帖子…'}
|
||||||
|
</span>
|
||||||
|
{postSearch.filters.hasAdvancedFilters && (
|
||||||
|
<span className="header-search-mobile-pill__dot" aria-hidden />
|
||||||
|
)}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!isCompose && (!isMobile || searchExpanded) && (
|
{!isCompose && !isMobile && (
|
||||||
<form
|
<form
|
||||||
className={`header-search-wrap${isMobile && searchExpanded ? ' header-search-wrap--expanded' : ''}${searchAdvanced ? ' header-search-wrap--advanced' : ''}`}
|
className="header-search-wrap"
|
||||||
role="search"
|
role="search"
|
||||||
onSubmit={e => {
|
onSubmit={e => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
doSearch();
|
doQuickSearch();
|
||||||
if (isMobile) setSearchExpanded(false);
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div className="header-search-row">
|
<div className="header-search-row">
|
||||||
@@ -385,89 +602,51 @@ export default function MainLayout() {
|
|||||||
ref={searchInputRef}
|
ref={searchInputRef}
|
||||||
className="header-search-input"
|
className="header-search-input"
|
||||||
type="search"
|
type="search"
|
||||||
placeholder="搜索帖子..."
|
placeholder="搜索帖子…"
|
||||||
aria-label="搜索帖子"
|
aria-label="搜索帖子"
|
||||||
value={keyword}
|
value={keywordDraft}
|
||||||
onChange={e => setKeyword(e.target.value)}
|
onChange={e => setKeywordDraft(e.target.value)}
|
||||||
maxLength={forumLimits.search_keyword_max > 0 ? forumLimits.search_keyword_max : undefined}
|
maxLength={forumLimits.search_keyword_max > 0 ? forumLimits.search_keyword_max : undefined}
|
||||||
enterKeyHint="search"
|
enterKeyHint="search"
|
||||||
/>
|
/>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className={cn('header-search-adv-toggle', searchAdvanced && 'active')}
|
className={cn(
|
||||||
onClick={() => setSearchAdvanced((v) => !v)}
|
'header-search-filter-btn',
|
||||||
aria-expanded={searchAdvanced}
|
postSearch.filters.hasAdvancedFilters && 'header-search-filter-btn--active',
|
||||||
title="高级搜索"
|
)}
|
||||||
|
onClick={openSearchPanel}
|
||||||
|
aria-label="搜索筛选"
|
||||||
|
title="筛选"
|
||||||
>
|
>
|
||||||
筛选
|
<SlidersHorizontal size={15} aria-hidden />
|
||||||
|
{postSearch.filters.hasAdvancedFilters && (
|
||||||
|
<span className="header-search-filter-btn__dot" aria-hidden />
|
||||||
|
)}
|
||||||
</button>
|
</button>
|
||||||
{(keyword || searchAuthor) && (
|
{(keywordDraft || postSearch.filters.isFiltered) && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="header-search-clear"
|
className="header-search-clear"
|
||||||
onClick={() => {
|
onClick={handleHeaderClear}
|
||||||
setKeyword('');
|
|
||||||
setSearchAuthor('');
|
|
||||||
setSearchTitleOnly(false);
|
|
||||||
navigateFeed(nav, '/');
|
|
||||||
}}
|
|
||||||
aria-label="清除搜索"
|
aria-label="清除搜索"
|
||||||
>×</button>
|
>×</button>
|
||||||
)}
|
)}
|
||||||
{isMobile && searchExpanded && (
|
<kbd className="header-search-kbd" aria-hidden>Ctrl K</kbd>
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="header-search-cancel"
|
|
||||||
onClick={() => setSearchExpanded(false)}
|
|
||||||
>
|
|
||||||
取消
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
{searchAdvanced && (
|
|
||||||
<div className="header-search-advanced">
|
|
||||||
<label className="header-search-opt">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={searchTitleOnly}
|
|
||||||
onChange={(e) => setSearchTitleOnly(e.target.checked)}
|
|
||||||
/>
|
|
||||||
仅标题
|
|
||||||
</label>
|
|
||||||
{boardId > 0 && (
|
|
||||||
<label className="header-search-opt">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={searchInBoard}
|
|
||||||
onChange={(e) => setSearchInBoard(e.target.checked)}
|
|
||||||
/>
|
|
||||||
当前板块
|
|
||||||
</label>
|
|
||||||
)}
|
|
||||||
<input
|
|
||||||
className="header-search-author"
|
|
||||||
type="text"
|
|
||||||
placeholder="作者用户名/昵称"
|
|
||||||
aria-label="作者"
|
|
||||||
value={searchAuthor}
|
|
||||||
onChange={(e) => setSearchAuthor(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</form>
|
</form>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!(isMobile && searchExpanded) && (
|
|
||||||
<div className="header-actions">
|
<div className="header-actions">
|
||||||
{!isCompose && (
|
{!isCompose && (
|
||||||
<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>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -478,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 />
|
||||||
@@ -508,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 && (
|
||||||
@@ -528,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' ? '切换暗色模式' : '切换亮色模式'}
|
||||||
@@ -561,17 +738,33 @@ export default function MainLayout() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div className={`app-body${isCompose ? ' app-body--compose' : ''}`}>
|
|
||||||
{!isCompose && (
|
{!isCompose && (
|
||||||
|
<PostSearchPanel
|
||||||
|
open={searchPanelOpen}
|
||||||
|
onOpenChange={setSearchPanelOpen}
|
||||||
|
draft={searchPanelDraft}
|
||||||
|
contextBoardId={boardId}
|
||||||
|
contextBoardName={contextBoard?.name}
|
||||||
|
onSubmit={(input) => {
|
||||||
|
const ok = postSearch.submitSearch(input);
|
||||||
|
if (ok) setKeywordDraft((input.keyword ?? '').trim());
|
||||||
|
return ok;
|
||||||
|
}}
|
||||||
|
onClear={postSearch.clearSearch}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className={`app-body${isCompose ? ' app-body--compose' : ''}`}>
|
||||||
|
{!isCompose && shellReady && (
|
||||||
<Sidebar
|
<Sidebar
|
||||||
boards={boards}
|
boards={boards}
|
||||||
activeBoard={boardId}
|
activeBoard={boardId}
|
||||||
onSelectBoard={setBoardId}
|
onSelectBoard={setBoardId}
|
||||||
boardsLoading={boardsLoading}
|
boardsLoading={boardsLoading}
|
||||||
|
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -580,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
|
||||||
|
className={cn(
|
||||||
'main-content',
|
'main-content',
|
||||||
isCompose && 'main-content--compose',
|
isCompose && 'main-content--compose',
|
||||||
// 手机 Feed:整栏滚动,板块条 / 排序栏可滚出视口,多露出帖子列表
|
// 手机 Feed:整栏滚动,板块条 / 排序栏可滚出视口,多露出帖子列表
|
||||||
isMobile && !isCompose && isFeedHome && 'main-content--feed-mobile-scroll',
|
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"
|
||||||
@@ -624,21 +820,27 @@ export default function MainLayout() {
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<Suspense fallback={isFeedHome ? <FeedPageSkeleton /> : <PageLoader />}>
|
{shellReady ? (
|
||||||
|
<Suspense fallback={null}>
|
||||||
<Outlet context={layoutCtx} />
|
<Outlet context={layoutCtx} />
|
||||||
</Suspense>
|
</Suspense>
|
||||||
|
) : null}
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
{!isCompose && (
|
{!isCompose && (
|
||||||
<aside className="aside-panel">
|
<aside className="aside-panel" aria-busy={!shellReady}>
|
||||||
|
{shellReady && (
|
||||||
<RightPanel
|
<RightPanel
|
||||||
hot={hot}
|
|
||||||
recentComments={recentComments}
|
recentComments={recentComments}
|
||||||
|
recentUsers={recentUsers}
|
||||||
tags={tags}
|
tags={tags}
|
||||||
tagsLoading={tagsLoading}
|
tagsLoading={tagsLoading}
|
||||||
|
stats={stats}
|
||||||
loading={asideLoading}
|
loading={asideLoading}
|
||||||
|
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,
|
||||||
@@ -647,6 +849,7 @@ export default function MainLayout() {
|
|||||||
outlineTitle: postOutline?.title,
|
outlineTitle: postOutline?.title,
|
||||||
} : null}
|
} : null}
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
</aside>
|
</aside>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -686,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"
|
||||||
@@ -699,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"
|
||||||
@@ -730,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"
|
||||||
@@ -746,13 +951,15 @@ export default function MainLayout() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="aside-drawer-body">
|
<div className="aside-drawer-body">
|
||||||
<RightPanel
|
<RightPanel
|
||||||
hot={hot}
|
|
||||||
recentComments={recentComments}
|
recentComments={recentComments}
|
||||||
|
recentUsers={recentUsers}
|
||||||
tags={tags}
|
tags={tags}
|
||||||
tagsLoading={tagsLoading}
|
tagsLoading={tagsLoading}
|
||||||
|
stats={stats}
|
||||||
loading={asideLoading}
|
loading={asideLoading}
|
||||||
|
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,
|
||||||
|
|||||||
@@ -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)
|
||||||
|
window.addEventListener('vite:preloadError', (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
reloadForStaleChunk();
|
||||||
|
});
|
||||||
|
|
||||||
|
function hasSSRHome(): boolean {
|
||||||
|
return !!document.querySelector('#root .ssr-home');
|
||||||
|
}
|
||||||
|
|
||||||
|
function waitForStylesheets(): Promise<void> {
|
||||||
|
const links = Array.from(document.querySelectorAll('link[rel="stylesheet"]'));
|
||||||
|
if (links.length === 0) return Promise.resolve();
|
||||||
|
return Promise.all(
|
||||||
|
links.map(
|
||||||
|
(node) =>
|
||||||
|
new Promise<void>((resolve) => {
|
||||||
|
const link = node as HTMLLinkElement;
|
||||||
|
try {
|
||||||
|
if (link.sheet) {
|
||||||
|
resolve();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* cross-origin */
|
||||||
|
}
|
||||||
|
const finish = () => resolve();
|
||||||
|
link.addEventListener('load', finish, { once: true });
|
||||||
|
link.addEventListener('error', finish, { once: true });
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).then(() => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderApp() {
|
||||||
|
return (
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
<App />
|
<App />
|
||||||
</React.StrictMode>
|
</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();
|
||||||
|
|||||||
@@ -30,6 +30,8 @@ import type { Board } from '../api/types';
|
|||||||
import { BoardColorPicker, BoardIconPicker } from '../components/BoardAppearancePicker';
|
import { BoardColorPicker, BoardIconPicker } from '../components/BoardAppearancePicker';
|
||||||
import BoardIconDisplay from '../components/BoardIconDisplay';
|
import BoardIconDisplay from '../components/BoardIconDisplay';
|
||||||
import { getBoardThemeIndex } from '../utils/boardTheme';
|
import { getBoardThemeIndex } from '../utils/boardTheme';
|
||||||
|
import AdminSortableList, { SortableDragHandle, SortableMoveButtons } from '../components/admin/AdminSortableList';
|
||||||
|
import { persistSortOrderChanges, shouldShowSortableMoveButtons } from '../utils/sortOrder';
|
||||||
|
|
||||||
const boardSchema = z.object({
|
const boardSchema = z.object({
|
||||||
name: z.string().min(1, '请输入名称').max(64),
|
name: z.string().min(1, '请输入名称').max(64),
|
||||||
@@ -48,6 +50,7 @@ export default function BoardsManagePage() {
|
|||||||
const [modalOpen, setModalOpen] = useState(false);
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
const [editing, setEditing] = useState<Board | null>(null);
|
const [editing, setEditing] = useState<Board | null>(null);
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [reordering, setReordering] = useState(false);
|
||||||
|
|
||||||
const form = useForm<BoardFormValues>({
|
const form = useForm<BoardFormValues>({
|
||||||
resolver: zodResolver(boardSchema),
|
resolver: zodResolver(boardSchema),
|
||||||
@@ -125,6 +128,32 @@ export default function BoardsManagePage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleBoardReorder = async (reordered: Board[]) => {
|
||||||
|
const before = [...boards];
|
||||||
|
setReordering(true);
|
||||||
|
try {
|
||||||
|
const after = await persistSortOrderChanges(before, reordered, board =>
|
||||||
|
api.updateBoard(board.id, {
|
||||||
|
name: board.name,
|
||||||
|
description: board.description ?? '',
|
||||||
|
sort_order: board.sort_order ?? 0,
|
||||||
|
icon: board.icon ?? '',
|
||||||
|
color_index: board.color_index ?? -1,
|
||||||
|
}).then(() => undefined),
|
||||||
|
);
|
||||||
|
setBoards(after);
|
||||||
|
notify.success('板块排序已更新');
|
||||||
|
window.dispatchEvent(new Event('boards-refresh'));
|
||||||
|
} catch (e: unknown) {
|
||||||
|
setBoards(before);
|
||||||
|
notify.error(e instanceof Error ? e.message : '排序保存失败');
|
||||||
|
} finally {
|
||||||
|
setReordering(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const showMoveButtons = shouldShowSortableMoveButtons(boards.length);
|
||||||
|
|
||||||
if (!ready) {
|
if (!ready) {
|
||||||
return <div className="flex justify-center py-16"><Spinner size="lg" /></div>;
|
return <div className="flex justify-center py-16"><Spinner size="lg" /></div>;
|
||||||
}
|
}
|
||||||
@@ -152,20 +181,36 @@ export default function BoardsManagePage() {
|
|||||||
<Table>
|
<Table>
|
||||||
<TableHeader>
|
<TableHeader>
|
||||||
<TableRow>
|
<TableRow>
|
||||||
|
<TableHead className="w-[72px]">排序</TableHead>
|
||||||
<TableHead className="w-[60px]">ID</TableHead>
|
<TableHead className="w-[60px]">ID</TableHead>
|
||||||
<TableHead className="w-[52px]">图标</TableHead>
|
<TableHead className="w-[52px]">图标</TableHead>
|
||||||
<TableHead>名称</TableHead>
|
<TableHead>名称</TableHead>
|
||||||
<TableHead>简介</TableHead>
|
<TableHead>简介</TableHead>
|
||||||
<TableHead className="w-[70px]">排序</TableHead>
|
<TableHead className="w-[70px]">权重</TableHead>
|
||||||
<TableHead className="w-[80px]">帖子数</TableHead>
|
<TableHead className="w-[80px]">帖子数</TableHead>
|
||||||
<TableHead className="w-[160px]">操作</TableHead>
|
<TableHead className="w-[160px]">操作</TableHead>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
<AdminSortableList
|
||||||
{boards.map(board => {
|
as={TableBody}
|
||||||
|
items={boards}
|
||||||
|
getId={board => board.id}
|
||||||
|
onReorder={handleBoardReorder}
|
||||||
|
showMoveButtons="auto"
|
||||||
|
renderItem={(board, _index, controls) => {
|
||||||
const themeIdx = getBoardThemeIndex(board);
|
const themeIdx = getBoardThemeIndex(board);
|
||||||
return (
|
return (
|
||||||
<TableRow key={board.id}>
|
<TableRow
|
||||||
|
ref={controls.setNodeRef}
|
||||||
|
style={controls.style}
|
||||||
|
className={cn('admin-sortable-table-row', controls.isDragging && 'is-dragging')}
|
||||||
|
>
|
||||||
|
<TableCell>
|
||||||
|
<div className="flex items-center gap-0">
|
||||||
|
<SortableDragHandle label={`拖拽调整「${board.name}」顺序`} {...controls.dragHandleProps} />
|
||||||
|
{showMoveButtons && <SortableMoveButtons controls={controls} />}
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
<TableCell>{board.id}</TableCell>
|
<TableCell>{board.id}</TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<span className={cn('board-table-icon', `sidebar-board-icon--${themeIdx}`)}>
|
<span className={cn('board-table-icon', `sidebar-board-icon--${themeIdx}`)}>
|
||||||
@@ -178,10 +223,10 @@ export default function BoardsManagePage() {
|
|||||||
<TableCell><Badge variant="secondary">{board.post_count ?? 0}</Badge></TableCell>
|
<TableCell><Badge variant="secondary">{board.post_count ?? 0}</Badge></TableCell>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
<div className="flex items-center gap-1">
|
<div className="flex items-center gap-1">
|
||||||
<Button variant="ghost" size="sm" onClick={() => openEdit(board)}>编辑</Button>
|
<Button variant="ghost" size="sm" onClick={() => openEdit(board)} disabled={reordering}>编辑</Button>
|
||||||
<AlertDialog>
|
<AlertDialog>
|
||||||
<AlertDialogTrigger asChild>
|
<AlertDialogTrigger asChild>
|
||||||
<Button variant="ghost" size="sm" className="text-destructive hover:text-destructive">
|
<Button variant="ghost" size="sm" className="text-destructive hover:text-destructive" disabled={reordering}>
|
||||||
删除
|
删除
|
||||||
</Button>
|
</Button>
|
||||||
</AlertDialogTrigger>
|
</AlertDialogTrigger>
|
||||||
@@ -204,8 +249,8 @@ export default function BoardsManagePage() {
|
|||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
);
|
);
|
||||||
})}
|
}}
|
||||||
</TableBody>
|
/>
|
||||||
</Table>
|
</Table>
|
||||||
{boards.length === 0 && (
|
{boards.length === 0 && (
|
||||||
<div className="empty-state">
|
<div className="empty-state">
|
||||||
|
|||||||
@@ -13,7 +13,16 @@ import { serializeTags, parseTags } from '../components/TagInput';
|
|||||||
import { Spinner } from '@/components/ui/spinner';
|
import { Spinner } from '@/components/ui/spinner';
|
||||||
import ComposeHeader from '../components/compose/ComposeHeader';
|
import ComposeHeader from '../components/compose/ComposeHeader';
|
||||||
import ComposeContextBar, { type PostType } from '../components/compose/ComposeContextBar';
|
import ComposeContextBar, { type PostType } from '../components/compose/ComposeContextBar';
|
||||||
|
import ComposeSpecialFields, {
|
||||||
|
buildPollOptionsPayload,
|
||||||
|
countValidPollOptions,
|
||||||
|
defaultPollEndsAtLocal,
|
||||||
|
pollEndsAtISOToLocal,
|
||||||
|
pollEndsAtLocalToISO,
|
||||||
|
validatePollEndsAtLocal,
|
||||||
|
} from '../components/compose/ComposeSpecialFields';
|
||||||
import ComposeDocument from '../components/compose/ComposeDocument';
|
import ComposeDocument from '../components/compose/ComposeDocument';
|
||||||
|
import { sortBoardsForCompose } from '../utils/board';
|
||||||
import { getCachedBoards } from '../utils/layoutCache';
|
import { getCachedBoards } from '../utils/layoutCache';
|
||||||
import type { LayoutCtx } from '../layouts/MainLayout';
|
import type { LayoutCtx } from '../layouts/MainLayout';
|
||||||
import { loginPath } from '../utils/authRedirect';
|
import { loginPath } from '../utils/authRedirect';
|
||||||
@@ -36,8 +45,8 @@ interface ComposeBaseline {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function resolveBoards(ctxBoards?: Board[]): Board[] {
|
function resolveBoards(ctxBoards?: Board[]): Board[] {
|
||||||
if (ctxBoards && ctxBoards.length > 0) return ctxBoards;
|
const raw = ctxBoards && ctxBoards.length > 0 ? ctxBoards : getCachedBoards();
|
||||||
return getCachedBoards();
|
return sortBoardsForCompose(raw);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 格式化剩余可编辑时间 */
|
/** 格式化剩余可编辑时间 */
|
||||||
@@ -74,6 +83,13 @@ export default function ComposePage() {
|
|||||||
const [tags, setTags] = useState('');
|
const [tags, setTags] = useState('');
|
||||||
const [content, setContent] = useState('');
|
const [content, setContent] = useState('');
|
||||||
const [postType, setPostType] = useState<PostType>('normal');
|
const [postType, setPostType] = useState<PostType>('normal');
|
||||||
|
const [pollOptions, setPollOptions] = useState(['', '']);
|
||||||
|
const [pollMulti, setPollMulti] = useState(false);
|
||||||
|
const [pollMaxChoices, setPollMaxChoices] = useState(2);
|
||||||
|
const [pollEndsAt, setPollEndsAt] = useState(defaultPollEndsAtLocal);
|
||||||
|
const [pollNoEndTime, setPollNoEndTime] = useState(false);
|
||||||
|
const [bountyPoints, setBountyPoints] = useState(0);
|
||||||
|
const [lotteryWinners, setLotteryWinners] = useState(1);
|
||||||
const [publishing, setPublishing] = useState(false);
|
const [publishing, setPublishing] = useState(false);
|
||||||
const [loading, setLoading] = useState(isEdit);
|
const [loading, setLoading] = useState(isEdit);
|
||||||
/** 新建帖:板块列表是否已就绪(避免请求中误显空态) */
|
/** 新建帖:板块列表是否已就绪(避免请求中误显空态) */
|
||||||
@@ -101,7 +117,7 @@ export default function ComposePage() {
|
|||||||
: api.boards();
|
: api.boards();
|
||||||
Promise.all([boardsPromise, api.post(editId!, { skipView: true })])
|
Promise.all([boardsPromise, api.post(editId!, { skipView: true })])
|
||||||
.then(([boardsData, postData]) => {
|
.then(([boardsData, postData]) => {
|
||||||
const list = boardsData.boards ?? [];
|
const list = sortBoardsForCompose(boardsData.boards ?? []);
|
||||||
setBoards(list);
|
setBoards(list);
|
||||||
const post = postData.post;
|
const post = postData.post;
|
||||||
const isOwnerOrAdmin = user.role === 'admin' || post.user_id === user.id;
|
const isOwnerOrAdmin = user.role === 'admin' || post.user_id === user.id;
|
||||||
@@ -116,7 +132,13 @@ export default function ComposePage() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const loadedBoardId = String(post.board_id);
|
const loadedBoardId = String(post.board_id);
|
||||||
const loadedType = post.post_type === 'question' ? 'question' : 'normal';
|
const loadedType = (
|
||||||
|
post.post_type === 'question' ? 'question'
|
||||||
|
: post.post_type === 'poll' ? 'poll'
|
||||||
|
: post.post_type === 'bounty' ? 'bounty'
|
||||||
|
: post.post_type === 'lottery' ? 'lottery'
|
||||||
|
: 'normal'
|
||||||
|
) as PostType;
|
||||||
const serverBaseline: ComposeBaseline = {
|
const serverBaseline: ComposeBaseline = {
|
||||||
title: post.title,
|
title: post.title,
|
||||||
tags: post.tags ?? '',
|
tags: post.tags ?? '',
|
||||||
@@ -130,6 +152,18 @@ export default function ComposePage() {
|
|||||||
setTags(serverBaseline.tags);
|
setTags(serverBaseline.tags);
|
||||||
setContent(serverBaseline.content);
|
setContent(serverBaseline.content);
|
||||||
setPostType(loadedType);
|
setPostType(loadedType);
|
||||||
|
if (postData.poll) {
|
||||||
|
setPollOptions(postData.poll.options.map(o => o.text));
|
||||||
|
setPollMulti(postData.poll.multi);
|
||||||
|
setPollMaxChoices(postData.poll.max_choices);
|
||||||
|
if (postData.poll.ends_at) {
|
||||||
|
setPollNoEndTime(false);
|
||||||
|
setPollEndsAt(pollEndsAtISOToLocal(postData.poll.ends_at));
|
||||||
|
} else {
|
||||||
|
setPollNoEndTime(true);
|
||||||
|
setPollEndsAt(defaultPollEndsAtLocal());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const windowHours = postData.post_edit_window_hours ?? 0;
|
const windowHours = postData.post_edit_window_hours ?? 0;
|
||||||
if (user.role !== 'admin' && windowHours > 0) {
|
if (user.role !== 'admin' && windowHours > 0) {
|
||||||
@@ -175,6 +209,13 @@ export default function ComposePage() {
|
|||||||
setTags(draft.tags);
|
setTags(draft.tags);
|
||||||
setContent(draft.content);
|
setContent(draft.content);
|
||||||
setPostType(draft.postType);
|
setPostType(draft.postType);
|
||||||
|
if (draft.postType === 'poll') {
|
||||||
|
if (draft.pollOptions?.length) setPollOptions(draft.pollOptions);
|
||||||
|
if (typeof draft.pollMulti === 'boolean') setPollMulti(draft.pollMulti);
|
||||||
|
if (typeof draft.pollMaxChoices === 'number') setPollMaxChoices(draft.pollMaxChoices);
|
||||||
|
if (typeof draft.pollNoEndTime === 'boolean') setPollNoEndTime(draft.pollNoEndTime);
|
||||||
|
if (typeof draft.pollEndsAt === 'string' && draft.pollEndsAt) setPollEndsAt(draft.pollEndsAt);
|
||||||
|
}
|
||||||
setBaseline(emptyBaseline);
|
setBaseline(emptyBaseline);
|
||||||
setDraftHint('已恢复本地草稿,编辑中将自动保存');
|
setDraftHint('已恢复本地草稿,编辑中将自动保存');
|
||||||
return;
|
return;
|
||||||
@@ -229,11 +270,18 @@ export default function ComposePage() {
|
|||||||
content,
|
content,
|
||||||
boardId,
|
boardId,
|
||||||
postType,
|
postType,
|
||||||
|
...(postType === 'poll' ? {
|
||||||
|
pollOptions,
|
||||||
|
pollMulti,
|
||||||
|
pollMaxChoices,
|
||||||
|
pollEndsAt,
|
||||||
|
pollNoEndTime,
|
||||||
|
} : {}),
|
||||||
});
|
});
|
||||||
setDraftHint('草稿已自动保存到本机');
|
setDraftHint('草稿已自动保存到本机');
|
||||||
}, 800);
|
}, 800);
|
||||||
return () => window.clearTimeout(timer);
|
return () => window.clearTimeout(timer);
|
||||||
}, [isEdit, baseline, isDirty, title, tags, content, boardId, postType]);
|
}, [isEdit, baseline, isDirty, title, tags, content, boardId, postType, pollOptions, pollMulti, pollMaxChoices, pollEndsAt, pollNoEndTime]);
|
||||||
|
|
||||||
const {
|
const {
|
||||||
dialogOpen,
|
dialogOpen,
|
||||||
@@ -307,15 +355,42 @@ export default function ComposePage() {
|
|||||||
if (!boardId) { notify.warning('请选择板块'); return; }
|
if (!boardId) { notify.warning('请选择板块'); return; }
|
||||||
if (!trimmedTitle) { notify.warning('请输入标题'); return; }
|
if (!trimmedTitle) { notify.warning('请输入标题'); return; }
|
||||||
if (isHtmlEmpty(content)) { notify.warning('请输入正文内容'); return; }
|
if (isHtmlEmpty(content)) { notify.warning('请输入正文内容'); return; }
|
||||||
|
if (postType === 'poll' && !isEdit && countValidPollOptions(pollOptions) < 2) {
|
||||||
|
notify.warning('投票至少需要 2 个非空选项');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (postType === 'poll' && !isEdit && !pollNoEndTime) {
|
||||||
|
const err = validatePollEndsAtLocal(pollEndsAt);
|
||||||
|
if (err) { notify.warning(err); return; }
|
||||||
|
}
|
||||||
|
if (postType === 'bounty' && !isEdit) {
|
||||||
|
const balance = user?.points ?? 0;
|
||||||
|
if (bountyPoints < 1) {
|
||||||
|
notify.warning('请填写悬赏积分');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (bountyPoints > balance) {
|
||||||
|
notify.warning('积分不足');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
setPublishing(true);
|
setPublishing(true);
|
||||||
try {
|
try {
|
||||||
|
const pollEndsAtISO = postType === 'poll' && !pollNoEndTime
|
||||||
|
? pollEndsAtLocalToISO(pollEndsAt)
|
||||||
|
: null;
|
||||||
const payload = {
|
const payload = {
|
||||||
title: trimmedTitle,
|
title: trimmedTitle,
|
||||||
content: content.trim(),
|
content: content.trim(),
|
||||||
tags: serializeTags(parseTags(tags)),
|
tags: serializeTags(parseTags(tags)),
|
||||||
board_id: boardId,
|
board_id: boardId,
|
||||||
post_type: postType,
|
post_type: postType,
|
||||||
|
poll_options: postType === 'poll'
|
||||||
|
? buildPollOptionsPayload(pollOptions, pollMulti, pollMaxChoices, pollEndsAtISO)
|
||||||
|
: undefined,
|
||||||
|
bounty_points: postType === 'bounty' ? bountyPoints : undefined,
|
||||||
|
lottery_winner_count: postType === 'lottery' ? lotteryWinners : undefined,
|
||||||
};
|
};
|
||||||
if (isEdit) {
|
if (isEdit) {
|
||||||
await api.updatePost(editId!, payload);
|
await api.updatePost(editId!, payload);
|
||||||
@@ -372,6 +447,25 @@ export default function ComposePage() {
|
|||||||
onTagsChange={setTags}
|
onTagsChange={setTags}
|
||||||
limits={limits}
|
limits={limits}
|
||||||
/>
|
/>
|
||||||
|
<ComposeSpecialFields
|
||||||
|
postType={postType}
|
||||||
|
pollOptions={pollOptions}
|
||||||
|
onPollOptionsChange={setPollOptions}
|
||||||
|
pollMulti={pollMulti}
|
||||||
|
onPollMultiChange={setPollMulti}
|
||||||
|
pollMaxChoices={pollMaxChoices}
|
||||||
|
onPollMaxChoicesChange={setPollMaxChoices}
|
||||||
|
pollEndsAt={pollEndsAt}
|
||||||
|
onPollEndsAtChange={setPollEndsAt}
|
||||||
|
pollNoEndTime={pollNoEndTime}
|
||||||
|
onPollNoEndTimeChange={setPollNoEndTime}
|
||||||
|
bountyPoints={bountyPoints}
|
||||||
|
onBountyPointsChange={setBountyPoints}
|
||||||
|
userPointsBalance={!isEdit ? user?.points : undefined}
|
||||||
|
lotteryWinners={lotteryWinners}
|
||||||
|
onLotteryWinnersChange={setLotteryWinners}
|
||||||
|
disabled={isEdit && postType !== 'normal' && postType !== 'question'}
|
||||||
|
/>
|
||||||
</ComposeDocument>
|
</ComposeDocument>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -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>;
|
||||||
@@ -44,16 +48,18 @@ export default function FavoritesPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="page-wrap">
|
<div className="page-wrap">
|
||||||
<div className="page-inner-wide">
|
<div className="feed-panel list-page-panel">
|
||||||
<Button variant="ghost" className="mb-3" onClick={() => nav('/')}>
|
<header className="list-page-panel__head">
|
||||||
|
<Button variant="ghost" size="sm" className="list-page-panel__back" onClick={() => nav('/')}>
|
||||||
<ArrowLeft />
|
<ArrowLeft />
|
||||||
返回
|
返回
|
||||||
</Button>
|
</Button>
|
||||||
<h1 className="page-title">我的收藏</h1>
|
<h1 className="page-title">我的收藏</h1>
|
||||||
<p className="page-desc">共 {list.length} 篇收藏帖子</p>
|
<p className="page-desc">共 {list.length} 篇收藏帖子</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
{list.length === 0 ? (
|
{list.length === 0 ? (
|
||||||
<div className="empty-state">
|
<div className="empty-state list-page-panel__empty">
|
||||||
<Star className="empty-state-icon" aria-hidden size={36} strokeWidth={1.5} />
|
<Star className="empty-state-icon" aria-hidden size={36} strokeWidth={1.5} />
|
||||||
<p>还没有收藏任何帖子</p>
|
<p>还没有收藏任何帖子</p>
|
||||||
<Button onClick={() => nav('/')}>去逛逛</Button>
|
<Button onClick={() => nav('/')}>去逛逛</Button>
|
||||||
|
|||||||
@@ -1,48 +1,112 @@
|
|||||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
import { useState, useEffect, useCallback, useRef, useMemo, startTransition as reactStartTransition } from 'react';
|
||||||
import { useNavigate, useOutletContext, useSearchParams, useLocation } 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 FeedPageSkeleton from '../components/FeedPageSkeleton';
|
import FeedSearchFilters from '../components/search/FeedSearchFilters';
|
||||||
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 {
|
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 NotFoundPage from './NotFoundPage';
|
||||||
|
|
||||||
|
/** 仅从 URL 解析板块 ID(不以 layout 状态回退,避免回首页误用上一板块) */
|
||||||
|
function boardIdFromLocation(routeId: string | undefined, searchParams: URLSearchParams): number {
|
||||||
|
if (routeId) {
|
||||||
|
const id = parsePermalinkID(routeId);
|
||||||
|
return Number.isFinite(id) && id > 0 ? id : 0;
|
||||||
|
}
|
||||||
|
const q = Number(searchParams.get('board')) || 0;
|
||||||
|
return q > 0 ? q : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
type FeedHydrate = {
|
||||||
|
posts: PostItem[];
|
||||||
|
postTotal: number;
|
||||||
|
page: number;
|
||||||
|
scrollTop: number;
|
||||||
|
loading: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 首屏同步读取 Zustand,避免先骨架屏再恢复 */
|
||||||
|
function readHydrate(
|
||||||
|
boardId: number,
|
||||||
|
keyword: string,
|
||||||
|
sort: FeedSort,
|
||||||
|
tag: string,
|
||||||
|
author: string,
|
||||||
|
titleOnly: boolean,
|
||||||
|
): FeedHydrate {
|
||||||
|
const key = feedCacheKey({ boardId, keyword, sort, tag, author, titleOnly });
|
||||||
|
const cached = getHomeStoreState().getFeed(key);
|
||||||
|
if (cached && cached.posts.length > 0) {
|
||||||
|
return {
|
||||||
|
posts: cached.posts,
|
||||||
|
postTotal: cached.postTotal,
|
||||||
|
page: cached.page,
|
||||||
|
scrollTop: cached.scrollTop,
|
||||||
|
loading: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { posts: [], postTotal: 0, page: 1, scrollTop: 0, loading: true };
|
||||||
|
}
|
||||||
|
|
||||||
export default function HomePage() {
|
export default function HomePage() {
|
||||||
const nav = useNavigate();
|
const nav = useNavigate();
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
|
const navType = useNavigationType();
|
||||||
|
const { id: boardRouteId } = useParams();
|
||||||
const [params] = useSearchParams();
|
const [params] = useSearchParams();
|
||||||
const ctx = useOutletContext<LayoutCtx>();
|
const ctx = useOutletContext<LayoutCtx>();
|
||||||
const { branding } = useSiteBranding();
|
const { branding } = useSiteBranding();
|
||||||
const { limits, loading: limitsLoading } = useForumLimits();
|
const { limits, loading: limitsLoading } = useForumLimits();
|
||||||
|
const postSearch = usePostSearch(limits);
|
||||||
const pageSize = Math.max(1, limits.page_size_default);
|
const pageSize = Math.max(1, limits.page_size_default);
|
||||||
|
|
||||||
const boardId = Number(params.get('board')) || ctx?.boardId || 0;
|
const boardId = boardIdFromLocation(boardRouteId, params);
|
||||||
|
const queryBoardId = Number(params.get('board')) || 0;
|
||||||
|
const isBoardRoute = !!boardRouteId;
|
||||||
|
const isInvalidBoardRoute = isBoardRoute && boardId === 0;
|
||||||
|
const boardsLoading = ctx?.boardsLoading ?? true;
|
||||||
|
const isMissingBoard = isBoardRoute && boardId > 0 && !boardsLoading && !(ctx?.boards ?? []).some(b => b.id === boardId);
|
||||||
const keyword = params.get('keyword') || '';
|
const keyword = params.get('keyword') || '';
|
||||||
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);
|
||||||
const feedTitle = tag
|
const feedTitle = tag
|
||||||
? `标签:${tag}`
|
? `标签:${tag}`
|
||||||
: keyword || author
|
: keyword || author
|
||||||
? `搜索:${keyword || ''}${author ? (keyword ? ` · 作者 ${author}` : `作者 ${author}`) : ''}${titleOnly ? '(仅标题)' : ''}`
|
? '搜索结果'
|
||||||
: (boardId && board ? board.name : '');
|
: (boardId && board ? board.name : '');
|
||||||
usePageSEO({
|
usePageSEO({
|
||||||
title: feedTitle || undefined,
|
title: feedTitle || undefined,
|
||||||
@@ -51,25 +115,141 @@ export default function HomePage() {
|
|||||||
canonicalPath: tag
|
canonicalPath: tag
|
||||||
? `/?tag=${encodeURIComponent(tag)}`
|
? `/?tag=${encodeURIComponent(tag)}`
|
||||||
: boardId
|
: boardId
|
||||||
? `/?board=${boardId}`
|
? boardPath(boardId, limits)
|
||||||
: '/',
|
: '/',
|
||||||
ogType: 'website',
|
ogType: 'website',
|
||||||
});
|
});
|
||||||
|
|
||||||
const [posts, setPosts] = useState<PostItem[]>([]);
|
// 旧版 /?board=id 重定向到规范板块路径
|
||||||
const [postTotal, setPostTotal] = useState(0);
|
useEffect(() => {
|
||||||
const [page, setPage] = useState(1);
|
if (queryBoardId && !boardRouteId) {
|
||||||
const [loading, setLoading] = useState(true);
|
const p = new URLSearchParams(params);
|
||||||
const [restoreScrollTop, setRestoreScrollTop] = useState<number | null>(null);
|
p.delete('board');
|
||||||
const [listResetKey, setListResetKey] = useState(0);
|
const qs = p.toString();
|
||||||
|
const target = boardPath(queryBoardId, limits) + (qs ? `?${qs}` : '');
|
||||||
|
nav(target, { replace: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (boardRouteId && boardId > 0) {
|
||||||
|
const redirect = canonicalRedirectPath('board', boardId, location.pathname, limits);
|
||||||
|
if (redirect) {
|
||||||
|
const qs = location.search;
|
||||||
|
nav(redirect + qs, { replace: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [queryBoardId, boardId, boardRouteId, params, nav, limits, location.pathname, location.search]);
|
||||||
|
|
||||||
const scrollTopRef = useRef(0);
|
// URL 上的 sort 已被后台关闭时,纠正为默认排序
|
||||||
const skipCacheSaveRef = useRef(false);
|
useEffect(() => {
|
||||||
const loadingRef = useRef(false);
|
if (limitsLoading) return;
|
||||||
const pageRef = useRef(1);
|
if (rawSort !== 'latest' && rawSort !== 'hot' && rawSort !== 'reply') return;
|
||||||
|
const stillOn = enabledFeedSortTabs(limits.feed_sort_tabs).some(t => t.id === rawSort);
|
||||||
|
if (stillOn) return;
|
||||||
|
const def = getDefaultFeedSort(limits.feed_sort_tabs);
|
||||||
|
nav(buildHomeUrl(boardId, def, { keyword, tag, author, titleOnly, permalink: limits }), { replace: true });
|
||||||
|
}, [
|
||||||
|
limitsLoading,
|
||||||
|
limits.feed_sort_tabs,
|
||||||
|
limits,
|
||||||
|
rawSort,
|
||||||
|
boardId,
|
||||||
|
keyword,
|
||||||
|
tag,
|
||||||
|
author,
|
||||||
|
titleOnly,
|
||||||
|
nav,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const cacheKey = useMemo(
|
||||||
|
() => feedCacheKey({ boardId, keyword, sort, tag, author, titleOnly }),
|
||||||
|
[boardId, keyword, sort, tag, author, titleOnly],
|
||||||
|
);
|
||||||
|
|
||||||
|
// 筛选键变化时同步水合(含首次挂载),保证第一帧就有列表数据
|
||||||
|
const initial = useMemo(
|
||||||
|
() => readHydrate(boardId, keyword, sort, tag, author, titleOnly),
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps -- 仅随筛选键变化重置
|
||||||
|
[cacheKey],
|
||||||
|
);
|
||||||
|
|
||||||
|
const [posts, setPosts] = useState<PostItem[]>(initial.posts);
|
||||||
|
const [postTotal, setPostTotal] = useState(initial.postTotal);
|
||||||
|
const [page, setPage] = useState(initial.page);
|
||||||
|
const [loading, setLoading] = useState(initial.loading);
|
||||||
|
/** 画面上已提交的筛选(URL 已变但数据未到时仍画上一份) */
|
||||||
|
const [view, setView] = useState({
|
||||||
|
cacheKey,
|
||||||
|
sort,
|
||||||
|
boardId,
|
||||||
|
keyword,
|
||||||
|
tag,
|
||||||
|
author,
|
||||||
|
titleOnly,
|
||||||
|
});
|
||||||
|
const [listPending, setListPending] = useState(false);
|
||||||
|
const [restoreScrollTop, setRestoreScrollTop] = useState<number | null>(
|
||||||
|
initial.posts.length > 0 ? initial.scrollTop : null,
|
||||||
|
);
|
||||||
|
const [listResetKey, setListResetKey] = useState(0);
|
||||||
|
/** hydrate 首帧用静态列表;完成后升级 VirtualPostList */
|
||||||
|
const [useVirtualList, setUseVirtualList] = useState(() => !isHomeHydrating());
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (useVirtualList) return;
|
||||||
|
reactStartTransition(() => setUseVirtualList(true));
|
||||||
|
}, [useVirtualList]);
|
||||||
|
|
||||||
|
const scrollTopRef = useRef(initial.scrollTop);
|
||||||
|
const fetchSeqRef = useRef(0);
|
||||||
|
const pageRef = useRef(initial.page);
|
||||||
|
const cacheKeyRef = useRef(cacheKey);
|
||||||
|
const viewKeyRef = useRef(view.cacheKey);
|
||||||
|
const postsRef = useRef(posts);
|
||||||
|
const scrollRafRef = useRef(0);
|
||||||
|
/** 当前筛选键是否已完成「进入页」水合(避免 effect 重跑时反复 setRestoreScrollTop) */
|
||||||
|
const hydratedKeyRef = useRef<string | null>(null);
|
||||||
|
/** 强制刷新已发起 loadFirst:消费 refreshFeed 后 effect 再跑时勿因空缓存重复请求 */
|
||||||
|
const refreshFetchKeyRef = useRef<string | null>(null);
|
||||||
pageRef.current = page;
|
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;
|
||||||
@@ -81,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,
|
||||||
@@ -100,144 +303,242 @@ 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) {
|
||||||
|
if (seq !== fetchSeqRef.current) return;
|
||||||
|
if (!silent) {
|
||||||
notify.error(e instanceof Error ? e.message : '加载失败');
|
notify.error(e instanceof Error ? e.message : '加载失败');
|
||||||
|
if (!keepView) {
|
||||||
setPosts([]);
|
setPosts([]);
|
||||||
setPostTotal(0);
|
setPostTotal(0);
|
||||||
setPage(1);
|
setPage(1);
|
||||||
pageRef.current = 1;
|
pageRef.current = 1;
|
||||||
} finally {
|
|
||||||
loadingRef.current = false;
|
|
||||||
setLoading(false);
|
|
||||||
}
|
}
|
||||||
}, [boardId, keyword, tag, author, titleOnly, sort, pageSize]);
|
}
|
||||||
|
} finally {
|
||||||
|
if (seq === fetchSeqRef.current) {
|
||||||
|
setLoading(false);
|
||||||
|
setListPending(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [boardId, keyword, tag, author, titleOnly, sort, pageSize, persistFeed]);
|
||||||
|
|
||||||
const loadFirst = useCallback(() => fetchPage(1), [fetchPage]);
|
const loadFirst = useCallback((opts?: { resetScroll?: boolean }) => (
|
||||||
|
fetchPage(1, { resetScroll: opts?.resetScroll })
|
||||||
|
), [fetchPage]);
|
||||||
|
|
||||||
const goToPage = useCallback((p: number) => {
|
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) 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) {
|
||||||
|
const needRestore = hydratedKeyRef.current !== cacheKey;
|
||||||
|
hydratedKeyRef.current = cacheKey;
|
||||||
|
if (needRestore) {
|
||||||
|
commitDisplayed({
|
||||||
|
posts: cached.posts,
|
||||||
|
postTotal: cached.postTotal,
|
||||||
|
page: cached.page,
|
||||||
|
scrollTop: cached.scrollTop,
|
||||||
|
loading: false,
|
||||||
|
}, { cacheKey, sort, boardId, keyword, tag, author, titleOnly });
|
||||||
|
} else {
|
||||||
setPosts(cached.posts);
|
setPosts(cached.posts);
|
||||||
setPostTotal(cached.postTotal);
|
setPostTotal(cached.postTotal);
|
||||||
setPage(cached.page);
|
setPage(cached.page);
|
||||||
pageRef.current = cached.page;
|
pageRef.current = cached.page;
|
||||||
setRestoreScrollTop(cached.scrollTop);
|
|
||||||
scrollTopRef.current = cached.scrollTop;
|
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
|
setListPending(false);
|
||||||
|
setView({ cacheKey, sort, boardId, keyword, tag, author, titleOnly });
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
hydratedKeyRef.current = cacheKey;
|
||||||
|
if (postsRef.current.length === 0) {
|
||||||
setRestoreScrollTop(null);
|
setRestoreScrollTop(null);
|
||||||
scrollTopRef.current = 0;
|
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,
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// 筛选未变时同步列表快照;变筛选的那一帧先保留旧快照供 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;
|
||||||
window.addEventListener('posts-refresh', fn);
|
const warm = getHomeStoreState().getFeed(key);
|
||||||
return () => window.removeEventListener('posts-refresh', fn);
|
if (warm && warm.posts.length > 0) {
|
||||||
}, [beginFeedRefresh, loadFirst]);
|
// 先写入新数据,再复位滚动(避免先 reset 造成空白闪一下)
|
||||||
|
commitDisplayed({
|
||||||
const handleSortChange = (next: FeedSort) => {
|
posts: warm.posts,
|
||||||
if (next === sort) {
|
postTotal: warm.postTotal,
|
||||||
beginFeedRefresh();
|
page: warm.page,
|
||||||
loadFirst();
|
scrollTop: 0,
|
||||||
|
loading: false,
|
||||||
|
}, { cacheKey: key, sort, boardId, keyword, tag, author, titleOnly });
|
||||||
|
setListResetKey((k) => k + 1);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
navigateFeed(nav, buildHomeUrl(boardId, next, { keyword, tag, author, titleOnly }));
|
// 未命中:保留旧 posts,静默重拉
|
||||||
|
if (postsRef.current.length > 0) {
|
||||||
|
setListPending(true);
|
||||||
|
setLoading(false);
|
||||||
|
void loadFirst();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoading(true);
|
||||||
|
void loadFirst();
|
||||||
|
};
|
||||||
|
window.addEventListener('posts-refresh', applyWarmOrReload);
|
||||||
|
window.addEventListener(FEED_PULL_REFRESH_EVENT, applyWarmOrReload);
|
||||||
|
window.addEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, applyWarmOrReload);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('posts-refresh', applyWarmOrReload);
|
||||||
|
window.removeEventListener(FEED_PULL_REFRESH_EVENT, applyWarmOrReload);
|
||||||
|
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, applyWarmOrReload);
|
||||||
|
};
|
||||||
|
}, [
|
||||||
|
commitDisplayed, loadFirst,
|
||||||
|
sort, boardId, keyword, tag, author, titleOnly,
|
||||||
|
]);
|
||||||
|
|
||||||
|
// 卸载时取消未执行的 scroll rAF
|
||||||
|
useEffect(() => () => {
|
||||||
|
if (scrollRafRef.current) cancelAnimationFrame(scrollRafRef.current);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleScrollTopChange = useCallback((top: number) => {
|
||||||
|
scrollTopRef.current = top;
|
||||||
|
// rAF 节流写入 store,避免每个 scroll 事件都触发订阅者
|
||||||
|
if (scrollRafRef.current) return;
|
||||||
|
scrollRafRef.current = requestAnimationFrame(() => {
|
||||||
|
scrollRafRef.current = 0;
|
||||||
|
getHomeStoreState().patchScroll(viewKeyRef.current, scrollTopRef.current);
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleSortChange = (next: FeedSort) => {
|
||||||
|
const url = buildHomeUrl(boardId, next, { keyword, tag, author, titleOnly, permalink: limits });
|
||||||
|
// 排序标签:一律强制刷新到第 1 页顶部,不恢复浏览进度
|
||||||
|
if (next === sort) {
|
||||||
|
const tid = startTransition();
|
||||||
|
getHomeStoreState().clearFeed(cacheKeyRef.current);
|
||||||
|
beginFeedRefresh();
|
||||||
|
void Promise.resolve(loadFirst({ resetScroll: true })).finally(() => doneTransition(tid));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
navigateFeed(nav, url, { refresh: true });
|
||||||
};
|
};
|
||||||
|
|
||||||
const showSortBar = !keyword && !tag && !author;
|
const showSortBar = !view.keyword && !view.tag && !view.author;
|
||||||
|
const searchFilters = parseSearchFromUrl(location.pathname, params);
|
||||||
|
const isSearchActive = !!(view.keyword || view.author);
|
||||||
|
|
||||||
// 首屏用同构骨架,避免标题/列表分区先后出现造成闪动
|
if (isInvalidBoardRoute || isMissingBoard) {
|
||||||
if ((loading || limitsLoading) && posts.length === 0) {
|
return (
|
||||||
return <FeedPageSkeleton />;
|
<NotFoundPage
|
||||||
|
title="板块不存在"
|
||||||
|
description="该板块不存在,或已被删除。"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 冷启动由门闩 / ensureColdBootReady 挡住;有旧列表时软刷新绝不卸空
|
||||||
|
if ((loading || limitsLoading || (isBoardRoute && boardsLoading)) && posts.length === 0) {
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -245,26 +546,50 @@ 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">
|
||||||
|
{!useVirtualList ? (
|
||||||
|
(view.keyword || view.tag || view.author) ? (
|
||||||
|
<h1 className="feed-header-title">
|
||||||
|
{view.tag
|
||||||
|
? `#${view.tag}`
|
||||||
|
: view.keyword
|
||||||
|
? `搜索:${view.keyword}`
|
||||||
|
: `作者:${view.author}`}
|
||||||
|
</h1>
|
||||||
|
) : null
|
||||||
|
) : (
|
||||||
<FeedHeader
|
<FeedHeader
|
||||||
boardId={boardId}
|
keyword={view.keyword}
|
||||||
keyword={keyword}
|
tag={view.tag}
|
||||||
tag={tag}
|
author={view.author}
|
||||||
author={author}
|
|
||||||
titleOnly={titleOnly}
|
|
||||||
boards={ctx?.boards ?? []}
|
|
||||||
stats={ctx?.stats ?? null}
|
|
||||||
postTotal={postTotal}
|
postTotal={postTotal}
|
||||||
titleAs={isSiteHome ? 'h2' : 'h1'}
|
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 && (
|
||||||
|
<FeedSearchFilters
|
||||||
|
filters={postSearch.filters}
|
||||||
|
boards={ctx?.boards ?? []}
|
||||||
|
onRemove={postSearch.removeFilter}
|
||||||
|
onClear={postSearch.clearSearch}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
{!useVirtualList ? (
|
||||||
|
<StaticFeedList posts={posts} sort={view.sort} boardId={view.boardId} />
|
||||||
|
) : (
|
||||||
<VirtualPostList
|
<VirtualPostList
|
||||||
posts={posts}
|
posts={posts}
|
||||||
sort={sort}
|
sort={view.sort}
|
||||||
loading={loading || limitsLoading}
|
loading={listPending ? false : (loading || limitsLoading)}
|
||||||
hasMore={hasMore}
|
hasMore={hasMore}
|
||||||
showPagination={showPagination}
|
showPagination={showPagination}
|
||||||
page={page}
|
page={page}
|
||||||
@@ -274,13 +599,20 @@ export default function HomePage() {
|
|||||||
onSelect={handleSelectPost}
|
onSelect={handleSelectPost}
|
||||||
restoreScrollTop={restoreScrollTop}
|
restoreScrollTop={restoreScrollTop}
|
||||||
resetScrollKey={listResetKey}
|
resetScrollKey={listResetKey}
|
||||||
onScrollTopChange={(top) => { scrollTopRef.current = top; }}
|
onScrollTopChange={handleScrollTopChange}
|
||||||
onScrollRestored={() => setRestoreScrollTop(null)}
|
onScrollRestored={() => setRestoreScrollTop(null)}
|
||||||
keyword={keyword || tag || author}
|
keyword={view.keyword || view.tag || view.author}
|
||||||
boardId={boardId}
|
isSearchMode={!!(view.keyword || view.author)}
|
||||||
boardName={ctx?.boards?.find(b => b.id === boardId)?.name || ''}
|
searchKeyword={view.keyword}
|
||||||
|
searchAuthor={view.author}
|
||||||
|
searchTitleOnly={view.titleOnly}
|
||||||
|
searchScopeBoardId={searchFilters.scopeBoardId}
|
||||||
|
onClearSearch={postSearch.clearSearch}
|
||||||
|
boardId={view.boardId}
|
||||||
|
boardName={ctx?.boards?.find(b => b.id === view.boardId)?.name || ''}
|
||||||
noBoards={!ctx?.boardsLoading && (ctx?.boards?.length ?? 0) === 0}
|
noBoards={!ctx?.boardsLoading && (ctx?.boards?.length ?? 0) === 0}
|
||||||
/>
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
361
frontend/src/pages/LinksPage.tsx
Normal file
361
frontend/src/pages/LinksPage.tsx
Normal file
@@ -0,0 +1,361 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
|
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
||||||
|
import { ArrowLeft, Link2, Pencil, Plus, Trash2 } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Spinner } from '@/components/ui/spinner';
|
||||||
|
import { notify } from '@/lib/notify';
|
||||||
|
import { api } from '../api/client';
|
||||||
|
import type { FriendLink, FriendLinkApply } from '../api/types';
|
||||||
|
import { useAuth } from '../hooks/useAuth';
|
||||||
|
import { joinSEOKeywords, usePageSEO } from '../hooks/usePageSEO';
|
||||||
|
import { getCachedSiteBranding, invalidateSiteBrandingCache, useSiteBranding } from '../hooks/useSiteBranding';
|
||||||
|
import { formatTime } from '../utils/content';
|
||||||
|
import { loginPath } from '../utils/authRedirect';
|
||||||
|
import { resolveFriendLinkLogo, isReciprocalChecking, reciprocalStatusLabel } from '../utils/friendLink';
|
||||||
|
import { InFlowSiteFooter } from '../components/SiteFooter';
|
||||||
|
import FriendLinkApplyDialog from '../components/FriendLinkApplyDialog';
|
||||||
|
import { useSessionResource } from '../hooks/useSessionResource';
|
||||||
|
|
||||||
|
const APPLY_STATUS_ORDER: Record<FriendLinkApply['status'], number> = {
|
||||||
|
pending: 0,
|
||||||
|
rejected: 1,
|
||||||
|
approved: 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
function applyStatusBadge(status: FriendLinkApply['status']) {
|
||||||
|
switch (status) {
|
||||||
|
case 'pending':
|
||||||
|
return <Badge variant="orange">待审核</Badge>;
|
||||||
|
case 'approved':
|
||||||
|
return <Badge variant="green">已通过</Badge>;
|
||||||
|
case 'rejected':
|
||||||
|
return <Badge variant="secondary">已拒绝</Badge>;
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function linkInitial(name: string): string {
|
||||||
|
const t = name.trim();
|
||||||
|
return t ? t.charAt(0).toUpperCase() : '?';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 友情链接独立页面:展示友链、申请与管理自己的申请 */
|
||||||
|
export default function LinksPage() {
|
||||||
|
const nav = useNavigate();
|
||||||
|
const [params, setParams] = useSearchParams();
|
||||||
|
const { branding } = useSiteBranding();
|
||||||
|
const { user } = useAuth();
|
||||||
|
const [applyOpen, setApplyOpen] = useState(false);
|
||||||
|
const [editApply, setEditApply] = useState<FriendLinkApply | null>(null);
|
||||||
|
const [cancelingId, setCancelingId] = useState<number | null>(null);
|
||||||
|
|
||||||
|
usePageSEO({
|
||||||
|
title: '友情链接',
|
||||||
|
description: `${branding.name} 的友情链接与申请入口`,
|
||||||
|
keywords: joinSEOKeywords('友情链接', getCachedSiteBranding().keywords),
|
||||||
|
canonicalPath: '/links',
|
||||||
|
});
|
||||||
|
|
||||||
|
const friendLinks = (branding.friend_links ?? []).filter(
|
||||||
|
(l: FriendLink) => l.name?.trim() && l.url?.trim(),
|
||||||
|
);
|
||||||
|
|
||||||
|
const { data: myApplies = [], loading: myLoading, replace: setMyApplies } = useSessionResource<FriendLinkApply[]>(
|
||||||
|
user ? 'links:applies' : null,
|
||||||
|
() => api.myFriendLinkApplies().then(r => r.applies ?? []),
|
||||||
|
{
|
||||||
|
enabled: !!user,
|
||||||
|
onError: (e) => notify.error(e instanceof Error ? e.message : '加载失败'),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const sortedApplies = useMemo(
|
||||||
|
() => [...myApplies].sort((a, b) => {
|
||||||
|
const byStatus = APPLY_STATUS_ORDER[a.status] - APPLY_STATUS_ORDER[b.status];
|
||||||
|
if (byStatus !== 0) return byStatus;
|
||||||
|
return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
|
||||||
|
}),
|
||||||
|
[myApplies],
|
||||||
|
);
|
||||||
|
|
||||||
|
const applyCounts = useMemo(() => {
|
||||||
|
let pending = 0;
|
||||||
|
let rejected = 0;
|
||||||
|
let approved = 0;
|
||||||
|
for (const a of myApplies) {
|
||||||
|
if (a.status === 'pending') pending += 1;
|
||||||
|
else if (a.status === 'rejected') rejected += 1;
|
||||||
|
else if (a.status === 'approved') approved += 1;
|
||||||
|
}
|
||||||
|
return { pending, rejected, approved };
|
||||||
|
}, [myApplies]);
|
||||||
|
|
||||||
|
const applySummaryText = useMemo(() => {
|
||||||
|
if (myApplies.length === 0) return '';
|
||||||
|
const parts: string[] = [];
|
||||||
|
if (applyCounts.pending > 0) parts.push(`${applyCounts.pending} 待审`);
|
||||||
|
if (applyCounts.rejected > 0) parts.push(`${applyCounts.rejected} 已拒绝`);
|
||||||
|
if (applyCounts.approved > 0) parts.push(`${applyCounts.approved} 已通过`);
|
||||||
|
return `我的申请 · ${parts.join(' / ')}`;
|
||||||
|
}, [myApplies.length, applyCounts]);
|
||||||
|
|
||||||
|
const loadMyApplies = useCallback(() => {
|
||||||
|
if (!user) {
|
||||||
|
setMyApplies([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
api.myFriendLinkApplies()
|
||||||
|
.then(r => setMyApplies(r.applies ?? []))
|
||||||
|
.catch(e => notify.error(e instanceof Error ? e.message : '加载失败'));
|
||||||
|
}, [user, setMyApplies]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!user || !myApplies.some(isReciprocalChecking)) return;
|
||||||
|
const timer = window.setInterval(loadMyApplies, 3000);
|
||||||
|
return () => window.clearInterval(timer);
|
||||||
|
}, [user, myApplies, loadMyApplies]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (params.get('apply') === '1') {
|
||||||
|
if (!user) {
|
||||||
|
nav(loginPath('/links?apply=1'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setApplyOpen(true);
|
||||||
|
const next = new URLSearchParams(params);
|
||||||
|
next.delete('apply');
|
||||||
|
setParams(next, { replace: true });
|
||||||
|
}
|
||||||
|
}, [params, setParams, user, nav]);
|
||||||
|
|
||||||
|
const openApply = () => {
|
||||||
|
if (!user) {
|
||||||
|
nav(loginPath('/links?apply=1'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setEditApply(null);
|
||||||
|
setApplyOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const openEditApply = (apply: FriendLinkApply) => {
|
||||||
|
setEditApply(apply);
|
||||||
|
setApplyOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleApplyOpenChange = (open: boolean) => {
|
||||||
|
setApplyOpen(open);
|
||||||
|
if (!open) setEditApply(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onApplySubmitted = useCallback(() => {
|
||||||
|
loadMyApplies();
|
||||||
|
invalidateSiteBrandingCache();
|
||||||
|
}, [loadMyApplies]);
|
||||||
|
|
||||||
|
const cancelApply = async (apply: FriendLinkApply) => {
|
||||||
|
if (apply.status !== 'pending') return;
|
||||||
|
setCancelingId(apply.id);
|
||||||
|
try {
|
||||||
|
const r = await api.cancelFriendLinkApply(apply.id);
|
||||||
|
notify.success(r.message);
|
||||||
|
loadMyApplies();
|
||||||
|
} catch (e: unknown) {
|
||||||
|
notify.error(e instanceof Error ? e.message : '撤销失败');
|
||||||
|
} finally {
|
||||||
|
setCancelingId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const friendLinksBlock = friendLinks.length === 0 ? (
|
||||||
|
<div className="empty-state links-page-empty list-page-panel__empty">
|
||||||
|
<Link2 className="empty-state-icon" aria-hidden size={36} strokeWidth={1.5} />
|
||||||
|
<p>暂无友情链接</p>
|
||||||
|
<p className="page-desc" style={{ marginTop: 8 }}>
|
||||||
|
注册登录后可提交申请,审核通过后将展示在此页
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="links-page-board">
|
||||||
|
<div className="links-page-grid">
|
||||||
|
{friendLinks.map(link => {
|
||||||
|
const logoURL = resolveFriendLinkLogo(link.logo, branding.site_url);
|
||||||
|
return (
|
||||||
|
<a
|
||||||
|
key={`${link.name}-${link.url}`}
|
||||||
|
href={link.url}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="links-page-card"
|
||||||
|
title={link.name}
|
||||||
|
>
|
||||||
|
<div className="links-page-card__logo">
|
||||||
|
{logoURL ? (
|
||||||
|
<img src={logoURL} alt="" loading="lazy" decoding="async" />
|
||||||
|
) : (
|
||||||
|
<span>{linkInitial(link.name)}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<strong className="links-page-card__name">{link.name}</strong>
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
const myAppliesBlock = user ? (
|
||||||
|
<section
|
||||||
|
id="my-applies"
|
||||||
|
className={`links-page-my${myApplies.length === 0 && !myLoading ? ' links-page-my--compact' : ''}`}
|
||||||
|
aria-label="我的友链申请"
|
||||||
|
>
|
||||||
|
<h2 className="links-page-my__title">我的申请</h2>
|
||||||
|
{myLoading ? (
|
||||||
|
<div className="flex justify-center py-10"><Spinner /></div>
|
||||||
|
) : myApplies.length === 0 ? (
|
||||||
|
<p className="links-page-my__empty">你还没有提交过友链申请,点击右上角「申请友链」即可提交</p>
|
||||||
|
) : (
|
||||||
|
<div className="links-page-my-list">
|
||||||
|
{sortedApplies.map(apply => (
|
||||||
|
<div key={apply.id} className="links-page-my-row">
|
||||||
|
{apply.logo?.trim() && (
|
||||||
|
<div className="links-page-my-row__logo">
|
||||||
|
<img src={resolveFriendLinkLogo(apply.logo, branding.site_url)} alt="" loading="lazy" decoding="async" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="links-page-my-row__main">
|
||||||
|
<div className="links-page-my-row__title">
|
||||||
|
<strong>{apply.name}</strong>
|
||||||
|
{applyStatusBadge(apply.status)}
|
||||||
|
</div>
|
||||||
|
<a href={apply.url} target="_blank" rel="noopener noreferrer" className="links-page-my-row__url">
|
||||||
|
{apply.url}
|
||||||
|
</a>
|
||||||
|
{apply.status === 'rejected' && apply.review_note?.trim() && (
|
||||||
|
<p className="links-page-my-row__note">拒绝原因:{apply.review_note}</p>
|
||||||
|
)}
|
||||||
|
{apply.status === 'pending' && (
|
||||||
|
<p className="links-page-my-row__note">
|
||||||
|
回链检测:{reciprocalStatusLabel(apply).text}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{apply.status === 'approved' && (
|
||||||
|
<p className="links-page-my-row__note">修改后将重新进入审核,友链会暂时从列表移除</p>
|
||||||
|
)}
|
||||||
|
<p className="links-page-my-row__meta">{formatTime(apply.created_at)}</p>
|
||||||
|
</div>
|
||||||
|
{apply.status === 'pending' && (
|
||||||
|
<div className="links-page-my-row__actions">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => openEditApply(apply)}
|
||||||
|
>
|
||||||
|
<Pencil size={14} aria-hidden />
|
||||||
|
修改
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={cancelingId === apply.id}
|
||||||
|
onClick={() => cancelApply(apply)}
|
||||||
|
>
|
||||||
|
<Trash2 size={14} aria-hidden />
|
||||||
|
撤销
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{apply.status === 'rejected' && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => openEditApply(apply)}
|
||||||
|
>
|
||||||
|
<Pencil size={14} aria-hidden />
|
||||||
|
修改并重新提交
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{apply.status === 'approved' && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => openEditApply(apply)}
|
||||||
|
>
|
||||||
|
<Pencil size={14} aria-hidden />
|
||||||
|
修改
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
) : null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="page-wrap">
|
||||||
|
<div className="feed-panel list-page-panel">
|
||||||
|
<header className="list-page-panel__head">
|
||||||
|
<Button variant="ghost" size="sm" className="list-page-panel__back" onClick={() => nav('/')}>
|
||||||
|
<ArrowLeft />
|
||||||
|
返回
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<div className="links-page-head">
|
||||||
|
<div>
|
||||||
|
<h1 className="page-title">友情链接</h1>
|
||||||
|
<p className="page-desc">
|
||||||
|
与本站互链的站点列表
|
||||||
|
{friendLinks.length > 0 ? ` · 共 ${friendLinks.length} 个` : ''}
|
||||||
|
</p>
|
||||||
|
{user && myApplies.length > 0 && applySummaryText ? (
|
||||||
|
<p
|
||||||
|
className={`links-page-summary${applyCounts.pending > 0 ? ' links-page-summary--pending' : applyCounts.rejected > 0 ? ' links-page-summary--rejected' : ''}`}
|
||||||
|
>
|
||||||
|
{applySummaryText}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<Button type="button" onClick={openApply}>
|
||||||
|
<Plus size={16} aria-hidden />
|
||||||
|
申请友链
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{/* 登录:申请区在上;游客:友链在上 */}
|
||||||
|
{user ? (
|
||||||
|
<>
|
||||||
|
{myAppliesBlock}
|
||||||
|
{friendLinksBlock}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
{friendLinksBlock}
|
||||||
|
<p className="links-page-login-hint">
|
||||||
|
<Link to={loginPath('/links')}>登录</Link>
|
||||||
|
或
|
||||||
|
<Link to="/register">注册</Link>
|
||||||
|
后可申请友链并管理自己的申请
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<InFlowSiteFooter />
|
||||||
|
|
||||||
|
<FriendLinkApplyDialog
|
||||||
|
open={applyOpen}
|
||||||
|
onOpenChange={handleApplyOpenChange}
|
||||||
|
editApply={editApply}
|
||||||
|
onSubmitted={onApplySubmitted}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user