Compare commits
14 Commits
v1.1.5
...
76be8926f2
| Author | SHA1 | Date | |
|---|---|---|---|
| 76be8926f2 | |||
| 4d93e455f9 | |||
| c958dcfd80 | |||
| 84bfbd9a3e | |||
| 500e452c2f | |||
| 1c0f7ede55 | |||
| 2e9c42a34c | |||
| dff60dde6a | |||
| ea9e0058d4 | |||
| d5aa36416c | |||
| 2159280af5 | |||
| bc9a031890 | |||
| 0d81787125 | |||
| 68713c053b |
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.5
|
VERSION := 1.1.7
|
||||||
LDFLAGS := -s -w -X main.version=$(VERSION)
|
LDFLAGS := -s -w -X main.version=$(VERSION)
|
||||||
REGISTRY_IMAGE := hangzhang714128/jiang13-forum
|
REGISTRY_IMAGE := hangzhang714128/jiang13-forum
|
||||||
|
|
||||||
|
|||||||
36
README.md
36
README.md
@@ -20,6 +20,7 @@
|
|||||||
[快速开始](#-快速开始) ·
|
[快速开始](#-快速开始) ·
|
||||||
[界面预览](#-界面预览) ·
|
[界面预览](#-界面预览) ·
|
||||||
[功能亮点](#-功能亮点) ·
|
[功能亮点](#-功能亮点) ·
|
||||||
|
[更新日志](docs/site-posts/changelog.md) ·
|
||||||
[路线图](ROADMAP.md) ·
|
[路线图](ROADMAP.md) ·
|
||||||
[参与贡献](CONTRIBUTING.md)
|
[参与贡献](CONTRIBUTING.md)
|
||||||
|
|
||||||
@@ -172,6 +173,11 @@ make compose-up
|
|||||||
|
|
||||||
浏览器打开 `http://localhost:3000/register` 注册;**首个用户自动成为管理员**。
|
浏览器打开 `http://localhost:3000/register` 注册;**首个用户自动成为管理员**。
|
||||||
|
|
||||||
|
版本变更与升级说明见 **[更新日志](docs/site-posts/changelog.md)**。Docker 与 Windows / Linux 单文件共用同一版本号。
|
||||||
|
|
||||||
|
- Docker 标签:[hub.docker.com/r/hangzhang714128/jiang13-forum/tags](https://hub.docker.com/r/hangzhang714128/jiang13-forum/tags)
|
||||||
|
- 预编译包:[Gitea Releases](https://git.iioio.com/freefire/jiang13-forum/releases)
|
||||||
|
|
||||||
**拉取已构建镜像(Docker Hub):**
|
**拉取已构建镜像(Docker Hub):**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -206,15 +212,15 @@ docker run -d --name jiang13 \
|
|||||||
docker login
|
docker login
|
||||||
.\build.bat -Target docker # Windows
|
.\build.bat -Target docker # Windows
|
||||||
# make docker # Linux/macOS
|
# make docker # Linux/macOS
|
||||||
docker push hangzhang714128/jiang13-forum:1.1.5
|
docker push hangzhang714128/jiang13-forum:1.1.7
|
||||||
docker push hangzhang714128/jiang13-forum:latest
|
docker push hangzhang714128/jiang13-forum:latest
|
||||||
```
|
```
|
||||||
|
|
||||||
或直接构建:
|
或直接构建:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker build --build-arg VERSION=1.1.5 -t hangzhang714128/jiang13-forum:1.1.5 -t hangzhang714128/jiang13-forum:latest .
|
docker build --build-arg VERSION=1.1.7 -t hangzhang714128/jiang13-forum:1.1.7 -t hangzhang714128/jiang13-forum:latest .
|
||||||
docker push hangzhang714128/jiang13-forum:1.1.5
|
docker push hangzhang714128/jiang13-forum:1.1.7
|
||||||
docker push hangzhang714128/jiang13-forum:latest
|
docker push hangzhang714128/jiang13-forum:latest
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -239,7 +245,29 @@ docker push hangzhang714128/jiang13-forum:latest
|
|||||||
|
|
||||||
### 3. 直接启动(二进制)
|
### 3. 直接启动(二进制)
|
||||||
|
|
||||||
把二进制放到目标目录后直接运行(首次会在同目录生成 `app.ini`):
|
不想自己编译时,从 [Gitea Releases](https://git.iioio.com/freefire/jiang13-forum/releases) 下载与 Docker 同版本号的文件即可:
|
||||||
|
|
||||||
|
| 文件 | 平台 |
|
||||||
|
|------|------|
|
||||||
|
| `jiang13-*-windows-amd64.exe` | Windows x64 |
|
||||||
|
| `jiang13-*-linux-amd64` | Linux x64 |
|
||||||
|
|
||||||
|
当前 **1.1.7:** [Windows](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/jiang13-1.1.7-windows-amd64.exe) · [Linux](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/jiang13-1.1.7-linux-amd64)
|
||||||
|
|
||||||
|
把文件放到目标目录后直接运行(首次会在同目录生成 `app.ini`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Windows
|
||||||
|
.\jiang13-1.1.7-windows-amd64.exe
|
||||||
|
# 或改名为 jiang13.exe 后:
|
||||||
|
.\jiang13.exe
|
||||||
|
|
||||||
|
# Linux
|
||||||
|
chmod +x jiang13-1.1.7-linux-amd64
|
||||||
|
./jiang13-1.1.7-linux-amd64
|
||||||
|
```
|
||||||
|
|
||||||
|
本地刚编译的产物在 `dist/`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Windows
|
# Windows
|
||||||
|
|||||||
@@ -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.5'
|
$Version = '1.1.7'
|
||||||
$RegistryImage = 'hangzhang714128/jiang13-forum'
|
$RegistryImage = 'hangzhang714128/jiang13-forum'
|
||||||
$Ldlags = "-s -w -X main.version=$Version"
|
$Ldlags = "-s -w -X main.version=$Version"
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"github.com/kardianos/service"
|
"github.com/kardianos/service"
|
||||||
|
|
||||||
"git.iioio.com/freefire/jiang13-forum/config"
|
"git.iioio.com/freefire/jiang13-forum/config"
|
||||||
|
forumsvc "git.iioio.com/freefire/jiang13-forum/service"
|
||||||
"git.iioio.com/freefire/jiang13-forum/model"
|
"git.iioio.com/freefire/jiang13-forum/model"
|
||||||
"git.iioio.com/freefire/jiang13-forum/router"
|
"git.iioio.com/freefire/jiang13-forum/router"
|
||||||
)
|
)
|
||||||
@@ -78,6 +79,9 @@ func (p *program) setup() error {
|
|||||||
if err := model.InitDB(cfg.DBPath()); err != nil {
|
if err := model.InitDB(cfg.DBPath()); err != nil {
|
||||||
return fmt.Errorf("数据库初始化失败: %w", err)
|
return fmt.Errorf("数据库初始化失败: %w", err)
|
||||||
}
|
}
|
||||||
|
if err := forumsvc.BackfillModerationNotifyRefs(); err != nil {
|
||||||
|
log.Printf("待审通知关联字段回填警告: %v", err)
|
||||||
|
}
|
||||||
if err := model.InitMonitorDB(cfg.MonitorDBPath()); err != nil {
|
if err := model.InitMonitorDB(cfg.MonitorDBPath()); err != nil {
|
||||||
return fmt.Errorf("监控库初始化失败: %w", err)
|
return fmt.Errorf("监控库初始化失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,16 @@
|
|||||||
|
|
||||||
把原先分篇的「上手 / 功能 / 部署」三帖 **删除**,避免与长文重复。
|
把原先分篇的「上手 / 功能 / 部署」三帖 **删除**,避免与长文重复。
|
||||||
|
|
||||||
|
## 自定义单页(推荐)
|
||||||
|
|
||||||
|
站务帖之外,建议在后台 **单页管理** 发一篇更新日志,方便 Docker / Windows 用户对照版本:
|
||||||
|
|
||||||
|
| 文件 | 标题 | slug | 操作 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| [changelog.md](./changelog.md) | 更新日志 | `changelog` | 发布;页脚展示(可选侧栏导航) |
|
||||||
|
|
||||||
|
访问路径:`/page/changelog`。
|
||||||
|
|
||||||
## 可选短文
|
## 可选短文
|
||||||
|
|
||||||
若站务区希望不止一篇,见 [optional.md](./optional.md):
|
若站务区希望不止一篇,见 [optional.md](./optional.md):
|
||||||
|
|||||||
160
docs/site-posts/changelog.md
Normal file
160
docs/site-posts/changelog.md
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
# 更新日志
|
||||||
|
|
||||||
|
> 建议标题:更新日志
|
||||||
|
> 建议 slug:`changelog`
|
||||||
|
> 建议路径:`/page/changelog`
|
||||||
|
> 建议操作:后台「单页管理」新建并发布;勾选「页脚展示」(可选「侧栏导航」)
|
||||||
|
> 复制正文时:从下方第一个 `---` **之后**开始粘贴(Markdown 模式)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Docker 镜像、Windows exe、Linux 单文件 **共用同一版本号**。有新版本时,以本页为准。
|
||||||
|
|
||||||
|
**当前版本:1.1.7**(2026-09-02)
|
||||||
|
|
||||||
|
## 去哪看新版本
|
||||||
|
|
||||||
|
| 渠道 | 看什么 | 地址 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 本页 | 版本号、变更说明、升级注意 | 本站 `/page/changelog` |
|
||||||
|
| Docker | 镜像标签(`latest` 与 `1.1.x`) | [Docker Hub · Tags](https://hub.docker.com/r/hangzhang714128/jiang13-forum/tags) |
|
||||||
|
| Windows / Linux | 预编译单文件(与 Docker 同版本) | [Gitea Releases](https://git.iioio.com/freefire/jiang13-forum/releases) |
|
||||||
|
| 源码 | 提交记录与自行编译 | [Gitea 仓库](https://git.iioio.com/freefire/jiang13-forum) |
|
||||||
|
|
||||||
|
**1.1.7 直接下载:**
|
||||||
|
|
||||||
|
- Windows x64:[jiang13-1.1.7-windows-amd64.exe](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/jiang13-1.1.7-windows-amd64.exe)
|
||||||
|
- Linux x64:[jiang13-1.1.7-linux-amd64](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/jiang13-1.1.7-linux-amd64)
|
||||||
|
- 校验文件:[SHA256SUMS.txt](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.7/SHA256SUMS.txt)
|
||||||
|
|
||||||
|
拉取指定版本镜像:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker pull hangzhang714128/jiang13-forum:1.1.7
|
||||||
|
# 或始终跟随最新
|
||||||
|
docker pull hangzhang714128/jiang13-forum:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
Windows:停掉正在跑的进程或服务,用新下载的 exe 覆盖原文件(可改名为 `jiang13.exe`),**不要动**旁边的 `data/` 与 `app.ini`,再启动即可。
|
||||||
|
|
||||||
|
Linux:赋予执行权限后放到原目录覆盖,同样保留 `data/` 与 `app.ini`。
|
||||||
|
|
||||||
|
## 升级注意
|
||||||
|
|
||||||
|
- 一般只需换镜像或换 exe,数据目录向后兼容。
|
||||||
|
- Docker 请继续挂载原来的 `/data` 卷,切勿新建空目录当「升级」。
|
||||||
|
- 升级后若页面样式异常,强制刷新浏览器(Ctrl+F5)。程序也会在前端资源失效时自动硬刷新。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1.1.7 — 2026-09-02
|
||||||
|
|
||||||
|
私信与开源展柜体验升级,待审通知的审核态更及时。
|
||||||
|
|
||||||
|
**新增 / 调整**
|
||||||
|
|
||||||
|
- 私信改为飞书风布局:缩略图表情/图片、按会话草稿、用户搜索发起会话
|
||||||
|
- 主页「发私信」直达消息页对应会话
|
||||||
|
- 开源展柜改为目录式 UI,空列表不再粘滞
|
||||||
|
- 消息页体验重构;待审通知打开后实时回填审核态
|
||||||
|
|
||||||
|
**修复**
|
||||||
|
|
||||||
|
- 帖子详情右栏默认头像改为深绿底白字,与列表默认头像配色一致
|
||||||
|
|
||||||
|
## 1.1.6 — 2026-09-01
|
||||||
|
|
||||||
|
编辑器插入体验与首页默认 Feed 排序更合理。
|
||||||
|
|
||||||
|
**新增 / 调整**
|
||||||
|
|
||||||
|
- 链接对话框支持网址、链接文字与站内帖子/单页搜索;站内搜索收进「高级选项」,点选同步链接文字
|
||||||
|
- 文章与评论共用统一图片插入选择器(上传 / 链接 / 已上传)
|
||||||
|
- 链接是否新标签打开交由全站设置,对话框不再单独开关
|
||||||
|
- 首页默认「最新」按发帖与最后评论的较晚时间混排,零回复新帖不再沉底
|
||||||
|
- 单页详情右侧栏与帖子共用目录布局;三栏主滚动区统一细绿色滚动条
|
||||||
|
|
||||||
|
**修复**
|
||||||
|
|
||||||
|
- 帖子目录从正文同步派生,避免预取缓存竞态导致空树
|
||||||
|
|
||||||
|
## 1.1.5 — 2026-09-01
|
||||||
|
|
||||||
|
首页首屏与交互更稳,Feed 排序语义更清楚。
|
||||||
|
本版起同时提供 **Docker 镜像** 与 **Windows / Linux 预编译单文件**(Gitea Release `v1.1.5`)。
|
||||||
|
|
||||||
|
**新增 / 调整**
|
||||||
|
|
||||||
|
- 首页改为 Go SSR 与 React hydrate(注水)同构,打开首页不再先闪一层空壳再跳内容
|
||||||
|
- Feed 排序改为:**新评论 / 新帖子 / 推荐帖**;推荐帖只出精华(featured)
|
||||||
|
- 点击排序会强制刷新列表;软刷新时同步站点限额与品牌文案
|
||||||
|
- 返回列表用缓存恢复滚动位置,不再重复请求
|
||||||
|
|
||||||
|
**修复**
|
||||||
|
|
||||||
|
- 发版后软刷新会检测入口壳;chunk(代码分片)404 时自动硬刷新,避免卡在旧页面
|
||||||
|
- 软刷新齐套前保留旧画面,避免一点击就把内容卸光
|
||||||
|
- 补齐 `/favicon.ico` 与页面 head 图标;拆除爬虫专用 HTML
|
||||||
|
- 桌面端隐藏多余的导航汉堡按钮
|
||||||
|
- 帖行评论数、列表「共 N 条」右对齐;排序栏数字紧跟标签
|
||||||
|
- 手机端 SSR 顶栏 / 页脚与 React 一致,减少闪动
|
||||||
|
|
||||||
|
## 1.1.4 — 2026-08-31
|
||||||
|
|
||||||
|
网站监控的地理信息与口径更准确。
|
||||||
|
|
||||||
|
- 补全 IP2Location(IP 地理位置库)中国城市中文名,同名城市按省消歧
|
||||||
|
- 对齐监控概览「双通道」口径文案与诊断抽样说明
|
||||||
|
|
||||||
|
## 1.1.3 — 2026-08-31
|
||||||
|
|
||||||
|
管理后台可看站点访问情况。
|
||||||
|
|
||||||
|
- 新增管理端 **网站监控**:浏览量写入独立 `monitor.db`,与主库分开
|
||||||
|
|
||||||
|
## 1.1.2 — 2026-08-31
|
||||||
|
|
||||||
|
可选接入官方社区展柜。
|
||||||
|
|
||||||
|
- 可选社区上报,以及官方精选展柜(自建站可出现在官方社区列表中)
|
||||||
|
|
||||||
|
## 1.1.1 — 2026-08-31
|
||||||
|
|
||||||
|
- 评论管理操作收进「更多」菜单,管理员界面更干净
|
||||||
|
|
||||||
|
## 1.1.0 — 2026-08-30
|
||||||
|
|
||||||
|
一批社区功能与界面整理,版本号从 1.0 跨到 1.1。
|
||||||
|
|
||||||
|
**新增**
|
||||||
|
|
||||||
|
- 友链申请、独立友链页;页脚左右区域可分别开关
|
||||||
|
- 自定义单页(后台「单页管理」,如本页)
|
||||||
|
- 投票帖、悬赏帖、抽奖帖
|
||||||
|
- 侧栏签到;右侧栏「最新注册」
|
||||||
|
- 搜索重设计:筛选面板、结果页 chips(筛选标签)
|
||||||
|
- 帖子管理收进右上角菜单;手机端评论输入默认折叠
|
||||||
|
|
||||||
|
**优化**
|
||||||
|
|
||||||
|
- 首页帖子列表密度与标题样式
|
||||||
|
- 开源码桶展示加强,去掉 Feed 顶栏统计
|
||||||
|
- 单页编辑、列表留白与友链申请体验
|
||||||
|
- 开发与发行版共用 `dist/data` 数据目录,避免两套数据打架
|
||||||
|
|
||||||
|
**修复**
|
||||||
|
|
||||||
|
- 手机端搜索入口与底部 Sheet(抽屉面板)
|
||||||
|
- 占位头像对比度;无头像用户不再误用游客灰底
|
||||||
|
- 页面双指缩放锁死,正文原图与灯箱仍可 pinch(捏合)放大
|
||||||
|
- 单页正文排版与帖子详情对齐
|
||||||
|
|
||||||
|
## 1.0.0 — 2026-08-23
|
||||||
|
|
||||||
|
首次发布 Docker 镜像 `hangzhang714128/jiang13-forum:1.0.0`。
|
||||||
|
|
||||||
|
当时已包含论坛核心能力:板块与发帖、楼层评论、点赞收藏、私信、TipTap 富文本、贴纸、修订历史、管理后台、OIDC(开放身份连接)/ SSO(单点登录)、邮件验证码、Gitea 仓库同步、SQLite 单二进制部署,以及 Docker 一键运行。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
之后发版时:Docker 推 `x.y.z` + `latest`,Gitea 打 tag `vx.y.z` 并挂上对应 exe / linux 文件,再把新版本写到本页最上方。
|
||||||
@@ -419,6 +419,14 @@ export const api = {
|
|||||||
fd.append('image', file);
|
fd.append('image', file);
|
||||||
return request<{ url: string }>('/api/uploads/image', { method: 'POST', body: fd, headers: {} });
|
return request<{ url: string }>('/api/uploads/image', { method: 'POST', body: fd, headers: {} });
|
||||||
},
|
},
|
||||||
|
/** 当前用户历史上传的帖子图片 */
|
||||||
|
myPostImages: (params?: { page?: number; size?: number }) => {
|
||||||
|
const q = new URLSearchParams();
|
||||||
|
if (params?.page) q.set('page', String(params.page));
|
||||||
|
if (params?.size) q.set('size', String(params.size));
|
||||||
|
const qs = q.toString();
|
||||||
|
return request<MediaListResult>(`/api/uploads/images${qs ? `?${qs}` : ''}`);
|
||||||
|
},
|
||||||
createPost: (data: {
|
createPost: (data: {
|
||||||
board_id: string; title: string; content: string; tags?: string; post_type?: string;
|
board_id: string; title: string; content: string; tags?: string; post_type?: string;
|
||||||
poll_options?: string; bounty_points?: number; lottery_winner_count?: number;
|
poll_options?: string; bounty_points?: number; lottery_winner_count?: number;
|
||||||
@@ -656,6 +664,8 @@ export const api = {
|
|||||||
},
|
},
|
||||||
markNotificationsRead: () =>
|
markNotificationsRead: () =>
|
||||||
request<{ message: string }>('/api/messages/notifications/read', { method: 'POST' }),
|
request<{ message: string }>('/api/messages/notifications/read', { method: 'POST' }),
|
||||||
|
markMessageRead: (id: number) =>
|
||||||
|
request<{ message: string }>(`/api/messages/${id}/read`, { method: 'POST' }),
|
||||||
sendMessage: (body: { to_user_id: number; subject?: string; content: string }) =>
|
sendMessage: (body: { to_user_id: number; subject?: string; content: string }) =>
|
||||||
request<{ message: PrivateMessage }>('/api/messages', {
|
request<{ message: PrivateMessage }>('/api/messages', {
|
||||||
method: 'POST', body: JSON.stringify(body),
|
method: 'POST', body: JSON.stringify(body),
|
||||||
|
|||||||
@@ -224,7 +224,7 @@ export interface FeedSortTab {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const DEFAULT_FEED_SORT_TABS: FeedSortTab[] = [
|
export const DEFAULT_FEED_SORT_TABS: FeedSortTab[] = [
|
||||||
{ id: 'reply', label: '新评论', enabled: true },
|
{ id: 'reply', label: '最新', enabled: true },
|
||||||
{ id: 'latest', label: '新帖子', enabled: true },
|
{ id: 'latest', label: '新帖子', enabled: true },
|
||||||
{ id: 'hot', label: '推荐帖', enabled: true },
|
{ id: 'hot', label: '推荐帖', enabled: true },
|
||||||
];
|
];
|
||||||
@@ -717,9 +717,13 @@ export interface PrivateMessage {
|
|||||||
to_user_id: number;
|
to_user_id: number;
|
||||||
subject: string;
|
subject: string;
|
||||||
content: string;
|
content: string;
|
||||||
kind: 'user' | 'system' | 'reject' | 'report_result' | string;
|
kind: 'user' | 'system' | 'reject' | 'report_result' | 'reply' | 'mention' | 'moderation' | string;
|
||||||
related_post_id?: number;
|
related_post_id?: number;
|
||||||
related_report_id?: number;
|
related_report_id?: number;
|
||||||
|
related_comment_id?: number;
|
||||||
|
related_floor?: number;
|
||||||
|
/** 待审目标实时状态:pending|published|rejected|deleted */
|
||||||
|
related_status?: string;
|
||||||
is_read: boolean;
|
is_read: boolean;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
from_user?: User;
|
from_user?: User;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
useRef, useEffect, useImperativeHandle, forwardRef, useCallback, useState, useMemo, type ReactNode,
|
useRef, useEffect, useImperativeHandle, forwardRef, useCallback, useState, useMemo,
|
||||||
|
type ReactNode, type Ref,
|
||||||
} from 'react';
|
} from 'react';
|
||||||
import { useEditor, EditorContent, type Editor } from '@tiptap/react';
|
import { useEditor, EditorContent, type Editor } from '@tiptap/react';
|
||||||
import { TextSelection, NodeSelection } from '@tiptap/pm/state';
|
import { TextSelection, NodeSelection } from '@tiptap/pm/state';
|
||||||
@@ -31,16 +32,19 @@ import {
|
|||||||
insertMarkdownLink,
|
insertMarkdownLink,
|
||||||
} from '../utils/markdownFormat';
|
} from '../utils/markdownFormat';
|
||||||
import { countWords } from '../utils/text';
|
import { countWords } from '../utils/text';
|
||||||
import { api } from '../api/client';
|
|
||||||
import { notify } from '@/lib/notify';
|
import { notify } from '@/lib/notify';
|
||||||
import { MembersOnly } from './editor/MembersOnlyExtension';
|
import { MembersOnly } from './editor/MembersOnlyExtension';
|
||||||
import { ReplyOnly } from './editor/ReplyOnlyExtension';
|
import { ReplyOnly } from './editor/ReplyOnlyExtension';
|
||||||
import { PointsOnly } from './editor/PointsOnlyExtension';
|
import { PointsOnly } from './editor/PointsOnlyExtension';
|
||||||
import { TabIndent } from './editor/TabIndentExtension';
|
import { TabIndent } from './editor/TabIndentExtension';
|
||||||
import { ArticleImage, type ImageDisplay } from './editor/ArticleImageExtension';
|
import { ArticleImage, type ImageDisplay } from './editor/ArticleImageExtension';
|
||||||
|
import { ArticleSticker } from './editor/ArticleStickerExtension';
|
||||||
import { ImageGroup, suggestImageGroupLayout } from './editor/ImageGroupExtension';
|
import { ImageGroup, suggestImageGroupLayout } from './editor/ImageGroupExtension';
|
||||||
|
import StickerPicker from './emoji/StickerPicker';
|
||||||
|
import type { Sticker } from '../data/stickers';
|
||||||
import { ClearFloatParagraph, ClearFloatSync } from './editor/ClearFloatParagraph';
|
import { ClearFloatParagraph, ClearFloatSync } from './editor/ClearFloatParagraph';
|
||||||
import { ArticleLinkDialog } from './editor/ArticleLinkDialog';
|
import { ArticleLinkDialog, type ArticleLinkConfirm } from './editor/ArticleLinkDialog';
|
||||||
|
import { ArticleImagePickerDialog } from './editor/ArticleImagePickerDialog';
|
||||||
import { ArticleCodeBlockDialog } from './editor/ArticleCodeBlockDialog';
|
import { ArticleCodeBlockDialog } from './editor/ArticleCodeBlockDialog';
|
||||||
import { ArticleCodeBlock } from './editor/ArticleCodeBlockExtension';
|
import { ArticleCodeBlock } from './editor/ArticleCodeBlockExtension';
|
||||||
import {
|
import {
|
||||||
@@ -73,6 +77,7 @@ interface Props {
|
|||||||
|
|
||||||
type EditorMode = 'rich' | 'markdown';
|
type EditorMode = 'rich' | 'markdown';
|
||||||
type LinkTarget = 'rich' | 'markdown';
|
type LinkTarget = 'rich' | 'markdown';
|
||||||
|
type ImagePickerTarget = 'rich' | 'markdown';
|
||||||
type CodeBlockTarget = 'rich' | 'markdown';
|
type CodeBlockTarget = 'rich' | 'markdown';
|
||||||
type TableTarget = 'rich' | 'markdown';
|
type TableTarget = 'rich' | 'markdown';
|
||||||
|
|
||||||
@@ -83,6 +88,7 @@ interface ToolBtn {
|
|||||||
align?: 'start' | 'center' | 'end';
|
align?: 'start' | 'center' | 'end';
|
||||||
active?: boolean;
|
active?: boolean;
|
||||||
className?: string;
|
className?: string;
|
||||||
|
buttonRef?: Ref<HTMLButtonElement>;
|
||||||
action: () => void;
|
action: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,9 +124,17 @@ function sanitizeHtml(html: string): string {
|
|||||||
return DOMPurify.sanitize(html, POST_CONTENT_PURIFY_CONFIG);
|
return DOMPurify.sanitize(html, POST_CONTENT_PURIFY_CONFIG);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 判断编辑器内容是否为空 */
|
/** 判断编辑器内容是否为空(纯贴纸/图片也算有内容) */
|
||||||
function isEditorEmpty(editor: Editor): boolean {
|
function isEditorEmpty(editor: Editor): boolean {
|
||||||
return editor.state.doc.textContent.trim().length === 0;
|
if (editor.state.doc.textContent.trim().length > 0) return false;
|
||||||
|
let hasMedia = false;
|
||||||
|
editor.state.doc.descendants((node) => {
|
||||||
|
if (node.type.name === 'image' || node.type.name === 'sticker' || node.type.name === 'imageGroup') {
|
||||||
|
hasMedia = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return !hasMedia;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -167,34 +181,6 @@ function cycleHeading(editor: Editor) {
|
|||||||
editor.chain().focus().toggleHeading({ level: 2 }).run();
|
editor.chain().focus().toggleHeading({ level: 2 }).run();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 触发图片文件选择并上传(支持多选) */
|
|
||||||
async function uploadPostImageFiles(multiple = true): Promise<string[]> {
|
|
||||||
return new Promise(resolve => {
|
|
||||||
const input = document.createElement('input');
|
|
||||||
input.type = 'file';
|
|
||||||
input.accept = 'image/jpeg,image/png,image/gif,image/webp';
|
|
||||||
input.multiple = multiple;
|
|
||||||
input.onchange = async () => {
|
|
||||||
const files = [...(input.files ?? [])];
|
|
||||||
if (!files.length) {
|
|
||||||
resolve([]);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const urls: string[] = [];
|
|
||||||
for (const file of files) {
|
|
||||||
try {
|
|
||||||
const { url } = await api.uploadPostImage(file);
|
|
||||||
urls.push(url);
|
|
||||||
} catch (e: unknown) {
|
|
||||||
notify.error(e instanceof Error ? e.message : '图片上传失败');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
resolve(urls);
|
|
||||||
};
|
|
||||||
input.click();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 渲染工具栏按钮列表 */
|
/** 渲染工具栏按钮列表 */
|
||||||
function renderToolButtons(tools: ToolBtn[]) {
|
function renderToolButtons(tools: ToolBtn[]) {
|
||||||
return tools.map((t, i) => (
|
return tools.map((t, i) => (
|
||||||
@@ -204,10 +190,12 @@ function renderToolButtons(tools: ToolBtn[]) {
|
|||||||
) : null}
|
) : null}
|
||||||
<Tooltip content={t.title} hint={t.hint} align={t.align} side="bottom">
|
<Tooltip content={t.title} hint={t.hint} align={t.align} side="bottom">
|
||||||
<button
|
<button
|
||||||
|
ref={t.buttonRef}
|
||||||
type="button"
|
type="button"
|
||||||
className={`article-tool-btn${t.active ? ' active' : ''}${t.className ? ` ${t.className}` : ''}`}
|
className={`article-tool-btn${t.active ? ' active' : ''}${t.className ? ` ${t.className}` : ''}`}
|
||||||
onMouseDown={e => e.preventDefault()}
|
onMouseDown={e => e.preventDefault()}
|
||||||
onClick={t.action}
|
onClick={t.action}
|
||||||
|
aria-pressed={t.active || undefined}
|
||||||
>
|
>
|
||||||
{t.icon}
|
{t.icon}
|
||||||
</button>
|
</button>
|
||||||
@@ -228,7 +216,11 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
const [markdownSource, setMarkdownSource] = useState('');
|
const [markdownSource, setMarkdownSource] = useState('');
|
||||||
const [linkDialogOpen, setLinkDialogOpen] = useState(false);
|
const [linkDialogOpen, setLinkDialogOpen] = useState(false);
|
||||||
const [linkDialogUrl, setLinkDialogUrl] = useState('');
|
const [linkDialogUrl, setLinkDialogUrl] = useState('');
|
||||||
|
const [linkDialogText, setLinkDialogText] = useState('');
|
||||||
|
const [linkDialogEditing, setLinkDialogEditing] = useState(false);
|
||||||
const [linkTarget, setLinkTarget] = useState<LinkTarget>('rich');
|
const [linkTarget, setLinkTarget] = useState<LinkTarget>('rich');
|
||||||
|
const [imagePickerOpen, setImagePickerOpen] = useState(false);
|
||||||
|
const [imagePickerTarget, setImagePickerTarget] = useState<ImagePickerTarget>('rich');
|
||||||
const [codeBlockDialogOpen, setCodeBlockDialogOpen] = useState(false);
|
const [codeBlockDialogOpen, setCodeBlockDialogOpen] = useState(false);
|
||||||
const [codeBlockTarget, setCodeBlockTarget] = useState<CodeBlockTarget>('rich');
|
const [codeBlockTarget, setCodeBlockTarget] = useState<CodeBlockTarget>('rich');
|
||||||
const [codeBlockEditing, setCodeBlockEditing] = useState(false);
|
const [codeBlockEditing, setCodeBlockEditing] = useState(false);
|
||||||
@@ -236,7 +228,10 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
const [tableDialogOpen, setTableDialogOpen] = useState(false);
|
const [tableDialogOpen, setTableDialogOpen] = useState(false);
|
||||||
const [tableTarget, setTableTarget] = useState<TableTarget>('rich');
|
const [tableTarget, setTableTarget] = useState<TableTarget>('rich');
|
||||||
const [tableEditing, setTableEditing] = useState(false);
|
const [tableEditing, setTableEditing] = useState(false);
|
||||||
|
const [showSticker, setShowSticker] = useState(false);
|
||||||
const markdownRef = useRef<HTMLTextAreaElement>(null);
|
const markdownRef = useRef<HTMLTextAreaElement>(null);
|
||||||
|
const editorBoxRef = useRef<HTMLDivElement>(null);
|
||||||
|
const stickerBtnRef = useRef<HTMLButtonElement>(null);
|
||||||
|
|
||||||
const editor = useEditor({
|
const editor = useEditor({
|
||||||
extensions: [
|
extensions: [
|
||||||
@@ -262,8 +257,14 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
openOnClick: false,
|
openOnClick: false,
|
||||||
autolink: true,
|
autolink: true,
|
||||||
defaultProtocol: 'https',
|
defaultProtocol: 'https',
|
||||||
|
// 新标签由全站设置在展示层处理,编辑器不写 target/rel
|
||||||
|
HTMLAttributes: {
|
||||||
|
target: null,
|
||||||
|
rel: null,
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
ArticleImage.configure({ inline: false, allowBase64: false }),
|
ArticleImage.configure({ inline: false, allowBase64: false }),
|
||||||
|
ArticleSticker,
|
||||||
ImageGroup,
|
ImageGroup,
|
||||||
Placeholder.configure({
|
Placeholder.configure({
|
||||||
placeholder: ({ node }) => {
|
placeholder: ({ node }) => {
|
||||||
@@ -340,23 +341,42 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
placeCaretInFirstTextblock(editor);
|
placeCaretInFirstTextblock(editor);
|
||||||
}, [value, editor, mode]);
|
}, [value, editor, mode]);
|
||||||
|
|
||||||
// 全屏时锁定页面滚动,Esc 退出
|
// 全屏时锁定页面滚动;Esc 先关表情面板,再退出全屏
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!fullscreen) return undefined;
|
if (!fullscreen && !showSticker) return undefined;
|
||||||
|
|
||||||
const prevOverflow = document.body.style.overflow;
|
const prevOverflow = fullscreen ? document.body.style.overflow : null;
|
||||||
document.body.style.overflow = 'hidden';
|
if (fullscreen) document.body.style.overflow = 'hidden';
|
||||||
|
|
||||||
const onKeyDown = (e: KeyboardEvent) => {
|
const onKeyDown = (e: KeyboardEvent) => {
|
||||||
if (e.key === 'Escape') setFullscreen(false);
|
if (e.key !== 'Escape') return;
|
||||||
|
if (showSticker) {
|
||||||
|
setShowSticker(false);
|
||||||
|
stickerBtnRef.current?.focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (fullscreen) setFullscreen(false);
|
||||||
};
|
};
|
||||||
window.addEventListener('keydown', onKeyDown);
|
window.addEventListener('keydown', onKeyDown);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
document.body.style.overflow = prevOverflow;
|
if (prevOverflow !== null) document.body.style.overflow = prevOverflow;
|
||||||
window.removeEventListener('keydown', onKeyDown);
|
window.removeEventListener('keydown', onKeyDown);
|
||||||
};
|
};
|
||||||
}, [fullscreen]);
|
}, [fullscreen, showSticker]);
|
||||||
|
|
||||||
|
// 点击编辑器外关闭贴纸面板
|
||||||
|
useEffect(() => {
|
||||||
|
if (!showSticker) return;
|
||||||
|
const onPointer = (e: MouseEvent) => {
|
||||||
|
if (editorBoxRef.current && !editorBoxRef.current.contains(e.target as Node)) {
|
||||||
|
setShowSticker(false);
|
||||||
|
stickerBtnRef.current?.focus();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener('mousedown', onPointer);
|
||||||
|
return () => document.removeEventListener('mousedown', onPointer);
|
||||||
|
}, [showSticker]);
|
||||||
|
|
||||||
useImperativeHandle(ref, () => ({
|
useImperativeHandle(ref, () => ({
|
||||||
getHTML: () => {
|
getHTML: () => {
|
||||||
@@ -393,14 +413,33 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
const openLinkDialog = useCallback((target: LinkTarget) => {
|
const openLinkDialog = useCallback((target: LinkTarget) => {
|
||||||
if (target === 'rich') {
|
if (target === 'rich') {
|
||||||
if (!editor) return;
|
if (!editor) return;
|
||||||
const prev = editor.getAttributes('link').href as string | undefined;
|
const { from, to, empty } = editor.state.selection;
|
||||||
setLinkDialogUrl(prev ?? '');
|
let text = empty ? '' : editor.state.doc.textBetween(from, to, '');
|
||||||
|
let href = '';
|
||||||
|
let editing = false;
|
||||||
|
if (editor.isActive('link')) {
|
||||||
|
const attrs = editor.getAttributes('link');
|
||||||
|
href = (attrs.href as string) || '';
|
||||||
|
editing = Boolean(href);
|
||||||
|
editor.chain().focus().extendMarkRange('link').run();
|
||||||
|
const sel = editor.state.selection;
|
||||||
|
text = editor.state.doc.textBetween(sel.from, sel.to, '') || text;
|
||||||
|
}
|
||||||
|
setLinkDialogUrl(href);
|
||||||
|
setLinkDialogText(text);
|
||||||
|
setLinkDialogEditing(editing);
|
||||||
} else {
|
} else {
|
||||||
|
const textarea = markdownRef.current;
|
||||||
|
const selected = textarea
|
||||||
|
? markdownSource.slice(textarea.selectionStart, textarea.selectionEnd)
|
||||||
|
: '';
|
||||||
setLinkDialogUrl('');
|
setLinkDialogUrl('');
|
||||||
|
setLinkDialogText(selected);
|
||||||
|
setLinkDialogEditing(false);
|
||||||
}
|
}
|
||||||
setLinkTarget(target);
|
setLinkTarget(target);
|
||||||
setLinkDialogOpen(true);
|
setLinkDialogOpen(true);
|
||||||
}, [editor]);
|
}, [editor, markdownSource]);
|
||||||
|
|
||||||
const openCodeBlockDialog = useCallback((target: CodeBlockTarget) => {
|
const openCodeBlockDialog = useCallback((target: CodeBlockTarget) => {
|
||||||
setCodeBlockTarget(target);
|
setCodeBlockTarget(target);
|
||||||
@@ -477,11 +516,12 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
}
|
}
|
||||||
}, [editor]);
|
}, [editor]);
|
||||||
|
|
||||||
const applyLink = useCallback((url: string) => {
|
const applyLink = useCallback((payload: ArticleLinkConfirm) => {
|
||||||
|
const { url, text } = payload;
|
||||||
if (linkTarget === 'markdown') {
|
if (linkTarget === 'markdown') {
|
||||||
const textarea = markdownRef.current;
|
const textarea = markdownRef.current;
|
||||||
if (!textarea || !url) return;
|
if (!textarea || !url) return;
|
||||||
insertMarkdownLink(textarea, markdownSource, url, handleMarkdownChange);
|
insertMarkdownLink(textarea, markdownSource, url, handleMarkdownChange, { text });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!editor) return;
|
if (!editor) return;
|
||||||
@@ -489,7 +529,31 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
|
// 新标签行为由全站 open_content_links_in_new_tab 在展示层处理
|
||||||
|
const linkAttrs = { href: url };
|
||||||
|
const { empty } = editor.state.selection;
|
||||||
|
const hasLink = editor.isActive('link');
|
||||||
|
if (!empty || hasLink) {
|
||||||
|
editor.chain().focus().extendMarkRange('link').setLink(linkAttrs).run();
|
||||||
|
const { from, to } = editor.state.selection;
|
||||||
|
const current = editor.state.doc.textBetween(from, to, '');
|
||||||
|
if (text && current !== text) {
|
||||||
|
editor.chain().focus().insertContentAt(
|
||||||
|
{ from, to },
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
text,
|
||||||
|
marks: [{ type: 'link', attrs: linkAttrs }],
|
||||||
|
},
|
||||||
|
).run();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
editor.chain().focus().insertContent({
|
||||||
|
type: 'text',
|
||||||
|
text: text || '链接文字',
|
||||||
|
marks: [{ type: 'link', attrs: linkAttrs }],
|
||||||
|
}).run();
|
||||||
}, [editor, linkTarget, markdownSource, handleMarkdownChange]);
|
}, [editor, linkTarget, markdownSource, handleMarkdownChange]);
|
||||||
|
|
||||||
const removeLink = useCallback(() => {
|
const removeLink = useCallback(() => {
|
||||||
@@ -497,16 +561,57 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
||||||
}, [editor]);
|
}, [editor]);
|
||||||
|
|
||||||
const setImage = useCallback(async () => {
|
const insertSticker = useCallback((sticker: Sticker) => {
|
||||||
|
if (mode === 'markdown') {
|
||||||
|
const textarea = markdownRef.current;
|
||||||
|
if (!textarea) return;
|
||||||
|
const snippet = (sticker.type === 'text' && sticker.text)
|
||||||
|
? sticker.text
|
||||||
|
: (sticker.url ? `` : '');
|
||||||
|
if (!snippet) return;
|
||||||
|
insertAtCursor(textarea, markdownSource, snippet, handleMarkdownChange);
|
||||||
|
setShowSticker(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (!editor) return;
|
if (!editor) return;
|
||||||
const urls = await uploadPostImageFiles(true);
|
if (sticker.type === 'text' && sticker.text) {
|
||||||
|
editor.chain().focus().insertContent(sticker.text).run();
|
||||||
|
} else if (sticker.url) {
|
||||||
|
editor.chain().focus().insertContent([
|
||||||
|
{ type: 'sticker', attrs: { src: sticker.url, alt: sticker.name } },
|
||||||
|
{ type: 'text', text: ' ' },
|
||||||
|
]).run();
|
||||||
|
}
|
||||||
|
setShowSticker(false);
|
||||||
|
}, [editor, mode, markdownSource, handleMarkdownChange]);
|
||||||
|
|
||||||
|
const openImagePicker = useCallback((target: ImagePickerTarget) => {
|
||||||
|
setImagePickerTarget(target);
|
||||||
|
setImagePickerOpen(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const applyImageUrls = useCallback((urls: string[]) => {
|
||||||
if (!urls.length) return;
|
if (!urls.length) return;
|
||||||
|
if (imagePickerTarget === 'markdown') {
|
||||||
|
const textarea = markdownRef.current;
|
||||||
|
if (!textarea) return;
|
||||||
|
if (urls.length === 1) {
|
||||||
|
insertAtCursor(textarea, markdownSource, `\n\n\n\n`, handleMarkdownChange);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const layout = suggestImageGroupLayout(urls.length);
|
||||||
|
const imgs = urls.map(u => `<img src="${u}" alt="">`).join('');
|
||||||
|
const block = `\n\n<div data-image-group data-layout="${layout}" class="image-group image-group--${layout}">${imgs}</div>\n\n`;
|
||||||
|
insertAtCursor(textarea, markdownSource, block, handleMarkdownChange);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!editor) return;
|
||||||
if (urls.length === 1) {
|
if (urls.length === 1) {
|
||||||
editor.chain().focus().setImage({ src: urls[0] }).run();
|
editor.chain().focus().setImage({ src: urls[0] }).run();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
editor.chain().focus().insertImageGroup(urls, suggestImageGroupLayout(urls.length)).run();
|
editor.chain().focus().insertImageGroup(urls, suggestImageGroupLayout(urls.length)).run();
|
||||||
}, [editor]);
|
}, [editor, imagePickerTarget, markdownSource, handleMarkdownChange]);
|
||||||
|
|
||||||
const setImageDisplay = useCallback((display: ImageDisplay) => {
|
const setImageDisplay = useCallback((display: ImageDisplay) => {
|
||||||
if (!editor) return;
|
if (!editor) return;
|
||||||
@@ -571,6 +676,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
const html = sanitizeHtml(editor.getHTML());
|
const html = sanitizeHtml(editor.getHTML());
|
||||||
lastValueRef.current = html;
|
lastValueRef.current = html;
|
||||||
setMarkdownSource(htmlToMarkdown(html));
|
setMarkdownSource(htmlToMarkdown(html));
|
||||||
|
setShowSticker(false);
|
||||||
setMode('markdown');
|
setMode('markdown');
|
||||||
}, [editor]);
|
}, [editor]);
|
||||||
|
|
||||||
@@ -583,6 +689,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
editor.commands.setContent(html || '', { emitUpdate: false });
|
editor.commands.setContent(html || '', { emitUpdate: false });
|
||||||
placeCaretInFirstTextblock(editor);
|
placeCaretInFirstTextblock(editor);
|
||||||
}
|
}
|
||||||
|
setShowSticker(false);
|
||||||
setMode('rich');
|
setMode('rich');
|
||||||
}, [editor, markdownSource, onChange]);
|
}, [editor, markdownSource, onChange]);
|
||||||
|
|
||||||
@@ -596,21 +703,6 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
fn(textarea, markdownSource, handleMarkdownChange);
|
fn(textarea, markdownSource, handleMarkdownChange);
|
||||||
}, [markdownSource, handleMarkdownChange]);
|
}, [markdownSource, handleMarkdownChange]);
|
||||||
|
|
||||||
const insertMarkdownImage = useCallback(async () => {
|
|
||||||
const textarea = markdownRef.current;
|
|
||||||
if (!textarea) return;
|
|
||||||
const urls = await uploadPostImageFiles(true);
|
|
||||||
if (!urls.length) return;
|
|
||||||
if (urls.length === 1) {
|
|
||||||
insertAtCursor(textarea, markdownSource, `\n\n\n\n`, handleMarkdownChange);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const layout = suggestImageGroupLayout(urls.length);
|
|
||||||
const imgs = urls.map(u => `<img src="${u}" alt="">`).join('');
|
|
||||||
const block = `\n\n<div data-image-group data-layout="${layout}" class="image-group image-group--${layout}">${imgs}</div>\n\n`;
|
|
||||||
insertAtCursor(textarea, markdownSource, block, handleMarkdownChange);
|
|
||||||
}, [markdownSource, handleMarkdownChange]);
|
|
||||||
|
|
||||||
const markdownPreviewHtml = useMemo(
|
const markdownPreviewHtml = useMemo(
|
||||||
() => sanitizeHtml(markdownToHtml(markdownSource)),
|
() => sanitizeHtml(markdownToHtml(markdownSource)),
|
||||||
[markdownSource],
|
[markdownSource],
|
||||||
@@ -637,9 +729,9 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
{ icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: () => openLinkDialog('rich') },
|
{ icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: () => openLinkDialog('rich') },
|
||||||
{
|
{
|
||||||
icon: <ImageIcon size={15} />,
|
icon: <ImageIcon size={15} />,
|
||||||
title: '上传图片',
|
title: '图片',
|
||||||
hint: '可多选;多张自动并排成图组',
|
hint: '上传、链接或从已上传中选择',
|
||||||
action: setImage,
|
action: () => openImagePicker('rich'),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
icon: <Columns2 size={15} />,
|
icon: <Columns2 size={15} />,
|
||||||
@@ -648,6 +740,15 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
active: groupActive,
|
active: groupActive,
|
||||||
action: wrapSelectedAsGroup,
|
action: wrapSelectedAsGroup,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
icon: <span className="article-tool-btn__owo">OwO</span>,
|
||||||
|
title: '表情 OwO',
|
||||||
|
hint: '插入贴纸或颜文字',
|
||||||
|
active: showSticker,
|
||||||
|
className: 'article-tool-btn--owo',
|
||||||
|
buttonRef: stickerBtnRef,
|
||||||
|
action: () => setShowSticker(v => !v),
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
if (editor.isActive('table')) {
|
if (editor.isActive('table')) {
|
||||||
@@ -732,7 +833,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
}
|
}
|
||||||
|
|
||||||
return tools;
|
return tools;
|
||||||
}, [editor, enableContentGates, openLinkDialog, openCodeBlockDialog, openTableDialog, setImage, wrapMembersOnly, wrapReplyOnly, wrapPointsOnly, wrapSelectedAsGroup, setImageDisplay]);
|
}, [editor, enableContentGates, showSticker, openLinkDialog, openCodeBlockDialog, openTableDialog, openImagePicker, wrapMembersOnly, wrapReplyOnly, wrapPointsOnly, wrapSelectedAsGroup, setImageDisplay]);
|
||||||
|
|
||||||
const buildMarkdownTools = useCallback((): ToolBtn[] => {
|
const buildMarkdownTools = useCallback((): ToolBtn[] => {
|
||||||
const tools: ToolBtn[] = [
|
const tools: ToolBtn[] = [
|
||||||
@@ -748,7 +849,21 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
{ icon: <Code size={15} />, title: '代码块', hint: '语言、行号与折叠', action: () => openCodeBlockDialog('markdown') },
|
{ icon: <Code size={15} />, title: '代码块', hint: '语言、行号与折叠', action: () => openCodeBlockDialog('markdown') },
|
||||||
{ icon: <TableIcon size={15} />, title: '表格', hint: '插入 GFM 管道表', action: () => openTableDialog('markdown') },
|
{ icon: <TableIcon size={15} />, title: '表格', hint: '插入 GFM 管道表', action: () => openTableDialog('markdown') },
|
||||||
{ icon: <LinkIcon size={15} />, title: '链接', action: () => openLinkDialog('markdown') },
|
{ icon: <LinkIcon size={15} />, title: '链接', action: () => openLinkDialog('markdown') },
|
||||||
{ icon: <ImageIcon size={15} />, title: '上传图片', action: insertMarkdownImage },
|
{
|
||||||
|
icon: <ImageIcon size={15} />,
|
||||||
|
title: '图片',
|
||||||
|
hint: '上传、链接或从已上传中选择',
|
||||||
|
action: () => openImagePicker('markdown'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
icon: <span className="article-tool-btn__owo">OwO</span>,
|
||||||
|
title: '表情 OwO',
|
||||||
|
hint: '插入贴纸或颜文字',
|
||||||
|
active: showSticker,
|
||||||
|
className: 'article-tool-btn--owo',
|
||||||
|
buttonRef: stickerBtnRef,
|
||||||
|
action: () => setShowSticker(v => !v),
|
||||||
|
},
|
||||||
];
|
];
|
||||||
if (enableContentGates) {
|
if (enableContentGates) {
|
||||||
tools.push(
|
tools.push(
|
||||||
@@ -776,7 +891,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
return tools;
|
return tools;
|
||||||
}, [enableContentGates, withMarkdown, openLinkDialog, openCodeBlockDialog, openTableDialog, insertMarkdownImage]);
|
}, [enableContentGates, showSticker, withMarkdown, openLinkDialog, openCodeBlockDialog, openTableDialog, openImagePicker]);
|
||||||
|
|
||||||
const tools = mode === 'rich' ? buildRichTools() : buildMarkdownTools();
|
const tools = mode === 'rich' ? buildRichTools() : buildMarkdownTools();
|
||||||
const words = mode === 'markdown'
|
const words = mode === 'markdown'
|
||||||
@@ -784,12 +899,16 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
: (editor ? countWords(editor.getText()) : 0);
|
: (editor ? countWords(editor.getText()) : 0);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`article-editor article-editor--${mode}${fullscreen ? ' article-editor--fullscreen' : ''}`}>
|
<div
|
||||||
|
ref={editorBoxRef}
|
||||||
|
className={`article-editor article-editor--${mode}${fullscreen ? ' article-editor--fullscreen' : ''}`}
|
||||||
|
>
|
||||||
<div className="article-editor-bar">
|
<div className="article-editor-bar">
|
||||||
<div className="article-editor-tools">
|
<div className="article-editor-tools">
|
||||||
{renderToolButtons(tools)}
|
{renderToolButtons(tools)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{showSticker && <StickerPicker onSelect={insertSticker} />}
|
||||||
|
|
||||||
<div className="article-editor-body">
|
<div className="article-editor-body">
|
||||||
{mode === 'rich' ? (
|
{mode === 'rich' ? (
|
||||||
@@ -897,8 +1016,15 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
|||||||
open={linkDialogOpen}
|
open={linkDialogOpen}
|
||||||
onOpenChange={setLinkDialogOpen}
|
onOpenChange={setLinkDialogOpen}
|
||||||
initialUrl={linkDialogUrl}
|
initialUrl={linkDialogUrl}
|
||||||
|
initialText={linkDialogText}
|
||||||
|
editing={linkDialogEditing}
|
||||||
onConfirm={applyLink}
|
onConfirm={applyLink}
|
||||||
onRemove={linkTarget === 'rich' && linkDialogUrl ? removeLink : undefined}
|
onRemove={linkTarget === 'rich' && linkDialogEditing ? removeLink : undefined}
|
||||||
|
/>
|
||||||
|
<ArticleImagePickerDialog
|
||||||
|
open={imagePickerOpen}
|
||||||
|
onOpenChange={setImagePickerOpen}
|
||||||
|
onInsert={applyImageUrls}
|
||||||
/>
|
/>
|
||||||
<ArticleCodeBlockDialog
|
<ArticleCodeBlockDialog
|
||||||
open={codeBlockDialogOpen}
|
open={codeBlockDialogOpen}
|
||||||
|
|||||||
@@ -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),
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,11 +12,11 @@ import {
|
|||||||
List, ListOrdered, Code, Link as LinkIcon, Image as ImageIcon,
|
List, ListOrdered, Code, Link as LinkIcon, Image as ImageIcon,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { POST_CONTENT_PURIFY_CONFIG } from '../utils/postContent';
|
import { POST_CONTENT_PURIFY_CONFIG } from '../utils/postContent';
|
||||||
import { api } from '../api/client';
|
|
||||||
import { notify } from '@/lib/notify';
|
|
||||||
import { ArticleCodeBlock } from './editor/ArticleCodeBlockExtension';
|
import { ArticleCodeBlock } from './editor/ArticleCodeBlockExtension';
|
||||||
import { ArticleCodeBlockDialog } from './editor/ArticleCodeBlockDialog';
|
import { ArticleCodeBlockDialog } from './editor/ArticleCodeBlockDialog';
|
||||||
import { ArticleImage } from './editor/ArticleImageExtension';
|
import { ArticleImage } from './editor/ArticleImageExtension';
|
||||||
|
import { ArticleImagePickerDialog } from './editor/ArticleImagePickerDialog';
|
||||||
|
import { ArticleLinkDialog, type ArticleLinkConfirm } from './editor/ArticleLinkDialog';
|
||||||
import { TabIndent } from './editor/TabIndentExtension';
|
import { TabIndent } from './editor/TabIndentExtension';
|
||||||
import type { CodeBlockInsertOptions } from '../utils/codeBlockOptions';
|
import type { CodeBlockInsertOptions } from '../utils/codeBlockOptions';
|
||||||
import { Tooltip } from './ui/Tooltip';
|
import { Tooltip } from './ui/Tooltip';
|
||||||
@@ -49,28 +49,6 @@ function isEditorEmpty(editor: Editor): boolean {
|
|||||||
return !hasImage;
|
return !hasImage;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 触发图片文件选择并上传 */
|
|
||||||
async function uploadImageFiles(): Promise<string[]> {
|
|
||||||
return new Promise(resolve => {
|
|
||||||
const input = document.createElement('input');
|
|
||||||
input.type = 'file';
|
|
||||||
input.accept = 'image/jpeg,image/png,image/gif,image/webp';
|
|
||||||
input.multiple = false;
|
|
||||||
input.onchange = async () => {
|
|
||||||
const files = [...(input.files ?? [])];
|
|
||||||
if (!files.length) { resolve([]); return; }
|
|
||||||
try {
|
|
||||||
const { url } = await api.uploadPostImage(files[0]);
|
|
||||||
resolve([url]);
|
|
||||||
} catch (e: unknown) {
|
|
||||||
notify.error(e instanceof Error ? e.message : '图片上传失败');
|
|
||||||
resolve([]);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
input.click();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEditor(
|
const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEditor(
|
||||||
{ value, onChange, placeholder = '说点什么吧…' },
|
{ value, onChange, placeholder = '说点什么吧…' },
|
||||||
ref,
|
ref,
|
||||||
@@ -79,6 +57,11 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
|||||||
const lastValueRef = useRef(value);
|
const lastValueRef = useRef(value);
|
||||||
const [, setTick] = useState(0);
|
const [, setTick] = useState(0);
|
||||||
const [showSticker, setShowSticker] = useState(false);
|
const [showSticker, setShowSticker] = useState(false);
|
||||||
|
const [imagePickerOpen, setImagePickerOpen] = useState(false);
|
||||||
|
const [linkDialogOpen, setLinkDialogOpen] = useState(false);
|
||||||
|
const [linkDialogUrl, setLinkDialogUrl] = useState('');
|
||||||
|
const [linkDialogText, setLinkDialogText] = useState('');
|
||||||
|
const [linkDialogEditing, setLinkDialogEditing] = useState(false);
|
||||||
const [codeBlockDialogOpen, setCodeBlockDialogOpen] = useState(false);
|
const [codeBlockDialogOpen, setCodeBlockDialogOpen] = useState(false);
|
||||||
const [codeBlockEditing, setCodeBlockEditing] = useState(false);
|
const [codeBlockEditing, setCodeBlockEditing] = useState(false);
|
||||||
const [codeBlockInitial, setCodeBlockInitial] = useState<CodeBlockInsertOptions | null>(null);
|
const [codeBlockInitial, setCodeBlockInitial] = useState<CodeBlockInsertOptions | null>(null);
|
||||||
@@ -99,6 +82,11 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
|||||||
openOnClick: false,
|
openOnClick: false,
|
||||||
autolink: true,
|
autolink: true,
|
||||||
defaultProtocol: 'https',
|
defaultProtocol: 'https',
|
||||||
|
// 新标签由全站设置在展示层处理,编辑器不写 target/rel
|
||||||
|
HTMLAttributes: {
|
||||||
|
target: null,
|
||||||
|
rel: null,
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
ArticleImage.configure({ inline: true, allowBase64: true }),
|
ArticleImage.configure({ inline: true, allowBase64: true }),
|
||||||
Placeholder.configure({ placeholder }),
|
Placeholder.configure({ placeholder }),
|
||||||
@@ -179,11 +167,14 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
|||||||
setShowSticker(false);
|
setShowSticker(false);
|
||||||
}, [editor]);
|
}, [editor]);
|
||||||
|
|
||||||
const setImage = useCallback(async () => {
|
const applyImageUrls = useCallback((urls: string[]) => {
|
||||||
if (!editor) return;
|
if (!editor || !urls.length) return;
|
||||||
const urls = await uploadImageFiles();
|
// 评论为 inline 图,无图组:逐张插入并跟空格,便于光标落在右侧
|
||||||
if (!urls.length) return;
|
const nodes = urls.flatMap(src => [
|
||||||
editor.chain().focus().setImage({ src: urls[0] }).run();
|
{ type: 'image' as const, attrs: { src } },
|
||||||
|
{ type: 'text' as const, text: ' ' },
|
||||||
|
]);
|
||||||
|
editor.chain().focus().insertContent(nodes).run();
|
||||||
}, [editor]);
|
}, [editor]);
|
||||||
|
|
||||||
const openCodeBlockDialog = useCallback(() => {
|
const openCodeBlockDialog = useCallback(() => {
|
||||||
@@ -213,23 +204,70 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
|||||||
}).run();
|
}).run();
|
||||||
}, [editor]);
|
}, [editor]);
|
||||||
|
|
||||||
const setLink = useCallback(() => {
|
const openLinkDialog = useCallback(() => {
|
||||||
if (!editor) return;
|
if (!editor) return;
|
||||||
const prev = editor.getAttributes('link').href as string | undefined;
|
const { from, to, empty } = editor.state.selection;
|
||||||
const url = window.prompt('链接地址', prev ?? 'https://');
|
let text = empty ? '' : editor.state.doc.textBetween(from, to, '');
|
||||||
if (url === null) return;
|
let href = '';
|
||||||
|
let editing = false;
|
||||||
|
if (editor.isActive('link')) {
|
||||||
|
const attrs = editor.getAttributes('link');
|
||||||
|
href = (attrs.href as string) || '';
|
||||||
|
editing = Boolean(href);
|
||||||
|
editor.chain().focus().extendMarkRange('link').run();
|
||||||
|
const sel = editor.state.selection;
|
||||||
|
text = editor.state.doc.textBetween(sel.from, sel.to, '') || text;
|
||||||
|
}
|
||||||
|
setLinkDialogUrl(href);
|
||||||
|
setLinkDialogText(text);
|
||||||
|
setLinkDialogEditing(editing);
|
||||||
|
setLinkDialogOpen(true);
|
||||||
|
}, [editor]);
|
||||||
|
|
||||||
|
const applyLink = useCallback((payload: ArticleLinkConfirm) => {
|
||||||
|
if (!editor) return;
|
||||||
|
const { url, text } = payload;
|
||||||
if (!url) {
|
if (!url) {
|
||||||
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
|
// 新标签行为由全站 open_content_links_in_new_tab 在展示层处理
|
||||||
|
const linkAttrs = { href: url };
|
||||||
|
const { empty } = editor.state.selection;
|
||||||
|
const hasLink = editor.isActive('link');
|
||||||
|
if (!empty || hasLink) {
|
||||||
|
editor.chain().focus().extendMarkRange('link').setLink(linkAttrs).run();
|
||||||
|
const { from, to } = editor.state.selection;
|
||||||
|
const current = editor.state.doc.textBetween(from, to, '');
|
||||||
|
if (text && current !== text) {
|
||||||
|
editor.chain().focus().insertContentAt(
|
||||||
|
{ from, to },
|
||||||
|
{
|
||||||
|
type: 'text',
|
||||||
|
text,
|
||||||
|
marks: [{ type: 'link', attrs: linkAttrs }],
|
||||||
|
},
|
||||||
|
).run();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
editor.chain().focus().insertContent({
|
||||||
|
type: 'text',
|
||||||
|
text: text || '链接文字',
|
||||||
|
marks: [{ type: 'link', attrs: linkAttrs }],
|
||||||
|
}).run();
|
||||||
|
}, [editor]);
|
||||||
|
|
||||||
|
const removeLink = useCallback(() => {
|
||||||
|
if (!editor) return;
|
||||||
|
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
||||||
}, [editor]);
|
}, [editor]);
|
||||||
|
|
||||||
if (!editor) {
|
if (!editor) {
|
||||||
return <div className="comment-editor"><div className="article-editor-bar" /><div className="article-editor-body" /></div>;
|
return <div className="comment-editor"><div className="article-editor-bar" /><div className="article-editor-body" /></div>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const tools: { icon: React.ReactNode; title: string; active?: boolean; action: () => void; className?: string }[] = [
|
const tools: { icon: React.ReactNode; title: string; hint?: string; active?: boolean; action: () => void; className?: string }[] = [
|
||||||
{ icon: <Bold size={15} />, title: '加粗', active: editor.isActive('bold'), action: () => editor.chain().focus().toggleBold().run() },
|
{ icon: <Bold size={15} />, title: '加粗', active: editor.isActive('bold'), action: () => editor.chain().focus().toggleBold().run() },
|
||||||
{ icon: <Italic size={15} />, title: '斜体', active: editor.isActive('italic'), action: () => editor.chain().focus().toggleItalic().run() },
|
{ icon: <Italic size={15} />, title: '斜体', active: editor.isActive('italic'), action: () => editor.chain().focus().toggleItalic().run() },
|
||||||
{ icon: <UnderlineIcon size={15} />, title: '下划线', active: editor.isActive('underline'), action: () => editor.chain().focus().toggleUnderline().run() },
|
{ icon: <UnderlineIcon size={15} />, title: '下划线', active: editor.isActive('underline'), action: () => editor.chain().focus().toggleUnderline().run() },
|
||||||
@@ -237,8 +275,13 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
|||||||
{ icon: <List size={15} />, title: '无序列表', active: editor.isActive('bulletList'), action: () => editor.chain().focus().toggleBulletList().run() },
|
{ icon: <List size={15} />, title: '无序列表', active: editor.isActive('bulletList'), action: () => editor.chain().focus().toggleBulletList().run() },
|
||||||
{ icon: <ListOrdered size={15} />, title: '有序列表', active: editor.isActive('orderedList'), action: () => editor.chain().focus().toggleOrderedList().run() },
|
{ icon: <ListOrdered size={15} />, title: '有序列表', active: editor.isActive('orderedList'), action: () => editor.chain().focus().toggleOrderedList().run() },
|
||||||
{ icon: <Code size={15} />, title: '代码块', active: editor.isActive('codeBlock'), action: openCodeBlockDialog },
|
{ icon: <Code size={15} />, title: '代码块', active: editor.isActive('codeBlock'), action: openCodeBlockDialog },
|
||||||
{ icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: setLink },
|
{ icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: openLinkDialog },
|
||||||
{ icon: <ImageIcon size={15} />, title: '上传图片', action: setImage },
|
{
|
||||||
|
icon: <ImageIcon size={15} />,
|
||||||
|
title: '图片',
|
||||||
|
hint: '上传、链接或从已上传中选择',
|
||||||
|
action: () => setImagePickerOpen(true),
|
||||||
|
},
|
||||||
{ icon: <span className="article-tool-btn__owo">OwO</span>, title: '表情 OwO', active: showSticker, action: () => setShowSticker(v => !v), className: 'article-tool-btn--owo' },
|
{ icon: <span className="article-tool-btn__owo">OwO</span>, title: '表情 OwO', active: showSticker, action: () => setShowSticker(v => !v), className: 'article-tool-btn--owo' },
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -247,14 +290,14 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
|||||||
<div className="article-editor-bar">
|
<div className="article-editor-bar">
|
||||||
<div className="article-editor-tools">
|
<div className="article-editor-tools">
|
||||||
{tools.map((t, i) => (
|
{tools.map((t, i) => (
|
||||||
<Tooltip key={i} content={t.title} side="bottom">
|
<Tooltip key={i} content={t.title} hint={t.hint} side="bottom">
|
||||||
<button
|
<button
|
||||||
ref={i === tools.length - 1 ? stickerBtnRef : undefined}
|
ref={i === tools.length - 1 ? stickerBtnRef : undefined}
|
||||||
type="button"
|
type="button"
|
||||||
className={`article-tool-btn${t.active ? ' active' : ''}${t.className ? ` ${t.className}` : ''}`}
|
className={`article-tool-btn${t.active ? ' active' : ''}${t.className ? ` ${t.className}` : ''}`}
|
||||||
onMouseDown={e => e.preventDefault()}
|
onMouseDown={e => e.preventDefault()}
|
||||||
onClick={t.action}
|
onClick={t.action}
|
||||||
aria-label={t.title}
|
aria-label={t.hint ? `${t.title},${t.hint}` : t.title}
|
||||||
>
|
>
|
||||||
{t.icon}
|
{t.icon}
|
||||||
</button>
|
</button>
|
||||||
@@ -268,6 +311,20 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{showSticker && <StickerPicker onSelect={insertSticker} />}
|
{showSticker && <StickerPicker onSelect={insertSticker} />}
|
||||||
|
<ArticleLinkDialog
|
||||||
|
open={linkDialogOpen}
|
||||||
|
onOpenChange={setLinkDialogOpen}
|
||||||
|
initialUrl={linkDialogUrl}
|
||||||
|
initialText={linkDialogText}
|
||||||
|
editing={linkDialogEditing}
|
||||||
|
onConfirm={applyLink}
|
||||||
|
onRemove={linkDialogEditing ? removeLink : undefined}
|
||||||
|
/>
|
||||||
|
<ArticleImagePickerDialog
|
||||||
|
open={imagePickerOpen}
|
||||||
|
onOpenChange={setImagePickerOpen}
|
||||||
|
onInsert={applyImageUrls}
|
||||||
|
/>
|
||||||
<ArticleCodeBlockDialog
|
<ArticleCodeBlockDialog
|
||||||
open={codeBlockDialogOpen}
|
open={codeBlockDialogOpen}
|
||||||
onOpenChange={setCodeBlockDialogOpen}
|
onOpenChange={setCodeBlockDialogOpen}
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import type { FeedSortTab } from '../api/types';
|
|||||||
export type FeedSort = 'latest' | 'reply' | 'hot';
|
export type FeedSort = 'latest' | 'reply' | 'hot';
|
||||||
|
|
||||||
const SORT_META: Record<FeedSort, { hint: string; icon: typeof Clock }> = {
|
const SORT_META: Record<FeedSort, { hint: string; icon: typeof Clock }> = {
|
||||||
reply: { hint: '最近有人评论', icon: MessageCircle },
|
reply: { hint: '按最近活动(发帖或评论)', icon: MessageCircle },
|
||||||
latest: { hint: '按发帖时间', icon: Clock },
|
latest: { hint: '按发帖时间', icon: Clock },
|
||||||
hot: { hint: '仅展示推荐帖', icon: BadgeCheck },
|
hot: { hint: '仅展示推荐帖', icon: BadgeCheck },
|
||||||
};
|
};
|
||||||
|
|||||||
227
frontend/src/components/PmComposerInput.tsx
Normal file
227
frontend/src/components/PmComposerInput.tsx
Normal file
@@ -0,0 +1,227 @@
|
|||||||
|
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef } from 'react';
|
||||||
|
import type { Sticker } from '../data/stickers';
|
||||||
|
|
||||||
|
export type PmComposerInputHandle = {
|
||||||
|
insertSticker: (sticker: Sticker) => void;
|
||||||
|
insertText: (text: string) => void;
|
||||||
|
focus: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
value: string;
|
||||||
|
onChange: (next: string) => void;
|
||||||
|
placeholder?: string;
|
||||||
|
maxLength?: number;
|
||||||
|
disabled?: boolean;
|
||||||
|
onSubmit?: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 站点内置贴纸路径(评论/私信共用) */
|
||||||
|
export function isPmStickerSrc(src: string) {
|
||||||
|
return src.includes('/stickers/');
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(s: string) {
|
||||||
|
return s
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"');
|
||||||
|
}
|
||||||
|
|
||||||
|
function draftToHtml(text: string): string {
|
||||||
|
if (!text) return '';
|
||||||
|
const parts = text.split(/(!\[[^\]]*]\([^)]+\))/g);
|
||||||
|
return parts.map((part) => {
|
||||||
|
const m = part.match(/^!\[([^\]]*)]\(([^)]+)\)$/);
|
||||||
|
if (m) {
|
||||||
|
const alt = escapeHtml(m[1] || '表情');
|
||||||
|
const src = escapeHtml(m[2]);
|
||||||
|
const cls = isPmStickerSrc(m[2]) ? 'pm-composer__sticker' : 'pm-composer__inline-img';
|
||||||
|
return `<img class="${cls}" src="${src}" alt="${alt}" draggable="false">`;
|
||||||
|
}
|
||||||
|
return escapeHtml(part).replace(/\n/g, '<br>');
|
||||||
|
}).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
function serializeComposer(root: HTMLElement): string {
|
||||||
|
let out = '';
|
||||||
|
|
||||||
|
const walk = (node: Node) => {
|
||||||
|
if (node.nodeType === Node.TEXT_NODE) {
|
||||||
|
out += node.textContent || '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (node.nodeType !== Node.ELEMENT_NODE) return;
|
||||||
|
const el = node as HTMLElement;
|
||||||
|
const tag = el.tagName;
|
||||||
|
if (tag === 'IMG') {
|
||||||
|
const src = el.getAttribute('src') || '';
|
||||||
|
const alt = el.getAttribute('alt') || '表情';
|
||||||
|
out += ``;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (tag === 'BR') {
|
||||||
|
out += '\n';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (tag === 'DIV' || tag === 'P') {
|
||||||
|
if (out.length > 0 && !out.endsWith('\n')) out += '\n';
|
||||||
|
el.childNodes.forEach(walk);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
el.childNodes.forEach(walk);
|
||||||
|
};
|
||||||
|
|
||||||
|
root.childNodes.forEach(walk);
|
||||||
|
return out.replace(/\n$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function placeCaretAfter(node: Node) {
|
||||||
|
const sel = window.getSelection();
|
||||||
|
if (!sel) return;
|
||||||
|
const range = document.createRange();
|
||||||
|
range.setStartAfter(node);
|
||||||
|
range.collapse(true);
|
||||||
|
sel.removeAllRanges();
|
||||||
|
sel.addRange(range);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 私信输入框:可内联插入贴纸(与评论编辑器一致),序列化为 markdown 图片语法 */
|
||||||
|
const PmComposerInput = forwardRef<PmComposerInputHandle, Props>(function PmComposerInput(
|
||||||
|
{ value, onChange, placeholder, maxLength = 4000, disabled, onSubmit },
|
||||||
|
ref,
|
||||||
|
) {
|
||||||
|
const elRef = useRef<HTMLDivElement>(null);
|
||||||
|
const savedRangeRef = useRef<Range | null>(null);
|
||||||
|
const valueRef = useRef(value);
|
||||||
|
valueRef.current = value;
|
||||||
|
|
||||||
|
const emit = useCallback(() => {
|
||||||
|
const el = elRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
const next = serializeComposer(el);
|
||||||
|
if (maxLength && next.length > maxLength) {
|
||||||
|
el.innerHTML = draftToHtml(valueRef.current);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
el.dataset.empty = next ? 'false' : 'true';
|
||||||
|
if (next !== valueRef.current) onChange(next);
|
||||||
|
}, [maxLength, onChange]);
|
||||||
|
|
||||||
|
const restoreRange = useCallback(() => {
|
||||||
|
const el = elRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
el.focus();
|
||||||
|
const sel = window.getSelection();
|
||||||
|
if (!sel) return;
|
||||||
|
const saved = savedRangeRef.current;
|
||||||
|
if (saved && el.contains(saved.startContainer)) {
|
||||||
|
sel.removeAllRanges();
|
||||||
|
sel.addRange(saved);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const range = document.createRange();
|
||||||
|
range.selectNodeContents(el);
|
||||||
|
range.collapse(false);
|
||||||
|
sel.removeAllRanges();
|
||||||
|
sel.addRange(range);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const saveRange = useCallback(() => {
|
||||||
|
const el = elRef.current;
|
||||||
|
const sel = window.getSelection();
|
||||||
|
if (!el || !sel || sel.rangeCount === 0) return;
|
||||||
|
if (!el.contains(sel.anchorNode)) return;
|
||||||
|
savedRangeRef.current = sel.getRangeAt(0).cloneRange();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const insertNodes = useCallback((nodes: Node[]) => {
|
||||||
|
const el = elRef.current;
|
||||||
|
if (!el || !nodes.length) return;
|
||||||
|
restoreRange();
|
||||||
|
const sel = window.getSelection();
|
||||||
|
if (!sel) return;
|
||||||
|
const range = sel.rangeCount > 0 ? sel.getRangeAt(0) : document.createRange();
|
||||||
|
range.deleteContents();
|
||||||
|
const frag = document.createDocumentFragment();
|
||||||
|
nodes.forEach((n) => frag.appendChild(n));
|
||||||
|
const last = nodes[nodes.length - 1];
|
||||||
|
range.insertNode(frag);
|
||||||
|
placeCaretAfter(last);
|
||||||
|
saveRange();
|
||||||
|
emit();
|
||||||
|
}, [emit, restoreRange, saveRange]);
|
||||||
|
|
||||||
|
useImperativeHandle(ref, () => ({
|
||||||
|
insertSticker(sticker) {
|
||||||
|
if (!sticker.url) return;
|
||||||
|
const img = document.createElement('img');
|
||||||
|
img.className = 'pm-composer__sticker';
|
||||||
|
img.src = sticker.url;
|
||||||
|
img.alt = sticker.name || '表情';
|
||||||
|
img.draggable = false;
|
||||||
|
// 尾随空格,光标可停在贴纸右侧(对齐评论编辑器)
|
||||||
|
insertNodes([img, document.createTextNode(' ')]);
|
||||||
|
},
|
||||||
|
insertText(text) {
|
||||||
|
if (!text) return;
|
||||||
|
insertNodes([document.createTextNode(text)]);
|
||||||
|
},
|
||||||
|
focus() {
|
||||||
|
restoreRange();
|
||||||
|
},
|
||||||
|
}), [insertNodes, restoreRange]);
|
||||||
|
|
||||||
|
// 外部改 value(切会话 / 发送清空)时回填;输入过程中 serialize 与 value 一致则不重绘
|
||||||
|
useEffect(() => {
|
||||||
|
const el = elRef.current;
|
||||||
|
if (!el) return;
|
||||||
|
if (serializeComposer(el) === value) {
|
||||||
|
el.dataset.empty = value ? 'false' : 'true';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
el.innerHTML = draftToHtml(value);
|
||||||
|
el.dataset.empty = value ? 'false' : 'true';
|
||||||
|
}, [value]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onSel = () => saveRange();
|
||||||
|
document.addEventListener('selectionchange', onSel);
|
||||||
|
return () => document.removeEventListener('selectionchange', onSel);
|
||||||
|
}, [saveRange]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
ref={elRef}
|
||||||
|
className="pm-composer__input"
|
||||||
|
role="textbox"
|
||||||
|
aria-multiline="true"
|
||||||
|
aria-label="私信内容"
|
||||||
|
contentEditable={!disabled}
|
||||||
|
data-placeholder={placeholder || ''}
|
||||||
|
data-empty={value ? 'false' : 'true'}
|
||||||
|
suppressContentEditableWarning
|
||||||
|
onInput={emit}
|
||||||
|
onBlur={saveRange}
|
||||||
|
onPaste={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const text = e.clipboardData.getData('text/plain');
|
||||||
|
if (text) insertNodes([document.createTextNode(text)]);
|
||||||
|
}}
|
||||||
|
onDrop={(e) => {
|
||||||
|
// 禁止把文件拖成「大图附件」;贴纸只走选择器
|
||||||
|
if (e.dataTransfer?.files?.length) e.preventDefault();
|
||||||
|
}}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.nativeEvent.isComposing) return;
|
||||||
|
if (e.key === 'Enter' && !e.shiftKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
onSubmit?.();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default PmComposerInput;
|
||||||
@@ -9,7 +9,6 @@ import { useAuth } from '../hooks/useAuth';
|
|||||||
import { loginPath } from '../utils/authRedirect';
|
import { loginPath } from '../utils/authRedirect';
|
||||||
import { formatTime } from '../utils/content';
|
import { formatTime } from '../utils/content';
|
||||||
import { userPath } from '../utils/userPath';
|
import { userPath } from '../utils/userPath';
|
||||||
import ComposeMessageDialog from './ComposeMessageDialog';
|
|
||||||
import UserLink from './UserLink';
|
import UserLink from './UserLink';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -28,7 +27,6 @@ export default function PostAuthorCard({
|
|||||||
const { user: me } = useAuth();
|
const { user: me } = useAuth();
|
||||||
const [profile, setProfile] = useState<UserPublic | null>(null);
|
const [profile, setProfile] = useState<UserPublic | null>(null);
|
||||||
const [stats, setStats] = useState<UserActivityStats | null>(null);
|
const [stats, setStats] = useState<UserActivityStats | null>(null);
|
||||||
const [msgOpen, setMsgOpen] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!author?.id) {
|
if (!author?.id) {
|
||||||
@@ -78,7 +76,7 @@ export default function PostAuthorCard({
|
|||||||
nav(loginPath(profileHref));
|
nav(loginPath(profileHref));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setMsgOpen(true);
|
nav(`/messages?peer=${author.id}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -159,16 +157,6 @@ export default function PostAuthorCard({
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{!isSelf && (
|
|
||||||
<ComposeMessageDialog
|
|
||||||
open={msgOpen}
|
|
||||||
onOpenChange={setMsgOpen}
|
|
||||||
toUserId={author.id}
|
|
||||||
toNickname={nick}
|
|
||||||
onSent={() => nav(`/messages?peer=${author.id}`)}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useMemo, useCallback, useEffect, useState } from 'react';
|
import { useMemo, useCallback, useState } from 'react';
|
||||||
import { useNavigate, useParams } from 'react-router-dom';
|
import { useNavigate, useParams } from 'react-router-dom';
|
||||||
import { renderPostContentHtml } from '../utils/postContent';
|
import { renderPostContentHtml } from '../utils/postContent';
|
||||||
import { extractHeadingsFromHtml, type PostHeading } from '../utils/postHeadings';
|
import { handleMdCodeBlockUiClick } from '../utils/enhanceCodeBlocks';
|
||||||
import { loginPath, registerPath } from '../utils/authRedirect';
|
import { loginPath, registerPath } from '../utils/authRedirect';
|
||||||
import { useForumLimits } from '../hooks/useForumLimits';
|
import { useForumLimits } from '../hooks/useForumLimits';
|
||||||
import { notify } from '@/lib/notify';
|
import { notify } from '@/lib/notify';
|
||||||
@@ -12,8 +12,6 @@ interface Props {
|
|||||||
html: string;
|
html: string;
|
||||||
isLoggedIn: boolean;
|
isLoggedIn: boolean;
|
||||||
className?: string;
|
className?: string;
|
||||||
/** 正文标题树变化时回调(用于侧栏目录) */
|
|
||||||
onHeadingsChange?: (headings: PostHeading[]) => void;
|
|
||||||
/** 点击「回复可见」门控的「去回复」 */
|
/** 点击「回复可见」门控的「去回复」 */
|
||||||
onRequestReply?: () => void;
|
onRequestReply?: () => void;
|
||||||
/** 积分解锁成功后刷新正文 */
|
/** 积分解锁成功后刷新正文 */
|
||||||
@@ -26,7 +24,6 @@ export default function PostContent({
|
|||||||
html,
|
html,
|
||||||
isLoggedIn,
|
isLoggedIn,
|
||||||
className = 'post-detail-content',
|
className = 'post-detail-content',
|
||||||
onHeadingsChange,
|
|
||||||
onRequestReply,
|
onRequestReply,
|
||||||
onUnlocked,
|
onUnlocked,
|
||||||
postId: postIdProp,
|
postId: postIdProp,
|
||||||
@@ -39,19 +36,12 @@ export default function PostContent({
|
|||||||
const [lightboxAlt, setLightboxAlt] = useState('');
|
const [lightboxAlt, setLightboxAlt] = useState('');
|
||||||
const [unlocking, setUnlocking] = useState(false);
|
const [unlocking, setUnlocking] = useState(false);
|
||||||
|
|
||||||
const prepared = useMemo(() => {
|
const preparedHtml = useMemo(
|
||||||
const rendered = renderPostContentHtml(html, isLoggedIn, {
|
() => renderPostContentHtml(html, isLoggedIn, {
|
||||||
openLinksInNewTab: limits.open_content_links_in_new_tab,
|
openLinksInNewTab: limits.open_content_links_in_new_tab,
|
||||||
});
|
}),
|
||||||
return {
|
[html, isLoggedIn, limits.open_content_links_in_new_tab],
|
||||||
html: rendered,
|
);
|
||||||
headings: extractHeadingsFromHtml(rendered),
|
|
||||||
};
|
|
||||||
}, [html, isLoggedIn, limits.open_content_links_in_new_tab]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
onHeadingsChange?.(prepared.headings);
|
|
||||||
}, [prepared.headings, onHeadingsChange]);
|
|
||||||
|
|
||||||
const openLightbox = useCallback((img: HTMLImageElement) => {
|
const openLightbox = useCallback((img: HTMLImageElement) => {
|
||||||
const full = img.getAttribute('data-full') || img.currentSrc || img.src;
|
const full = img.getAttribute('data-full') || img.currentSrc || img.src;
|
||||||
@@ -116,40 +106,12 @@ export default function PostContent({
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const foldBtn = target.closest<HTMLElement>('[data-code-fold]');
|
try {
|
||||||
if (foldBtn) {
|
if (await handleMdCodeBlockUiClick(target)) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const block = foldBtn.closest('.md-codeblock');
|
|
||||||
if (!block) return;
|
|
||||||
const collapsed = block.classList.toggle('md-codeblock--collapsed');
|
|
||||||
const lineCount = parseInt(block.getAttribute('data-line-count') || '0', 10)
|
|
||||||
|| block.querySelectorAll('.md-code-line').length
|
|
||||||
|| 1;
|
|
||||||
if (collapsed && lineCount <= 5) block.classList.add('md-codeblock--short');
|
|
||||||
else block.classList.remove('md-codeblock--short');
|
|
||||||
foldBtn.textContent = collapsed ? '展开' : '收起';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const copyBtn = target.closest<HTMLElement>('[data-code-copy]');
|
|
||||||
if (copyBtn) {
|
|
||||||
e.preventDefault();
|
|
||||||
const block = copyBtn.closest('.md-codeblock');
|
|
||||||
const bodies = block?.querySelectorAll('.md-code-line__body');
|
|
||||||
const text = bodies && bodies.length
|
|
||||||
? [...bodies].map(el => el.textContent ?? '').join('\n')
|
|
||||||
: (block?.querySelector('pre')?.textContent ?? '');
|
|
||||||
try {
|
|
||||||
await navigator.clipboard.writeText(text);
|
|
||||||
const prev = copyBtn.textContent;
|
|
||||||
copyBtn.textContent = '已复制';
|
|
||||||
copyBtn.classList.add('is-copied');
|
|
||||||
window.setTimeout(() => {
|
|
||||||
copyBtn.textContent = prev || '复制';
|
|
||||||
copyBtn.classList.remove('is-copied');
|
|
||||||
}, 1600);
|
|
||||||
} catch {
|
|
||||||
notify.error('复制失败');
|
|
||||||
}
|
}
|
||||||
|
} catch {
|
||||||
|
notify.error('复制失败');
|
||||||
}
|
}
|
||||||
}, [nav, openLightbox, onRequestReply, onUnlocked, postId, unlocking]);
|
}, [nav, openLightbox, onRequestReply, onUnlocked, postId, unlocking]);
|
||||||
|
|
||||||
@@ -167,7 +129,7 @@ export default function PostContent({
|
|||||||
className={className}
|
className={className}
|
||||||
onClick={handleClick}
|
onClick={handleClick}
|
||||||
onKeyDown={handleKeyDown}
|
onKeyDown={handleKeyDown}
|
||||||
dangerouslySetInnerHTML={{ __html: prepared.html }}
|
dangerouslySetInnerHTML={{ __html: preparedHtml }}
|
||||||
/>
|
/>
|
||||||
<ImageLightbox
|
<ImageLightbox
|
||||||
src={lightboxSrc}
|
src={lightboxSrc}
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ function pickScrollEl(): HTMLElement | null {
|
|||||||
const page = document.querySelector<HTMLElement>('.page-wrap:not(.page-wrap--feed)');
|
const page = document.querySelector<HTMLElement>('.page-wrap:not(.page-wrap--feed)');
|
||||||
if (page) return page;
|
if (page) return page;
|
||||||
|
|
||||||
const showcase = document.querySelector<HTMLElement>('.showcase-page');
|
const showcase = document.querySelector<HTMLElement>('.showcase-panel');
|
||||||
if (showcase) return showcase.closest<HTMLElement>('.main-content') ?? showcase;
|
if (showcase) return showcase.closest<HTMLElement>('.main-content') ?? showcase;
|
||||||
|
|
||||||
const admin = document.querySelector<HTMLElement>('.admin-main');
|
const admin = document.querySelector<HTMLElement>('.admin-main');
|
||||||
|
|||||||
@@ -232,11 +232,13 @@ export default function RightPanel({
|
|||||||
<div className={`aside-panel-inner${isPostDetail ? ' aside-panel-inner--post-detail' : ''}`}>
|
<div className={`aside-panel-inner${isPostDetail ? ' aside-panel-inner--post-detail' : ''}`}>
|
||||||
{isPostDetail && (
|
{isPostDetail && (
|
||||||
<>
|
<>
|
||||||
<PostAuthorCard
|
{postDetail.author?.id ? (
|
||||||
author={postDetail.author}
|
<PostAuthorCard
|
||||||
publishedAt={postDetail.publishedAt}
|
author={postDetail.author}
|
||||||
viewCount={postDetail.viewCount}
|
publishedAt={postDetail.publishedAt}
|
||||||
/>
|
viewCount={postDetail.viewCount}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
<div className="widget-card widget-card--outline">
|
<div className="widget-card widget-card--outline">
|
||||||
<div className="widget-card-head">
|
<div className="widget-card-head">
|
||||||
<ListTree className="widget-card-icon widget-card-icon--outline" aria-hidden />
|
<ListTree className="widget-card-icon widget-card-icon--outline" aria-hidden />
|
||||||
|
|||||||
@@ -19,12 +19,14 @@ export default function ShowcaseAsideWidget() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
const hit = getSessionSnapshot<CommunityShowcaseItem[]>(SHOWCASE_KEY);
|
const hit = getSessionSnapshot<CommunityShowcaseItem[]>(SHOWCASE_KEY);
|
||||||
if (hit !== undefined) {
|
// 非空快照直接用;空数组可能是启动竞态假空,仍再拉
|
||||||
|
if (hit !== undefined && hit.length > 0) {
|
||||||
setItems(hit);
|
setItems(hit);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setLoading(true);
|
if (hit !== undefined) setItems(hit);
|
||||||
|
setLoading(hit === undefined);
|
||||||
api.communityShowcase()
|
api.communityShowcase()
|
||||||
.then((r) => {
|
.then((r) => {
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
@@ -33,10 +35,8 @@ export default function ShowcaseAsideWidget() {
|
|||||||
setItems(next);
|
setItems(next);
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
if (!cancelled) {
|
// 失败不写空快照,避免假空粘死
|
||||||
setSessionSnapshot(SHOWCASE_KEY, []);
|
if (!cancelled && hit === undefined) setItems([]);
|
||||||
setItems([]);
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
if (!cancelled) setLoading(false);
|
if (!cancelled) setLoading(false);
|
||||||
@@ -54,17 +54,13 @@ export default function ShowcaseAsideWidget() {
|
|||||||
setItems(next);
|
setItems(next);
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
if (opts.showLoading) {
|
// 软刷新 / 强刷失败:保持旧 UI,不写空快照
|
||||||
setSessionSnapshot(SHOWCASE_KEY, []);
|
|
||||||
setItems([]);
|
|
||||||
}
|
|
||||||
// 软刷新失败:保持旧 UI
|
|
||||||
})
|
})
|
||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
};
|
};
|
||||||
const applyHitOrReload = (showLoading: boolean) => {
|
const applyHitOrReload = (showLoading: boolean) => {
|
||||||
const hit = getSessionSnapshot<CommunityShowcaseItem[]>(SHOWCASE_KEY);
|
const hit = getSessionSnapshot<CommunityShowcaseItem[]>(SHOWCASE_KEY);
|
||||||
if (hit !== undefined) {
|
if (hit !== undefined && hit.length > 0) {
|
||||||
setItems(hit);
|
setItems(hit);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import type { FeedSortId, FeedSortTab } from '../../api/types';
|
|||||||
import { normalizeFeedSortTabs } from '../../utils/feedSortTabs';
|
import { normalizeFeedSortTabs } from '../../utils/feedSortTabs';
|
||||||
|
|
||||||
const TAB_META: Record<FeedSortId, { hint: string; placeholder: string }> = {
|
const TAB_META: Record<FeedSortId, { hint: string; placeholder: string }> = {
|
||||||
reply: { hint: '按最后评论时间', placeholder: '新评论' },
|
reply: { hint: '按最近活动(发帖或评论)', placeholder: '最新' },
|
||||||
latest: { hint: '按发帖时间', placeholder: '新帖子' },
|
latest: { hint: '按发帖时间', placeholder: '新帖子' },
|
||||||
hot: { hint: '仅展示推荐帖', placeholder: '推荐帖' },
|
hot: { hint: '仅展示推荐帖', placeholder: '推荐帖' },
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import Image from '@tiptap/extension-image';
|
import Image from '@tiptap/extension-image';
|
||||||
import { mergeAttributes } from '@tiptap/core';
|
import { mergeAttributes } from '@tiptap/core';
|
||||||
|
import { isStickerSrc } from './ArticleStickerExtension';
|
||||||
|
|
||||||
/** 单图展示形态(对齐 Notion / Medium 常见选项) */
|
/** 单图展示形态(对齐 Notion / Medium 常见选项) */
|
||||||
export type ImageDisplay = 'default' | 'wide' | 'float-left' | 'float-right';
|
export type ImageDisplay = 'default' | 'wide' | 'float-left' | 'float-right';
|
||||||
@@ -19,6 +20,19 @@ declare module '@tiptap/core' {
|
|||||||
export const ArticleImage = Image.extend({
|
export const ArticleImage = Image.extend({
|
||||||
name: 'image',
|
name: 'image',
|
||||||
|
|
||||||
|
parseHTML() {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
tag: this.options.allowBase64 ? 'img[src]' : 'img[src]:not([src^="data:"])',
|
||||||
|
getAttrs: (node) => {
|
||||||
|
if (typeof node === 'string') return false;
|
||||||
|
if (isStickerSrc(node.getAttribute('src'))) return false;
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
},
|
||||||
|
|
||||||
addAttributes() {
|
addAttributes() {
|
||||||
return {
|
return {
|
||||||
...this.parent?.(),
|
...this.parent?.(),
|
||||||
|
|||||||
351
frontend/src/components/editor/ArticleImagePickerDialog.tsx
Normal file
351
frontend/src/components/editor/ArticleImagePickerDialog.tsx
Normal file
@@ -0,0 +1,351 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState, type DragEvent } from 'react';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { notify } from '@/lib/notify';
|
||||||
|
import { api } from '@/api/client';
|
||||||
|
import type { MediaItem } from '@/api/types';
|
||||||
|
import { toPostImageThumbSrc } from '@/utils/postContent';
|
||||||
|
import { Upload, Link2, Images, Loader2 } from 'lucide-react';
|
||||||
|
|
||||||
|
export type ImagePickerTarget = 'rich' | 'markdown';
|
||||||
|
type PickerTab = 'upload' | 'link' | 'gallery';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
/** 上传或选中后插入一张或多张图片 URL */
|
||||||
|
onInsert: (urls: string[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 校验可插入的图片地址:外链或站内绝对路径 */
|
||||||
|
export function isValidImageSrc(url: string): boolean {
|
||||||
|
const u = url.trim();
|
||||||
|
if (!u) return false;
|
||||||
|
if (u.startsWith('/') && !u.startsWith('//')) return true;
|
||||||
|
try {
|
||||||
|
const parsed = new URL(u);
|
||||||
|
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const ACCEPT = 'image/jpeg,image/png,image/gif,image/webp';
|
||||||
|
const PAGE_SIZE = 24;
|
||||||
|
|
||||||
|
/** 文章编辑器:统一图片插入(上传 / 链接 / 我的图片) */
|
||||||
|
export function ArticleImagePickerDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
onInsert,
|
||||||
|
}: Props) {
|
||||||
|
const [tab, setTab] = useState<PickerTab>('upload');
|
||||||
|
const [url, setUrl] = useState('');
|
||||||
|
const [uploading, setUploading] = useState(false);
|
||||||
|
const [dragOver, setDragOver] = useState(false);
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
const [gallery, setGallery] = useState<MediaItem[]>([]);
|
||||||
|
const [galleryPage, setGalleryPage] = useState(1);
|
||||||
|
const [galleryTotalPages, setGalleryTotalPages] = useState(1);
|
||||||
|
const [galleryLoading, setGalleryLoading] = useState(false);
|
||||||
|
const [galleryLoaded, setGalleryLoaded] = useState(false);
|
||||||
|
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||||
|
|
||||||
|
const resetState = useCallback(() => {
|
||||||
|
setTab('upload');
|
||||||
|
setUrl('');
|
||||||
|
setUploading(false);
|
||||||
|
setDragOver(false);
|
||||||
|
setGallery([]);
|
||||||
|
setGalleryPage(1);
|
||||||
|
setGalleryTotalPages(1);
|
||||||
|
setGalleryLoading(false);
|
||||||
|
setGalleryLoaded(false);
|
||||||
|
setSelected(new Set());
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) resetState();
|
||||||
|
}, [open, resetState]);
|
||||||
|
|
||||||
|
const handleOpenChange = (next: boolean) => {
|
||||||
|
if (!next) resetState();
|
||||||
|
onOpenChange(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
const finishInsert = (urls: string[]) => {
|
||||||
|
if (!urls.length) return;
|
||||||
|
onInsert(urls);
|
||||||
|
handleOpenChange(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const uploadFiles = async (files: File[]) => {
|
||||||
|
const images = files.filter(f => f.type.startsWith('image/'));
|
||||||
|
if (!images.length) {
|
||||||
|
notify.warning('请选择图片文件(jpeg / png / gif / webp)');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setUploading(true);
|
||||||
|
const urls: string[] = [];
|
||||||
|
try {
|
||||||
|
for (const file of images) {
|
||||||
|
try {
|
||||||
|
const { url: uploaded } = await api.uploadPostImage(file);
|
||||||
|
urls.push(uploaded);
|
||||||
|
} catch (e: unknown) {
|
||||||
|
notify.error(e instanceof Error ? e.message : '图片上传失败');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (urls.length) finishInsert(urls);
|
||||||
|
} finally {
|
||||||
|
setUploading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const onFileChange = (list: FileList | null) => {
|
||||||
|
if (!list?.length) return;
|
||||||
|
void uploadFiles([...list]);
|
||||||
|
};
|
||||||
|
|
||||||
|
const onDrop = (e: DragEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDragOver(false);
|
||||||
|
if (uploading) return;
|
||||||
|
void uploadFiles([...e.dataTransfer.files]);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleLinkInsert = () => {
|
||||||
|
const next = url.trim();
|
||||||
|
if (!next) {
|
||||||
|
notify.warning('请输入图片地址');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!isValidImageSrc(next)) {
|
||||||
|
notify.warning('请使用 http(s) 外链或本站以 / 开头的路径');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
finishInsert([next]);
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadGallery = useCallback(async (page: number, append: boolean) => {
|
||||||
|
setGalleryLoading(true);
|
||||||
|
try {
|
||||||
|
const res = await api.myPostImages({ page, size: PAGE_SIZE });
|
||||||
|
setGallery(prev => (append ? [...prev, ...res.files] : res.files));
|
||||||
|
setGalleryPage(res.page);
|
||||||
|
setGalleryTotalPages(res.total_pages);
|
||||||
|
setGalleryLoaded(true);
|
||||||
|
} catch (e: unknown) {
|
||||||
|
notify.error(e instanceof Error ? e.message : '加载图片失败');
|
||||||
|
setGalleryLoaded(true);
|
||||||
|
} finally {
|
||||||
|
setGalleryLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open && tab === 'gallery' && !galleryLoaded && !galleryLoading) {
|
||||||
|
void loadGallery(1, false);
|
||||||
|
}
|
||||||
|
}, [open, tab, galleryLoaded, galleryLoading, loadGallery]);
|
||||||
|
|
||||||
|
const toggleSelect = (itemUrl: string) => {
|
||||||
|
setSelected(prev => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
if (next.has(itemUrl)) next.delete(itemUrl);
|
||||||
|
else next.add(itemUrl);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleGalleryInsert = () => {
|
||||||
|
if (!selected.size) {
|
||||||
|
notify.warning('请先选择图片');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 保持网格出现顺序
|
||||||
|
const urls = gallery.filter(f => selected.has(f.url)).map(f => f.url);
|
||||||
|
finishInsert(urls);
|
||||||
|
};
|
||||||
|
|
||||||
|
const tabs: { id: PickerTab; label: string; icon: typeof Upload }[] = [
|
||||||
|
{ id: 'upload', label: '上传', icon: Upload },
|
||||||
|
{ id: 'link', label: '链接', icon: Link2 },
|
||||||
|
{ id: 'gallery', label: '我的图片', icon: Images },
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||||||
|
<DialogContent className="article-image-picker">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>插入图片</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
上传本地文件、粘贴链接,或从已上传图库中选择。
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="article-image-picker__tabs" role="tablist">
|
||||||
|
{tabs.map(t => {
|
||||||
|
const Icon = t.icon;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={t.id}
|
||||||
|
type="button"
|
||||||
|
role="tab"
|
||||||
|
aria-selected={tab === t.id}
|
||||||
|
className={`article-image-picker__tab${tab === t.id ? ' is-active' : ''}`}
|
||||||
|
onClick={() => setTab(t.id)}
|
||||||
|
disabled={uploading}
|
||||||
|
>
|
||||||
|
<Icon size={14} aria-hidden />
|
||||||
|
{t.label}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{tab === 'upload' && (
|
||||||
|
<div className="article-image-picker__panel">
|
||||||
|
<div
|
||||||
|
className={`article-image-picker__drop${dragOver ? ' is-dragover' : ''}${uploading ? ' is-busy' : ''}`}
|
||||||
|
onDragOver={e => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!uploading) setDragOver(true);
|
||||||
|
}}
|
||||||
|
onDragLeave={() => setDragOver(false)}
|
||||||
|
onDrop={onDrop}
|
||||||
|
onClick={() => !uploading && fileInputRef.current?.click()}
|
||||||
|
role="button"
|
||||||
|
tabIndex={0}
|
||||||
|
onKeyDown={e => {
|
||||||
|
if (e.key === 'Enter' || e.key === ' ') {
|
||||||
|
e.preventDefault();
|
||||||
|
fileInputRef.current?.click();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{uploading ? (
|
||||||
|
<>
|
||||||
|
<Loader2 size={28} className="article-image-picker__spin" />
|
||||||
|
<p>正在上传…</p>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Upload size={28} />
|
||||||
|
<p>拖拽图片到此处,或点击选择文件</p>
|
||||||
|
<span>支持 jpeg / png / gif / webp;多选将并排成图组</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept={ACCEPT}
|
||||||
|
multiple
|
||||||
|
className="sr-only"
|
||||||
|
onChange={e => {
|
||||||
|
onFileChange(e.target.files);
|
||||||
|
e.target.value = '';
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{tab === 'link' && (
|
||||||
|
<div className="article-image-picker__panel">
|
||||||
|
<Input
|
||||||
|
type="url"
|
||||||
|
value={url}
|
||||||
|
placeholder="https://… 或 /uploads/posts/…"
|
||||||
|
onChange={e => setUrl(e.target.value)}
|
||||||
|
onKeyDown={e => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
handleLinkInsert();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
<p className="article-image-picker__hint">
|
||||||
|
粘贴外链或本站已上传地址,无需重复上传。
|
||||||
|
</p>
|
||||||
|
<DialogFooter className="article-image-picker__footer">
|
||||||
|
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)}>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button type="button" onClick={handleLinkInsert}>
|
||||||
|
插入
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{tab === 'gallery' && (
|
||||||
|
<div className="article-image-picker__panel">
|
||||||
|
{galleryLoading && !gallery.length ? (
|
||||||
|
<div className="article-image-picker__empty">
|
||||||
|
<Loader2 size={22} className="article-image-picker__spin" />
|
||||||
|
<span>加载中…</span>
|
||||||
|
</div>
|
||||||
|
) : !gallery.length ? (
|
||||||
|
<div className="article-image-picker__empty">暂无上传记录</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="article-image-picker__grid">
|
||||||
|
{gallery.map(item => {
|
||||||
|
const thumb = toPostImageThumbSrc(item.url) || item.url;
|
||||||
|
const isSel = selected.has(item.url);
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={item.url}
|
||||||
|
type="button"
|
||||||
|
className={`article-image-picker__thumb${isSel ? ' is-selected' : ''}`}
|
||||||
|
title={item.name}
|
||||||
|
onClick={() => toggleSelect(item.url)}
|
||||||
|
>
|
||||||
|
<img src={thumb} alt={item.name} loading="lazy" />
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
{galleryPage < galleryTotalPages && (
|
||||||
|
<div className="article-image-picker__more">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={galleryLoading}
|
||||||
|
onClick={() => void loadGallery(galleryPage + 1, true)}
|
||||||
|
>
|
||||||
|
{galleryLoading ? '加载中…' : '加载更多'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<DialogFooter className="article-image-picker__footer">
|
||||||
|
<span className="article-image-picker__selected-count">
|
||||||
|
已选 {selected.size}
|
||||||
|
</span>
|
||||||
|
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)}>
|
||||||
|
取消
|
||||||
|
</Button>
|
||||||
|
<Button type="button" disabled={!selected.size} onClick={handleGalleryInsert}>
|
||||||
|
插入选中
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,39 +1,172 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
Dialog,
|
Dialog,
|
||||||
DialogContent,
|
DialogContent,
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
DialogFooter,
|
||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from '@/components/ui/dialog';
|
} from '@/components/ui/dialog';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { notify } from '@/lib/notify';
|
||||||
|
import { api } from '@/api/client';
|
||||||
|
import type { PostItem, SitePageSummary } from '@/api/types';
|
||||||
|
import { pagePath, postPath } from '@/utils/permalink';
|
||||||
|
import { useForumLimits } from '@/hooks/useForumLimits';
|
||||||
|
import { ChevronDown, Loader2 } from 'lucide-react';
|
||||||
|
|
||||||
|
export interface ArticleLinkConfirm {
|
||||||
|
url: string;
|
||||||
|
text: string;
|
||||||
|
}
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
onOpenChange: (open: boolean) => void;
|
onOpenChange: (open: boolean) => void;
|
||||||
initialUrl?: string;
|
initialUrl?: string;
|
||||||
onConfirm: (url: string) => void;
|
initialText?: string;
|
||||||
|
/** 是否正在编辑已有链接 */
|
||||||
|
editing?: boolean;
|
||||||
|
onConfirm: (payload: ArticleLinkConfirm) => void;
|
||||||
onRemove?: () => void;
|
onRemove?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 文章编辑器链接输入弹窗 */
|
type SiteHit = {
|
||||||
|
key: string;
|
||||||
|
title: string;
|
||||||
|
url: string;
|
||||||
|
kind: 'post' | 'page';
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 校验可插入的链接地址:外链或站内绝对路径 */
|
||||||
|
export function isValidLinkHref(url: string): boolean {
|
||||||
|
const u = url.trim();
|
||||||
|
if (!u) return false;
|
||||||
|
if (u.startsWith('/') && !u.startsWith('//')) return true;
|
||||||
|
if (u.startsWith('#') && u.length > 1) return true;
|
||||||
|
try {
|
||||||
|
const parsed = new URL(u);
|
||||||
|
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const SEARCH_DEBOUNCE_MS = 300;
|
||||||
|
const POST_PAGE_SIZE = 12;
|
||||||
|
|
||||||
|
/** 文章/评论编辑器:插入或编辑链接(含站内内容搜索) */
|
||||||
export function ArticleLinkDialog({
|
export function ArticleLinkDialog({
|
||||||
open,
|
open,
|
||||||
onOpenChange,
|
onOpenChange,
|
||||||
initialUrl = '',
|
initialUrl = '',
|
||||||
|
initialText = '',
|
||||||
|
editing = false,
|
||||||
onConfirm,
|
onConfirm,
|
||||||
onRemove,
|
onRemove,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const [url, setUrl] = useState(initialUrl);
|
const { limits } = useForumLimits();
|
||||||
|
const [url, setUrl] = useState('');
|
||||||
|
const [text, setText] = useState('');
|
||||||
|
const [advancedOpen, setAdvancedOpen] = useState(false);
|
||||||
|
const [query, setQuery] = useState('');
|
||||||
|
const [debouncedQuery, setDebouncedQuery] = useState('');
|
||||||
|
const [posts, setPosts] = useState<PostItem[]>([]);
|
||||||
|
const [pages, setPages] = useState<SitePageSummary[]>([]);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [loaded, setLoaded] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (open) setUrl(initialUrl || 'https://');
|
if (!open) return;
|
||||||
}, [open, initialUrl]);
|
setUrl(initialUrl || '');
|
||||||
|
setText(initialText || '');
|
||||||
|
setAdvancedOpen(false);
|
||||||
|
setQuery('');
|
||||||
|
setDebouncedQuery('');
|
||||||
|
setPosts([]);
|
||||||
|
setPages([]);
|
||||||
|
setLoaded(false);
|
||||||
|
}, [open, initialUrl, initialText]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || !advancedOpen) return;
|
||||||
|
const t = window.setTimeout(() => setDebouncedQuery(query.trim()), SEARCH_DEBOUNCE_MS);
|
||||||
|
return () => window.clearTimeout(t);
|
||||||
|
}, [query, open, advancedOpen]);
|
||||||
|
|
||||||
|
const loadSiteHits = useCallback(async (keyword: string) => {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const [postsRes, pagesRes] = await Promise.all([
|
||||||
|
api.posts({
|
||||||
|
page: 1,
|
||||||
|
size: POST_PAGE_SIZE,
|
||||||
|
sort: 'new',
|
||||||
|
...(keyword ? { keyword, title_only: '1' } : {}),
|
||||||
|
}),
|
||||||
|
api.pages(),
|
||||||
|
]);
|
||||||
|
setPosts(postsRes.posts || []);
|
||||||
|
let nextPages = pagesRes.pages || [];
|
||||||
|
if (keyword) {
|
||||||
|
const q = keyword.toLowerCase();
|
||||||
|
nextPages = nextPages.filter(
|
||||||
|
p => p.title.toLowerCase().includes(q) || p.slug.toLowerCase().includes(q),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
setPages(nextPages.slice(0, POST_PAGE_SIZE));
|
||||||
|
setLoaded(true);
|
||||||
|
} catch (e: unknown) {
|
||||||
|
notify.error(e instanceof Error ? e.message : '加载站内内容失败');
|
||||||
|
setLoaded(true);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 仅展开高级选项时再请求站内内容,避免默认打开就打接口
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || !advancedOpen) return;
|
||||||
|
void loadSiteHits(debouncedQuery);
|
||||||
|
}, [open, advancedOpen, debouncedQuery, loadSiteHits]);
|
||||||
|
|
||||||
|
const hits: SiteHit[] = useMemo(() => {
|
||||||
|
const postHits: SiteHit[] = posts.map(p => ({
|
||||||
|
key: `post-${p.id}`,
|
||||||
|
title: p.title,
|
||||||
|
url: postPath(p.id, limits),
|
||||||
|
kind: 'post',
|
||||||
|
}));
|
||||||
|
const pageHits: SiteHit[] = pages.map(p => ({
|
||||||
|
key: `page-${p.slug}`,
|
||||||
|
title: p.title,
|
||||||
|
url: pagePath(p.slug, limits),
|
||||||
|
kind: 'page',
|
||||||
|
}));
|
||||||
|
return [...postHits, ...pageHits];
|
||||||
|
}, [posts, pages, limits]);
|
||||||
|
|
||||||
|
const pickHit = (hit: SiteHit) => {
|
||||||
|
setUrl(hit.url);
|
||||||
|
// 选站内内容时同步用标题作为链接文字
|
||||||
|
setText(hit.title);
|
||||||
|
};
|
||||||
|
|
||||||
const handleConfirm = () => {
|
const handleConfirm = () => {
|
||||||
onConfirm(url.trim());
|
const nextUrl = url.trim();
|
||||||
|
if (!nextUrl) {
|
||||||
|
notify.warning('请输入网址');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!isValidLinkHref(nextUrl)) {
|
||||||
|
notify.warning('请使用 http(s) 外链或本站以 / 开头的路径');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onConfirm({
|
||||||
|
url: nextUrl,
|
||||||
|
text: text.trim() || '链接文字',
|
||||||
|
});
|
||||||
onOpenChange(false);
|
onOpenChange(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -41,25 +174,119 @@ export function ArticleLinkDialog({
|
|||||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
<DialogContent className="article-link-dialog">
|
<DialogContent className="article-link-dialog">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle>插入链接</DialogTitle>
|
<DialogTitle>插入或编辑链接</DialogTitle>
|
||||||
<DialogDescription>输入完整 URL,留空并确认可移除已有链接。</DialogDescription>
|
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<Input
|
|
||||||
type="url"
|
<section className="article-link-dialog__section">
|
||||||
value={url}
|
<div className="article-link-dialog__field">
|
||||||
placeholder="https://"
|
<Label htmlFor="article-link-url">网址</Label>
|
||||||
onChange={e => setUrl(e.target.value)}
|
<Input
|
||||||
onKeyDown={e => {
|
id="article-link-url"
|
||||||
if (e.key === 'Enter') {
|
type="url"
|
||||||
e.preventDefault();
|
value={url}
|
||||||
handleConfirm();
|
placeholder="https://… 或 /post/123"
|
||||||
}
|
onChange={e => setUrl(e.target.value)}
|
||||||
}}
|
onKeyDown={e => {
|
||||||
autoFocus
|
if (e.key === 'Enter') {
|
||||||
/>
|
e.preventDefault();
|
||||||
|
handleConfirm();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="article-link-dialog__field">
|
||||||
|
<Label htmlFor="article-link-text">链接文字</Label>
|
||||||
|
<Input
|
||||||
|
id="article-link-text"
|
||||||
|
value={text}
|
||||||
|
placeholder="显示在正文中的文字"
|
||||||
|
onChange={e => setText(e.target.value)}
|
||||||
|
onKeyDown={e => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
handleConfirm();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="article-link-dialog__section article-link-dialog__advanced">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`article-link-dialog__advanced-toggle${advancedOpen ? ' is-open' : ''}`}
|
||||||
|
aria-expanded={advancedOpen}
|
||||||
|
onClick={() => setAdvancedOpen(v => !v)}
|
||||||
|
>
|
||||||
|
<span>高级选项</span>
|
||||||
|
<ChevronDown size={16} aria-hidden className="article-link-dialog__advanced-chevron" />
|
||||||
|
</button>
|
||||||
|
{advancedOpen ? (
|
||||||
|
<div className="article-link-dialog__advanced-body">
|
||||||
|
<h3 className="article-link-dialog__section-title">链接到站点中的内容</h3>
|
||||||
|
<div className="article-link-dialog__field">
|
||||||
|
<Label htmlFor="article-link-search">搜索</Label>
|
||||||
|
<Input
|
||||||
|
id="article-link-search"
|
||||||
|
type="search"
|
||||||
|
value={query}
|
||||||
|
placeholder="搜索帖子或单页…"
|
||||||
|
onChange={e => setQuery(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="article-link-dialog__hits">
|
||||||
|
<p className="article-link-dialog__hits-hint">
|
||||||
|
{debouncedQuery
|
||||||
|
? `搜索「${debouncedQuery}」`
|
||||||
|
: '未指定搜索条件。自动显示最近发布条目。'}
|
||||||
|
</p>
|
||||||
|
{loading && !loaded ? (
|
||||||
|
<div className="article-link-dialog__hits-empty">
|
||||||
|
<Loader2 size={18} className="article-link-dialog__spin" />
|
||||||
|
<span>加载中…</span>
|
||||||
|
</div>
|
||||||
|
) : !hits.length ? (
|
||||||
|
<div className="article-link-dialog__hits-empty">暂无匹配内容</div>
|
||||||
|
) : (
|
||||||
|
<ul className="article-link-dialog__hit-list">
|
||||||
|
{hits.map(hit => (
|
||||||
|
<li key={hit.key}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`article-link-dialog__hit${url === hit.url ? ' is-selected' : ''}`}
|
||||||
|
onClick={() => pickHit(hit)}
|
||||||
|
>
|
||||||
|
<span className="article-link-dialog__hit-title">{hit.title}</span>
|
||||||
|
<span className="article-link-dialog__hit-kind">
|
||||||
|
{hit.kind === 'post' ? '帖子' : '单页'}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
{loading && loaded ? (
|
||||||
|
<div className="article-link-dialog__hits-loading">
|
||||||
|
<Loader2 size={14} className="article-link-dialog__spin" />
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</section>
|
||||||
|
|
||||||
<DialogFooter className="article-link-dialog__footer">
|
<DialogFooter className="article-link-dialog__footer">
|
||||||
{onRemove && initialUrl ? (
|
{editing && onRemove ? (
|
||||||
<Button type="button" variant="outline" onClick={() => { onRemove(); onOpenChange(false); }}>
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
className="article-link-dialog__remove"
|
||||||
|
onClick={() => {
|
||||||
|
onRemove();
|
||||||
|
onOpenChange(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
移除链接
|
移除链接
|
||||||
</Button>
|
</Button>
|
||||||
) : null}
|
) : null}
|
||||||
@@ -67,7 +294,7 @@ export function ArticleLinkDialog({
|
|||||||
取消
|
取消
|
||||||
</Button>
|
</Button>
|
||||||
<Button type="button" onClick={handleConfirm}>
|
<Button type="button" onClick={handleConfirm}>
|
||||||
确定
|
{editing ? '更新链接' : '添加链接'}
|
||||||
</Button>
|
</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
|
|||||||
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: ['怀疑', '思考'] },
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -13,15 +13,22 @@ type Fetcher<T> = () => Promise<T>;
|
|||||||
* 会话快照数据源:有缓存则跳过请求;无缓存时保留上一份画面直到新数据返回。
|
* 会话快照数据源:有缓存则跳过请求;无缓存时保留上一份画面直到新数据返回。
|
||||||
* 手机下拉软刷新 commit / PAGE_FORCE_REFRESH_EVENT 会应用新快照。
|
* 手机下拉软刷新 commit / PAGE_FORCE_REFRESH_EVENT 会应用新快照。
|
||||||
*/
|
*/
|
||||||
|
function isEmptyArray(value: unknown): boolean {
|
||||||
|
return Array.isArray(value) && value.length === 0;
|
||||||
|
}
|
||||||
|
|
||||||
export function useSessionResource<T>(
|
export function useSessionResource<T>(
|
||||||
key: string | null,
|
key: string | null,
|
||||||
fetcher: Fetcher<T>,
|
fetcher: Fetcher<T>,
|
||||||
opts?: {
|
opts?: {
|
||||||
enabled?: boolean;
|
enabled?: boolean;
|
||||||
onError?: (e: unknown) => void;
|
onError?: (e: unknown) => void;
|
||||||
|
/** 缓存为空数组时仍后台再拉,避免启动竞态假空粘死 */
|
||||||
|
revalidateEmpty?: boolean;
|
||||||
},
|
},
|
||||||
) {
|
) {
|
||||||
const enabled = opts?.enabled !== false;
|
const enabled = opts?.enabled !== false;
|
||||||
|
const revalidateEmpty = opts?.revalidateEmpty === true;
|
||||||
const fetcherRef = useRef(fetcher);
|
const fetcherRef = useRef(fetcher);
|
||||||
fetcherRef.current = fetcher;
|
fetcherRef.current = fetcher;
|
||||||
const onErrorRef = useRef(opts?.onError);
|
const onErrorRef = useRef(opts?.onError);
|
||||||
@@ -49,7 +56,7 @@ export function useSessionResource<T>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const hit = getSessionSnapshot<T>(key);
|
const hit = getSessionSnapshot<T>(key);
|
||||||
if (hit !== undefined) {
|
if (hit !== undefined && !(revalidateEmpty && isEmptyArray(hit))) {
|
||||||
setData(hit);
|
setData(hit);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
setPending(false);
|
setPending(false);
|
||||||
@@ -57,9 +64,16 @@ export function useSessionResource<T>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const seq = ++seqRef.current;
|
const seq = ++seqRef.current;
|
||||||
const keep = dataRef.current !== undefined;
|
const keep = dataRef.current !== undefined || (hit !== undefined && isEmptyArray(hit));
|
||||||
if (keep) setPending(true);
|
if (hit !== undefined && isEmptyArray(hit)) {
|
||||||
else setLoading(true);
|
setData(hit);
|
||||||
|
setPending(true);
|
||||||
|
setLoading(false);
|
||||||
|
} else if (keep && dataRef.current !== undefined) {
|
||||||
|
setPending(true);
|
||||||
|
} else {
|
||||||
|
setLoading(true);
|
||||||
|
}
|
||||||
|
|
||||||
fetcherRef.current()
|
fetcherRef.current()
|
||||||
.then((next) => {
|
.then((next) => {
|
||||||
@@ -70,6 +84,7 @@ export function useSessionResource<T>(
|
|||||||
.catch((e: unknown) => {
|
.catch((e: unknown) => {
|
||||||
if (seq !== seqRef.current) return;
|
if (seq !== seqRef.current) return;
|
||||||
onErrorRef.current?.(e);
|
onErrorRef.current?.(e);
|
||||||
|
// 失败不写空快照;已有画面则保留
|
||||||
if (!keep) setData(undefined);
|
if (!keep) setData(undefined);
|
||||||
})
|
})
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
@@ -81,7 +96,7 @@ export function useSessionResource<T>(
|
|||||||
return () => {
|
return () => {
|
||||||
seqRef.current += 1;
|
seqRef.current += 1;
|
||||||
};
|
};
|
||||||
}, [key, enabled]);
|
}, [key, enabled, revalidateEmpty]);
|
||||||
|
|
||||||
const replace = useCallback((next: T | ((prev: T | undefined) => T)) => {
|
const replace = useCallback((next: T | ((prev: T | undefined) => T)) => {
|
||||||
setData((prev) => {
|
setData((prev) => {
|
||||||
@@ -99,18 +114,20 @@ export function useSessionResource<T>(
|
|||||||
const reload = (opts: { allowLoading: boolean }) => {
|
const reload = (opts: { allowLoading: boolean }) => {
|
||||||
if (!key || !enabled) return;
|
if (!key || !enabled) return;
|
||||||
const warm = getSessionSnapshot<T>(key);
|
const warm = getSessionSnapshot<T>(key);
|
||||||
if (warm !== undefined) {
|
if (warm !== undefined && !(revalidateEmpty && isEmptyArray(warm))) {
|
||||||
setData(warm);
|
setData(warm);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
setPending(false);
|
setPending(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const seq = ++seqRef.current;
|
const seq = ++seqRef.current;
|
||||||
const keep = dataRef.current !== undefined;
|
const keep = dataRef.current !== undefined || (warm !== undefined && isEmptyArray(warm));
|
||||||
if (opts.allowLoading) {
|
if (opts.allowLoading) {
|
||||||
deleteSessionSnapshot(key);
|
deleteSessionSnapshot(key);
|
||||||
if (keep) setPending(true);
|
if (keep) setPending(true);
|
||||||
else setLoading(true);
|
else setLoading(true);
|
||||||
|
} else if (warm !== undefined && isEmptyArray(warm)) {
|
||||||
|
setPending(true);
|
||||||
}
|
}
|
||||||
fetcherRef.current()
|
fetcherRef.current()
|
||||||
.then((next) => {
|
.then((next) => {
|
||||||
@@ -138,7 +155,7 @@ export function useSessionResource<T>(
|
|||||||
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
window.removeEventListener(PAGE_FORCE_REFRESH_EVENT, onForce);
|
||||||
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
window.removeEventListener(PAGE_SOFT_REFRESH_COMMIT_EVENT, onCommit);
|
||||||
};
|
};
|
||||||
}, [key, enabled]);
|
}, [key, enabled, revalidateEmpty]);
|
||||||
|
|
||||||
return { data, loading, pending, replace, invalidate };
|
return { data, loading, pending, replace, invalidate };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -72,6 +72,8 @@ export default function MainLayout() {
|
|||||||
const [recentComments, setRecentComments] = useState<RecentComment[]>(() => getCachedRecentComments());
|
const [recentComments, setRecentComments] = useState<RecentComment[]>(() => getCachedRecentComments());
|
||||||
const [recentUsers, setRecentUsers] = useState<RecentUser[]>(() => getCachedRecentUsers());
|
const [recentUsers, setRecentUsers] = useState<RecentUser[]>(() => getCachedRecentUsers());
|
||||||
const [unreadMessages, setUnreadMessages] = useState(() => getBootUnread());
|
const [unreadMessages, setUnreadMessages] = useState(() => getBootUnread());
|
||||||
|
const [dmUnread, setDmUnread] = useState(0);
|
||||||
|
const [notifyUnread, setNotifyUnread] = useState(0);
|
||||||
const [tags, setTags] = useState<TagCount[]>(() => getCachedTags());
|
const [tags, setTags] = useState<TagCount[]>(() => getCachedTags());
|
||||||
const [tagsLoading, setTagsLoading] = useState(() => getCachedTags().length === 0);
|
const [tagsLoading, setTagsLoading] = useState(() => getCachedTags().length === 0);
|
||||||
const [postOutline, setPostOutline] = useState<{
|
const [postOutline, setPostOutline] = useState<{
|
||||||
@@ -148,7 +150,10 @@ export default function MainLayout() {
|
|||||||
setSidebarOpen(false);
|
setSidebarOpen(false);
|
||||||
}, [loc.pathname, loc.search]);
|
}, [loc.pathname, loc.search]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!/^\/post\/\d+/.test(loc.pathname)) setPostOutline(null);
|
const isArticleAside =
|
||||||
|
(/^\/post\/\d+/.test(loc.pathname) && !/\/edit$/.test(loc.pathname))
|
||||||
|
|| /^\/page\//.test(loc.pathname);
|
||||||
|
if (!isArticleAside) setPostOutline(null);
|
||||||
}, [loc.pathname]);
|
}, [loc.pathname]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!hideAside) setAsideOpen(false);
|
if (!hideAside) setAsideOpen(false);
|
||||||
@@ -306,13 +311,29 @@ export default function MainLayout() {
|
|||||||
const refreshUnreadMessages = useCallback(() => {
|
const refreshUnreadMessages = useCallback(() => {
|
||||||
if (!user) {
|
if (!user) {
|
||||||
setUnreadMessages(0);
|
setUnreadMessages(0);
|
||||||
|
setDmUnread(0);
|
||||||
|
setNotifyUnread(0);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
api.messageUnreadCount()
|
api.messageUnreadCount()
|
||||||
.then((r) => setUnreadMessages(r.count || 0))
|
.then((r) => {
|
||||||
.catch(() => setUnreadMessages(0));
|
setUnreadMessages(r.count || 0);
|
||||||
|
setDmUnread(r.dm_count ?? 0);
|
||||||
|
setNotifyUnread(r.notify_count ?? 0);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
setUnreadMessages(0);
|
||||||
|
setDmUnread(0);
|
||||||
|
setNotifyUnread(0);
|
||||||
|
});
|
||||||
}, [user]);
|
}, [user]);
|
||||||
|
|
||||||
|
/** 仅有通知未读时直达通知 Tab,避免先看到空私信列表 */
|
||||||
|
const openMessages = useCallback(() => {
|
||||||
|
const path = notifyUnread > 0 && dmUnread === 0 ? '/messages?tab=notify' : '/messages';
|
||||||
|
void transitionTo(nav, path);
|
||||||
|
}, [nav, notifyUnread, dmUnread]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
refreshUnreadMessages();
|
refreshUnreadMessages();
|
||||||
const onRefresh = () => refreshUnreadMessages();
|
const onRefresh = () => refreshUnreadMessages();
|
||||||
@@ -477,6 +498,10 @@ export default function MainLayout() {
|
|||||||
const activeChipIndex = Math.max(0, boardChipIds.indexOf(mobileActiveBoard === -1 ? 0 : mobileActiveBoard));
|
const activeChipIndex = Math.max(0, boardChipIds.indexOf(mobileActiveBoard === -1 ? 0 : mobileActiveBoard));
|
||||||
|
|
||||||
const isPostDetail = /^\/post\/\d+/.test(loc.pathname) && !/\/edit$/.test(loc.pathname);
|
const isPostDetail = /^\/post\/\d+/.test(loc.pathname) && !/\/edit$/.test(loc.pathname);
|
||||||
|
const isSitePage = /^\/page\//.test(loc.pathname);
|
||||||
|
const isArticleAside = isPostDetail || isSitePage;
|
||||||
|
// 帖子有作者 →「作者与目录」;单页仅目录
|
||||||
|
const articleAsideLabel = isPostDetail ? '作者与目录' : '文章目录';
|
||||||
const setPostOutlineSafe = useCallback((outline: {
|
const setPostOutlineSafe = useCallback((outline: {
|
||||||
headings: PostHeading[];
|
headings: PostHeading[];
|
||||||
scrollRoot: HTMLElement | null;
|
scrollRoot: HTMLElement | null;
|
||||||
@@ -632,10 +657,10 @@ export default function MainLayout() {
|
|||||||
type="button"
|
type="button"
|
||||||
className="header-icon-btn"
|
className="header-icon-btn"
|
||||||
onClick={openAside}
|
onClick={openAside}
|
||||||
aria-label={isPostDetail ? '打开作者与目录' : '打开社区动态'}
|
aria-label={isArticleAside ? `打开${articleAsideLabel}` : '打开社区动态'}
|
||||||
aria-expanded={asideOpen}
|
aria-expanded={asideOpen}
|
||||||
aria-controls="aside-drawer"
|
aria-controls="aside-drawer"
|
||||||
title={isPostDetail ? '作者与目录' : '社区动态'}
|
title={isArticleAside ? articleAsideLabel : '社区动态'}
|
||||||
>
|
>
|
||||||
<PanelRight size={18} aria-hidden />
|
<PanelRight size={18} aria-hidden />
|
||||||
</button>
|
</button>
|
||||||
@@ -660,7 +685,7 @@ export default function MainLayout() {
|
|||||||
className="header-icon-btn header-msg-btn"
|
className="header-icon-btn header-msg-btn"
|
||||||
title={unreadMessages > 0 ? `${unreadMessages} 条未读消息` : '站内消息'}
|
title={unreadMessages > 0 ? `${unreadMessages} 条未读消息` : '站内消息'}
|
||||||
aria-label={unreadMessages > 0 ? `站内消息,${unreadMessages} 条未读` : '站内消息'}
|
aria-label={unreadMessages > 0 ? `站内消息,${unreadMessages} 条未读` : '站内消息'}
|
||||||
onClick={() => void transitionTo(nav, '/messages')}
|
onClick={openMessages}
|
||||||
>
|
>
|
||||||
<Mail size={18} aria-hidden />
|
<Mail size={18} aria-hidden />
|
||||||
{unreadMessages > 0 && (
|
{unreadMessages > 0 && (
|
||||||
@@ -684,7 +709,7 @@ export default function MainLayout() {
|
|||||||
<DropdownMenuItem onClick={() => void transitionTo(nav, '/profile')}>
|
<DropdownMenuItem onClick={() => void transitionTo(nav, '/profile')}>
|
||||||
账号设置{typeof user.points === 'number' ? ` · ${user.points} 积分` : ''}
|
账号设置{typeof user.points === 'number' ? ` · ${user.points} 积分` : ''}
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem onClick={() => void transitionTo(nav, '/messages')}>
|
<DropdownMenuItem onClick={openMessages}>
|
||||||
站内消息{unreadMessages > 0 ? ` (${unreadMessages})` : ''}
|
站内消息{unreadMessages > 0 ? ` (${unreadMessages})` : ''}
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem onClick={() => void transitionTo(nav, '/favorites')}>我的收藏</DropdownMenuItem>
|
<DropdownMenuItem onClick={() => void transitionTo(nav, '/favorites')}>我的收藏</DropdownMenuItem>
|
||||||
@@ -815,7 +840,7 @@ export default function MainLayout() {
|
|||||||
asideWidgets={asideWidgets}
|
asideWidgets={asideWidgets}
|
||||||
onPostClick={openPost}
|
onPostClick={openPost}
|
||||||
|
|
||||||
postDetail={isPostDetail ? {
|
postDetail={isArticleAside ? {
|
||||||
author: postOutline?.author ?? null,
|
author: postOutline?.author ?? null,
|
||||||
publishedAt: postOutline?.publishedAt,
|
publishedAt: postOutline?.publishedAt,
|
||||||
viewCount: postOutline?.viewCount,
|
viewCount: postOutline?.viewCount,
|
||||||
@@ -879,7 +904,7 @@ export default function MainLayout() {
|
|||||||
onClick={() => { closeSidebar(); openAside(); }}
|
onClick={() => { closeSidebar(); openAside(); }}
|
||||||
>
|
>
|
||||||
<PanelRight size={16} aria-hidden />
|
<PanelRight size={16} aria-hidden />
|
||||||
{isPostDetail ? '作者与目录' : '社区动态'}
|
{isArticleAside ? articleAsideLabel : '社区动态'}
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -910,10 +935,10 @@ export default function MainLayout() {
|
|||||||
className="aside-drawer"
|
className="aside-drawer"
|
||||||
role="dialog"
|
role="dialog"
|
||||||
aria-modal="true"
|
aria-modal="true"
|
||||||
aria-label={isPostDetail ? '作者与目录' : '社区动态'}
|
aria-label={isArticleAside ? articleAsideLabel : '社区动态'}
|
||||||
>
|
>
|
||||||
<div className="aside-drawer-head">
|
<div className="aside-drawer-head">
|
||||||
<span>{isPostDetail ? '作者与目录' : '社区动态'}</span>
|
<span>{isArticleAside ? articleAsideLabel : '社区动态'}</span>
|
||||||
<button
|
<button
|
||||||
ref={asideCloseRef}
|
ref={asideCloseRef}
|
||||||
type="button"
|
type="button"
|
||||||
@@ -934,7 +959,7 @@ export default function MainLayout() {
|
|||||||
loading={asideLoading}
|
loading={asideLoading}
|
||||||
asideWidgets={asideWidgets}
|
asideWidgets={asideWidgets}
|
||||||
onPostClick={openPost}
|
onPostClick={openPost}
|
||||||
postDetail={isPostDetail ? {
|
postDetail={isArticleAside ? {
|
||||||
author: postOutline?.author ?? null,
|
author: postOutline?.author ?? null,
|
||||||
publishedAt: postOutline?.publishedAt,
|
publishedAt: postOutline?.publishedAt,
|
||||||
viewCount: postOutline?.viewCount,
|
viewCount: postOutline?.viewCount,
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,4 @@
|
|||||||
import { useState, useEffect, useLayoutEffect, useRef, useCallback } from 'react';
|
import { useState, useEffect, useLayoutEffect, useRef, useCallback, useMemo } from 'react';
|
||||||
import { useParams, useNavigate, useOutletContext, useLocation, useNavigationType } from 'react-router-dom';
|
import { useParams, useNavigate, useOutletContext, useLocation, useNavigationType } from 'react-router-dom';
|
||||||
import { ArrowLeft, ThumbsUp, Star, Lock, MessageSquare, MessageSquareOff, Flag, MoreHorizontal } from 'lucide-react';
|
import { ArrowLeft, ThumbsUp, Star, Lock, MessageSquare, MessageSquareOff, Flag, MoreHorizontal } from 'lucide-react';
|
||||||
import FeaturedIcon from '@/components/FeaturedIcon';
|
import FeaturedIcon from '@/components/FeaturedIcon';
|
||||||
@@ -60,7 +60,8 @@ import { excerptFromHTML, firstImageFromHTML } from '../utils/seoText';
|
|||||||
import { canonicalRedirectPath, parsePermalinkID, postPath } from '../utils/permalink';
|
import { canonicalRedirectPath, parsePermalinkID, postPath } from '../utils/permalink';
|
||||||
import { useForumLimits } from '../hooks/useForumLimits';
|
import { useForumLimits } from '../hooks/useForumLimits';
|
||||||
import type { LayoutCtx } from '../layouts/MainLayout';
|
import type { LayoutCtx } from '../layouts/MainLayout';
|
||||||
import type { PostHeading } from '../utils/postHeadings';
|
import { extractHeadingsFromHtml } from '../utils/postHeadings';
|
||||||
|
import { renderPostContentHtml } from '../utils/postContent';
|
||||||
import { InFlowSiteFooter } from '../components/SiteFooter';
|
import { InFlowSiteFooter } from '../components/SiteFooter';
|
||||||
import NotFoundPage from './NotFoundPage';
|
import NotFoundPage from './NotFoundPage';
|
||||||
|
|
||||||
@@ -132,7 +133,6 @@ export default function PostDetailPage() {
|
|||||||
const [deletingPost, setDeletingPost] = useState(false);
|
const [deletingPost, setDeletingPost] = useState(false);
|
||||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||||
const [composerOpen, setComposerOpen] = useState(false);
|
const [composerOpen, setComposerOpen] = useState(false);
|
||||||
const [headings, setHeadings] = useState<PostHeading[]>([]);
|
|
||||||
const [reportOpen, setReportOpen] = useState(false);
|
const [reportOpen, setReportOpen] = useState(false);
|
||||||
const [reportReason, setReportReason] = useState<ReportReason>('spam');
|
const [reportReason, setReportReason] = useState<ReportReason>('spam');
|
||||||
const [reportDetail, setReportDetail] = useState('');
|
const [reportDetail, setReportDetail] = useState('');
|
||||||
@@ -173,6 +173,15 @@ export default function PostDetailPage() {
|
|||||||
|
|
||||||
const brand = getCachedSiteBranding();
|
const brand = getCachedSiteBranding();
|
||||||
const postContent = post?.content ?? '';
|
const postContent = post?.content ?? '';
|
||||||
|
const isLoggedIn = !!user;
|
||||||
|
// 同步从正文派生目录,避免预取缓存命中后 setHeadings([]) 盖掉子组件上报且不再回调
|
||||||
|
const headings = useMemo(() => {
|
||||||
|
if (!postContent.trim()) return [];
|
||||||
|
const rendered = renderPostContentHtml(postContent, isLoggedIn, {
|
||||||
|
openLinksInNewTab: limits.open_content_links_in_new_tab,
|
||||||
|
});
|
||||||
|
return extractHeadingsFromHtml(rendered);
|
||||||
|
}, [postContent, isLoggedIn, limits.open_content_links_in_new_tab]);
|
||||||
const postSEO = post ? {
|
const postSEO = post ? {
|
||||||
title: post.title,
|
title: post.title,
|
||||||
description: excerptFromHTML(postContent),
|
description: excerptFromHTML(postContent),
|
||||||
@@ -196,10 +205,6 @@ export default function PostDetailPage() {
|
|||||||
} : null;
|
} : null;
|
||||||
usePageSEO(postSEO);
|
usePageSEO(postSEO);
|
||||||
|
|
||||||
const handleHeadingsChange = useCallback((next: PostHeading[]) => {
|
|
||||||
setHeadings(next);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (loading || !post) {
|
if (loading || !post) {
|
||||||
setPostOutline({ headings: [], scrollRoot: null, title: '文章目录' });
|
setPostOutline({ headings: [], scrollRoot: null, title: '文章目录' });
|
||||||
@@ -263,7 +268,6 @@ export default function PostDetailPage() {
|
|||||||
setReplyTo(null);
|
setReplyTo(null);
|
||||||
setEditingCommentId(null);
|
setEditingCommentId(null);
|
||||||
setComposerOpen(false);
|
setComposerOpen(false);
|
||||||
setHeadings([]);
|
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -272,7 +276,6 @@ export default function PostDetailPage() {
|
|||||||
setReplyTo(null);
|
setReplyTo(null);
|
||||||
setEditingCommentId(null);
|
setEditingCommentId(null);
|
||||||
setComposerOpen(false);
|
setComposerOpen(false);
|
||||||
setHeadings([]);
|
|
||||||
if (!keep) {
|
if (!keep) {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setPost(null);
|
setPost(null);
|
||||||
@@ -1124,9 +1127,8 @@ export default function PostDetailPage() {
|
|||||||
|
|
||||||
<PostContent
|
<PostContent
|
||||||
html={post.content || ''}
|
html={post.content || ''}
|
||||||
isLoggedIn={!!user}
|
isLoggedIn={isLoggedIn}
|
||||||
postId={post.id}
|
postId={post.id}
|
||||||
onHeadingsChange={handleHeadingsChange}
|
|
||||||
onRequestReply={scrollToCommentBox}
|
onRequestReply={scrollToCommentBox}
|
||||||
onUnlocked={() => { void reloadPostContent(); }}
|
onUnlocked={() => { void reloadPostContent(); }}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
import { ExternalLink, Globe2 } from 'lucide-react';
|
import { useState } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { ArrowLeft, ExternalLink, Globe2 } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
import { Spinner } from '@/components/ui/spinner';
|
import { Spinner } from '@/components/ui/spinner';
|
||||||
import { api } from '../api/client';
|
import { api } from '../api/client';
|
||||||
import type { CommunityShowcaseItem } from '../api/types';
|
import type { CommunityShowcaseItem } from '../api/types';
|
||||||
@@ -7,12 +10,65 @@ import { getCachedSiteBranding, useSiteBranding } from '../hooks/useSiteBranding
|
|||||||
import { InFlowSiteFooter } from '../components/SiteFooter';
|
import { InFlowSiteFooter } from '../components/SiteFooter';
|
||||||
import { useSessionResource } from '../hooks/useSessionResource';
|
import { useSessionResource } from '../hooks/useSessionResource';
|
||||||
|
|
||||||
|
function siteMark(name: string, url: string): string {
|
||||||
|
const raw = (name || '').trim() || url.replace(/^https?:\/\//i, '');
|
||||||
|
const ch = Array.from(raw)[0];
|
||||||
|
return ch ? ch.toUpperCase() : '?';
|
||||||
|
}
|
||||||
|
|
||||||
|
function hostLabel(url: string): string {
|
||||||
|
try {
|
||||||
|
return new URL(url).host;
|
||||||
|
} catch {
|
||||||
|
return url.replace(/^https?:\/\//i, '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 目标站约定路径 /favicon.ico */
|
||||||
|
function faviconURL(siteURL: string): string | null {
|
||||||
|
try {
|
||||||
|
return new URL('/favicon.ico', siteURL).href;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function ShowcaseFavicon({ name, url }: { name: string; url: string }) {
|
||||||
|
const src = faviconURL(url);
|
||||||
|
const [failed, setFailed] = useState(!src);
|
||||||
|
const mark = siteMark(name, url);
|
||||||
|
|
||||||
|
if (failed || !src) {
|
||||||
|
return (
|
||||||
|
<span className="showcase-item-mark" aria-hidden>
|
||||||
|
{mark}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span className="showcase-item-favicon">
|
||||||
|
<img
|
||||||
|
src={src}
|
||||||
|
alt=""
|
||||||
|
width={40}
|
||||||
|
height={40}
|
||||||
|
referrerPolicy="no-referrer"
|
||||||
|
decoding="async"
|
||||||
|
onError={() => setFailed(true)}
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/** 官方精选的公网部署展柜(只读;仅人工精选条目) */
|
/** 官方精选的公网部署展柜(只读;仅人工精选条目) */
|
||||||
export default function ShowcasePage() {
|
export default function ShowcasePage() {
|
||||||
|
const nav = useNavigate();
|
||||||
const { branding } = useSiteBranding();
|
const { branding } = useSiteBranding();
|
||||||
const { data: items = [], loading } = useSessionResource<CommunityShowcaseItem[]>(
|
const { data: items = [], loading } = useSessionResource<CommunityShowcaseItem[]>(
|
||||||
'showcase',
|
'showcase',
|
||||||
() => api.communityShowcase().then((r) => (Array.isArray(r.items) ? r.items : [])),
|
() => api.communityShowcase().then((r) => (Array.isArray(r.items) ? r.items : [])),
|
||||||
|
{ revalidateEmpty: true },
|
||||||
);
|
);
|
||||||
|
|
||||||
usePageSEO({
|
usePageSEO({
|
||||||
@@ -24,52 +80,65 @@ export default function ShowcasePage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="page-wrap">
|
<div className="page-wrap">
|
||||||
<div className="showcase-page">
|
<div className="feed-panel list-page-panel showcase-panel">
|
||||||
<header className="showcase-head">
|
<header className="list-page-panel__head showcase-head">
|
||||||
<div className="showcase-head-mark" aria-hidden>
|
<Button variant="ghost" size="sm" className="list-page-panel__back" onClick={() => nav('/')}>
|
||||||
<Globe2 size={22} />
|
<ArrowLeft />
|
||||||
</div>
|
返回
|
||||||
<div>
|
</Button>
|
||||||
<h1 className="showcase-title">开源部署展柜</h1>
|
<div className="showcase-head__title-row">
|
||||||
<p className="showcase-desc">
|
<h1 className="page-title">开源部署展柜</h1>
|
||||||
|
{!loading && items.length > 0 && (
|
||||||
|
<span className="showcase-head__count">精选 {items.length} 站</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="page-desc">
|
||||||
以下站点自愿开启社区上报,并由官方演示站精选推荐(非全量目录)
|
以下站点自愿开启社区上报,并由官方演示站精选推荐(非全量目录)
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</header>
|
||||||
</header>
|
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="flex justify-center py-16"><Spinner size="lg" /></div>
|
<div className="flex justify-center py-16"><Spinner size="lg" /></div>
|
||||||
) : items.length === 0 ? (
|
) : items.length === 0 ? (
|
||||||
<p className="showcase-empty">暂无精选实例</p>
|
<div className="showcase-empty list-page-panel__empty">
|
||||||
) : (
|
<Globe2 size={28} strokeWidth={1.5} aria-hidden />
|
||||||
<ul className="showcase-list">
|
<p>暂无精选实例</p>
|
||||||
{items.map((item) => (
|
<span>有站点被官方推荐后会出现在这里</span>
|
||||||
<li key={item.site_url} className="showcase-item">
|
</div>
|
||||||
<a
|
) : (
|
||||||
href={item.site_url}
|
<ul className="showcase-list">
|
||||||
target="_blank"
|
{items.map((item) => {
|
||||||
rel="noopener noreferrer"
|
const name = item.site_name || '未命名站点';
|
||||||
className="showcase-item-link"
|
return (
|
||||||
>
|
<li key={item.site_url} className="showcase-item">
|
||||||
<span className="showcase-item-name">{item.site_name || '未命名站点'}</span>
|
<a
|
||||||
<span className="showcase-item-url">
|
href={item.site_url}
|
||||||
{item.site_url}
|
target="_blank"
|
||||||
<ExternalLink size={12} aria-hidden />
|
rel="noopener noreferrer"
|
||||||
</span>
|
className="showcase-item-link"
|
||||||
{(item.featured_note || item.version) && (
|
>
|
||||||
<span className="showcase-item-meta">
|
<ShowcaseFavicon name={name} url={item.site_url} />
|
||||||
{item.featured_note || null}
|
<span className="showcase-item-body">
|
||||||
{item.featured_note && item.version ? ' · ' : null}
|
<span className="showcase-item-name">{name}</span>
|
||||||
{item.version ? `v${item.version}` : null}
|
<span className="showcase-item-url">
|
||||||
</span>
|
{hostLabel(item.site_url)}
|
||||||
)}
|
<ExternalLink size={12} aria-hidden />
|
||||||
</a>
|
</span>
|
||||||
</li>
|
{item.featured_note ? (
|
||||||
))}
|
<span className="showcase-item-note">{item.featured_note}</span>
|
||||||
</ul>
|
) : null}
|
||||||
)}
|
</span>
|
||||||
|
{item.version ? (
|
||||||
|
<span className="showcase-item-version">v{item.version}</span>
|
||||||
|
) : null}
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
|
||||||
<InFlowSiteFooter />
|
<InFlowSiteFooter />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,13 +1,18 @@
|
|||||||
import { useParams } from 'react-router-dom';
|
import { useEffect, useMemo, useRef } from 'react';
|
||||||
|
import { useOutletContext, useParams } from 'react-router-dom';
|
||||||
import NotFoundPage from './NotFoundPage';
|
import NotFoundPage from './NotFoundPage';
|
||||||
import { api } from '../api/client';
|
import { api } from '../api/client';
|
||||||
import type { SitePage } from '../api/types';
|
import type { SitePage } from '../api/types';
|
||||||
|
import ArticleOutline from '../components/ArticleOutline';
|
||||||
import PostContent from '../components/PostContent';
|
import PostContent from '../components/PostContent';
|
||||||
import { usePageSEO } from '../hooks/usePageSEO';
|
import { usePageSEO } from '../hooks/usePageSEO';
|
||||||
import { parsePermalinkSlug, pagePath } from '../utils/permalink';
|
import { parsePermalinkSlug, pagePath } from '../utils/permalink';
|
||||||
import { useForumLimits } from '../hooks/useForumLimits';
|
import { useForumLimits } from '../hooks/useForumLimits';
|
||||||
import { useAuth } from '../hooks/useAuth';
|
import { useAuth } from '../hooks/useAuth';
|
||||||
import { useSessionResource } from '../hooks/useSessionResource';
|
import { useSessionResource } from '../hooks/useSessionResource';
|
||||||
|
import type { LayoutCtx } from '../layouts/MainLayout';
|
||||||
|
import { extractHeadingsFromHtml } from '../utils/postHeadings';
|
||||||
|
import { renderPostContentHtml } from '../utils/postContent';
|
||||||
|
|
||||||
/** 自定义单页(关于我们、版规等) */
|
/** 自定义单页(关于我们、版规等) */
|
||||||
export default function SitePageView() {
|
export default function SitePageView() {
|
||||||
@@ -15,12 +20,25 @@ export default function SitePageView() {
|
|||||||
const slug = parsePermalinkSlug(rawSlug);
|
const slug = parsePermalinkSlug(rawSlug);
|
||||||
const { limits } = useForumLimits();
|
const { limits } = useForumLimits();
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
|
const { setPostOutline, isMobile } = useOutletContext<LayoutCtx>();
|
||||||
|
const pageRef = useRef<HTMLDivElement>(null);
|
||||||
const { data: page, loading } = useSessionResource<SitePage | null>(
|
const { data: page, loading } = useSessionResource<SitePage | null>(
|
||||||
slug ? `sitepage:${slug}` : null,
|
slug ? `sitepage:${slug}` : null,
|
||||||
() => api.page(slug).then(d => d.page),
|
() => api.page(slug).then(d => d.page),
|
||||||
{ enabled: !!slug },
|
{ enabled: !!slug },
|
||||||
);
|
);
|
||||||
const notFound = !slug || (!loading && !page);
|
const notFound = !slug || (!loading && !page);
|
||||||
|
const isLoggedIn = !!user;
|
||||||
|
const pageContent = page?.content ?? '';
|
||||||
|
|
||||||
|
// 同步从正文派生目录,与帖子详情共用右侧栏目录布局
|
||||||
|
const headings = useMemo(() => {
|
||||||
|
if (!pageContent.trim()) return [];
|
||||||
|
const rendered = renderPostContentHtml(pageContent, isLoggedIn, {
|
||||||
|
openLinksInNewTab: limits.open_content_links_in_new_tab,
|
||||||
|
});
|
||||||
|
return extractHeadingsFromHtml(rendered);
|
||||||
|
}, [pageContent, isLoggedIn, limits.open_content_links_in_new_tab]);
|
||||||
|
|
||||||
usePageSEO({
|
usePageSEO({
|
||||||
title: page?.title,
|
title: page?.title,
|
||||||
@@ -29,19 +47,42 @@ export default function SitePageView() {
|
|||||||
ogType: 'article',
|
ogType: 'article',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (loading || !page) {
|
||||||
|
setPostOutline({ headings: [], scrollRoot: null, title: '文章目录' });
|
||||||
|
return () => setPostOutline(null);
|
||||||
|
}
|
||||||
|
setPostOutline({
|
||||||
|
headings,
|
||||||
|
scrollRoot: pageRef.current,
|
||||||
|
title: '文章目录',
|
||||||
|
});
|
||||||
|
return () => setPostOutline(null);
|
||||||
|
}, [headings, loading, page, setPostOutline]);
|
||||||
|
|
||||||
if (!slug) return <NotFoundPage title="页面不存在" />;
|
if (!slug) return <NotFoundPage title="页面不存在" />;
|
||||||
if (loading) return null;
|
if (loading) return null;
|
||||||
if (notFound || !page) return <NotFoundPage title="页面不存在" description="该页面不存在或未发布" />;
|
if (notFound || !page) return <NotFoundPage title="页面不存在" description="该页面不存在或未发布" />;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="page-wrap">
|
<div className="page-wrap" ref={pageRef}>
|
||||||
<article className="site-page">
|
<article className="site-page">
|
||||||
<header className="site-page__head">
|
<header className="site-page__head">
|
||||||
<h1>{page.title}</h1>
|
<h1>{page.title}</h1>
|
||||||
</header>
|
</header>
|
||||||
|
{isMobile && headings.length > 0 && (
|
||||||
|
<details className="post-detail-toc-mobile">
|
||||||
|
<summary>文章目录({headings.length})</summary>
|
||||||
|
<ArticleOutline
|
||||||
|
headings={headings}
|
||||||
|
scrollRoot={pageRef.current}
|
||||||
|
title="目录"
|
||||||
|
/>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
<PostContent
|
<PostContent
|
||||||
html={page.content}
|
html={page.content}
|
||||||
isLoggedIn={!!user}
|
isLoggedIn={isLoggedIn}
|
||||||
className="site-page__body post-detail-content"
|
className="site-page__body post-detail-content"
|
||||||
/>
|
/>
|
||||||
</article>
|
</article>
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ import { useForumLimits } from '../hooks/useForumLimits';
|
|||||||
import { useSessionResource } from '../hooks/useSessionResource';
|
import { useSessionResource } from '../hooks/useSessionResource';
|
||||||
import PostListItem from '../components/PostListItem';
|
import PostListItem from '../components/PostListItem';
|
||||||
import FeedPagination from '../components/FeedPagination';
|
import FeedPagination from '../components/FeedPagination';
|
||||||
import ComposeMessageDialog from '../components/ComposeMessageDialog';
|
|
||||||
import { openForumPost } from '../utils/openPost';
|
import { openForumPost } from '../utils/openPost';
|
||||||
import { formatDateTime } from '../utils/content';
|
import { formatDateTime } from '../utils/content';
|
||||||
import { usePageSEO } from '../hooks/usePageSEO';
|
import { usePageSEO } from '../hooks/usePageSEO';
|
||||||
@@ -44,7 +43,6 @@ export default function UserProfilePage() {
|
|||||||
const { limits } = useForumLimits();
|
const { limits } = useForumLimits();
|
||||||
const pageSize = limits.page_size_default > 0 ? limits.page_size_default : 20;
|
const pageSize = limits.page_size_default > 0 ? limits.page_size_default : 20;
|
||||||
|
|
||||||
const [msgOpen, setMsgOpen] = useState(false);
|
|
||||||
const [notFound, setNotFound] = useState(false);
|
const [notFound, setNotFound] = useState(false);
|
||||||
const [postPage, setPostPage] = useState(1);
|
const [postPage, setPostPage] = useState(1);
|
||||||
|
|
||||||
@@ -183,7 +181,7 @@ export default function UserProfilePage() {
|
|||||||
nav(loginPath(userPath(profile.id)));
|
nav(loginPath(userPath(profile.id)));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setMsgOpen(true);
|
nav(`/messages?peer=${profile.id}`);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Mail size={14} />
|
<Mail size={14} />
|
||||||
@@ -265,16 +263,6 @@ export default function UserProfilePage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<InFlowSiteFooter />
|
<InFlowSiteFooter />
|
||||||
|
|
||||||
{!isSelf && profile && me && (
|
|
||||||
<ComposeMessageDialog
|
|
||||||
open={msgOpen}
|
|
||||||
onOpenChange={setMsgOpen}
|
|
||||||
toUserId={profile.id}
|
|
||||||
toNickname={profile.nickname}
|
|
||||||
onSent={() => nav(`/messages?peer=${profile.id}`)}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||||
import { Trash2, RotateCcw } from 'lucide-react';
|
import { Trash2, RotateCcw } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
@@ -40,6 +40,8 @@ function formatAdminTime(iso: string) {
|
|||||||
|
|
||||||
export default function AdminCommentsPage() {
|
export default function AdminCommentsPage() {
|
||||||
const nav = useNavigate();
|
const nav = useNavigate();
|
||||||
|
const [searchParams, setSearchParams] = useSearchParams();
|
||||||
|
const focusId = Number(searchParams.get('id') || 0) || 0;
|
||||||
const { ready } = useAdminGuard();
|
const { ready } = useAdminGuard();
|
||||||
const [tab, setTab] = useState<Tab>('pending');
|
const [tab, setTab] = useState<Tab>('pending');
|
||||||
const [comments, setComments] = useState<Comment[]>([]);
|
const [comments, setComments] = useState<Comment[]>([]);
|
||||||
@@ -49,6 +51,9 @@ export default function AdminCommentsPage() {
|
|||||||
const [totalPages, setTotalPages] = useState(1);
|
const [totalPages, setTotalPages] = useState(1);
|
||||||
const [pendingCount, setPendingCount] = useState(0);
|
const [pendingCount, setPendingCount] = useState(0);
|
||||||
const [revComment, setRevComment] = useState<Comment | null>(null);
|
const [revComment, setRevComment] = useState<Comment | null>(null);
|
||||||
|
const [highlightId, setHighlightId] = useState<number | null>(focusId > 0 ? focusId : null);
|
||||||
|
const focusTriedRef = useRef(false);
|
||||||
|
const highlightTimer = useRef<ReturnType<typeof setTimeout>>();
|
||||||
|
|
||||||
const loadList = (p = page, st: Tab = tab) => {
|
const loadList = (p = page, st: Tab = tab) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -90,6 +95,45 @@ export default function AdminCommentsPage() {
|
|||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [ready, tab]);
|
}, [ready, tab]);
|
||||||
|
|
||||||
|
// 从通知深链 ?id= 定位并高亮待审行
|
||||||
|
useEffect(() => {
|
||||||
|
if (!ready || loading || focusId <= 0 || focusTriedRef.current) return;
|
||||||
|
if (tab === 'trash') return;
|
||||||
|
|
||||||
|
const found = comments.find((c) => c.id === focusId);
|
||||||
|
if (found) {
|
||||||
|
focusTriedRef.current = true;
|
||||||
|
setHighlightId(focusId);
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
document.getElementById(`admin-comment-row-${focusId}`)?.scrollIntoView({
|
||||||
|
behavior: 'smooth',
|
||||||
|
block: 'center',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
clearTimeout(highlightTimer.current);
|
||||||
|
highlightTimer.current = setTimeout(() => setHighlightId(null), 2800);
|
||||||
|
const next = new URLSearchParams(searchParams);
|
||||||
|
next.delete('id');
|
||||||
|
setSearchParams(next, { replace: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// pending 未找到则切到全部再试一次
|
||||||
|
if (tab === 'pending') {
|
||||||
|
setTab('all');
|
||||||
|
setPage(1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
focusTriedRef.current = true;
|
||||||
|
notify.warning('该评论可能已审核或不在当前列表');
|
||||||
|
const next = new URLSearchParams(searchParams);
|
||||||
|
next.delete('id');
|
||||||
|
setSearchParams(next, { replace: true });
|
||||||
|
}, [ready, loading, comments, focusId, tab, searchParams, setSearchParams]);
|
||||||
|
|
||||||
|
useEffect(() => () => clearTimeout(highlightTimer.current), []);
|
||||||
|
|
||||||
const approve = async (id: number) => {
|
const approve = async (id: number) => {
|
||||||
try {
|
try {
|
||||||
const r = await api.adminApproveComment(id);
|
const r = await api.adminApproveComment(id);
|
||||||
@@ -268,7 +312,11 @@ export default function AdminCommentsPage() {
|
|||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{comments.map(c => (
|
{comments.map(c => (
|
||||||
<tr key={c.id}>
|
<tr
|
||||||
|
key={c.id}
|
||||||
|
id={`admin-comment-row-${c.id}`}
|
||||||
|
className={cn(highlightId === c.id && 'admin-row-highlight')}
|
||||||
|
>
|
||||||
<td>{c.id}</td>
|
<td>{c.id}</td>
|
||||||
<td>#{c.floor}</td>
|
<td>#{c.floor}</td>
|
||||||
<td>
|
<td>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||||
import { Search, Lock, LockOpen, MessageSquareOff, Trash2, RotateCcw } from 'lucide-react';
|
import { Search, Lock, LockOpen, MessageSquareOff, Trash2, RotateCcw } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
@@ -32,6 +32,8 @@ function formatAdminTime(iso: string) {
|
|||||||
|
|
||||||
export default function AdminPostsPage() {
|
export default function AdminPostsPage() {
|
||||||
const nav = useNavigate();
|
const nav = useNavigate();
|
||||||
|
const [searchParams, setSearchParams] = useSearchParams();
|
||||||
|
const focusId = Number(searchParams.get('id') || 0) || 0;
|
||||||
const { ready } = useAdminGuard();
|
const { ready } = useAdminGuard();
|
||||||
const [tab, setTab] = useState<Tab>('pending');
|
const [tab, setTab] = useState<Tab>('pending');
|
||||||
const [posts, setPosts] = useState<PostItem[]>([]);
|
const [posts, setPosts] = useState<PostItem[]>([]);
|
||||||
@@ -42,6 +44,9 @@ export default function AdminPostsPage() {
|
|||||||
const [pendingCount, setPendingCount] = useState(0);
|
const [pendingCount, setPendingCount] = useState(0);
|
||||||
const [keyword, setKeyword] = useState('');
|
const [keyword, setKeyword] = useState('');
|
||||||
const [search, setSearch] = useState('');
|
const [search, setSearch] = useState('');
|
||||||
|
const [highlightId, setHighlightId] = useState<number | null>(focusId > 0 ? focusId : null);
|
||||||
|
const focusTriedRef = useRef(false);
|
||||||
|
const highlightTimer = useRef<ReturnType<typeof setTimeout>>();
|
||||||
|
|
||||||
const loadActive = (p = page, kw = search, status = tab === 'pending' ? 'pending' : 'all') => {
|
const loadActive = (p = page, kw = search, status = tab === 'pending' ? 'pending' : 'all') => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -92,6 +97,43 @@ export default function AdminPostsPage() {
|
|||||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- 仅随 tab/search/ready 刷新
|
// eslint-disable-next-line react-hooks/exhaustive-deps -- 仅随 tab/search/ready 刷新
|
||||||
}, [ready, search, tab]);
|
}, [ready, search, tab]);
|
||||||
|
|
||||||
|
// 从通知深链 ?id= 定位并高亮
|
||||||
|
useEffect(() => {
|
||||||
|
if (!ready || loading || focusId <= 0 || focusTriedRef.current) return;
|
||||||
|
if (tab === 'trash') return;
|
||||||
|
|
||||||
|
const found = posts.find((p) => p.id === focusId);
|
||||||
|
if (found) {
|
||||||
|
focusTriedRef.current = true;
|
||||||
|
setHighlightId(focusId);
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
document.getElementById(`admin-post-row-${focusId}`)?.scrollIntoView({
|
||||||
|
behavior: 'smooth',
|
||||||
|
block: 'center',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
clearTimeout(highlightTimer.current);
|
||||||
|
highlightTimer.current = setTimeout(() => setHighlightId(null), 2800);
|
||||||
|
const next = new URLSearchParams(searchParams);
|
||||||
|
next.delete('id');
|
||||||
|
setSearchParams(next, { replace: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tab === 'pending') {
|
||||||
|
setTab('active');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
focusTriedRef.current = true;
|
||||||
|
notify.warning('该帖子可能已审核或不在当前列表');
|
||||||
|
const next = new URLSearchParams(searchParams);
|
||||||
|
next.delete('id');
|
||||||
|
setSearchParams(next, { replace: true });
|
||||||
|
}, [ready, loading, posts, focusId, tab, searchParams, setSearchParams]);
|
||||||
|
|
||||||
|
useEffect(() => () => clearTimeout(highlightTimer.current), []);
|
||||||
|
|
||||||
const switchTab = (next: Tab) => {
|
const switchTab = (next: Tab) => {
|
||||||
if (next === tab) return;
|
if (next === tab) return;
|
||||||
setTab(next);
|
setTab(next);
|
||||||
@@ -352,7 +394,11 @@ export default function AdminPostsPage() {
|
|||||||
{posts.map(p => {
|
{posts.map(p => {
|
||||||
const edited = p.updated_at && isTimeDiffSignificant(p.created_at, p.updated_at);
|
const edited = p.updated_at && isTimeDiffSignificant(p.created_at, p.updated_at);
|
||||||
return (
|
return (
|
||||||
<tr key={p.id}>
|
<tr
|
||||||
|
key={p.id}
|
||||||
|
id={`admin-post-row-${p.id}`}
|
||||||
|
className={cn(highlightId === p.id && 'admin-row-highlight')}
|
||||||
|
>
|
||||||
<td>{p.id}</td>
|
<td>{p.id}</td>
|
||||||
<td className="max-w-[200px] truncate">
|
<td className="max-w-[200px] truncate">
|
||||||
<button type="button" className="admin-text-link" onClick={() => nav(`/post/${p.id}`)}>
|
<button type="button" className="admin-text-link" onClick={() => nav(`/post/${p.id}`)}>
|
||||||
|
|||||||
@@ -952,7 +952,7 @@ export default function AdminSettingsPage() {
|
|||||||
<div className="admin-settings-subsection">
|
<div className="admin-settings-subsection">
|
||||||
<h4 className="admin-settings-subsection-title">首页排序标签</h4>
|
<h4 className="admin-settings-subsection-title">首页排序标签</h4>
|
||||||
<p className="admin-settings-subsection-desc">
|
<p className="admin-settings-subsection-desc">
|
||||||
拖拽调整顺序;在「显示名称」框中改首页文案;右侧开关控制启停。第一个启用项为默认排序
|
拖拽调整顺序;在「显示名称」框中改首页文案;右侧开关控制启停。第一个启用项为默认排序。「最新」按发帖与评论的最近时间混排
|
||||||
</p>
|
</p>
|
||||||
<FeedSortTabList
|
<FeedSortTabList
|
||||||
tabs={normalizeFeedSortTabs(limits.feed_sort_tabs ?? DEFAULT_FEED_SORT_TABS)}
|
tabs={normalizeFeedSortTabs(limits.feed_sort_tabs ?? DEFAULT_FEED_SORT_TABS)}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -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);
|
||||||
}
|
}
|
||||||
@@ -89,6 +94,25 @@ export function formatTime(iso: string) {
|
|||||||
return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`;
|
return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 会话列表时间:今天 HH:mm,同年 M月D日,更早含年 */
|
||||||
|
export function formatConvListTime(iso: string) {
|
||||||
|
const d = new Date(iso);
|
||||||
|
if (Number.isNaN(d.getTime())) return iso;
|
||||||
|
const now = new Date();
|
||||||
|
const pad = (n: number) => String(n).padStart(2, '0');
|
||||||
|
if (
|
||||||
|
d.getFullYear() === now.getFullYear()
|
||||||
|
&& d.getMonth() === now.getMonth()
|
||||||
|
&& d.getDate() === now.getDate()
|
||||||
|
) {
|
||||||
|
return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||||
|
}
|
||||||
|
if (d.getFullYear() === now.getFullYear()) {
|
||||||
|
return `${d.getMonth() + 1}月${d.getDate()}日`;
|
||||||
|
}
|
||||||
|
return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`;
|
||||||
|
}
|
||||||
|
|
||||||
/** 完整日期时间(用于帖子发布/修改时间展示) */
|
/** 完整日期时间(用于帖子发布/修改时间展示) */
|
||||||
export function formatDateTime(iso: string) {
|
export function formatDateTime(iso: string) {
|
||||||
const d = new Date(iso);
|
const d = new Date(iso);
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { DEFAULT_FEED_SORT_TABS } from '../api/types';
|
|||||||
const FEED_SORT_IDS: FeedSortId[] = ['reply', 'latest', 'hot'];
|
const FEED_SORT_IDS: FeedSortId[] = ['reply', 'latest', 'hot'];
|
||||||
|
|
||||||
const DEFAULT_LABELS: Record<FeedSortId, string> = {
|
const DEFAULT_LABELS: Record<FeedSortId, string> = {
|
||||||
reply: '新评论',
|
reply: '最新',
|
||||||
latest: '新帖子',
|
latest: '新帖子',
|
||||||
hot: '推荐帖',
|
hot: '推荐帖',
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ export type HomeBootPayload = {
|
|||||||
recent_comments: RecentComment[];
|
recent_comments: RecentComment[];
|
||||||
recent_users: RecentUser[];
|
recent_users: RecentUser[];
|
||||||
tags: TagCount[];
|
tags: TagCount[];
|
||||||
showcase: CommunityShowcaseItem[];
|
showcase?: CommunityShowcaseItem[];
|
||||||
pages: SitePageSummary[];
|
pages: SitePageSummary[];
|
||||||
limits: ForumLimitsPublic;
|
limits: ForumLimitsPublic;
|
||||||
branding: SiteBranding;
|
branding: SiteBranding;
|
||||||
@@ -77,7 +77,10 @@ export function consumeHomeBoot(): HomeBootPayload | null {
|
|||||||
if (Array.isArray(boot.recent_comments)) setCachedRecentComments(boot.recent_comments);
|
if (Array.isArray(boot.recent_comments)) setCachedRecentComments(boot.recent_comments);
|
||||||
if (Array.isArray(boot.recent_users)) setCachedRecentUsers(boot.recent_users);
|
if (Array.isArray(boot.recent_users)) setCachedRecentUsers(boot.recent_users);
|
||||||
if (Array.isArray(boot.tags)) setCachedTags(boot.tags);
|
if (Array.isArray(boot.tags)) setCachedTags(boot.tags);
|
||||||
if (Array.isArray(boot.showcase)) setSessionSnapshot('showcase', boot.showcase);
|
// 仅当 boot 显式带 showcase 时灌入(侧栏关闭时省略,避免 [] 粘死)
|
||||||
|
if ('showcase' in boot && Array.isArray(boot.showcase)) {
|
||||||
|
setSessionSnapshot('showcase', boot.showcase);
|
||||||
|
}
|
||||||
|
|
||||||
// 鉴权 / 签到:有 user 字段即种子(含 null = 已确认访客)
|
// 鉴权 / 签到:有 user 字段即种子(含 null = 已确认访客)
|
||||||
if ('user' in boot) {
|
if ('user' in boot) {
|
||||||
|
|||||||
@@ -122,9 +122,12 @@ export function insertMarkdownLink(
|
|||||||
value: string,
|
value: string,
|
||||||
url: string,
|
url: string,
|
||||||
onChange: ChangeHandler,
|
onChange: ChangeHandler,
|
||||||
|
opts?: { text?: string },
|
||||||
) {
|
) {
|
||||||
const { selectionStart, selectionEnd } = textarea;
|
const { selectionStart, selectionEnd } = textarea;
|
||||||
const selected = value.slice(selectionStart, selectionEnd) || '链接文字';
|
const selected = opts?.text?.trim()
|
||||||
|
|| value.slice(selectionStart, selectionEnd)
|
||||||
|
|| '链接文字';
|
||||||
const insert = `[${selected}](${url})`;
|
const insert = `[${selected}](${url})`;
|
||||||
const next = value.slice(0, selectionStart) + insert + value.slice(selectionEnd);
|
const next = value.slice(0, selectionStart) + insert + value.slice(selectionEnd);
|
||||||
applyTextareaChange(
|
applyTextareaChange(
|
||||||
|
|||||||
@@ -421,13 +421,18 @@ func (h *Handlers) APIAdminRejectComment(c *gin.Context) {
|
|||||||
title = "未知帖子"
|
title = "未知帖子"
|
||||||
}
|
}
|
||||||
pid := comment.PostID
|
pid := comment.PostID
|
||||||
_, _ = h.Message.SendSystem(
|
cid := comment.ID
|
||||||
|
floor := comment.Floor
|
||||||
|
_, _ = h.Message.SendSystemWithRefs(
|
||||||
comment.UserID,
|
comment.UserID,
|
||||||
"评论未通过审核",
|
"评论未通过审核",
|
||||||
service.FormatCommentRejectContent(title, comment.PostID, comment.Floor, reason),
|
service.FormatCommentRejectContent(title, comment.PostID, comment.Floor, reason),
|
||||||
model.MessageKindReject,
|
model.MessageKindReject,
|
||||||
&pid,
|
service.SystemNotifyRefs{
|
||||||
nil,
|
PostID: &pid,
|
||||||
|
CommentID: &cid,
|
||||||
|
Floor: &floor,
|
||||||
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
c.JSON(http.StatusOK, gin.H{"message": "已拒绝该评论并通知作者", "status": model.ContentStatusRejected})
|
c.JSON(http.StatusOK, gin.H{"message": "已拒绝该评论并通知作者", "status": model.ContentStatusRejected})
|
||||||
|
|||||||
@@ -8,6 +8,27 @@ import (
|
|||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// APIMyPostImages 当前用户已上传的帖子图片列表
|
||||||
|
func (h *Handlers) APIMyPostImages(c *gin.Context) {
|
||||||
|
if h.Store == nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "上传存储未初始化"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
uid := h.currentUserID(c)
|
||||||
|
if uid == 0 {
|
||||||
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||||
|
size, _ := strconv.Atoi(c.DefaultQuery("size", "24"))
|
||||||
|
result, err := h.Store.ListUserPostImages(uid, page, size)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, result)
|
||||||
|
}
|
||||||
|
|
||||||
// APIAdminMedia 列出媒体资源
|
// APIAdminMedia 列出媒体资源
|
||||||
func (h *Handlers) APIAdminMedia(c *gin.Context) {
|
func (h *Handlers) APIAdminMedia(c *gin.Context) {
|
||||||
if h.Store == nil {
|
if h.Store == nil {
|
||||||
|
|||||||
@@ -136,6 +136,20 @@ func (h *Handlers) APIMarkNotificationsRead(c *gin.Context) {
|
|||||||
c.JSON(http.StatusOK, gin.H{"message": "通知已全部标为已读"})
|
c.JSON(http.StatusOK, gin.H{"message": "通知已全部标为已读"})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// APIMarkMessageRead 单条消息已读
|
||||||
|
func (h *Handlers) APIMarkMessageRead(c *gin.Context) {
|
||||||
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||||
|
if err != nil || id == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的消息"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := h.Message.MarkMessageRead(h.currentUserID(c), uint(id)); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, gin.H{"message": "已标为已读"})
|
||||||
|
}
|
||||||
|
|
||||||
// APISendMessage 发送私信
|
// APISendMessage 发送私信
|
||||||
func (h *Handlers) APISendMessage(c *gin.Context) {
|
func (h *Handlers) APISendMessage(c *gin.Context) {
|
||||||
var req struct {
|
var req struct {
|
||||||
|
|||||||
@@ -36,7 +36,8 @@ type homeBootPayload struct {
|
|||||||
RecentComments []service.RecentCommentItem `json:"recent_comments"`
|
RecentComments []service.RecentCommentItem `json:"recent_comments"`
|
||||||
RecentUsers []service.RecentUserItem `json:"recent_users"`
|
RecentUsers []service.RecentUserItem `json:"recent_users"`
|
||||||
Tags []service.TagCount `json:"tags"`
|
Tags []service.TagCount `json:"tags"`
|
||||||
Showcase []service.CommunityShowcaseItem `json:"showcase"`
|
// omitempty:侧栏关闭或未拉取时不写字段,避免 SPA 把 [] 当成有效会话快照
|
||||||
|
Showcase []service.CommunityShowcaseItem `json:"showcase,omitempty"`
|
||||||
Pages []service.SitePageSummary `json:"pages"`
|
Pages []service.SitePageSummary `json:"pages"`
|
||||||
Limits service.ForumLimitsPublic `json:"limits"`
|
Limits service.ForumLimitsPublic `json:"limits"`
|
||||||
Branding service.SiteBranding `json:"branding"`
|
Branding service.SiteBranding `json:"branding"`
|
||||||
@@ -261,13 +262,15 @@ func (h *Handlers) gatherHomeSSR(c *gin.Context, boardID uint) (*homeSSRData, er
|
|||||||
go func() {
|
go func() {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
items, err := h.Community.ListShowcase(c.Request.Host)
|
items, err := h.Community.ListShowcase(c.Request.Host)
|
||||||
if err != nil || items == nil {
|
if err != nil {
|
||||||
|
// 失败不写 showcase,让前端自行请求,避免假空粘死
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if items == nil {
|
||||||
items = []service.CommunityShowcaseItem{}
|
items = []service.CommunityShowcaseItem{}
|
||||||
}
|
}
|
||||||
out.boot.Showcase = items
|
out.boot.Showcase = items
|
||||||
}()
|
}()
|
||||||
} else {
|
|
||||||
out.boot.Showcase = []service.CommunityShowcaseItem{}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
uid := h.currentUserID(c)
|
uid := h.currentUserID(c)
|
||||||
@@ -553,7 +556,7 @@ func writeSSRFeed(b *strings.Builder, boot homeBootPayload, meta homeSSRMeta) {
|
|||||||
tabs := boot.Limits.FeedSortTabs
|
tabs := boot.Limits.FeedSortTabs
|
||||||
if len(tabs) == 0 {
|
if len(tabs) == 0 {
|
||||||
tabs = []service.FeedSortTab{
|
tabs = []service.FeedSortTab{
|
||||||
{ID: service.FeedSortReply, Label: "新评论", Enabled: true},
|
{ID: service.FeedSortReply, Label: "最新", Enabled: true},
|
||||||
{ID: service.FeedSortLatest, Label: "新帖子", Enabled: true},
|
{ID: service.FeedSortLatest, Label: "新帖子", Enabled: true},
|
||||||
{ID: service.FeedSortHot, Label: "推荐帖", Enabled: true},
|
{ID: service.FeedSortHot, Label: "推荐帖", Enabled: true},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -226,16 +226,20 @@ const (
|
|||||||
|
|
||||||
// PrivateMessage 站内私信
|
// PrivateMessage 站内私信
|
||||||
type PrivateMessage struct {
|
type PrivateMessage struct {
|
||||||
ID uint `gorm:"primaryKey" json:"id"`
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
FromUserID uint `gorm:"index;not null" json:"from_user_id"` // 0 表示系统
|
FromUserID uint `gorm:"index;not null" json:"from_user_id"` // 0 表示系统
|
||||||
ToUserID uint `gorm:"index;not null" json:"to_user_id"`
|
ToUserID uint `gorm:"index;not null" json:"to_user_id"`
|
||||||
Subject string `gorm:"size:256;not null" json:"subject"`
|
Subject string `gorm:"size:256;not null" json:"subject"`
|
||||||
Content string `gorm:"type:text;not null" json:"content"`
|
Content string `gorm:"type:text;not null" json:"content"`
|
||||||
Kind string `gorm:"size:32;default:user;index" json:"kind"`
|
Kind string `gorm:"size:32;default:user;index" json:"kind"`
|
||||||
RelatedPostID *uint `gorm:"index" json:"related_post_id,omitempty"`
|
RelatedPostID *uint `gorm:"index" json:"related_post_id,omitempty"`
|
||||||
RelatedReportID *uint `gorm:"index" json:"related_report_id,omitempty"`
|
RelatedReportID *uint `gorm:"index" json:"related_report_id,omitempty"`
|
||||||
IsRead bool `gorm:"default:false;index" json:"is_read"`
|
RelatedCommentID *uint `gorm:"index" json:"related_comment_id,omitempty"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
RelatedFloor *int `json:"related_floor,omitempty"` // 评论自身楼号,对应 #floor-N
|
||||||
|
IsRead bool `gorm:"default:false;index" json:"is_read"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
// RelatedStatus 列表接口实时回填:pending|published|rejected|deleted(不落库)
|
||||||
|
RelatedStatus string `json:"related_status,omitempty" gorm:"-"`
|
||||||
|
|
||||||
FromUser User `gorm:"foreignKey:FromUserID" json:"from_user,omitempty"`
|
FromUser User `gorm:"foreignKey:FromUserID" json:"from_user,omitempty"`
|
||||||
ToUser User `gorm:"foreignKey:ToUserID" json:"to_user,omitempty"`
|
ToUser User `gorm:"foreignKey:ToUserID" json:"to_user,omitempty"`
|
||||||
|
|||||||
@@ -177,6 +177,7 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
|||||||
api.POST("/profile/password", h.APIUpdatePassword)
|
api.POST("/profile/password", h.APIUpdatePassword)
|
||||||
api.POST("/profile/avatar", h.APIUploadAvatar)
|
api.POST("/profile/avatar", h.APIUploadAvatar)
|
||||||
api.POST("/uploads/image", h.APIUploadPostImage)
|
api.POST("/uploads/image", h.APIUploadPostImage)
|
||||||
|
api.GET("/uploads/images", h.APIMyPostImages)
|
||||||
api.POST("/posts", middleware.RateLimitMiddleware(limiter, "post"), h.APICreatePost)
|
api.POST("/posts", middleware.RateLimitMiddleware(limiter, "post"), h.APICreatePost)
|
||||||
api.PUT("/posts/:id", h.APIUpdatePost)
|
api.PUT("/posts/:id", h.APIUpdatePost)
|
||||||
api.DELETE("/posts/:id", h.APIDeletePost)
|
api.DELETE("/posts/:id", h.APIDeletePost)
|
||||||
@@ -194,6 +195,7 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
|||||||
api.GET("/messages/unread-count", h.APIMessageUnreadCount)
|
api.GET("/messages/unread-count", h.APIMessageUnreadCount)
|
||||||
api.GET("/messages/notifications", h.APIMessageNotifications)
|
api.GET("/messages/notifications", h.APIMessageNotifications)
|
||||||
api.POST("/messages/notifications/read", h.APIMarkNotificationsRead)
|
api.POST("/messages/notifications/read", h.APIMarkNotificationsRead)
|
||||||
|
api.POST("/messages/:id/read", h.APIMarkMessageRead)
|
||||||
api.GET("/messages/conversations", h.APIMessageConversations)
|
api.GET("/messages/conversations", h.APIMessageConversations)
|
||||||
api.GET("/messages/conversations/:peerId", h.APIConversationMessages)
|
api.GET("/messages/conversations/:peerId", h.APIConversationMessages)
|
||||||
api.POST("/messages/conversations/:peerId/read", h.APIMarkConversationRead)
|
api.POST("/messages/conversations/:peerId/read", h.APIMarkConversationRead)
|
||||||
|
|||||||
116
service/media.go
116
service/media.go
@@ -154,6 +154,122 @@ func (s *UploadStore) ListMedia(category, query string, page, size int) (*MediaL
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ListUserPostImages 列出当前用户历史上传的帖子图片(category=posts)
|
||||||
|
func (s *UploadStore) ListUserPostImages(userID uint, page, size int) (*MediaListResult, error) {
|
||||||
|
if s == nil {
|
||||||
|
return nil, errors.New("上传存储未初始化")
|
||||||
|
}
|
||||||
|
if model.DB == nil {
|
||||||
|
return nil, errors.New("数据库未初始化")
|
||||||
|
}
|
||||||
|
if userID == 0 {
|
||||||
|
return nil, errors.New("未登录")
|
||||||
|
}
|
||||||
|
if page < 1 {
|
||||||
|
page = 1
|
||||||
|
}
|
||||||
|
if size < 1 {
|
||||||
|
size = 24
|
||||||
|
}
|
||||||
|
if size > 100 {
|
||||||
|
size = 100
|
||||||
|
}
|
||||||
|
|
||||||
|
var records []model.Media
|
||||||
|
if err := model.DB.Where("category = ? AND user_id = ?", UploadCategoryPosts, userID).
|
||||||
|
Order("created_at desc, id desc").
|
||||||
|
Find(&records).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 上传会登记原图 + WebP;图库按 stem 去重,优先展示 WebP(与插入 URL 一致)
|
||||||
|
records = dedupePostMediaPreferWebP(records)
|
||||||
|
|
||||||
|
total := len(records)
|
||||||
|
totalPages := 1
|
||||||
|
if total > 0 {
|
||||||
|
totalPages = (total + size - 1) / size
|
||||||
|
}
|
||||||
|
if page > totalPages {
|
||||||
|
page = totalPages
|
||||||
|
}
|
||||||
|
start := (page - 1) * size
|
||||||
|
if start > total {
|
||||||
|
start = total
|
||||||
|
}
|
||||||
|
end := start + size
|
||||||
|
if end > total {
|
||||||
|
end = total
|
||||||
|
}
|
||||||
|
pageRecords := records[start:end]
|
||||||
|
|
||||||
|
files := make([]MediaItem, 0, len(pageRecords))
|
||||||
|
for _, r := range pageRecords {
|
||||||
|
mod := r.UpdatedAt
|
||||||
|
if mod.IsZero() {
|
||||||
|
mod = r.CreatedAt
|
||||||
|
}
|
||||||
|
files = append(files, MediaItem{
|
||||||
|
Category: r.Category,
|
||||||
|
Name: r.Name,
|
||||||
|
URL: r.URL,
|
||||||
|
Size: r.Size,
|
||||||
|
ModifiedAt: mod.UTC(),
|
||||||
|
ContentType: r.ContentType,
|
||||||
|
StorageType: r.StorageType,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
mode, _, _, _ := s.snapshot()
|
||||||
|
storageType := config.StorageTypeLocal
|
||||||
|
if mode == config.StorageTypeS3 {
|
||||||
|
storageType = config.StorageTypeS3
|
||||||
|
}
|
||||||
|
|
||||||
|
return &MediaListResult{
|
||||||
|
Files: files,
|
||||||
|
Total: total,
|
||||||
|
Page: page,
|
||||||
|
TotalPages: totalPages,
|
||||||
|
StorageType: storageType,
|
||||||
|
CategoryCounts: map[string]int{UploadCategoryPosts: total},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// dedupePostMediaPreferWebP 同一上传的原图/WebP 只保留一条,优先 WebP
|
||||||
|
func dedupePostMediaPreferWebP(records []model.Media) []model.Media {
|
||||||
|
type slot struct {
|
||||||
|
idx int
|
||||||
|
isWebP bool
|
||||||
|
}
|
||||||
|
seen := map[string]slot{}
|
||||||
|
out := make([]model.Media, 0, len(records))
|
||||||
|
for _, r := range records {
|
||||||
|
stem := mediaFileStem(r.Name)
|
||||||
|
isWebP := strings.EqualFold(filepath.Ext(r.Name), ".webp") ||
|
||||||
|
strings.EqualFold(r.ContentType, "image/webp")
|
||||||
|
if s, ok := seen[stem]; ok {
|
||||||
|
if isWebP && !s.isWebP {
|
||||||
|
out[s.idx] = r
|
||||||
|
seen[stem] = slot{idx: s.idx, isWebP: true}
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[stem] = slot{idx: len(out), isWebP: isWebP}
|
||||||
|
out = append(out, r)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func mediaFileStem(name string) string {
|
||||||
|
name = filepath.Base(strings.TrimSpace(name))
|
||||||
|
ext := filepath.Ext(name)
|
||||||
|
if ext == "" {
|
||||||
|
return strings.ToLower(name)
|
||||||
|
}
|
||||||
|
return strings.ToLower(strings.TrimSuffix(name, ext))
|
||||||
|
}
|
||||||
|
|
||||||
// DeleteMedia 按 URL 批量删除媒体(含伴生扩展名与数据库索引)
|
// DeleteMedia 按 URL 批量删除媒体(含伴生扩展名与数据库索引)
|
||||||
func (s *UploadStore) DeleteMedia(urls []string) (int, error) {
|
func (s *UploadStore) DeleteMedia(urls []string) (int, error) {
|
||||||
if s == nil {
|
if s == nil {
|
||||||
|
|||||||
@@ -3,11 +3,13 @@ package service
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
|
||||||
"git.iioio.com/freefire/jiang13-forum/model"
|
"git.iioio.com/freefire/jiang13-forum/model"
|
||||||
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -24,13 +26,15 @@ func NewMessageService(filter *SensitiveFilter, settings *ForumSettingsService)
|
|||||||
}
|
}
|
||||||
|
|
||||||
type MessageSendInput struct {
|
type MessageSendInput struct {
|
||||||
FromUserID uint
|
FromUserID uint
|
||||||
ToUserID uint
|
ToUserID uint
|
||||||
Subject string
|
Subject string
|
||||||
Content string
|
Content string
|
||||||
Kind string
|
Kind string
|
||||||
RelatedPostID *uint
|
RelatedPostID *uint
|
||||||
RelatedReportID *uint
|
RelatedReportID *uint
|
||||||
|
RelatedCommentID *uint
|
||||||
|
RelatedFloor *int
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send 发送私信(用户互发或系统通知)
|
// Send 发送私信(用户互发或系统通知)
|
||||||
@@ -82,14 +86,16 @@ func (s *MessageService) Send(in MessageSendInput) (*model.PrivateMessage, error
|
|||||||
}
|
}
|
||||||
|
|
||||||
msg := &model.PrivateMessage{
|
msg := &model.PrivateMessage{
|
||||||
FromUserID: in.FromUserID,
|
FromUserID: in.FromUserID,
|
||||||
ToUserID: in.ToUserID,
|
ToUserID: in.ToUserID,
|
||||||
Subject: subject,
|
Subject: subject,
|
||||||
Content: content,
|
Content: content,
|
||||||
Kind: kind,
|
Kind: kind,
|
||||||
RelatedPostID: in.RelatedPostID,
|
RelatedPostID: in.RelatedPostID,
|
||||||
RelatedReportID: in.RelatedReportID,
|
RelatedReportID: in.RelatedReportID,
|
||||||
IsRead: false,
|
RelatedCommentID: in.RelatedCommentID,
|
||||||
|
RelatedFloor: in.RelatedFloor,
|
||||||
|
IsRead: false,
|
||||||
}
|
}
|
||||||
if err := model.DB.Create(msg).Error; err != nil {
|
if err := model.DB.Create(msg).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -98,22 +104,54 @@ func (s *MessageService) Send(in MessageSendInput) (*model.PrivateMessage, error
|
|||||||
return msg, nil
|
return msg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SystemNotifyRefs 系统通知关联目标(帖子 / 评论 / 举报)
|
||||||
|
type SystemNotifyRefs struct {
|
||||||
|
PostID *uint
|
||||||
|
ReportID *uint
|
||||||
|
CommentID *uint
|
||||||
|
Floor *int
|
||||||
|
}
|
||||||
|
|
||||||
// SendSystem 系统私信(管理员/系统 → 用户)
|
// SendSystem 系统私信(管理员/系统 → 用户)
|
||||||
func (s *MessageService) SendSystem(toUserID uint, subject, content, kind string, relatedPostID, relatedReportID *uint) (*model.PrivateMessage, error) {
|
func (s *MessageService) SendSystem(toUserID uint, subject, content, kind string, relatedPostID, relatedReportID *uint) (*model.PrivateMessage, error) {
|
||||||
|
return s.SendSystemWithRefs(toUserID, subject, content, kind, SystemNotifyRefs{
|
||||||
|
PostID: relatedPostID,
|
||||||
|
ReportID: relatedReportID,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendSystemWithRefs 系统私信(可附带评论楼层深链)
|
||||||
|
func (s *MessageService) SendSystemWithRefs(toUserID uint, subject, content, kind string, refs SystemNotifyRefs) (*model.PrivateMessage, error) {
|
||||||
if kind == "" {
|
if kind == "" {
|
||||||
kind = model.MessageKindSystem
|
kind = model.MessageKindSystem
|
||||||
}
|
}
|
||||||
return s.Send(MessageSendInput{
|
return s.Send(MessageSendInput{
|
||||||
FromUserID: 0,
|
FromUserID: 0,
|
||||||
ToUserID: toUserID,
|
ToUserID: toUserID,
|
||||||
Subject: subject,
|
Subject: subject,
|
||||||
Content: content,
|
Content: content,
|
||||||
Kind: kind,
|
Kind: kind,
|
||||||
RelatedPostID: relatedPostID,
|
RelatedPostID: refs.PostID,
|
||||||
RelatedReportID: relatedReportID,
|
RelatedReportID: refs.ReportID,
|
||||||
|
RelatedCommentID: refs.CommentID,
|
||||||
|
RelatedFloor: refs.Floor,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MarkMessageRead 将单条消息标为已读(仅收件人本人)
|
||||||
|
func (s *MessageService) MarkMessageRead(userID, messageID uint) error {
|
||||||
|
if messageID == 0 {
|
||||||
|
return errors.New("无效的消息")
|
||||||
|
}
|
||||||
|
res := model.DB.Model(&model.PrivateMessage{}).
|
||||||
|
Where("id = ? AND to_user_id = ? AND is_read = ?", messageID, userID, false).
|
||||||
|
Update("is_read", true)
|
||||||
|
if res.Error != nil {
|
||||||
|
return res.Error
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// MarkAllRead 全部标为已读
|
// MarkAllRead 全部标为已读
|
||||||
func (s *MessageService) MarkAllRead(userID uint) error {
|
func (s *MessageService) MarkAllRead(userID uint) error {
|
||||||
return model.DB.Model(&model.PrivateMessage{}).
|
return model.DB.Model(&model.PrivateMessage{}).
|
||||||
@@ -175,9 +213,212 @@ func (s *MessageService) ListNotifications(userID uint, page, size int, kind str
|
|||||||
if list == nil {
|
if list == nil {
|
||||||
list = []model.PrivateMessage{}
|
list = []model.PrivateMessage{}
|
||||||
}
|
}
|
||||||
|
s.enrichModerationStatus(list)
|
||||||
return list, total, nil
|
return list, total, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// enrichModerationStatus 为待审通知回填目标当前审核状态
|
||||||
|
func (s *MessageService) enrichModerationStatus(list []model.PrivateMessage) {
|
||||||
|
if len(list) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
resolvedByIndex := enrichModerationCommentIDs(list)
|
||||||
|
|
||||||
|
commentIDs := make([]uint, 0, len(list))
|
||||||
|
postIDs := make([]uint, 0, len(list))
|
||||||
|
// 历史评论通知:按帖+楼层回查(兜底)
|
||||||
|
type pfKey struct {
|
||||||
|
PostID uint
|
||||||
|
Floor int
|
||||||
|
}
|
||||||
|
pfNeeded := make([]pfKey, 0, len(list))
|
||||||
|
seenC := map[uint]struct{}{}
|
||||||
|
seenP := map[uint]struct{}{}
|
||||||
|
seenPF := map[pfKey]struct{}{}
|
||||||
|
|
||||||
|
for i := range list {
|
||||||
|
m := &list[i]
|
||||||
|
if m.Kind != model.MessageKindModeration {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if m.RelatedCommentID != nil && *m.RelatedCommentID > 0 {
|
||||||
|
id := *m.RelatedCommentID
|
||||||
|
if _, ok := seenC[id]; !ok {
|
||||||
|
seenC[id] = struct{}{}
|
||||||
|
commentIDs = append(commentIDs, id)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if cid, ok := resolvedByIndex[i]; ok && cid > 0 {
|
||||||
|
if _, ok := seenC[cid]; !ok {
|
||||||
|
seenC[cid] = struct{}{}
|
||||||
|
commentIDs = append(commentIDs, cid)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if m.RelatedPostID == nil || *m.RelatedPostID == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pid := *m.RelatedPostID
|
||||||
|
if looksLikeModerationComment(m.Subject, m.Content) {
|
||||||
|
floor := 0
|
||||||
|
if m.RelatedFloor != nil && *m.RelatedFloor > 0 {
|
||||||
|
floor = *m.RelatedFloor
|
||||||
|
} else {
|
||||||
|
floor = parseNotifyFloor(m.Content)
|
||||||
|
}
|
||||||
|
if floor > 0 {
|
||||||
|
k := pfKey{PostID: pid, Floor: floor}
|
||||||
|
if _, ok := seenPF[k]; !ok {
|
||||||
|
seenPF[k] = struct{}{}
|
||||||
|
pfNeeded = append(pfNeeded, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, ok := seenP[pid]; !ok {
|
||||||
|
seenP[pid] = struct{}{}
|
||||||
|
postIDs = append(postIDs, pid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
commentStatus := map[uint]string{}
|
||||||
|
if len(commentIDs) > 0 {
|
||||||
|
type row struct {
|
||||||
|
ID uint
|
||||||
|
Status string
|
||||||
|
DeletedAt gorm.DeletedAt
|
||||||
|
}
|
||||||
|
var rows []row
|
||||||
|
_ = model.DB.Unscoped().Model(&model.Comment{}).
|
||||||
|
Select("id", "status", "deleted_at").
|
||||||
|
Where("id IN ?", commentIDs).
|
||||||
|
Find(&rows)
|
||||||
|
for _, r := range rows {
|
||||||
|
commentStatus[r.ID] = contentStatusOrDeleted(r.Status, r.DeletedAt)
|
||||||
|
}
|
||||||
|
for _, id := range commentIDs {
|
||||||
|
if _, ok := commentStatus[id]; !ok {
|
||||||
|
commentStatus[id] = "deleted"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
statusByPF := map[pfKey]string{}
|
||||||
|
if len(pfNeeded) > 0 {
|
||||||
|
postSet := map[uint]struct{}{}
|
||||||
|
for _, k := range pfNeeded {
|
||||||
|
postSet[k.PostID] = struct{}{}
|
||||||
|
}
|
||||||
|
pids := make([]uint, 0, len(postSet))
|
||||||
|
for id := range postSet {
|
||||||
|
pids = append(pids, id)
|
||||||
|
}
|
||||||
|
type row struct {
|
||||||
|
PostID uint
|
||||||
|
Floor int
|
||||||
|
Status string
|
||||||
|
DeletedAt gorm.DeletedAt
|
||||||
|
}
|
||||||
|
var rows []row
|
||||||
|
_ = model.DB.Unscoped().Model(&model.Comment{}).
|
||||||
|
Select("post_id", "floor", "status", "deleted_at").
|
||||||
|
Where("post_id IN ?", pids).
|
||||||
|
Find(&rows)
|
||||||
|
for _, r := range rows {
|
||||||
|
k := pfKey{PostID: r.PostID, Floor: r.Floor}
|
||||||
|
// 同楼多条时后者覆盖;正常业务一帖一楼唯一
|
||||||
|
statusByPF[k] = contentStatusOrDeleted(r.Status, r.DeletedAt)
|
||||||
|
}
|
||||||
|
for _, k := range pfNeeded {
|
||||||
|
if _, ok := statusByPF[k]; !ok {
|
||||||
|
statusByPF[k] = "deleted"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
postStatus := map[uint]string{}
|
||||||
|
if len(postIDs) > 0 {
|
||||||
|
type row struct {
|
||||||
|
ID uint
|
||||||
|
Status string
|
||||||
|
DeletedAt gorm.DeletedAt
|
||||||
|
}
|
||||||
|
var rows []row
|
||||||
|
_ = model.DB.Unscoped().Model(&model.Post{}).
|
||||||
|
Select("id", "status", "deleted_at").
|
||||||
|
Where("id IN ?", postIDs).
|
||||||
|
Find(&rows)
|
||||||
|
for _, r := range rows {
|
||||||
|
postStatus[r.ID] = contentStatusOrDeleted(r.Status, r.DeletedAt)
|
||||||
|
}
|
||||||
|
for _, id := range postIDs {
|
||||||
|
if _, ok := postStatus[id]; !ok {
|
||||||
|
postStatus[id] = "deleted"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := range list {
|
||||||
|
m := &list[i]
|
||||||
|
if m.Kind != model.MessageKindModeration {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if m.RelatedCommentID != nil && *m.RelatedCommentID > 0 {
|
||||||
|
m.RelatedStatus = commentStatus[*m.RelatedCommentID]
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if cid, ok := resolvedByIndex[i]; ok && cid > 0 {
|
||||||
|
m.RelatedStatus = commentStatus[cid]
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if m.RelatedPostID == nil || *m.RelatedPostID == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pid := *m.RelatedPostID
|
||||||
|
if looksLikeModerationComment(m.Subject, m.Content) {
|
||||||
|
floor := 0
|
||||||
|
if m.RelatedFloor != nil && *m.RelatedFloor > 0 {
|
||||||
|
floor = *m.RelatedFloor
|
||||||
|
} else {
|
||||||
|
floor = parseNotifyFloor(m.Content)
|
||||||
|
}
|
||||||
|
if floor > 0 {
|
||||||
|
m.RelatedStatus = statusByPF[pfKey{PostID: pid, Floor: floor}]
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
m.RelatedStatus = postStatus[pid]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var notifyFloorRe = regexp.MustCompile(`#(\d+)\s*楼`)
|
||||||
|
|
||||||
|
// parseNotifyFloor 从待审评论文案解析楼号(如「#2 楼评论」「#1 楼下」)
|
||||||
|
func parseNotifyFloor(content string) int {
|
||||||
|
m := notifyFloorRe.FindStringSubmatch(content)
|
||||||
|
if len(m) < 2 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
var n int
|
||||||
|
_, _ = fmt.Sscanf(m[1], "%d", &n)
|
||||||
|
if n < 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
func contentStatusOrDeleted(status string, deletedAt gorm.DeletedAt) string {
|
||||||
|
if deletedAt.Valid {
|
||||||
|
return "deleted"
|
||||||
|
}
|
||||||
|
if status != "" {
|
||||||
|
return status
|
||||||
|
}
|
||||||
|
return model.ContentStatusPublished
|
||||||
|
}
|
||||||
|
|
||||||
// MarkNotificationsRead 将系统通知全部标为已读
|
// MarkNotificationsRead 将系统通知全部标为已读
|
||||||
func (s *MessageService) MarkNotificationsRead(userID uint) error {
|
func (s *MessageService) MarkNotificationsRead(userID uint) error {
|
||||||
return s.MarkConversationRead(userID, 0)
|
return s.MarkConversationRead(userID, 0)
|
||||||
|
|||||||
166
service/message_moderation.go
Normal file
166
service/message_moderation.go
Normal file
@@ -0,0 +1,166 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.iioio.com/freefire/jiang13-forum/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
// looksLikeModerationComment 判断待审通知是否指向评论(含嵌套回复)
|
||||||
|
func looksLikeModerationComment(subject, content string) bool {
|
||||||
|
if strings.Contains(subject, "评论") || strings.Contains(content, "评论") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return strings.Contains(content, "回复") || strings.Contains(content, "楼下")
|
||||||
|
}
|
||||||
|
|
||||||
|
// isNestedModerationContent 嵌套回复待审(正文为「#N 楼下…」)
|
||||||
|
func isNestedModerationContent(content string) bool {
|
||||||
|
return strings.Contains(content, "楼下")
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveModerationCommentRef 为历史待审评论通知推断目标评论 ID 与自身楼号
|
||||||
|
func resolveModerationCommentRef(postID uint, content string, notifyAt time.Time) (commentID uint, floor int) {
|
||||||
|
if postID == 0 || model.DB == nil {
|
||||||
|
return 0, 0
|
||||||
|
}
|
||||||
|
displayFloor := parseNotifyFloor(content)
|
||||||
|
if displayFloor <= 0 {
|
||||||
|
return 0, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
if isNestedModerationContent(content) {
|
||||||
|
var parent struct {
|
||||||
|
ID uint
|
||||||
|
}
|
||||||
|
err := model.DB.Unscoped().Model(&model.Comment{}).
|
||||||
|
Select("id").
|
||||||
|
Where("post_id = ? AND floor = ?", postID, displayFloor).
|
||||||
|
First(&parent).Error
|
||||||
|
if err != nil || parent.ID == 0 {
|
||||||
|
return 0, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
type childRow struct {
|
||||||
|
ID uint
|
||||||
|
Floor int
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
var children []childRow
|
||||||
|
_ = model.DB.Unscoped().Model(&model.Comment{}).
|
||||||
|
Select("id", "floor", "created_at").
|
||||||
|
Where("post_id = ? AND reply_to = ?", postID, parent.ID).
|
||||||
|
Find(&children).Error
|
||||||
|
if len(children) == 0 {
|
||||||
|
return 0, 0
|
||||||
|
}
|
||||||
|
if len(children) == 1 {
|
||||||
|
return children[0].ID, children[0].Floor
|
||||||
|
}
|
||||||
|
best := children[0]
|
||||||
|
bestDiff := math.MaxFloat64
|
||||||
|
for _, c := range children {
|
||||||
|
diff := math.Abs(float64(c.CreatedAt.Sub(notifyAt)))
|
||||||
|
if diff < bestDiff {
|
||||||
|
bestDiff = diff
|
||||||
|
best = c
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 通知与评论创建时间相差超过 7 天则放弃,避免误配旧回复
|
||||||
|
if bestDiff > float64(7*24*time.Hour) {
|
||||||
|
return 0, 0
|
||||||
|
}
|
||||||
|
return best.ID, best.Floor
|
||||||
|
}
|
||||||
|
|
||||||
|
var row struct {
|
||||||
|
ID uint
|
||||||
|
Floor int
|
||||||
|
}
|
||||||
|
err := model.DB.Unscoped().Model(&model.Comment{}).
|
||||||
|
Select("id", "floor").
|
||||||
|
Where("post_id = ? AND floor = ?", postID, displayFloor).
|
||||||
|
First(&row).Error
|
||||||
|
if err != nil || row.ID == 0 {
|
||||||
|
return 0, 0
|
||||||
|
}
|
||||||
|
return row.ID, row.Floor
|
||||||
|
}
|
||||||
|
|
||||||
|
// BackfillModerationNotifyRefs 为历史 moderation 通知补写 related_comment_id / related_floor
|
||||||
|
func BackfillModerationNotifyRefs() error {
|
||||||
|
if model.DB == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var rows []model.PrivateMessage
|
||||||
|
err := model.DB.Where("kind = ? AND (related_comment_id IS NULL OR related_comment_id = 0)", model.MessageKindModeration).
|
||||||
|
Find(&rows).Error
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, m := range rows {
|
||||||
|
if m.RelatedPostID == nil || *m.RelatedPostID == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !looksLikeModerationComment(m.Subject, m.Content) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
cid, fl := resolveModerationCommentRef(*m.RelatedPostID, m.Content, m.CreatedAt)
|
||||||
|
if cid == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
floor := fl
|
||||||
|
updates := map[string]interface{}{
|
||||||
|
"related_comment_id": cid,
|
||||||
|
"related_floor": floor,
|
||||||
|
}
|
||||||
|
_ = model.DB.Model(&model.PrivateMessage{}).Where("id = ?", m.ID).Updates(updates).Error
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// enrichModerationCommentIDs 为无 related_comment_id 的评论类待审通知解析评论 ID
|
||||||
|
func enrichModerationCommentIDs(list []model.PrivateMessage) map[int]uint {
|
||||||
|
out := make(map[int]uint)
|
||||||
|
for i := range list {
|
||||||
|
m := &list[i]
|
||||||
|
if m.Kind != model.MessageKindModeration {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if m.RelatedCommentID != nil && *m.RelatedCommentID > 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if m.RelatedPostID == nil || *m.RelatedPostID == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !looksLikeModerationComment(m.Subject, m.Content) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// 嵌套回复优先按子评论匹配,避免 displayFloor 查到父评论状态
|
||||||
|
if isNestedModerationContent(m.Content) {
|
||||||
|
cid, _ := resolveModerationCommentRef(*m.RelatedPostID, m.Content, m.CreatedAt)
|
||||||
|
if cid > 0 {
|
||||||
|
out[i] = cid
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// 顶层评论:有 related_floor 时按楼号查 ID
|
||||||
|
if m.RelatedFloor != nil && *m.RelatedFloor > 0 {
|
||||||
|
var row struct{ ID uint }
|
||||||
|
if err := model.DB.Unscoped().Model(&model.Comment{}).
|
||||||
|
Select("id").
|
||||||
|
Where("post_id = ? AND floor = ?", *m.RelatedPostID, *m.RelatedFloor).
|
||||||
|
First(&row).Error; err == nil && row.ID > 0 {
|
||||||
|
out[i] = row.ID
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
cid, _ := resolveModerationCommentRef(*m.RelatedPostID, m.Content, m.CreatedAt)
|
||||||
|
if cid > 0 {
|
||||||
|
out[i] = cid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
61
service/message_moderation_integration_test.go
Normal file
61
service/message_moderation_integration_test.go
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.iioio.com/freefire/jiang13-forum/model"
|
||||||
|
"github.com/glebarez/sqlite"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestProductionDBModerationEnrich 用本地生产库拷贝验证 related_status 回填(无库则跳过)
|
||||||
|
func TestProductionDBModerationEnrich(t *testing.T) {
|
||||||
|
dbPath := filepath.Join("..", "dist", "data", "jiang13.db")
|
||||||
|
if _, err := os.Stat(dbPath); err != nil {
|
||||||
|
t.Skip("dist/data/jiang13.db 不存在,跳过")
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
model.DB = db
|
||||||
|
|
||||||
|
if err := BackfillModerationNotifyRefs(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var adminID uint
|
||||||
|
if err := db.Model(&model.User{}).Where("role = ?", model.RoleAdmin).Order("id asc").Limit(1).Pluck("id", &adminID).Error; err != nil || adminID == 0 {
|
||||||
|
t.Skip("无管理员用户,跳过")
|
||||||
|
}
|
||||||
|
|
||||||
|
svc := &MessageService{}
|
||||||
|
list, _, err := svc.ListNotifications(adminID, 1, 100, "moderation")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(list) == 0 {
|
||||||
|
t.Skip("无 moderation 通知")
|
||||||
|
}
|
||||||
|
|
||||||
|
pendingUI := 0
|
||||||
|
published := 0
|
||||||
|
for _, m := range list {
|
||||||
|
if m.RelatedStatus == model.ContentStatusPublished {
|
||||||
|
published++
|
||||||
|
} else if m.RelatedStatus == "" || m.RelatedStatus == model.ContentStatusPending {
|
||||||
|
pendingUI++
|
||||||
|
t.Logf("仍无 published 状态: id=%d subject=%q status=%q content=%q", m.ID, m.Subject, m.RelatedStatus, m.Content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Logf("moderation=%d published=%d pending_or_empty=%d", len(list), published, pendingUI)
|
||||||
|
if published == 0 {
|
||||||
|
t.Fatal("没有任何 moderation 通知回填为 published")
|
||||||
|
}
|
||||||
|
if pendingUI > 0 {
|
||||||
|
t.Fatalf("%d 条通知仍会被 UI 判为待审", pendingUI)
|
||||||
|
}
|
||||||
|
}
|
||||||
102
service/message_moderation_test.go
Normal file
102
service/message_moderation_test.go
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.iioio.com/freefire/jiang13-forum/model"
|
||||||
|
"github.com/glebarez/sqlite"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParseNotifyFloor(t *testing.T) {
|
||||||
|
cases := map[string]int{
|
||||||
|
"用户 X 在《Y》提交了待审核 #2 楼评论": 2,
|
||||||
|
"用户 X 在《Y》#3 楼下提交了待审核回复": 3,
|
||||||
|
"无楼号": 0,
|
||||||
|
}
|
||||||
|
for content, want := range cases {
|
||||||
|
if got := parseNotifyFloor(content); got != want {
|
||||||
|
t.Errorf("parseNotifyFloor(%q) = %d, want %d", content, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnrichModerationStatusPublished(t *testing.T) {
|
||||||
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := db.AutoMigrate(&model.User{}, &model.Post{}, &model.Comment{}, &model.PrivateMessage{}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
model.DB = db
|
||||||
|
|
||||||
|
post := model.Post{Title: "测试帖", Status: model.ContentStatusPublished, UserID: 1}
|
||||||
|
if err := db.Create(&post).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
comment := model.Comment{
|
||||||
|
PostID: post.ID, UserID: 2, Floor: 2,
|
||||||
|
Status: model.ContentStatusPublished,
|
||||||
|
}
|
||||||
|
if err := db.Create(&comment).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
pid := post.ID
|
||||||
|
msg := model.PrivateMessage{
|
||||||
|
FromUserID: 0,
|
||||||
|
ToUserID: 1,
|
||||||
|
Subject: "新的待审核评论",
|
||||||
|
Content: "用户 A 在《测试帖》提交了待审核 #2 楼评论",
|
||||||
|
Kind: model.MessageKindModeration,
|
||||||
|
RelatedPostID: &pid,
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
}
|
||||||
|
if err := db.Create(&msg).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
svc := &MessageService{}
|
||||||
|
list := []model.PrivateMessage{msg}
|
||||||
|
svc.enrichModerationStatus(list)
|
||||||
|
if list[0].RelatedStatus != model.ContentStatusPublished {
|
||||||
|
t.Fatalf("RelatedStatus = %q, want published", list[0].RelatedStatus)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveNestedModerationCommentRef(t *testing.T) {
|
||||||
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := db.AutoMigrate(&model.Post{}, &model.Comment{}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
model.DB = db
|
||||||
|
|
||||||
|
post := model.Post{Title: "嵌套", Status: model.ContentStatusPublished}
|
||||||
|
if err := db.Create(&post).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
parent := model.Comment{PostID: post.ID, Floor: 1, Status: model.ContentStatusPublished}
|
||||||
|
child := model.Comment{
|
||||||
|
PostID: post.ID, Floor: 3, Status: model.ContentStatusPublished,
|
||||||
|
}
|
||||||
|
if err := db.Create(&parent).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
rt := parent.ID
|
||||||
|
child.ReplyTo = &rt
|
||||||
|
child.CreatedAt = time.Now()
|
||||||
|
if err := db.Create(&child).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
notifyAt := child.CreatedAt.Add(2 * time.Second)
|
||||||
|
cid, floor := resolveModerationCommentRef(post.ID, "用户 A 在《嵌套》#1 楼下提交了待审核回复", notifyAt)
|
||||||
|
if cid != child.ID || floor != 3 {
|
||||||
|
t.Fatalf("resolve = (%d, %d), want (%d, 3)", cid, floor, child.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -96,9 +96,15 @@ func (s *NotifyService) NotifyCommentPublished(comment *model.Comment) {
|
|||||||
subject := "收到新回复"
|
subject := "收到新回复"
|
||||||
content := FormatReplyContent(authorName, title, displayFloor, isNested)
|
content := FormatReplyContent(authorName, title, displayFloor, isNested)
|
||||||
pid := comment.PostID
|
pid := comment.PostID
|
||||||
_, _ = s.messages.SendSystem(toUserID, subject, content, model.MessageKindReply, &pid, nil)
|
cid := comment.ID
|
||||||
|
floor := comment.Floor
|
||||||
|
_, _ = s.messages.SendSystemWithRefs(toUserID, subject, content, model.MessageKindReply, SystemNotifyRefs{
|
||||||
|
PostID: &pid,
|
||||||
|
CommentID: &cid,
|
||||||
|
Floor: &floor,
|
||||||
|
})
|
||||||
|
|
||||||
s.sendReplyMail(toUserID, authorName, title, comment.PostID, displayFloor, isNested, comment.Content)
|
s.sendReplyMail(toUserID, authorName, title, comment.PostID, comment.Floor, displayFloor, isNested, comment.Content)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NotifyCommentMentions 评论公开后通知被 @提及的用户(跳过已收到回复通知的人)
|
// NotifyCommentMentions 评论公开后通知被 @提及的用户(跳过已收到回复通知的人)
|
||||||
@@ -125,6 +131,8 @@ func (s *NotifyService) NotifyCommentMentions(comment *model.Comment) {
|
|||||||
}
|
}
|
||||||
displayFloor := s.resolveDisplayFloor(comment)
|
displayFloor := s.resolveDisplayFloor(comment)
|
||||||
pid := comment.PostID
|
pid := comment.PostID
|
||||||
|
cid := comment.ID
|
||||||
|
floor := comment.Floor
|
||||||
subject := "有人 @了你"
|
subject := "有人 @了你"
|
||||||
content := FormatMentionContent(authorName, title, displayFloor)
|
content := FormatMentionContent(authorName, title, displayFloor)
|
||||||
|
|
||||||
@@ -132,7 +140,11 @@ func (s *NotifyService) NotifyCommentMentions(comment *model.Comment) {
|
|||||||
if uid == 0 || uid == comment.UserID || uid == replyTo {
|
if uid == 0 || uid == comment.UserID || uid == replyTo {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
_, _ = s.messages.SendSystem(uid, subject, content, model.MessageKindMention, &pid, nil)
|
_, _ = s.messages.SendSystemWithRefs(uid, subject, content, model.MessageKindMention, SystemNotifyRefs{
|
||||||
|
PostID: &pid,
|
||||||
|
CommentID: &cid,
|
||||||
|
Floor: &floor,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,8 +161,9 @@ func (s *NotifyService) NotifyPendingPost(post *model.Post) {
|
|||||||
subject := "新的待审核帖子"
|
subject := "新的待审核帖子"
|
||||||
content := FormatPendingPostContent(authorName, title, post.ID)
|
content := FormatPendingPostContent(authorName, title, post.ID)
|
||||||
pid := post.ID
|
pid := post.ID
|
||||||
s.notifyAdmins(subject, content, model.MessageKindModeration, &pid, func(siteName, baseURL string) (string, string, string) {
|
s.notifyAdmins(subject, content, model.MessageKindModeration, SystemNotifyRefs{PostID: &pid}, func(siteName, baseURL string) (string, string, string) {
|
||||||
return BuildModerationMail(siteName, "帖子", authorName, title, post.ID, 0, false, AbsoluteURL(baseURL, "/admin/posts"))
|
adminPath := fmt.Sprintf("/admin/posts?id=%d", post.ID)
|
||||||
|
return BuildModerationMail(siteName, "帖子", authorName, title, post.ID, 0, false, AbsoluteURL(baseURL, adminPath))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -173,14 +186,21 @@ func (s *NotifyService) NotifyPendingComment(comment *model.Comment) {
|
|||||||
isNested := comment.ReplyTo != nil && *comment.ReplyTo > 0
|
isNested := comment.ReplyTo != nil && *comment.ReplyTo > 0
|
||||||
content := FormatPendingCommentContent(authorName, title, displayFloor, isNested)
|
content := FormatPendingCommentContent(authorName, title, displayFloor, isNested)
|
||||||
pid := comment.PostID
|
pid := comment.PostID
|
||||||
s.notifyAdmins(subject, content, model.MessageKindModeration, &pid, func(siteName, baseURL string) (string, string, string) {
|
cid := comment.ID
|
||||||
return BuildModerationMail(siteName, "评论", authorName, title, comment.PostID, displayFloor, isNested, AbsoluteURL(baseURL, "/admin/comments"))
|
floor := comment.Floor
|
||||||
|
adminPath := fmt.Sprintf("/admin/comments?id=%d", comment.ID)
|
||||||
|
s.notifyAdmins(subject, content, model.MessageKindModeration, SystemNotifyRefs{
|
||||||
|
PostID: &pid,
|
||||||
|
CommentID: &cid,
|
||||||
|
Floor: &floor,
|
||||||
|
}, func(siteName, baseURL string) (string, string, string) {
|
||||||
|
return BuildModerationMail(siteName, "评论", authorName, title, comment.PostID, displayFloor, isNested, AbsoluteURL(baseURL, adminPath))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *NotifyService) notifyAdmins(
|
func (s *NotifyService) notifyAdmins(
|
||||||
subject, content, kind string,
|
subject, content, kind string,
|
||||||
relatedPostID *uint,
|
refs SystemNotifyRefs,
|
||||||
buildMail func(siteName, baseURL string) (subj, text, html string),
|
buildMail func(siteName, baseURL string) (subj, text, html string),
|
||||||
) {
|
) {
|
||||||
admins, err := s.listAdmins()
|
admins, err := s.listAdmins()
|
||||||
@@ -197,7 +217,7 @@ func (s *NotifyService) notifyAdmins(
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, admin := range admins {
|
for _, admin := range admins {
|
||||||
_, _ = s.messages.SendSystem(admin.ID, subject, content, kind, relatedPostID, nil)
|
_, _ = s.messages.SendSystemWithRefs(admin.ID, subject, content, kind, refs)
|
||||||
email := strings.TrimSpace(admin.Email)
|
email := strings.TrimSpace(admin.Email)
|
||||||
if email == "" || mailSubj == "" {
|
if email == "" || mailSubj == "" {
|
||||||
continue
|
continue
|
||||||
@@ -211,7 +231,7 @@ func (s *NotifyService) notifyAdmins(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *NotifyService) sendReplyMail(toUserID uint, authorName, postTitle string, postID uint, displayFloor int, isNested bool, rawContent string) {
|
func (s *NotifyService) sendReplyMail(toUserID uint, authorName, postTitle string, postID uint, ownFloor, displayFloor int, isNested bool, rawContent string) {
|
||||||
if s.mail == nil || !s.settings.MailReady() {
|
if s.mail == nil || !s.settings.MailReady() {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -227,6 +247,10 @@ func (s *NotifyService) sendReplyMail(toUserID uint, authorName, postTitle strin
|
|||||||
baseURL := s.settings.SitePublicBaseURL("")
|
baseURL := s.settings.SitePublicBaseURL("")
|
||||||
postPath := s.settings.Permalink().PostPath(postID)
|
postPath := s.settings.Permalink().PostPath(postID)
|
||||||
link := AbsoluteURL(baseURL, postPath)
|
link := AbsoluteURL(baseURL, postPath)
|
||||||
|
// 直达评论自身楼层(嵌套回复也有独立 floor)
|
||||||
|
if ownFloor > 0 {
|
||||||
|
link = fmt.Sprintf("%s#floor-%d", link, ownFloor)
|
||||||
|
}
|
||||||
excerpt := truncateNotifyExcerpt(rawContent, 120)
|
excerpt := truncateNotifyExcerpt(rawContent, 120)
|
||||||
subj, text, html := BuildReplyMail(siteName, authorName, postTitle, displayFloor, isNested, excerpt, link)
|
subj, text, html := BuildReplyMail(siteName, authorName, postTitle, displayFloor, isNested, excerpt, link)
|
||||||
_ = s.mail.SendHTML(email, subj, text, html)
|
_ = s.mail.SendHTML(email, subj, text, html)
|
||||||
|
|||||||
@@ -357,18 +357,12 @@ func (s *PostService) List(q PostListQuery) ([]model.Post, int64, error) {
|
|||||||
}
|
}
|
||||||
switch sortKey {
|
switch sortKey {
|
||||||
case "reply":
|
case "reply":
|
||||||
// 有回复的帖子优先,按最后回复时间倒序;无回复的帖子沉底(仅计已公开评论)
|
// 最近活动:按最后公开评论时间与发帖时间的较晚者倒序(零回复新帖也能靠前)
|
||||||
db = db.Order(`(
|
db = db.Order(`COALESCE((
|
||||||
SELECT COUNT(*) FROM comments
|
|
||||||
WHERE comments.post_id = posts.id AND comments.deleted_at IS NULL
|
|
||||||
AND comments.status = 'published'
|
|
||||||
) > 0 DESC`)
|
|
||||||
db = db.Order(`(
|
|
||||||
SELECT MAX(created_at) FROM comments
|
SELECT MAX(created_at) FROM comments
|
||||||
WHERE comments.post_id = posts.id AND comments.deleted_at IS NULL
|
WHERE comments.post_id = posts.id AND comments.deleted_at IS NULL
|
||||||
AND comments.status = 'published'
|
AND comments.status = 'published'
|
||||||
) DESC`)
|
), posts.created_at) DESC`)
|
||||||
db = db.Order("posts.created_at DESC")
|
|
||||||
case "hot":
|
case "hot":
|
||||||
// 仅推荐帖:按互动再按 id
|
// 仅推荐帖:按互动再按 id
|
||||||
db = db.Order("like_count desc, view_count desc")
|
db = db.Order("like_count desc, view_count desc")
|
||||||
@@ -384,7 +378,7 @@ func normalizePostSort(sort string) string {
|
|||||||
case "latest", "hot":
|
case "latest", "hot":
|
||||||
return sort
|
return sort
|
||||||
default:
|
default:
|
||||||
// 含空串 / reply:默认新评论
|
// 含空串 / reply:默认最近活动
|
||||||
return "reply"
|
return "reply"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -305,14 +305,20 @@ func (s *ReportService) Handle(in HandleReportInput) (*model.PostReport, error)
|
|||||||
if commentAuthorID > 0 {
|
if commentAuthorID > 0 {
|
||||||
pid := postID
|
pid := postID
|
||||||
rid := rep.ID
|
rid := rep.ID
|
||||||
|
cid := *rep.CommentID
|
||||||
|
floor := commentFloor
|
||||||
body := fmt.Sprintf("你在帖子《%s》下的评论(#%d)未通过审核。\n\n原因:\n%s", postTitle, commentFloor, reason)
|
body := fmt.Sprintf("你在帖子《%s》下的评论(#%d)未通过审核。\n\n原因:\n%s", postTitle, commentFloor, reason)
|
||||||
_, _ = s.messages.SendSystem(
|
_, _ = s.messages.SendSystemWithRefs(
|
||||||
commentAuthorID,
|
commentAuthorID,
|
||||||
fmt.Sprintf("评论未通过审核 · 《%s》", postTitle),
|
fmt.Sprintf("评论未通过审核 · 《%s》", postTitle),
|
||||||
body,
|
body,
|
||||||
model.MessageKindReject,
|
model.MessageKindReject,
|
||||||
&pid,
|
SystemNotifyRefs{
|
||||||
&rid,
|
PostID: &pid,
|
||||||
|
ReportID: &rid,
|
||||||
|
CommentID: &cid,
|
||||||
|
Floor: &floor,
|
||||||
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
@@ -345,13 +351,19 @@ func (s *ReportService) Handle(in HandleReportInput) (*model.PostReport, error)
|
|||||||
}
|
}
|
||||||
pid := postID
|
pid := postID
|
||||||
rid := rep.ID
|
rid := rep.ID
|
||||||
_, _ = s.messages.SendSystem(
|
resultRefs := SystemNotifyRefs{PostID: &pid, ReportID: &rid}
|
||||||
|
if isCommentReport && rep.CommentID != nil {
|
||||||
|
cid := *rep.CommentID
|
||||||
|
floor := commentFloor
|
||||||
|
resultRefs.CommentID = &cid
|
||||||
|
resultRefs.Floor = &floor
|
||||||
|
}
|
||||||
|
_, _ = s.messages.SendSystemWithRefs(
|
||||||
rep.ReporterID,
|
rep.ReporterID,
|
||||||
"举报处理结果通知",
|
"举报处理结果通知",
|
||||||
content,
|
content,
|
||||||
model.MessageKindReportResult,
|
model.MessageKindReportResult,
|
||||||
&pid,
|
resultRefs,
|
||||||
&rid,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
_ = model.DB.Preload("Post", func(tx *gorm.DB) *gorm.DB {
|
_ = model.DB.Preload("Post", func(tx *gorm.DB) *gorm.DB {
|
||||||
|
|||||||
@@ -206,7 +206,7 @@ var feedSortTabDefaultOrder = []string{
|
|||||||
}
|
}
|
||||||
|
|
||||||
var feedSortTabDefaultLabels = map[string]string{
|
var feedSortTabDefaultLabels = map[string]string{
|
||||||
FeedSortReply: "新评论",
|
FeedSortReply: "最新",
|
||||||
FeedSortLatest: "新帖子",
|
FeedSortLatest: "新帖子",
|
||||||
FeedSortHot: "推荐帖",
|
FeedSortHot: "推荐帖",
|
||||||
}
|
}
|
||||||
@@ -287,7 +287,7 @@ var forumSettingDefs = []settingDef{
|
|||||||
|
|
||||||
var feedSettingDefaults = map[string]string{
|
var feedSettingDefaults = map[string]string{
|
||||||
SettingFeedListStyle: "title",
|
SettingFeedListStyle: "title",
|
||||||
SettingFeedSortTabs: `[{"id":"reply","label":"新评论","enabled":true},{"id":"latest","label":"新帖子","enabled":true},{"id":"hot","label":"推荐帖","enabled":true}]`,
|
SettingFeedSortTabs: `[{"id":"reply","label":"最新","enabled":true},{"id":"latest","label":"新帖子","enabled":true},{"id":"hot","label":"推荐帖","enabled":true}]`,
|
||||||
}
|
}
|
||||||
|
|
||||||
var asideSettingDefaults = map[string]string{
|
var asideSettingDefaults = map[string]string{
|
||||||
|
|||||||
Reference in New Issue
Block a user