Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f3f50d7e90 | |||
| 67bef6dc08 | |||
| 23e304ac53 | |||
| cad53942e8 | |||
| 76be8926f2 | |||
| 4d93e455f9 |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -20,9 +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>
|
# Lucide path <20><>ȡ<EFBFBD><C8A1>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD>
|
||||||
frontend/tmp-lucide-paths.json
|
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,138 +0,0 @@
|
|||||||
# 修复主页右侧栏评论点击定位问题
|
|
||||||
|
|
||||||
## 问题描述
|
|
||||||
|
|
||||||
用户在主页右侧栏点击评论时,如果该评论不是帖子的第一个评论(`floor > 0`),页面跳转后没有定位到该评论上。
|
|
||||||
|
|
||||||
## 根因分析
|
|
||||||
|
|
||||||
### 问题 1:`jumpToFloor` 使用 `scrollIntoView` 而非 `pageRef.scrollTo`
|
|
||||||
|
|
||||||
**文件**: [PostDetailPage.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/pages/PostDetailPage.tsx#L235-L242)
|
|
||||||
|
|
||||||
当前 `jumpToFloor` 函数使用 `el.scrollIntoView()` 来滚动:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
const jumpToFloor = useCallback((floor: number) => {
|
|
||||||
const el = document.getElementById(`floor-${floor}`);
|
|
||||||
if (!el) return;
|
|
||||||
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
|
||||||
// ...
|
|
||||||
}, []);
|
|
||||||
```
|
|
||||||
|
|
||||||
但是页面使用了自定义滚动容器 `pageRef`(类名为 `.post-detail-page`),且 `useGlobalWheelScroll` 钩子拦截了滚轮事件,将其转换为对 `pageRef.scrollTop` 的直接操作。这导致原生 `scrollIntoView` 可能无法正确触发滚动。
|
|
||||||
|
|
||||||
对比 `jumpToHeadingHash` 函数(第 244-262 行),它正确地使用了 `pageRef.scrollTo()`:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
const jumpToHeadingHash = useCallback((hash: string, smooth = false) => {
|
|
||||||
// ...
|
|
||||||
const root = pageRef.current;
|
|
||||||
if (root) {
|
|
||||||
const rootRect = root.getBoundingClientRect();
|
|
||||||
const elRect = el.getBoundingClientRect();
|
|
||||||
const top = root.scrollTop + (elRect.top - rootRect.top) - 12;
|
|
||||||
root.scrollTo({ top: Math.max(0, top), behavior });
|
|
||||||
}
|
|
||||||
// ...
|
|
||||||
}, []);
|
|
||||||
```
|
|
||||||
|
|
||||||
### 问题 2:`#floor-N` 定位缺少重试机制
|
|
||||||
|
|
||||||
**文件**: [PostDetailPage.tsx](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/pages/PostDetailPage.tsx#L264-L273)
|
|
||||||
|
|
||||||
当前 `#floor-N` 定位只有一次 80ms 延迟,没有重试机制:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
useEffect(() => {
|
|
||||||
if (loading || !post) return;
|
|
||||||
const m = location.hash.match(/^#floor-(\d+)$/);
|
|
||||||
if (!m) return;
|
|
||||||
const floor = Number(m[1]);
|
|
||||||
if (!floor) return;
|
|
||||||
const t = window.setTimeout(() => jumpToFloor(floor), 80);
|
|
||||||
return () => clearTimeout(t);
|
|
||||||
}, [loading, post, comments, location.hash, jumpToFloor]);
|
|
||||||
```
|
|
||||||
|
|
||||||
对比 `#heading-N` 定位(第 275-299 行),它有完善的重试机制(最多 30 次,每次 50ms)。
|
|
||||||
|
|
||||||
## 修改方案
|
|
||||||
|
|
||||||
### 修改 1:修改 `jumpToFloor` 函数使用 `pageRef.scrollTo`
|
|
||||||
|
|
||||||
将 `jumpToFloor` 函数改为使用与 `jumpToHeadingHash` 相同的滚动方式:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
const jumpToFloor = useCallback((floor: number) => {
|
|
||||||
const el = document.getElementById(`floor-${floor}`);
|
|
||||||
if (!el) return false;
|
|
||||||
|
|
||||||
const root = pageRef.current;
|
|
||||||
if (root) {
|
|
||||||
const rootRect = root.getBoundingClientRect();
|
|
||||||
const elRect = el.getBoundingClientRect();
|
|
||||||
const top = root.scrollTop + (elRect.top - rootRect.top) - 12;
|
|
||||||
root.scrollTo({ top: Math.max(0, top), behavior: 'smooth' });
|
|
||||||
} else {
|
|
||||||
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
|
||||||
}
|
|
||||||
|
|
||||||
setHighlightFloor(floor);
|
|
||||||
clearTimeout(highlightTimer.current);
|
|
||||||
highlightTimer.current = setTimeout(() => setHighlightFloor(null), 2000);
|
|
||||||
return true;
|
|
||||||
}, []);
|
|
||||||
```
|
|
||||||
|
|
||||||
### 修改 2:为 `#floor-N` 定位添加重试机制
|
|
||||||
|
|
||||||
将 `#floor-N` 定位的 `useEffect` 改为类似 `#heading-N` 的重试机制:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
useEffect(() => {
|
|
||||||
if (loading || !post) return;
|
|
||||||
const m = location.hash.match(/^#floor-(\d+)$/);
|
|
||||||
if (!m) return;
|
|
||||||
const floor = Number(m[1]);
|
|
||||||
if (!floor) return;
|
|
||||||
|
|
||||||
let cancelled = false;
|
|
||||||
let attempts = 0;
|
|
||||||
let timer = 0;
|
|
||||||
|
|
||||||
const tryJump = () => {
|
|
||||||
if (cancelled) return;
|
|
||||||
if (jumpToFloor(floor)) return;
|
|
||||||
attempts += 1;
|
|
||||||
if (attempts < 30) {
|
|
||||||
timer = window.setTimeout(tryJump, 50);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
timer = window.setTimeout(tryJump, 0);
|
|
||||||
return () => {
|
|
||||||
cancelled = true;
|
|
||||||
window.clearTimeout(timer);
|
|
||||||
};
|
|
||||||
}, [loading, post, comments, location.hash, jumpToFloor]);
|
|
||||||
```
|
|
||||||
|
|
||||||
## 涉及文件
|
|
||||||
|
|
||||||
- `frontend/src/pages/PostDetailPage.tsx`:修改 `jumpToFloor` 函数和 `#floor-N` 定位的 `useEffect`
|
|
||||||
|
|
||||||
## 风险评估
|
|
||||||
|
|
||||||
- **低风险**:修改仅限于评论定位逻辑,不影响其他功能
|
|
||||||
- **需测试**:需要验证页面加载时评论定位是否正常工作,以及页面内部导航时是否正常
|
|
||||||
|
|
||||||
## 测试步骤
|
|
||||||
|
|
||||||
1. 进入主页,点击右侧栏的一个非第一条评论
|
|
||||||
2. 验证页面跳转到帖子详情后,是否正确定位到目标评论
|
|
||||||
3. 验证评论高亮效果是否正常显示
|
|
||||||
4. 测试第一条评论(floor=0)的定位是否仍然正常工作
|
|
||||||
5. 在帖子详情页直接加载带 hash 的 URL(如 `/post/123#floor-5`),验证定位效果
|
|
||||||
@@ -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 编译通过。
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
# 修复生产环境表情图片无法显示 Implementation Plan
|
|
||||||
|
|
||||||
## Repository Research
|
|
||||||
|
|
||||||
### 问题分析
|
|
||||||
|
|
||||||
表情图片在生产部署后无法加载,原因是 **Go 后端缺少 `/stickers/*` 路由的静态文件服务注册**。
|
|
||||||
|
|
||||||
当前架构:
|
|
||||||
1. 前端 emoji 数据中的 URL 为 `/stickers/{platform}/{file}.avif`(在 [emojiData.ts](file:///c:/Users/freefire/Documents/jiang13-forum/frontend/src/data/stickers/emojiData.ts) 中通过 `toLocalUrl()` 生成)
|
|
||||||
2. Vite 构建时将 `frontend/public/stickers/` 原样复制到 `embed_static/static/spa/stickers/`
|
|
||||||
3. Go 的 `//go:embed static/*` 会将 `embed_static/static/` 下所有文件(包括 stickers)打包进二进制
|
|
||||||
4. 但 [embed.go](file:///c:/Users/freefire/Documents/jiang13-forum/embed_static/embed.go) 的 `SetupEmbed()` **只注册了 `/assets/*filepath` 路由**(用于 JS/CSS chunk),没有注册 `/stickers/*filepath`
|
|
||||||
5. 同时 `IsSPARoute()` 函数也没有排除 `/stickers` 前缀,导致请求被 SPA NoRoute fallback 处理,返回 index.html 而非图片
|
|
||||||
|
|
||||||
开发模式之所以正常,是因为 Vite dev server 自动托管了 `public/stickers/` 下的静态文件。
|
|
||||||
|
|
||||||
### 当前代码状态
|
|
||||||
|
|
||||||
- `embed.go` 第 13 行: `//go:embed static/*` — 正确嵌入了所有静态资源(含 stickers)
|
|
||||||
- `embed.go` 第 33-43 行: `SetupEmbed()` — 只处理了 `static/spa/assets`,缺少 stickers 路由
|
|
||||||
- `embed.go` 第 63-77 行: `IsSPARoute()` — 缺少 `/stickers` 前缀排除
|
|
||||||
|
|
||||||
## Files and Modules
|
|
||||||
|
|
||||||
- `embed_static/embed.go`: 新增 `/stickers/*filepath` 文件服务路由;在 `IsSPARoute` 中排除 `/stickers` 前缀
|
|
||||||
|
|
||||||
## Implementation Steps
|
|
||||||
|
|
||||||
1. **在 `SetupEmbed` 中注册 `/stickers` 路由**
|
|
||||||
- 参照现有 `/assets` 路由的模式,添加对 `static/spa/stickers` 子目录的文件服务
|
|
||||||
- 使用 `fs.Sub(staticFS, "static/spa/stickers")` 获取 stickers 子文件系统
|
|
||||||
- 注册 `GET /stickers/*filepath` 路由,直接透传,不设置长期缓存(表情可能更新)
|
|
||||||
|
|
||||||
2. **在 `IsSPARoute` 中排除 `/stickers` 前缀**
|
|
||||||
- 在现有 `strings.HasPrefix(path, "/assets")` 附近添加 `strings.HasPrefix(path, "/stickers")`
|
|
||||||
- 确保表情请求不会被 SPA fallback 拦截
|
|
||||||
|
|
||||||
## Dependencies and Considerations
|
|
||||||
|
|
||||||
- stickers 目录下存储的是 `.avif` 图片文件,不需要设置特殊 MIME type(http.FileServer 会根据扩展名自动识别)
|
|
||||||
- stickers 资源不含哈希指纹,不应设置 `immutable` 缓存头(与 `/assets` 不同),但可以设置短过期缓存
|
|
||||||
- 需确保 `fs.Sub` 路径与实际构建输出路径一致:`embed_static/static/spa/stickers/`
|
|
||||||
|
|
||||||
## Validation
|
|
||||||
|
|
||||||
- 重新构建前端:`cd frontend && npm run build`
|
|
||||||
- 重新构建 Go 二进制:`go build -o jiang13-linux-amd64`
|
|
||||||
- 部署后访问 `/stickers/tieba/tb_01.avif` 应能直接返回图片内容(HTTP 200)
|
|
||||||
- 在评论框中打开表情选择器,所有平台的表情应正常显示
|
|
||||||
|
|
||||||
## Risks
|
|
||||||
|
|
||||||
- **风险**: 如果未来在 `public/` 下新增其他静态资源目录(如 `avatars/`、`flags/` 等),需要同样在 `embed.go` 中注册对应路由
|
|
||||||
- **应对**: 可考虑后续重构为自动扫描 `public/` 下所有子目录并自动注册路由,或改为统一的 SPA 静态文件服务方案
|
|
||||||
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「快速开始」如需对外暴露再更新
|
||||||
2
Makefile
2
Makefile
@@ -5,7 +5,7 @@ APP_NAME := jiang13
|
|||||||
MAIN_PKG := ./cmd/jiang13
|
MAIN_PKG := ./cmd/jiang13
|
||||||
BUILD_DIR := dist
|
BUILD_DIR := dist
|
||||||
DEV_DATA_DIR := dist/data
|
DEV_DATA_DIR := dist/data
|
||||||
VERSION := 1.1.7
|
VERSION := 1.1.8
|
||||||
LDFLAGS := -s -w -X main.version=$(VERSION)
|
LDFLAGS := -s -w -X main.version=$(VERSION)
|
||||||
REGISTRY_IMAGE := hangzhang714128/jiang13-forum
|
REGISTRY_IMAGE := hangzhang714128/jiang13-forum
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ $AppName = 'jiang13'
|
|||||||
$MainPkg = './cmd/jiang13'
|
$MainPkg = './cmd/jiang13'
|
||||||
$BuildDir = 'dist'
|
$BuildDir = 'dist'
|
||||||
$DevDataDir = 'dist/data'
|
$DevDataDir = 'dist/data'
|
||||||
$Version = '1.1.7'
|
$Version = '1.1.8'
|
||||||
$RegistryImage = 'hangzhang714128/jiang13-forum'
|
$RegistryImage = 'hangzhang714128/jiang13-forum'
|
||||||
$Ldlags = "-s -w -X main.version=$Version"
|
$Ldlags = "-s -w -X main.version=$Version"
|
||||||
|
|
||||||
|
|||||||
@@ -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';
|
||||||
@@ -37,7 +38,10 @@ 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, type ArticleLinkConfirm } from './editor/ArticleLinkDialog';
|
import { ArticleLinkDialog, type ArticleLinkConfirm } from './editor/ArticleLinkDialog';
|
||||||
import { ArticleImagePickerDialog } from './editor/ArticleImagePickerDialog';
|
import { ArticleImagePickerDialog } from './editor/ArticleImagePickerDialog';
|
||||||
@@ -84,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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -177,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>
|
||||||
@@ -213,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: [
|
||||||
@@ -246,6 +264,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
ArticleImage.configure({ inline: false, allowBase64: false }),
|
ArticleImage.configure({ inline: false, allowBase64: false }),
|
||||||
|
ArticleSticker,
|
||||||
ImageGroup,
|
ImageGroup,
|
||||||
Placeholder.configure({
|
Placeholder.configure({
|
||||||
placeholder: ({ node }) => {
|
placeholder: ({ node }) => {
|
||||||
@@ -322,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: () => {
|
||||||
@@ -523,6 +561,30 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
||||||
}, [editor]);
|
}, [editor]);
|
||||||
|
|
||||||
|
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 (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) => {
|
const openImagePicker = useCallback((target: ImagePickerTarget) => {
|
||||||
setImagePickerTarget(target);
|
setImagePickerTarget(target);
|
||||||
setImagePickerOpen(true);
|
setImagePickerOpen(true);
|
||||||
@@ -614,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]);
|
||||||
|
|
||||||
@@ -626,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]);
|
||||||
|
|
||||||
@@ -676,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')) {
|
||||||
@@ -760,7 +833,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
}
|
}
|
||||||
|
|
||||||
return tools;
|
return tools;
|
||||||
}, [editor, enableContentGates, openLinkDialog, openCodeBlockDialog, openTableDialog, openImagePicker, wrapMembersOnly, wrapReplyOnly, wrapPointsOnly, wrapSelectedAsGroup, setImageDisplay]);
|
}, [editor, enableContentGates, showSticker, openLinkDialog, openCodeBlockDialog, openTableDialog, openImagePicker, wrapMembersOnly, wrapReplyOnly, wrapPointsOnly, wrapSelectedAsGroup, setImageDisplay]);
|
||||||
|
|
||||||
const buildMarkdownTools = useCallback((): ToolBtn[] => {
|
const buildMarkdownTools = useCallback((): ToolBtn[] => {
|
||||||
const tools: ToolBtn[] = [
|
const tools: ToolBtn[] = [
|
||||||
@@ -782,6 +855,15 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
hint: '上传、链接或从已上传中选择',
|
hint: '上传、链接或从已上传中选择',
|
||||||
action: () => openImagePicker('markdown'),
|
action: () => openImagePicker('markdown'),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
icon: <span className="article-tool-btn__owo">OwO</span>,
|
||||||
|
title: '表情 OwO',
|
||||||
|
hint: '插入贴纸或颜文字',
|
||||||
|
active: showSticker,
|
||||||
|
className: 'article-tool-btn--owo',
|
||||||
|
buttonRef: stickerBtnRef,
|
||||||
|
action: () => setShowSticker(v => !v),
|
||||||
|
},
|
||||||
];
|
];
|
||||||
if (enableContentGates) {
|
if (enableContentGates) {
|
||||||
tools.push(
|
tools.push(
|
||||||
@@ -809,7 +891,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
return tools;
|
return tools;
|
||||||
}, [enableContentGates, withMarkdown, openLinkDialog, openCodeBlockDialog, openTableDialog, openImagePicker]);
|
}, [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'
|
||||||
@@ -817,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' ? (
|
||||||
|
|||||||
@@ -1,15 +1,19 @@
|
|||||||
|
import { useMemo, useCallback } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { api } from '../api/client';
|
import { api } from '../api/client';
|
||||||
import { renderCommentContent } from '../utils/content';
|
import { renderCommentContent } from '../utils/content';
|
||||||
|
import { handleMdCodeBlockUiClick } from '../utils/enhanceCodeBlocks';
|
||||||
import { userPath } from '../utils/userPath';
|
import { userPath } from '../utils/userPath';
|
||||||
|
import { notify } from '@/lib/notify';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
content: string;
|
content: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 渲染评论正文(支持正文内 @ 高亮与点击跳转) */
|
/** 渲染评论正文(支持正文内 @ 高亮、代码块阅读态与点击跳转) */
|
||||||
export default function CommentContent({ content }: Props) {
|
export default function CommentContent({ content }: Props) {
|
||||||
const nav = useNavigate();
|
const nav = useNavigate();
|
||||||
|
const html = useMemo(() => renderCommentContent(content), [content]);
|
||||||
|
|
||||||
const openMention = async (name: string) => {
|
const openMention = async (name: string) => {
|
||||||
try {
|
try {
|
||||||
@@ -26,17 +30,29 @@ export default function CommentContent({ content }: Props) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const onClick = useCallback(async (e: React.MouseEvent) => {
|
||||||
|
try {
|
||||||
|
if (await handleMdCodeBlockUiClick(e.target)) {
|
||||||
|
e.preventDefault();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
notify.error('复制失败');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const el = (e.target as HTMLElement).closest('.mention') as HTMLElement | null;
|
||||||
|
if (!el) return;
|
||||||
|
const name = el.getAttribute('data-name');
|
||||||
|
if (!name) return;
|
||||||
|
e.preventDefault();
|
||||||
|
void openMention(name);
|
||||||
|
}, [nav]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="floor-body"
|
className="floor-body post-detail-content"
|
||||||
onClick={(e) => {
|
onClick={(e) => { void onClick(e); }}
|
||||||
const el = (e.target as HTMLElement).closest('.mention') as HTMLElement | null;
|
|
||||||
if (!el) return;
|
|
||||||
const name = el.getAttribute('data-name');
|
|
||||||
if (!name) return;
|
|
||||||
e.preventDefault();
|
|
||||||
void openMention(name);
|
|
||||||
}}
|
|
||||||
onKeyDown={(e) => {
|
onKeyDown={(e) => {
|
||||||
if (e.key !== 'Enter' && e.key !== ' ') return;
|
if (e.key !== 'Enter' && e.key !== ' ') return;
|
||||||
const el = e.target as HTMLElement;
|
const el = e.target as HTMLElement;
|
||||||
@@ -46,9 +62,7 @@ export default function CommentContent({ content }: Props) {
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
void openMention(name);
|
void openMention(name);
|
||||||
}}
|
}}
|
||||||
dangerouslySetInnerHTML={{
|
dangerouslySetInnerHTML={{ __html: html }}
|
||||||
__html: renderCommentContent(content),
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
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;
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useMemo, useCallback, 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 { 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';
|
||||||
@@ -105,40 +106,12 @@ export default function PostContent({
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const foldBtn = target.closest<HTMLElement>('[data-code-fold]');
|
try {
|
||||||
if (foldBtn) {
|
if (await handleMdCodeBlockUiClick(target)) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const block = foldBtn.closest('.md-codeblock');
|
|
||||||
if (!block) return;
|
|
||||||
const collapsed = block.classList.toggle('md-codeblock--collapsed');
|
|
||||||
const lineCount = parseInt(block.getAttribute('data-line-count') || '0', 10)
|
|
||||||
|| block.querySelectorAll('.md-code-line').length
|
|
||||||
|| 1;
|
|
||||||
if (collapsed && lineCount <= 5) block.classList.add('md-codeblock--short');
|
|
||||||
else block.classList.remove('md-codeblock--short');
|
|
||||||
foldBtn.textContent = collapsed ? '展开' : '收起';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const copyBtn = target.closest<HTMLElement>('[data-code-copy]');
|
|
||||||
if (copyBtn) {
|
|
||||||
e.preventDefault();
|
|
||||||
const block = copyBtn.closest('.md-codeblock');
|
|
||||||
const bodies = block?.querySelectorAll('.md-code-line__body');
|
|
||||||
const text = bodies && bodies.length
|
|
||||||
? [...bodies].map(el => el.textContent ?? '').join('\n')
|
|
||||||
: (block?.querySelector('pre')?.textContent ?? '');
|
|
||||||
try {
|
|
||||||
await navigator.clipboard.writeText(text);
|
|
||||||
const prev = copyBtn.textContent;
|
|
||||||
copyBtn.textContent = '已复制';
|
|
||||||
copyBtn.classList.add('is-copied');
|
|
||||||
window.setTimeout(() => {
|
|
||||||
copyBtn.textContent = prev || '复制';
|
|
||||||
copyBtn.classList.remove('is-copied');
|
|
||||||
}, 1600);
|
|
||||||
} catch {
|
|
||||||
notify.error('复制失败');
|
|
||||||
}
|
}
|
||||||
|
} catch {
|
||||||
|
notify.error('复制失败');
|
||||||
}
|
}
|
||||||
}, [nav, openLightbox, onRequestReply, onUnlocked, postId, unlocking]);
|
}, [nav, openLightbox, onRequestReply, onUnlocked, postId, unlocking]);
|
||||||
|
|
||||||
|
|||||||
@@ -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?.(),
|
||||||
|
|||||||
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,33 +124,35 @@ export default function StickerPicker({ onSelect }: Props) {
|
|||||||
) : stickers.length === 0 ? (
|
) : stickers.length === 0 ? (
|
||||||
<div className="sticker-picker-loading">暂无贴纸</div>
|
<div className="sticker-picker-loading">暂无贴纸</div>
|
||||||
) : (
|
) : (
|
||||||
stickers.map((s, i) => (
|
stickers.map((s, i) => {
|
||||||
<button
|
const isText = s.type === 'text' && !!s.text;
|
||||||
key={s.id}
|
return (
|
||||||
id={`${autoId}-opt-${i}`}
|
<button
|
||||||
type="button"
|
key={s.id}
|
||||||
role="option"
|
id={`${autoId}-opt-${i}`}
|
||||||
tabIndex={focusIndex === i ? 0 : -1}
|
type="button"
|
||||||
aria-selected={focusIndex === i}
|
role="option"
|
||||||
aria-label={s.name}
|
tabIndex={focusIndex === i ? 0 : -1}
|
||||||
className="sticker-picker-item"
|
aria-selected={focusIndex === i}
|
||||||
onClick={() => onSelect(s)}
|
aria-label={s.name}
|
||||||
onFocus={() => setFocusIndex(i)}
|
className={isText ? 'sticker-picker-item sticker-picker-item--text' : 'sticker-picker-item sticker-picker-item--image'}
|
||||||
>
|
onClick={() => onSelect(s)}
|
||||||
{s.type === 'text' && s.text ? (
|
onFocus={() => setFocusIndex(i)}
|
||||||
<span className="sticker-picker-text">{s.text}</span>
|
>
|
||||||
) : (
|
{isText ? (
|
||||||
<img
|
<span className="sticker-picker-text">{s.text}</span>
|
||||||
src={s.url}
|
) : (
|
||||||
alt={s.name}
|
<img
|
||||||
width={32}
|
src={s.url}
|
||||||
height={32}
|
alt={s.name}
|
||||||
style={{ width: 32, height: 32, objectFit: 'contain' }}
|
width={32}
|
||||||
loading="lazy"
|
height={32}
|
||||||
/>
|
loading="lazy"
|
||||||
)}
|
/>
|
||||||
</button>
|
)}
|
||||||
))
|
</button>
|
||||||
|
);
|
||||||
|
})
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -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: ['怀疑', '思考'] },
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import { userPath } from '../utils/userPath';
|
|||||||
import { InFlowSiteFooter } from '../components/SiteFooter';
|
import { InFlowSiteFooter } from '../components/SiteFooter';
|
||||||
import StickerPicker from '../components/emoji/StickerPicker';
|
import StickerPicker from '../components/emoji/StickerPicker';
|
||||||
import type { Sticker } from '../data/stickers';
|
import type { Sticker } from '../data/stickers';
|
||||||
|
import PmComposerInput, { isPmStickerSrc, type PmComposerInputHandle } from '../components/PmComposerInput';
|
||||||
import { ArticleImagePickerDialog } from '../components/editor/ArticleImagePickerDialog';
|
import { ArticleImagePickerDialog } from '../components/editor/ArticleImagePickerDialog';
|
||||||
import { Tooltip } from '../components/ui/Tooltip';
|
import { Tooltip } from '../components/ui/Tooltip';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
@@ -130,12 +131,13 @@ function PmBubbleContent({ content }: { content: string }) {
|
|||||||
{parts.map((part, i) => {
|
{parts.map((part, i) => {
|
||||||
const m = part.match(/^!\[([^\]]*)]\(([^)]+)\)$/);
|
const m = part.match(/^!\[([^\]]*)]\(([^)]+)\)$/);
|
||||||
if (m) {
|
if (m) {
|
||||||
|
const sticker = isPmStickerSrc(m[2]);
|
||||||
return (
|
return (
|
||||||
<img
|
<img
|
||||||
key={i}
|
key={i}
|
||||||
className="pm-bubble__img"
|
className={sticker ? 'pm-bubble__sticker' : 'pm-bubble__img'}
|
||||||
src={m[2]}
|
src={m[2]}
|
||||||
alt={m[1] || '图片'}
|
alt={m[1] || (sticker ? '表情' : '图片')}
|
||||||
loading="lazy"
|
loading="lazy"
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
@@ -273,7 +275,7 @@ export default function MessagesPage() {
|
|||||||
const [draftEmbeds, setDraftEmbeds] = useState<PmDraftEmbed[]>([]);
|
const [draftEmbeds, setDraftEmbeds] = useState<PmDraftEmbed[]>([]);
|
||||||
const [showSticker, setShowSticker] = useState(false);
|
const [showSticker, setShowSticker] = useState(false);
|
||||||
const [imagePickerOpen, setImagePickerOpen] = useState(false);
|
const [imagePickerOpen, setImagePickerOpen] = useState(false);
|
||||||
const draftRef = useRef<HTMLTextAreaElement>(null);
|
const composerRef = useRef<PmComposerInputHandle>(null);
|
||||||
const draftsByPeerRef = useRef<Map<number, PmDraft>>(new Map());
|
const draftsByPeerRef = useRef<Map<number, PmDraft>>(new Map());
|
||||||
const draftPeerRef = useRef<number | null>(null);
|
const draftPeerRef = useRef<number | null>(null);
|
||||||
const draftTextRef = useRef(draftText);
|
const draftTextRef = useRef(draftText);
|
||||||
@@ -344,6 +346,23 @@ export default function MessagesPage() {
|
|||||||
});
|
});
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
/** 更新会话未读数,同时同步 session 缓存防止后续恢复 stale 数据 */
|
||||||
|
const updateConvUnread = useCallback((peerId: number, unread: number) => {
|
||||||
|
setConversations((prev) => {
|
||||||
|
const next = prev.map((c) =>
|
||||||
|
c.peer_user_id === peerId ? { ...c, unread_count: unread } : c
|
||||||
|
);
|
||||||
|
const cached = getSessionSnapshot<ConvSnap>('messages:conv:1');
|
||||||
|
if (cached) {
|
||||||
|
setSessionSnapshot('messages:conv:1', {
|
||||||
|
...cached,
|
||||||
|
conversations: next,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
const clearConvSearch = useCallback(() => {
|
const clearConvSearch = useCallback(() => {
|
||||||
setConvSearchQuery('');
|
setConvSearchQuery('');
|
||||||
setConvSearchResults([]);
|
setConvSearchResults([]);
|
||||||
@@ -582,6 +601,11 @@ export default function MessagesPage() {
|
|||||||
setPeerUser(cached.peerUser);
|
setPeerUser(cached.peerUser);
|
||||||
if (cached.peerUser) ensurePeerConversation(cached.peerUser);
|
if (cached.peerUser) ensurePeerConversation(cached.peerUser);
|
||||||
setThreadLoading(false);
|
setThreadLoading(false);
|
||||||
|
// 缓存命中时仍需标记后端已读,并更新前端会话列表未读数
|
||||||
|
void api.markConversationRead(selectedPeer).catch(() => undefined);
|
||||||
|
updateConvUnread(selectedPeer, 0);
|
||||||
|
window.dispatchEvent(new Event('messages-unread-refresh'));
|
||||||
|
void refreshUnreadSplit();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
@@ -601,9 +625,7 @@ export default function MessagesPage() {
|
|||||||
total: r.total || 0,
|
total: r.total || 0,
|
||||||
peerUser: peer,
|
peerUser: peer,
|
||||||
});
|
});
|
||||||
setConversations((prev) => prev.map((c) => (
|
updateConvUnread(selectedPeer, 0);
|
||||||
c.peer_user_id === selectedPeer ? { ...c, unread_count: 0 } : c
|
|
||||||
)));
|
|
||||||
window.dispatchEvent(new Event('messages-unread-refresh'));
|
window.dispatchEvent(new Event('messages-unread-refresh'));
|
||||||
void refreshUnreadSplit();
|
void refreshUnreadSplit();
|
||||||
})
|
})
|
||||||
@@ -660,7 +682,14 @@ export default function MessagesPage() {
|
|||||||
notify.success('通知已全部标为已读');
|
notify.success('通知已全部标为已读');
|
||||||
} else {
|
} else {
|
||||||
await api.markAllMessagesRead();
|
await api.markAllMessagesRead();
|
||||||
setConversations((prev) => prev.map((c) => ({ ...c, unread_count: 0 })));
|
setConversations((prev) => {
|
||||||
|
const next = prev.map((c) => ({ ...c, unread_count: 0 }));
|
||||||
|
const cached = getSessionSnapshot<ConvSnap>('messages:conv:1');
|
||||||
|
if (cached) {
|
||||||
|
setSessionSnapshot('messages:conv:1', { ...cached, conversations: next });
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
setDmUnread(0);
|
setDmUnread(0);
|
||||||
setNotifyUnread(0);
|
setNotifyUnread(0);
|
||||||
notify.success('已全部标为已读');
|
notify.success('已全部标为已读');
|
||||||
@@ -714,7 +743,7 @@ export default function MessagesPage() {
|
|||||||
|
|
||||||
const send = async () => {
|
const send = async () => {
|
||||||
if (!peerSelected || selectedPeer === null || selectedPeer === 0) return;
|
if (!peerSelected || selectedPeer === null || selectedPeer === 0) return;
|
||||||
const content = serializePmDraft(draftText, draftEmbeds);
|
const content = serializePmDraft(draftTextRef.current, draftEmbedsRef.current);
|
||||||
if (!content) {
|
if (!content) {
|
||||||
notify.warning('请填写内容或添加图片');
|
notify.warning('请填写内容或添加图片');
|
||||||
return;
|
return;
|
||||||
@@ -764,34 +793,15 @@ export default function MessagesPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const insertAtCursor = useCallback((text: string) => {
|
|
||||||
const el = draftRef.current;
|
|
||||||
if (!el) {
|
|
||||||
updateDraftText((d) => d + text);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const start = el.selectionStart ?? el.value.length;
|
|
||||||
const end = el.selectionEnd ?? el.value.length;
|
|
||||||
const next = el.value.slice(0, start) + text + el.value.slice(end);
|
|
||||||
updateDraftText(next);
|
|
||||||
requestAnimationFrame(() => {
|
|
||||||
el.focus();
|
|
||||||
const pos = start + text.length;
|
|
||||||
el.setSelectionRange(pos, pos);
|
|
||||||
});
|
|
||||||
}, [updateDraftText]);
|
|
||||||
|
|
||||||
const onPickSticker = useCallback((sticker: Sticker) => {
|
const onPickSticker = useCallback((sticker: Sticker) => {
|
||||||
if (sticker.type === 'text' && sticker.text) {
|
if (sticker.type === 'text' && sticker.text) {
|
||||||
insertAtCursor(sticker.text);
|
composerRef.current?.insertText(sticker.text);
|
||||||
} else if (sticker.url) {
|
} else if (sticker.url) {
|
||||||
updateDraftEmbeds((prev) => [
|
composerRef.current?.insertSticker(sticker);
|
||||||
...prev,
|
|
||||||
{ id: newEmbedId(), url: sticker.url!, name: sticker.name || '表情' },
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
setShowSticker(false);
|
setShowSticker(false);
|
||||||
}, [insertAtCursor, updateDraftEmbeds]);
|
composerRef.current?.focus();
|
||||||
|
}, []);
|
||||||
|
|
||||||
const onInsertImages = useCallback((urls: string[]) => {
|
const onInsertImages = useCallback((urls: string[]) => {
|
||||||
if (!urls.length) return;
|
if (!urls.length) return;
|
||||||
@@ -1173,20 +1183,13 @@ export default function MessagesPage() {
|
|||||||
|
|
||||||
{canCompose && (
|
{canCompose && (
|
||||||
<footer className="pm-composer">
|
<footer className="pm-composer">
|
||||||
<textarea
|
<PmComposerInput
|
||||||
ref={draftRef}
|
ref={composerRef}
|
||||||
className="pm-composer__input"
|
|
||||||
value={draftText}
|
value={draftText}
|
||||||
onChange={(e) => updateDraftText(e.target.value)}
|
onChange={updateDraftText}
|
||||||
rows={3}
|
|
||||||
maxLength={4000}
|
|
||||||
placeholder={`发送给 ${title}…`}
|
placeholder={`发送给 ${title}…`}
|
||||||
onKeyDown={(e) => {
|
onSubmit={() => { void send(); }}
|
||||||
if (e.key === 'Enter' && !e.shiftKey) {
|
disabled={sending}
|
||||||
e.preventDefault();
|
|
||||||
void send();
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
{draftEmbeds.length > 0 && (
|
{draftEmbeds.length > 0 && (
|
||||||
<ul className="pm-composer__embeds" aria-label="待发送图片">
|
<ul className="pm-composer__embeds" aria-label="待发送图片">
|
||||||
|
|||||||
@@ -109,7 +109,7 @@ export default function PostDetailPage() {
|
|||||||
const { limits } = useForumLimits();
|
const { limits } = useForumLimits();
|
||||||
const { setPostOutline, isMobile } = useOutletContext<LayoutCtx>();
|
const { setPostOutline, isMobile } = useOutletContext<LayoutCtx>();
|
||||||
|
|
||||||
const initialSnap = (postId && !Number.isNaN(postId))
|
const initialSnap = (postId && !Number.isNaN(postId) && navType === 'POP')
|
||||||
? getSessionSnapshot<PostDetailSnapshot>(postDetailCacheKey(postId))
|
? getSessionSnapshot<PostDetailSnapshot>(postDetailCacheKey(postId))
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
@@ -259,7 +259,7 @@ export default function PostDetailPage() {
|
|||||||
if (mode === 'force') {
|
if (mode === 'force') {
|
||||||
deleteSessionSnapshot(postDetailCacheKey(postId));
|
deleteSessionSnapshot(postDetailCacheKey(postId));
|
||||||
}
|
}
|
||||||
const cached = mode === 'force'
|
const cached = mode === 'force' || navType !== 'POP'
|
||||||
? undefined
|
? undefined
|
||||||
: getSessionSnapshot<PostDetailSnapshot>(postDetailCacheKey(postId));
|
: getSessionSnapshot<PostDetailSnapshot>(postDetailCacheKey(postId));
|
||||||
if (cached) {
|
if (cached) {
|
||||||
@@ -329,19 +329,9 @@ export default function PostDetailPage() {
|
|||||||
}, [postId]);
|
}, [postId]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// 下拉已预热则应用快照;否则强制重拉
|
// 下拉/软刷新:始终强制重拉,确保拿到最新数据
|
||||||
const onForce = () => {
|
const onForce = () => {
|
||||||
if (!postId || Number.isNaN(postId)) return;
|
if (!postId || Number.isNaN(postId)) return;
|
||||||
const warm = getSessionSnapshot<PostDetailSnapshot>(postDetailCacheKey(postId));
|
|
||||||
if (warm) {
|
|
||||||
loadSeq.current += 1;
|
|
||||||
applySnapshot(warm, { restoreScroll: false });
|
|
||||||
setLoading(false);
|
|
||||||
const el = pageRef.current;
|
|
||||||
if (el) el.scrollTop = 0;
|
|
||||||
scrollTopRef.current = 0;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
loadPostRef.current('force');
|
loadPostRef.current('force');
|
||||||
};
|
};
|
||||||
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
window.addEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||||
|
|||||||
@@ -5742,7 +5742,7 @@ a.post-title:visited {
|
|||||||
font-style: italic;
|
font-style: italic;
|
||||||
}
|
}
|
||||||
|
|
||||||
.post-detail-content img:not([src*="/stickers/"]) {
|
.post-detail-content img:not([src*="/stickers/"]):not(.article-sticker) {
|
||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
height: auto;
|
height: auto;
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
@@ -6849,6 +6849,17 @@ a.post-title:visited {
|
|||||||
z-index: 30;
|
z-index: 30;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.article-editor > .sticker-picker {
|
||||||
|
margin-top: 0;
|
||||||
|
flex-shrink: 0;
|
||||||
|
border-radius: 0;
|
||||||
|
border-left: none;
|
||||||
|
border-right: none;
|
||||||
|
border-top: none;
|
||||||
|
box-shadow: none;
|
||||||
|
z-index: 28;
|
||||||
|
}
|
||||||
|
|
||||||
.sticker-picker-tabs {
|
.sticker-picker-tabs {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
@@ -6875,30 +6886,86 @@ a.post-title:visited {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.sticker-picker-grid {
|
.sticker-picker-grid {
|
||||||
display: grid;
|
--sticker-size: 32px;
|
||||||
grid-template-columns: repeat(8, 1fr);
|
--sticker-gap: var(--sticker-size);
|
||||||
gap: 2px;
|
display: flex;
|
||||||
padding: 6px;
|
flex-wrap: wrap;
|
||||||
|
align-content: flex-start;
|
||||||
|
justify-content: flex-start;
|
||||||
|
column-gap: var(--sticker-gap);
|
||||||
|
row-gap: var(--sticker-gap);
|
||||||
|
padding: 8px;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
flex: 1;
|
flex: 1;
|
||||||
min-height: 0;
|
min-height: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.sticker-picker-grid:focus {
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
.sticker-picker-item {
|
.sticker-picker-item {
|
||||||
|
position: relative;
|
||||||
border: none;
|
border: none;
|
||||||
background: none;
|
background: none;
|
||||||
padding: 2px;
|
padding: 0;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
transition: background 0.1s, transform 0.1s;
|
transition: background 0.1s;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.sticker-picker-item--image {
|
||||||
|
flex: 0 0 var(--sticker-size);
|
||||||
|
width: var(--sticker-size);
|
||||||
|
height: var(--sticker-size);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sticker-picker-item--image img {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
display: block;
|
||||||
|
width: var(--sticker-size);
|
||||||
|
height: var(--sticker-size);
|
||||||
|
object-fit: contain;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sticker-picker-item--text {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
width: max-content;
|
||||||
|
max-width: 100%;
|
||||||
|
min-height: var(--sticker-size);
|
||||||
|
padding: 4px 8px;
|
||||||
|
}
|
||||||
|
|
||||||
.sticker-picker-item:hover {
|
.sticker-picker-item:hover {
|
||||||
background: var(--color-fill-2);
|
background: color-mix(in srgb, var(--color-text-1) 8%, var(--j13-bg-surface));
|
||||||
transform: scale(1.15);
|
}
|
||||||
|
|
||||||
|
/* 图片格与表情同大,浅灰底扩到空隙里才看得见 */
|
||||||
|
.sticker-picker-item--image::before {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
inset: -10px;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: transparent;
|
||||||
|
z-index: 0;
|
||||||
|
pointer-events: none;
|
||||||
|
transition: background 0.1s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sticker-picker-item--image:hover {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sticker-picker-item--image:hover::before {
|
||||||
|
background: color-mix(in srgb, var(--color-text-1) 8%, var(--j13-bg-surface));
|
||||||
|
}
|
||||||
|
|
||||||
|
.sticker-picker-item:focus {
|
||||||
|
outline: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.sticker-picker-item:focus-visible {
|
.sticker-picker-item:focus-visible {
|
||||||
@@ -6907,7 +6974,8 @@ a.post-title:visited {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.sticker-picker-loading {
|
.sticker-picker-loading {
|
||||||
grid-column: 1 / -1;
|
flex: 1 1 100%;
|
||||||
|
width: 100%;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
padding: 24px;
|
padding: 24px;
|
||||||
color: var(--color-text-4);
|
color: var(--color-text-4);
|
||||||
@@ -6939,9 +7007,10 @@ a.post-title:visited {
|
|||||||
padding: 0;
|
padding: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.comment-editor .article-tool-btn--owo {
|
.comment-editor .article-tool-btn--owo,
|
||||||
|
.article-tool-btn--owo {
|
||||||
width: auto;
|
width: auto;
|
||||||
min-width: 28px;
|
min-width: 32px;
|
||||||
padding: 0 8px;
|
padding: 0 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -6972,11 +7041,19 @@ a.post-title:visited {
|
|||||||
line-height: 1.6;
|
line-height: 1.6;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 评论正文中的贴纸 img */
|
/* 评论 / 帖子正文 / 发帖编辑器中的贴纸:行内小图,不占一段 */
|
||||||
.floor-body img[src*="/stickers/"],
|
.floor-body img[src*="/stickers/"],
|
||||||
.comment-body img[src*="/stickers/"] {
|
.comment-body img[src*="/stickers/"],
|
||||||
|
.post-detail-content img[src*="/stickers/"],
|
||||||
|
.post-detail-content img.article-sticker,
|
||||||
|
.site-page__body img[src*="/stickers/"],
|
||||||
|
.site-page__body img.article-sticker,
|
||||||
|
.article-prosemirror img[src*="/stickers/"],
|
||||||
|
.article-prosemirror img.article-sticker,
|
||||||
|
.article-editor-content img[src*="/stickers/"],
|
||||||
|
.article-editor-content img.article-sticker {
|
||||||
display: inline-block !important;
|
display: inline-block !important;
|
||||||
vertical-align: middle;
|
vertical-align: text-bottom;
|
||||||
width: 28px;
|
width: 28px;
|
||||||
height: 28px;
|
height: 28px;
|
||||||
max-width: 28px;
|
max-width: 28px;
|
||||||
@@ -6988,38 +7065,22 @@ a.post-title:visited {
|
|||||||
clear: none !important;
|
clear: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 编辑器内贴纸 img 尺寸约束 */
|
/* 选择器中颜文字:宽度随内容,不截断、不挤进固定格子 */
|
||||||
.comment-editor .article-prosemirror img[src*="/stickers/"],
|
|
||||||
.comment-editor .article-editor-content img[src*="/stickers/"] {
|
|
||||||
display: inline-block !important;
|
|
||||||
width: 28px;
|
|
||||||
height: 28px;
|
|
||||||
max-width: 28px;
|
|
||||||
vertical-align: middle;
|
|
||||||
margin: 0 1px !important;
|
|
||||||
border-radius: 4px;
|
|
||||||
box-shadow: none !important;
|
|
||||||
object-fit: contain;
|
|
||||||
clear: none !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 选择器中颜文字纯文本样式 */
|
|
||||||
.sticker-picker-text {
|
.sticker-picker-text {
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
max-width: 100%;
|
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
line-height: 1.4;
|
line-height: 1.4;
|
||||||
font-family: 'Segoe UI Emoji', 'Apple Color Emoji', 'Noto Sans Mono', monospace;
|
font-family: 'Segoe UI Emoji', 'Apple Color Emoji', 'Noto Sans Mono', monospace;
|
||||||
color: var(--color-text-1);
|
color: var(--color-text-1);
|
||||||
word-break: break-all;
|
white-space: nowrap;
|
||||||
|
word-break: normal;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
padding: 2px;
|
padding: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 移动端:贴纸选择器 4 列 */
|
/* 移动端:颜文字仍按内容宽度;图片间距仍等于一枚表情 */
|
||||||
@media (max-width: 640px) {
|
@media (max-width: 640px) {
|
||||||
.sticker-picker { max-height: 240px; }
|
.sticker-picker { max-height: 240px; }
|
||||||
.sticker-picker-grid { grid-template-columns: repeat(4, 1fr); }
|
|
||||||
.sticker-picker-tab { padding: 6px 10px; font-size: 12px; }
|
.sticker-picker-tab { padding: 6px 10px; font-size: 12px; }
|
||||||
.comment-editor .article-tool-btn { width: 30px; height: 30px; }
|
.comment-editor .article-tool-btn { width: 30px; height: 30px; }
|
||||||
.comment-editor .article-tool-btn--owo { width: auto; min-width: 30px; padding: 0 8px; }
|
.comment-editor .article-tool-btn--owo { width: auto; min-width: 30px; padding: 0 8px; }
|
||||||
@@ -7220,6 +7281,21 @@ a.waline-comment-author:hover {
|
|||||||
line-height: 1.65;
|
line-height: 1.65;
|
||||||
word-break: break-word;
|
word-break: break-word;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 评论沿用文章列表 / 段落间距:Enter 分段,Shift+Enter 为段内换行 */
|
||||||
|
.floor-body.post-detail-content {
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.65;
|
||||||
|
letter-spacing: normal;
|
||||||
|
}
|
||||||
|
|
||||||
|
.floor-body.post-detail-content > p:first-child,
|
||||||
|
.comment-editor .post-detail-content > p:first-child {
|
||||||
|
font-size: inherit;
|
||||||
|
line-height: inherit;
|
||||||
|
letter-spacing: inherit;
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
.waline-comment-bubble .quote-block {
|
.waline-comment-bubble .quote-block {
|
||||||
margin: 6px 0;
|
margin: 6px 0;
|
||||||
background: var(--j13-bg-block);
|
background: var(--j13-bg-block);
|
||||||
@@ -10401,7 +10477,7 @@ button.profile-stat:hover strong {
|
|||||||
text-underline-offset: 2px;
|
text-underline-offset: 2px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.article-prosemirror img {
|
.article-prosemirror img:not([src*="/stickers/"]):not(.article-sticker) {
|
||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
height: auto;
|
height: auto;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
@@ -13547,7 +13623,8 @@ a.pm-thread-head__name:hover {
|
|||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
min-height: 72px;
|
min-height: 72px;
|
||||||
max-height: 160px;
|
max-height: 160px;
|
||||||
resize: vertical;
|
overflow-y: auto;
|
||||||
|
cursor: text;
|
||||||
border: 1px solid var(--j13-border-light);
|
border: 1px solid var(--j13-border-light);
|
||||||
border-radius: 10px;
|
border-radius: 10px;
|
||||||
padding: 10px 14px;
|
padding: 10px 14px;
|
||||||
@@ -13557,6 +13634,8 @@ a.pm-thread-head__name:hover {
|
|||||||
color: var(--color-text-1);
|
color: var(--color-text-1);
|
||||||
background: var(--j13-bg-workspace);
|
background: var(--j13-bg-workspace);
|
||||||
outline: none;
|
outline: none;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-word;
|
||||||
transition: border-color 0.12s, box-shadow 0.12s;
|
transition: border-color 0.12s, box-shadow 0.12s;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -13565,6 +13644,35 @@ a.pm-thread-head__name:hover {
|
|||||||
box-shadow: 0 0 0 2px color-mix(in srgb, var(--j13-green) 8%, transparent);
|
box-shadow: 0 0 0 2px color-mix(in srgb, var(--j13-green) 8%, transparent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.pm-composer__input[data-empty="true"]::before {
|
||||||
|
content: attr(data-placeholder);
|
||||||
|
color: var(--color-text-4);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pm-composer__sticker,
|
||||||
|
.pm-bubble__sticker {
|
||||||
|
display: inline-block;
|
||||||
|
vertical-align: middle;
|
||||||
|
width: 28px;
|
||||||
|
height: 28px;
|
||||||
|
max-width: 28px;
|
||||||
|
margin: 0 1px;
|
||||||
|
border-radius: 4px;
|
||||||
|
object-fit: contain;
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pm-composer__inline-img {
|
||||||
|
display: inline-block;
|
||||||
|
vertical-align: middle;
|
||||||
|
max-width: 96px;
|
||||||
|
max-height: 64px;
|
||||||
|
margin: 0 2px;
|
||||||
|
border-radius: 6px;
|
||||||
|
object-fit: contain;
|
||||||
|
}
|
||||||
|
|
||||||
.pm-composer__embeds {
|
.pm-composer__embeds {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import DOMPurify from 'dompurify';
|
import DOMPurify from 'dompurify';
|
||||||
import { POST_CONTENT_PURIFY_CONFIG } from './postContent';
|
import { POST_CONTENT_PURIFY_CONFIG } from './postContent';
|
||||||
|
import { enhanceCodeBlocks } from './enhanceCodeBlocks';
|
||||||
|
|
||||||
/** 转义 HTML 并保留换行 */
|
/** 转义 HTML 并保留换行 */
|
||||||
function escapeWithBreaks(text: string): string {
|
function escapeWithBreaks(text: string): string {
|
||||||
@@ -60,11 +61,15 @@ function processMentionsInHtml(html: string): string {
|
|||||||
return div.innerHTML;
|
return div.innerHTML;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 渲染评论内容:HTML 净化 + @提及高亮,兼容旧版纯文本 */
|
/** 渲染评论内容:HTML 净化 + @提及高亮 + 代码块阅读态,兼容旧版纯文本 */
|
||||||
export function renderCommentContent(content: string): string {
|
export function renderCommentContent(content: string): string {
|
||||||
if (isHtmlContent(content)) {
|
if (isHtmlContent(content)) {
|
||||||
const sanitized = DOMPurify.sanitize(content, POST_CONTENT_PURIFY_CONFIG) as string;
|
const sanitized = DOMPurify.sanitize(content, POST_CONTENT_PURIFY_CONFIG) as string;
|
||||||
return processMentionsInHtml(sanitized);
|
const withMentions = processMentionsInHtml(sanitized);
|
||||||
|
const doc = new DOMParser().parseFromString(`<div id="j13-comment-root">${withMentions}</div>`, 'text/html');
|
||||||
|
const root = doc.getElementById('j13-comment-root') ?? doc.body;
|
||||||
|
enhanceCodeBlocks(root);
|
||||||
|
return root.innerHTML;
|
||||||
}
|
}
|
||||||
return highlightMentions(content);
|
return highlightMentions(content);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -177,3 +177,44 @@ export function enhanceCodeBlocks(root: ParentNode): void {
|
|||||||
if (display.lineNumbers) pre.classList.add('md-codeblock__pre--lines');
|
if (display.lineNumbers) pre.classList.add('md-codeblock__pre--lines');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const CODE_FOLD_SHORT_LINES = 5;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 阅读态代码块:折叠 / 复制。由帖子与评论共用,点击已处理时返回 true。
|
||||||
|
*/
|
||||||
|
export async function handleMdCodeBlockUiClick(target: EventTarget | null): Promise<boolean> {
|
||||||
|
if (!(target instanceof Element)) return false;
|
||||||
|
|
||||||
|
const foldBtn = target.closest<HTMLElement>('[data-code-fold]');
|
||||||
|
if (foldBtn) {
|
||||||
|
const block = foldBtn.closest('.md-codeblock');
|
||||||
|
if (!block) return true;
|
||||||
|
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 <= CODE_FOLD_SHORT_LINES) block.classList.add('md-codeblock--short');
|
||||||
|
else block.classList.remove('md-codeblock--short');
|
||||||
|
foldBtn.textContent = collapsed ? '展开' : '收起';
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const copyBtn = target.closest<HTMLElement>('[data-code-copy]');
|
||||||
|
if (!copyBtn) return false;
|
||||||
|
|
||||||
|
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 ?? '');
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
const prev = copyBtn.textContent;
|
||||||
|
copyBtn.textContent = '已复制';
|
||||||
|
copyBtn.classList.add('is-copied');
|
||||||
|
window.setTimeout(() => {
|
||||||
|
copyBtn.textContent = prev || '复制';
|
||||||
|
copyBtn.classList.remove('is-copied');
|
||||||
|
}, 1600);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user