Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2e9c42a34c | |||
| dff60dde6a | |||
| ea9e0058d4 | |||
| d5aa36416c | |||
| 2159280af5 | |||
| bc9a031890 | |||
| 0d81787125 | |||
| 68713c053b |
2
Makefile
2
Makefile
@@ -5,7 +5,7 @@ APP_NAME := jiang13
|
||||
MAIN_PKG := ./cmd/jiang13
|
||||
BUILD_DIR := dist
|
||||
DEV_DATA_DIR := dist/data
|
||||
VERSION := 1.1.5
|
||||
VERSION := 1.1.6
|
||||
LDFLAGS := -s -w -X main.version=$(VERSION)
|
||||
REGISTRY_IMAGE := hangzhang714128/jiang13-forum
|
||||
|
||||
|
||||
36
README.md
36
README.md
@@ -20,6 +20,7 @@
|
||||
[快速开始](#-快速开始) ·
|
||||
[界面预览](#-界面预览) ·
|
||||
[功能亮点](#-功能亮点) ·
|
||||
[更新日志](docs/site-posts/changelog.md) ·
|
||||
[路线图](ROADMAP.md) ·
|
||||
[参与贡献](CONTRIBUTING.md)
|
||||
|
||||
@@ -172,6 +173,11 @@ make compose-up
|
||||
|
||||
浏览器打开 `http://localhost:3000/register` 注册;**首个用户自动成为管理员**。
|
||||
|
||||
版本变更与升级说明见 **[更新日志](docs/site-posts/changelog.md)**。Docker 与 Windows / Linux 单文件共用同一版本号。
|
||||
|
||||
- Docker 标签:[hub.docker.com/r/hangzhang714128/jiang13-forum/tags](https://hub.docker.com/r/hangzhang714128/jiang13-forum/tags)
|
||||
- 预编译包:[Gitea Releases](https://git.iioio.com/freefire/jiang13-forum/releases)
|
||||
|
||||
**拉取已构建镜像(Docker Hub):**
|
||||
|
||||
```bash
|
||||
@@ -206,15 +212,15 @@ docker run -d --name jiang13 \
|
||||
docker login
|
||||
.\build.bat -Target docker # Windows
|
||||
# make docker # Linux/macOS
|
||||
docker push hangzhang714128/jiang13-forum:1.1.5
|
||||
docker push hangzhang714128/jiang13-forum:1.1.6
|
||||
docker push hangzhang714128/jiang13-forum:latest
|
||||
```
|
||||
|
||||
或直接构建:
|
||||
|
||||
```bash
|
||||
docker build --build-arg VERSION=1.1.5 -t hangzhang714128/jiang13-forum:1.1.5 -t hangzhang714128/jiang13-forum:latest .
|
||||
docker push hangzhang714128/jiang13-forum:1.1.5
|
||||
docker build --build-arg VERSION=1.1.6 -t hangzhang714128/jiang13-forum:1.1.6 -t hangzhang714128/jiang13-forum:latest .
|
||||
docker push hangzhang714128/jiang13-forum:1.1.6
|
||||
docker push hangzhang714128/jiang13-forum:latest
|
||||
```
|
||||
|
||||
@@ -239,7 +245,29 @@ docker push hangzhang714128/jiang13-forum:latest
|
||||
|
||||
### 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.6:** [Windows](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.6/jiang13-1.1.6-windows-amd64.exe) · [Linux](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.6/jiang13-1.1.6-linux-amd64)
|
||||
|
||||
把文件放到目标目录后直接运行(首次会在同目录生成 `app.ini`):
|
||||
|
||||
```bash
|
||||
# Windows
|
||||
.\jiang13-1.1.6-windows-amd64.exe
|
||||
# 或改名为 jiang13.exe 后:
|
||||
.\jiang13.exe
|
||||
|
||||
# Linux
|
||||
chmod +x jiang13-1.1.6-linux-amd64
|
||||
./jiang13-1.1.6-linux-amd64
|
||||
```
|
||||
|
||||
本地刚编译的产物在 `dist/`:
|
||||
|
||||
```bash
|
||||
# Windows
|
||||
|
||||
@@ -12,7 +12,7 @@ $AppName = 'jiang13'
|
||||
$MainPkg = './cmd/jiang13'
|
||||
$BuildDir = 'dist'
|
||||
$DevDataDir = 'dist/data'
|
||||
$Version = '1.1.5'
|
||||
$Version = '1.1.6'
|
||||
$RegistryImage = 'hangzhang714128/jiang13-forum'
|
||||
$Ldlags = "-s -w -X main.version=$Version"
|
||||
|
||||
|
||||
@@ -18,6 +18,16 @@
|
||||
|
||||
把原先分篇的「上手 / 功能 / 部署」三帖 **删除**,避免与长文重复。
|
||||
|
||||
## 自定义单页(推荐)
|
||||
|
||||
站务帖之外,建议在后台 **单页管理** 发一篇更新日志,方便 Docker / Windows 用户对照版本:
|
||||
|
||||
| 文件 | 标题 | slug | 操作 |
|
||||
| --- | --- | --- | --- |
|
||||
| [changelog.md](./changelog.md) | 更新日志 | `changelog` | 发布;页脚展示(可选侧栏导航) |
|
||||
|
||||
访问路径:`/page/changelog`。
|
||||
|
||||
## 可选短文
|
||||
|
||||
若站务区希望不止一篇,见 [optional.md](./optional.md):
|
||||
|
||||
145
docs/site-posts/changelog.md
Normal file
145
docs/site-posts/changelog.md
Normal file
@@ -0,0 +1,145 @@
|
||||
# 更新日志
|
||||
|
||||
> 建议标题:更新日志
|
||||
> 建议 slug:`changelog`
|
||||
> 建议路径:`/page/changelog`
|
||||
> 建议操作:后台「单页管理」新建并发布;勾选「页脚展示」(可选「侧栏导航」)
|
||||
> 复制正文时:从下方第一个 `---` **之后**开始粘贴(Markdown 模式)
|
||||
|
||||
---
|
||||
|
||||
Docker 镜像、Windows exe、Linux 单文件 **共用同一版本号**。有新版本时,以本页为准。
|
||||
|
||||
**当前版本:1.1.6**(2026-09-01)
|
||||
|
||||
## 去哪看新版本
|
||||
|
||||
| 渠道 | 看什么 | 地址 |
|
||||
| --- | --- | --- |
|
||||
| 本页 | 版本号、变更说明、升级注意 | 本站 `/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.6 直接下载:**
|
||||
|
||||
- Windows x64:[jiang13-1.1.6-windows-amd64.exe](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.6/jiang13-1.1.6-windows-amd64.exe)
|
||||
- Linux x64:[jiang13-1.1.6-linux-amd64](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.6/jiang13-1.1.6-linux-amd64)
|
||||
- 校验文件:[SHA256SUMS.txt](https://git.iioio.com/freefire/jiang13-forum/releases/download/v1.1.6/SHA256SUMS.txt)
|
||||
|
||||
拉取指定版本镜像:
|
||||
|
||||
```bash
|
||||
docker pull hangzhang714128/jiang13-forum:1.1.6
|
||||
# 或始终跟随最新
|
||||
docker pull hangzhang714128/jiang13-forum:latest
|
||||
```
|
||||
|
||||
Windows:停掉正在跑的进程或服务,用新下载的 exe 覆盖原文件(可改名为 `jiang13.exe`),**不要动**旁边的 `data/` 与 `app.ini`,再启动即可。
|
||||
|
||||
Linux:赋予执行权限后放到原目录覆盖,同样保留 `data/` 与 `app.ini`。
|
||||
|
||||
## 升级注意
|
||||
|
||||
- 一般只需换镜像或换 exe,数据目录向后兼容。
|
||||
- Docker 请继续挂载原来的 `/data` 卷,切勿新建空目录当「升级」。
|
||||
- 升级后若页面样式异常,强制刷新浏览器(Ctrl+F5)。程序也会在前端资源失效时自动硬刷新。
|
||||
|
||||
---
|
||||
|
||||
## 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);
|
||||
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: {
|
||||
board_id: string; title: string; content: string; tags?: string; post_type?: string;
|
||||
poll_options?: string; bounty_points?: number; lottery_winner_count?: number;
|
||||
|
||||
@@ -224,7 +224,7 @@ export interface FeedSortTab {
|
||||
}
|
||||
|
||||
export const DEFAULT_FEED_SORT_TABS: FeedSortTab[] = [
|
||||
{ id: 'reply', label: '新评论', enabled: true },
|
||||
{ id: 'reply', label: '最新', enabled: true },
|
||||
{ id: 'latest', label: '新帖子', enabled: true },
|
||||
{ id: 'hot', label: '推荐帖', enabled: true },
|
||||
];
|
||||
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
insertMarkdownLink,
|
||||
} from '../utils/markdownFormat';
|
||||
import { countWords } from '../utils/text';
|
||||
import { api } from '../api/client';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { MembersOnly } from './editor/MembersOnlyExtension';
|
||||
import { ReplyOnly } from './editor/ReplyOnlyExtension';
|
||||
@@ -40,7 +39,8 @@ import { TabIndent } from './editor/TabIndentExtension';
|
||||
import { ArticleImage, type ImageDisplay } from './editor/ArticleImageExtension';
|
||||
import { ImageGroup, suggestImageGroupLayout } from './editor/ImageGroupExtension';
|
||||
import { ClearFloatParagraph, ClearFloatSync } from './editor/ClearFloatParagraph';
|
||||
import { ArticleLinkDialog } from './editor/ArticleLinkDialog';
|
||||
import { ArticleLinkDialog, type ArticleLinkConfirm } from './editor/ArticleLinkDialog';
|
||||
import { ArticleImagePickerDialog } from './editor/ArticleImagePickerDialog';
|
||||
import { ArticleCodeBlockDialog } from './editor/ArticleCodeBlockDialog';
|
||||
import { ArticleCodeBlock } from './editor/ArticleCodeBlockExtension';
|
||||
import {
|
||||
@@ -73,6 +73,7 @@ interface Props {
|
||||
|
||||
type EditorMode = 'rich' | 'markdown';
|
||||
type LinkTarget = 'rich' | 'markdown';
|
||||
type ImagePickerTarget = 'rich' | 'markdown';
|
||||
type CodeBlockTarget = 'rich' | 'markdown';
|
||||
type TableTarget = 'rich' | 'markdown';
|
||||
|
||||
@@ -167,34 +168,6 @@ function cycleHeading(editor: Editor) {
|
||||
editor.chain().focus().toggleHeading({ level: 2 }).run();
|
||||
}
|
||||
|
||||
/** 触发图片文件选择并上传(支持多选) */
|
||||
async function uploadPostImageFiles(multiple = true): Promise<string[]> {
|
||||
return new Promise(resolve => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = 'image/jpeg,image/png,image/gif,image/webp';
|
||||
input.multiple = multiple;
|
||||
input.onchange = async () => {
|
||||
const files = [...(input.files ?? [])];
|
||||
if (!files.length) {
|
||||
resolve([]);
|
||||
return;
|
||||
}
|
||||
const urls: string[] = [];
|
||||
for (const file of files) {
|
||||
try {
|
||||
const { url } = await api.uploadPostImage(file);
|
||||
urls.push(url);
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '图片上传失败');
|
||||
}
|
||||
}
|
||||
resolve(urls);
|
||||
};
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
|
||||
/** 渲染工具栏按钮列表 */
|
||||
function renderToolButtons(tools: ToolBtn[]) {
|
||||
return tools.map((t, i) => (
|
||||
@@ -228,7 +201,11 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
const [markdownSource, setMarkdownSource] = useState('');
|
||||
const [linkDialogOpen, setLinkDialogOpen] = useState(false);
|
||||
const [linkDialogUrl, setLinkDialogUrl] = useState('');
|
||||
const [linkDialogText, setLinkDialogText] = useState('');
|
||||
const [linkDialogEditing, setLinkDialogEditing] = useState(false);
|
||||
const [linkTarget, setLinkTarget] = useState<LinkTarget>('rich');
|
||||
const [imagePickerOpen, setImagePickerOpen] = useState(false);
|
||||
const [imagePickerTarget, setImagePickerTarget] = useState<ImagePickerTarget>('rich');
|
||||
const [codeBlockDialogOpen, setCodeBlockDialogOpen] = useState(false);
|
||||
const [codeBlockTarget, setCodeBlockTarget] = useState<CodeBlockTarget>('rich');
|
||||
const [codeBlockEditing, setCodeBlockEditing] = useState(false);
|
||||
@@ -262,6 +239,11 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
openOnClick: false,
|
||||
autolink: true,
|
||||
defaultProtocol: 'https',
|
||||
// 新标签由全站设置在展示层处理,编辑器不写 target/rel
|
||||
HTMLAttributes: {
|
||||
target: null,
|
||||
rel: null,
|
||||
},
|
||||
}),
|
||||
ArticleImage.configure({ inline: false, allowBase64: false }),
|
||||
ImageGroup,
|
||||
@@ -393,14 +375,33 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
const openLinkDialog = useCallback((target: LinkTarget) => {
|
||||
if (target === 'rich') {
|
||||
if (!editor) return;
|
||||
const prev = editor.getAttributes('link').href as string | undefined;
|
||||
setLinkDialogUrl(prev ?? '');
|
||||
const { from, to, empty } = editor.state.selection;
|
||||
let text = empty ? '' : editor.state.doc.textBetween(from, to, '');
|
||||
let href = '';
|
||||
let editing = false;
|
||||
if (editor.isActive('link')) {
|
||||
const attrs = editor.getAttributes('link');
|
||||
href = (attrs.href as string) || '';
|
||||
editing = Boolean(href);
|
||||
editor.chain().focus().extendMarkRange('link').run();
|
||||
const sel = editor.state.selection;
|
||||
text = editor.state.doc.textBetween(sel.from, sel.to, '') || text;
|
||||
}
|
||||
setLinkDialogUrl(href);
|
||||
setLinkDialogText(text);
|
||||
setLinkDialogEditing(editing);
|
||||
} else {
|
||||
const textarea = markdownRef.current;
|
||||
const selected = textarea
|
||||
? markdownSource.slice(textarea.selectionStart, textarea.selectionEnd)
|
||||
: '';
|
||||
setLinkDialogUrl('');
|
||||
setLinkDialogText(selected);
|
||||
setLinkDialogEditing(false);
|
||||
}
|
||||
setLinkTarget(target);
|
||||
setLinkDialogOpen(true);
|
||||
}, [editor]);
|
||||
}, [editor, markdownSource]);
|
||||
|
||||
const openCodeBlockDialog = useCallback((target: CodeBlockTarget) => {
|
||||
setCodeBlockTarget(target);
|
||||
@@ -477,11 +478,12 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
}
|
||||
}, [editor]);
|
||||
|
||||
const applyLink = useCallback((url: string) => {
|
||||
const applyLink = useCallback((payload: ArticleLinkConfirm) => {
|
||||
const { url, text } = payload;
|
||||
if (linkTarget === 'markdown') {
|
||||
const textarea = markdownRef.current;
|
||||
if (!textarea || !url) return;
|
||||
insertMarkdownLink(textarea, markdownSource, url, handleMarkdownChange);
|
||||
insertMarkdownLink(textarea, markdownSource, url, handleMarkdownChange, { text });
|
||||
return;
|
||||
}
|
||||
if (!editor) return;
|
||||
@@ -489,7 +491,31 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
||||
return;
|
||||
}
|
||||
editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
|
||||
// 新标签行为由全站 open_content_links_in_new_tab 在展示层处理
|
||||
const linkAttrs = { href: url };
|
||||
const { empty } = editor.state.selection;
|
||||
const hasLink = editor.isActive('link');
|
||||
if (!empty || hasLink) {
|
||||
editor.chain().focus().extendMarkRange('link').setLink(linkAttrs).run();
|
||||
const { from, to } = editor.state.selection;
|
||||
const current = editor.state.doc.textBetween(from, to, '');
|
||||
if (text && current !== text) {
|
||||
editor.chain().focus().insertContentAt(
|
||||
{ from, to },
|
||||
{
|
||||
type: 'text',
|
||||
text,
|
||||
marks: [{ type: 'link', attrs: linkAttrs }],
|
||||
},
|
||||
).run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
editor.chain().focus().insertContent({
|
||||
type: 'text',
|
||||
text: text || '链接文字',
|
||||
marks: [{ type: 'link', attrs: linkAttrs }],
|
||||
}).run();
|
||||
}, [editor, linkTarget, markdownSource, handleMarkdownChange]);
|
||||
|
||||
const removeLink = useCallback(() => {
|
||||
@@ -497,16 +523,33 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
||||
}, [editor]);
|
||||
|
||||
const setImage = useCallback(async () => {
|
||||
if (!editor) return;
|
||||
const urls = await uploadPostImageFiles(true);
|
||||
const openImagePicker = useCallback((target: ImagePickerTarget) => {
|
||||
setImagePickerTarget(target);
|
||||
setImagePickerOpen(true);
|
||||
}, []);
|
||||
|
||||
const applyImageUrls = useCallback((urls: string[]) => {
|
||||
if (!urls.length) return;
|
||||
if (imagePickerTarget === 'markdown') {
|
||||
const textarea = markdownRef.current;
|
||||
if (!textarea) return;
|
||||
if (urls.length === 1) {
|
||||
insertAtCursor(textarea, markdownSource, `\n\n\n\n`, handleMarkdownChange);
|
||||
return;
|
||||
}
|
||||
const layout = suggestImageGroupLayout(urls.length);
|
||||
const imgs = urls.map(u => `<img src="${u}" alt="">`).join('');
|
||||
const block = `\n\n<div data-image-group data-layout="${layout}" class="image-group image-group--${layout}">${imgs}</div>\n\n`;
|
||||
insertAtCursor(textarea, markdownSource, block, handleMarkdownChange);
|
||||
return;
|
||||
}
|
||||
if (!editor) return;
|
||||
if (urls.length === 1) {
|
||||
editor.chain().focus().setImage({ src: urls[0] }).run();
|
||||
return;
|
||||
}
|
||||
editor.chain().focus().insertImageGroup(urls, suggestImageGroupLayout(urls.length)).run();
|
||||
}, [editor]);
|
||||
}, [editor, imagePickerTarget, markdownSource, handleMarkdownChange]);
|
||||
|
||||
const setImageDisplay = useCallback((display: ImageDisplay) => {
|
||||
if (!editor) return;
|
||||
@@ -596,21 +639,6 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
fn(textarea, markdownSource, handleMarkdownChange);
|
||||
}, [markdownSource, handleMarkdownChange]);
|
||||
|
||||
const insertMarkdownImage = useCallback(async () => {
|
||||
const textarea = markdownRef.current;
|
||||
if (!textarea) return;
|
||||
const urls = await uploadPostImageFiles(true);
|
||||
if (!urls.length) return;
|
||||
if (urls.length === 1) {
|
||||
insertAtCursor(textarea, markdownSource, `\n\n\n\n`, handleMarkdownChange);
|
||||
return;
|
||||
}
|
||||
const layout = suggestImageGroupLayout(urls.length);
|
||||
const imgs = urls.map(u => `<img src="${u}" alt="">`).join('');
|
||||
const block = `\n\n<div data-image-group data-layout="${layout}" class="image-group image-group--${layout}">${imgs}</div>\n\n`;
|
||||
insertAtCursor(textarea, markdownSource, block, handleMarkdownChange);
|
||||
}, [markdownSource, handleMarkdownChange]);
|
||||
|
||||
const markdownPreviewHtml = useMemo(
|
||||
() => sanitizeHtml(markdownToHtml(markdownSource)),
|
||||
[markdownSource],
|
||||
@@ -637,9 +665,9 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
{ icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: () => openLinkDialog('rich') },
|
||||
{
|
||||
icon: <ImageIcon size={15} />,
|
||||
title: '上传图片',
|
||||
hint: '可多选;多张自动并排成图组',
|
||||
action: setImage,
|
||||
title: '图片',
|
||||
hint: '上传、链接或从已上传中选择',
|
||||
action: () => openImagePicker('rich'),
|
||||
},
|
||||
{
|
||||
icon: <Columns2 size={15} />,
|
||||
@@ -732,7 +760,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
}
|
||||
|
||||
return tools;
|
||||
}, [editor, enableContentGates, openLinkDialog, openCodeBlockDialog, openTableDialog, setImage, wrapMembersOnly, wrapReplyOnly, wrapPointsOnly, wrapSelectedAsGroup, setImageDisplay]);
|
||||
}, [editor, enableContentGates, openLinkDialog, openCodeBlockDialog, openTableDialog, openImagePicker, wrapMembersOnly, wrapReplyOnly, wrapPointsOnly, wrapSelectedAsGroup, setImageDisplay]);
|
||||
|
||||
const buildMarkdownTools = useCallback((): ToolBtn[] => {
|
||||
const tools: ToolBtn[] = [
|
||||
@@ -748,7 +776,12 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
{ icon: <Code size={15} />, title: '代码块', hint: '语言、行号与折叠', action: () => openCodeBlockDialog('markdown') },
|
||||
{ icon: <TableIcon size={15} />, title: '表格', hint: '插入 GFM 管道表', action: () => openTableDialog('markdown') },
|
||||
{ icon: <LinkIcon size={15} />, title: '链接', action: () => openLinkDialog('markdown') },
|
||||
{ icon: <ImageIcon size={15} />, title: '上传图片', action: insertMarkdownImage },
|
||||
{
|
||||
icon: <ImageIcon size={15} />,
|
||||
title: '图片',
|
||||
hint: '上传、链接或从已上传中选择',
|
||||
action: () => openImagePicker('markdown'),
|
||||
},
|
||||
];
|
||||
if (enableContentGates) {
|
||||
tools.push(
|
||||
@@ -776,7 +809,7 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
);
|
||||
}
|
||||
return tools;
|
||||
}, [enableContentGates, withMarkdown, openLinkDialog, openCodeBlockDialog, openTableDialog, insertMarkdownImage]);
|
||||
}, [enableContentGates, withMarkdown, openLinkDialog, openCodeBlockDialog, openTableDialog, openImagePicker]);
|
||||
|
||||
const tools = mode === 'rich' ? buildRichTools() : buildMarkdownTools();
|
||||
const words = mode === 'markdown'
|
||||
@@ -897,8 +930,15 @@ const ArticleEditor = forwardRef<ArticleEditorHandle, Props>(function ArticleEdi
|
||||
open={linkDialogOpen}
|
||||
onOpenChange={setLinkDialogOpen}
|
||||
initialUrl={linkDialogUrl}
|
||||
initialText={linkDialogText}
|
||||
editing={linkDialogEditing}
|
||||
onConfirm={applyLink}
|
||||
onRemove={linkTarget === 'rich' && linkDialogUrl ? removeLink : undefined}
|
||||
onRemove={linkTarget === 'rich' && linkDialogEditing ? removeLink : undefined}
|
||||
/>
|
||||
<ArticleImagePickerDialog
|
||||
open={imagePickerOpen}
|
||||
onOpenChange={setImagePickerOpen}
|
||||
onInsert={applyImageUrls}
|
||||
/>
|
||||
<ArticleCodeBlockDialog
|
||||
open={codeBlockDialogOpen}
|
||||
|
||||
@@ -12,11 +12,11 @@ import {
|
||||
List, ListOrdered, Code, Link as LinkIcon, Image as ImageIcon,
|
||||
} from 'lucide-react';
|
||||
import { POST_CONTENT_PURIFY_CONFIG } from '../utils/postContent';
|
||||
import { api } from '../api/client';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { ArticleCodeBlock } from './editor/ArticleCodeBlockExtension';
|
||||
import { ArticleCodeBlockDialog } from './editor/ArticleCodeBlockDialog';
|
||||
import { ArticleImage } from './editor/ArticleImageExtension';
|
||||
import { ArticleImagePickerDialog } from './editor/ArticleImagePickerDialog';
|
||||
import { ArticleLinkDialog, type ArticleLinkConfirm } from './editor/ArticleLinkDialog';
|
||||
import { TabIndent } from './editor/TabIndentExtension';
|
||||
import type { CodeBlockInsertOptions } from '../utils/codeBlockOptions';
|
||||
import { Tooltip } from './ui/Tooltip';
|
||||
@@ -49,28 +49,6 @@ function isEditorEmpty(editor: Editor): boolean {
|
||||
return !hasImage;
|
||||
}
|
||||
|
||||
/** 触发图片文件选择并上传 */
|
||||
async function uploadImageFiles(): Promise<string[]> {
|
||||
return new Promise(resolve => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = 'image/jpeg,image/png,image/gif,image/webp';
|
||||
input.multiple = false;
|
||||
input.onchange = async () => {
|
||||
const files = [...(input.files ?? [])];
|
||||
if (!files.length) { resolve([]); return; }
|
||||
try {
|
||||
const { url } = await api.uploadPostImage(files[0]);
|
||||
resolve([url]);
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '图片上传失败');
|
||||
resolve([]);
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
|
||||
const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEditor(
|
||||
{ value, onChange, placeholder = '说点什么吧…' },
|
||||
ref,
|
||||
@@ -79,6 +57,11 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
||||
const lastValueRef = useRef(value);
|
||||
const [, setTick] = useState(0);
|
||||
const [showSticker, setShowSticker] = useState(false);
|
||||
const [imagePickerOpen, setImagePickerOpen] = useState(false);
|
||||
const [linkDialogOpen, setLinkDialogOpen] = useState(false);
|
||||
const [linkDialogUrl, setLinkDialogUrl] = useState('');
|
||||
const [linkDialogText, setLinkDialogText] = useState('');
|
||||
const [linkDialogEditing, setLinkDialogEditing] = useState(false);
|
||||
const [codeBlockDialogOpen, setCodeBlockDialogOpen] = useState(false);
|
||||
const [codeBlockEditing, setCodeBlockEditing] = useState(false);
|
||||
const [codeBlockInitial, setCodeBlockInitial] = useState<CodeBlockInsertOptions | null>(null);
|
||||
@@ -99,6 +82,11 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
||||
openOnClick: false,
|
||||
autolink: true,
|
||||
defaultProtocol: 'https',
|
||||
// 新标签由全站设置在展示层处理,编辑器不写 target/rel
|
||||
HTMLAttributes: {
|
||||
target: null,
|
||||
rel: null,
|
||||
},
|
||||
}),
|
||||
ArticleImage.configure({ inline: true, allowBase64: true }),
|
||||
Placeholder.configure({ placeholder }),
|
||||
@@ -179,11 +167,14 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
||||
setShowSticker(false);
|
||||
}, [editor]);
|
||||
|
||||
const setImage = useCallback(async () => {
|
||||
if (!editor) return;
|
||||
const urls = await uploadImageFiles();
|
||||
if (!urls.length) return;
|
||||
editor.chain().focus().setImage({ src: urls[0] }).run();
|
||||
const applyImageUrls = useCallback((urls: string[]) => {
|
||||
if (!editor || !urls.length) return;
|
||||
// 评论为 inline 图,无图组:逐张插入并跟空格,便于光标落在右侧
|
||||
const nodes = urls.flatMap(src => [
|
||||
{ type: 'image' as const, attrs: { src } },
|
||||
{ type: 'text' as const, text: ' ' },
|
||||
]);
|
||||
editor.chain().focus().insertContent(nodes).run();
|
||||
}, [editor]);
|
||||
|
||||
const openCodeBlockDialog = useCallback(() => {
|
||||
@@ -213,23 +204,70 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
||||
}).run();
|
||||
}, [editor]);
|
||||
|
||||
const setLink = useCallback(() => {
|
||||
const openLinkDialog = useCallback(() => {
|
||||
if (!editor) return;
|
||||
const prev = editor.getAttributes('link').href as string | undefined;
|
||||
const url = window.prompt('链接地址', prev ?? 'https://');
|
||||
if (url === null) return;
|
||||
const { from, to, empty } = editor.state.selection;
|
||||
let text = empty ? '' : editor.state.doc.textBetween(from, to, '');
|
||||
let href = '';
|
||||
let editing = false;
|
||||
if (editor.isActive('link')) {
|
||||
const attrs = editor.getAttributes('link');
|
||||
href = (attrs.href as string) || '';
|
||||
editing = Boolean(href);
|
||||
editor.chain().focus().extendMarkRange('link').run();
|
||||
const sel = editor.state.selection;
|
||||
text = editor.state.doc.textBetween(sel.from, sel.to, '') || text;
|
||||
}
|
||||
setLinkDialogUrl(href);
|
||||
setLinkDialogText(text);
|
||||
setLinkDialogEditing(editing);
|
||||
setLinkDialogOpen(true);
|
||||
}, [editor]);
|
||||
|
||||
const applyLink = useCallback((payload: ArticleLinkConfirm) => {
|
||||
if (!editor) return;
|
||||
const { url, text } = payload;
|
||||
if (!url) {
|
||||
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
||||
return;
|
||||
}
|
||||
editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
|
||||
// 新标签行为由全站 open_content_links_in_new_tab 在展示层处理
|
||||
const linkAttrs = { href: url };
|
||||
const { empty } = editor.state.selection;
|
||||
const hasLink = editor.isActive('link');
|
||||
if (!empty || hasLink) {
|
||||
editor.chain().focus().extendMarkRange('link').setLink(linkAttrs).run();
|
||||
const { from, to } = editor.state.selection;
|
||||
const current = editor.state.doc.textBetween(from, to, '');
|
||||
if (text && current !== text) {
|
||||
editor.chain().focus().insertContentAt(
|
||||
{ from, to },
|
||||
{
|
||||
type: 'text',
|
||||
text,
|
||||
marks: [{ type: 'link', attrs: linkAttrs }],
|
||||
},
|
||||
).run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
editor.chain().focus().insertContent({
|
||||
type: 'text',
|
||||
text: text || '链接文字',
|
||||
marks: [{ type: 'link', attrs: linkAttrs }],
|
||||
}).run();
|
||||
}, [editor]);
|
||||
|
||||
const removeLink = useCallback(() => {
|
||||
if (!editor) return;
|
||||
editor.chain().focus().extendMarkRange('link').unsetLink().run();
|
||||
}, [editor]);
|
||||
|
||||
if (!editor) {
|
||||
return <div className="comment-editor"><div className="article-editor-bar" /><div className="article-editor-body" /></div>;
|
||||
}
|
||||
|
||||
const tools: { icon: React.ReactNode; title: string; active?: boolean; action: () => void; 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: <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() },
|
||||
@@ -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: <ListOrdered size={15} />, title: '有序列表', active: editor.isActive('orderedList'), action: () => editor.chain().focus().toggleOrderedList().run() },
|
||||
{ icon: <Code size={15} />, title: '代码块', active: editor.isActive('codeBlock'), action: openCodeBlockDialog },
|
||||
{ icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: setLink },
|
||||
{ icon: <ImageIcon size={15} />, title: '上传图片', action: setImage },
|
||||
{ icon: <LinkIcon size={15} />, title: '链接', active: editor.isActive('link'), action: openLinkDialog },
|
||||
{
|
||||
icon: <ImageIcon size={15} />,
|
||||
title: '图片',
|
||||
hint: '上传、链接或从已上传中选择',
|
||||
action: () => setImagePickerOpen(true),
|
||||
},
|
||||
{ icon: <span className="article-tool-btn__owo">OwO</span>, title: '表情 OwO', active: showSticker, action: () => setShowSticker(v => !v), className: 'article-tool-btn--owo' },
|
||||
];
|
||||
|
||||
@@ -247,14 +290,14 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
||||
<div className="article-editor-bar">
|
||||
<div className="article-editor-tools">
|
||||
{tools.map((t, i) => (
|
||||
<Tooltip key={i} content={t.title} side="bottom">
|
||||
<Tooltip key={i} content={t.title} hint={t.hint} side="bottom">
|
||||
<button
|
||||
ref={i === tools.length - 1 ? stickerBtnRef : undefined}
|
||||
type="button"
|
||||
className={`article-tool-btn${t.active ? ' active' : ''}${t.className ? ` ${t.className}` : ''}`}
|
||||
onMouseDown={e => e.preventDefault()}
|
||||
onClick={t.action}
|
||||
aria-label={t.title}
|
||||
aria-label={t.hint ? `${t.title},${t.hint}` : t.title}
|
||||
>
|
||||
{t.icon}
|
||||
</button>
|
||||
@@ -268,6 +311,20 @@ const CommentEditor = forwardRef<CommentEditorHandle, Props>(function CommentEdi
|
||||
</div>
|
||||
</div>
|
||||
{showSticker && <StickerPicker onSelect={insertSticker} />}
|
||||
<ArticleLinkDialog
|
||||
open={linkDialogOpen}
|
||||
onOpenChange={setLinkDialogOpen}
|
||||
initialUrl={linkDialogUrl}
|
||||
initialText={linkDialogText}
|
||||
editing={linkDialogEditing}
|
||||
onConfirm={applyLink}
|
||||
onRemove={linkDialogEditing ? removeLink : undefined}
|
||||
/>
|
||||
<ArticleImagePickerDialog
|
||||
open={imagePickerOpen}
|
||||
onOpenChange={setImagePickerOpen}
|
||||
onInsert={applyImageUrls}
|
||||
/>
|
||||
<ArticleCodeBlockDialog
|
||||
open={codeBlockDialogOpen}
|
||||
onOpenChange={setCodeBlockDialogOpen}
|
||||
|
||||
@@ -15,7 +15,7 @@ import type { FeedSortTab } from '../api/types';
|
||||
export type FeedSort = 'latest' | 'reply' | 'hot';
|
||||
|
||||
const SORT_META: Record<FeedSort, { hint: string; icon: typeof Clock }> = {
|
||||
reply: { hint: '最近有人评论', icon: MessageCircle },
|
||||
reply: { hint: '按最近活动(发帖或评论)', icon: MessageCircle },
|
||||
latest: { hint: '按发帖时间', icon: Clock },
|
||||
hot: { hint: '仅展示推荐帖', icon: BadgeCheck },
|
||||
};
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useMemo, useCallback, useEffect, useState } from 'react';
|
||||
import { useMemo, useCallback, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { renderPostContentHtml } from '../utils/postContent';
|
||||
import { extractHeadingsFromHtml, type PostHeading } from '../utils/postHeadings';
|
||||
import { loginPath, registerPath } from '../utils/authRedirect';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
import { notify } from '@/lib/notify';
|
||||
@@ -12,8 +11,6 @@ interface Props {
|
||||
html: string;
|
||||
isLoggedIn: boolean;
|
||||
className?: string;
|
||||
/** 正文标题树变化时回调(用于侧栏目录) */
|
||||
onHeadingsChange?: (headings: PostHeading[]) => void;
|
||||
/** 点击「回复可见」门控的「去回复」 */
|
||||
onRequestReply?: () => void;
|
||||
/** 积分解锁成功后刷新正文 */
|
||||
@@ -26,7 +23,6 @@ export default function PostContent({
|
||||
html,
|
||||
isLoggedIn,
|
||||
className = 'post-detail-content',
|
||||
onHeadingsChange,
|
||||
onRequestReply,
|
||||
onUnlocked,
|
||||
postId: postIdProp,
|
||||
@@ -39,19 +35,12 @@ export default function PostContent({
|
||||
const [lightboxAlt, setLightboxAlt] = useState('');
|
||||
const [unlocking, setUnlocking] = useState(false);
|
||||
|
||||
const prepared = useMemo(() => {
|
||||
const rendered = renderPostContentHtml(html, isLoggedIn, {
|
||||
const preparedHtml = useMemo(
|
||||
() => renderPostContentHtml(html, isLoggedIn, {
|
||||
openLinksInNewTab: limits.open_content_links_in_new_tab,
|
||||
});
|
||||
return {
|
||||
html: rendered,
|
||||
headings: extractHeadingsFromHtml(rendered),
|
||||
};
|
||||
}, [html, isLoggedIn, limits.open_content_links_in_new_tab]);
|
||||
|
||||
useEffect(() => {
|
||||
onHeadingsChange?.(prepared.headings);
|
||||
}, [prepared.headings, onHeadingsChange]);
|
||||
}),
|
||||
[html, isLoggedIn, limits.open_content_links_in_new_tab],
|
||||
);
|
||||
|
||||
const openLightbox = useCallback((img: HTMLImageElement) => {
|
||||
const full = img.getAttribute('data-full') || img.currentSrc || img.src;
|
||||
@@ -167,7 +156,7 @@ export default function PostContent({
|
||||
className={className}
|
||||
onClick={handleClick}
|
||||
onKeyDown={handleKeyDown}
|
||||
dangerouslySetInnerHTML={{ __html: prepared.html }}
|
||||
dangerouslySetInnerHTML={{ __html: preparedHtml }}
|
||||
/>
|
||||
<ImageLightbox
|
||||
src={lightboxSrc}
|
||||
|
||||
@@ -232,11 +232,13 @@ export default function RightPanel({
|
||||
<div className={`aside-panel-inner${isPostDetail ? ' aside-panel-inner--post-detail' : ''}`}>
|
||||
{isPostDetail && (
|
||||
<>
|
||||
<PostAuthorCard
|
||||
author={postDetail.author}
|
||||
publishedAt={postDetail.publishedAt}
|
||||
viewCount={postDetail.viewCount}
|
||||
/>
|
||||
{postDetail.author?.id ? (
|
||||
<PostAuthorCard
|
||||
author={postDetail.author}
|
||||
publishedAt={postDetail.publishedAt}
|
||||
viewCount={postDetail.viewCount}
|
||||
/>
|
||||
) : null}
|
||||
<div className="widget-card widget-card--outline">
|
||||
<div className="widget-card-head">
|
||||
<ListTree className="widget-card-icon widget-card-icon--outline" aria-hidden />
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { FeedSortId, FeedSortTab } from '../../api/types';
|
||||
import { normalizeFeedSortTabs } from '../../utils/feedSortTabs';
|
||||
|
||||
const TAB_META: Record<FeedSortId, { hint: string; placeholder: string }> = {
|
||||
reply: { hint: '按最后评论时间', placeholder: '新评论' },
|
||||
reply: { hint: '按最近活动(发帖或评论)', placeholder: '最新' },
|
||||
latest: { hint: '按发帖时间', placeholder: '新帖子' },
|
||||
hot: { hint: '仅展示推荐帖', placeholder: '推荐帖' },
|
||||
};
|
||||
|
||||
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 {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { notify } from '@/lib/notify';
|
||||
import { api } from '@/api/client';
|
||||
import type { PostItem, SitePageSummary } from '@/api/types';
|
||||
import { pagePath, postPath } from '@/utils/permalink';
|
||||
import { useForumLimits } from '@/hooks/useForumLimits';
|
||||
import { ChevronDown, Loader2 } from 'lucide-react';
|
||||
|
||||
export interface ArticleLinkConfirm {
|
||||
url: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
initialUrl?: string;
|
||||
onConfirm: (url: string) => void;
|
||||
initialText?: string;
|
||||
/** 是否正在编辑已有链接 */
|
||||
editing?: boolean;
|
||||
onConfirm: (payload: ArticleLinkConfirm) => void;
|
||||
onRemove?: () => void;
|
||||
}
|
||||
|
||||
/** 文章编辑器链接输入弹窗 */
|
||||
type SiteHit = {
|
||||
key: string;
|
||||
title: string;
|
||||
url: string;
|
||||
kind: 'post' | 'page';
|
||||
};
|
||||
|
||||
/** 校验可插入的链接地址:外链或站内绝对路径 */
|
||||
export function isValidLinkHref(url: string): boolean {
|
||||
const u = url.trim();
|
||||
if (!u) return false;
|
||||
if (u.startsWith('/') && !u.startsWith('//')) return true;
|
||||
if (u.startsWith('#') && u.length > 1) return true;
|
||||
try {
|
||||
const parsed = new URL(u);
|
||||
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const SEARCH_DEBOUNCE_MS = 300;
|
||||
const POST_PAGE_SIZE = 12;
|
||||
|
||||
/** 文章/评论编辑器:插入或编辑链接(含站内内容搜索) */
|
||||
export function ArticleLinkDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
initialUrl = '',
|
||||
initialText = '',
|
||||
editing = false,
|
||||
onConfirm,
|
||||
onRemove,
|
||||
}: Props) {
|
||||
const [url, setUrl] = useState(initialUrl);
|
||||
const { limits } = useForumLimits();
|
||||
const [url, setUrl] = useState('');
|
||||
const [text, setText] = useState('');
|
||||
const [advancedOpen, setAdvancedOpen] = useState(false);
|
||||
const [query, setQuery] = useState('');
|
||||
const [debouncedQuery, setDebouncedQuery] = useState('');
|
||||
const [posts, setPosts] = useState<PostItem[]>([]);
|
||||
const [pages, setPages] = useState<SitePageSummary[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) setUrl(initialUrl || 'https://');
|
||||
}, [open, initialUrl]);
|
||||
if (!open) return;
|
||||
setUrl(initialUrl || '');
|
||||
setText(initialText || '');
|
||||
setAdvancedOpen(false);
|
||||
setQuery('');
|
||||
setDebouncedQuery('');
|
||||
setPosts([]);
|
||||
setPages([]);
|
||||
setLoaded(false);
|
||||
}, [open, initialUrl, initialText]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !advancedOpen) return;
|
||||
const t = window.setTimeout(() => setDebouncedQuery(query.trim()), SEARCH_DEBOUNCE_MS);
|
||||
return () => window.clearTimeout(t);
|
||||
}, [query, open, advancedOpen]);
|
||||
|
||||
const loadSiteHits = useCallback(async (keyword: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [postsRes, pagesRes] = await Promise.all([
|
||||
api.posts({
|
||||
page: 1,
|
||||
size: POST_PAGE_SIZE,
|
||||
sort: 'new',
|
||||
...(keyword ? { keyword, title_only: '1' } : {}),
|
||||
}),
|
||||
api.pages(),
|
||||
]);
|
||||
setPosts(postsRes.posts || []);
|
||||
let nextPages = pagesRes.pages || [];
|
||||
if (keyword) {
|
||||
const q = keyword.toLowerCase();
|
||||
nextPages = nextPages.filter(
|
||||
p => p.title.toLowerCase().includes(q) || p.slug.toLowerCase().includes(q),
|
||||
);
|
||||
}
|
||||
setPages(nextPages.slice(0, POST_PAGE_SIZE));
|
||||
setLoaded(true);
|
||||
} catch (e: unknown) {
|
||||
notify.error(e instanceof Error ? e.message : '加载站内内容失败');
|
||||
setLoaded(true);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 仅展开高级选项时再请求站内内容,避免默认打开就打接口
|
||||
useEffect(() => {
|
||||
if (!open || !advancedOpen) return;
|
||||
void loadSiteHits(debouncedQuery);
|
||||
}, [open, advancedOpen, debouncedQuery, loadSiteHits]);
|
||||
|
||||
const hits: SiteHit[] = useMemo(() => {
|
||||
const postHits: SiteHit[] = posts.map(p => ({
|
||||
key: `post-${p.id}`,
|
||||
title: p.title,
|
||||
url: postPath(p.id, limits),
|
||||
kind: 'post',
|
||||
}));
|
||||
const pageHits: SiteHit[] = pages.map(p => ({
|
||||
key: `page-${p.slug}`,
|
||||
title: p.title,
|
||||
url: pagePath(p.slug, limits),
|
||||
kind: 'page',
|
||||
}));
|
||||
return [...postHits, ...pageHits];
|
||||
}, [posts, pages, limits]);
|
||||
|
||||
const pickHit = (hit: SiteHit) => {
|
||||
setUrl(hit.url);
|
||||
// 选站内内容时同步用标题作为链接文字
|
||||
setText(hit.title);
|
||||
};
|
||||
|
||||
const handleConfirm = () => {
|
||||
onConfirm(url.trim());
|
||||
const nextUrl = url.trim();
|
||||
if (!nextUrl) {
|
||||
notify.warning('请输入网址');
|
||||
return;
|
||||
}
|
||||
if (!isValidLinkHref(nextUrl)) {
|
||||
notify.warning('请使用 http(s) 外链或本站以 / 开头的路径');
|
||||
return;
|
||||
}
|
||||
onConfirm({
|
||||
url: nextUrl,
|
||||
text: text.trim() || '链接文字',
|
||||
});
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
@@ -41,25 +174,119 @@ export function ArticleLinkDialog({
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="article-link-dialog">
|
||||
<DialogHeader>
|
||||
<DialogTitle>插入链接</DialogTitle>
|
||||
<DialogDescription>输入完整 URL,留空并确认可移除已有链接。</DialogDescription>
|
||||
<DialogTitle>插入或编辑链接</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Input
|
||||
type="url"
|
||||
value={url}
|
||||
placeholder="https://"
|
||||
onChange={e => setUrl(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
handleConfirm();
|
||||
}
|
||||
}}
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
<section className="article-link-dialog__section">
|
||||
<div className="article-link-dialog__field">
|
||||
<Label htmlFor="article-link-url">网址</Label>
|
||||
<Input
|
||||
id="article-link-url"
|
||||
type="url"
|
||||
value={url}
|
||||
placeholder="https://… 或 /post/123"
|
||||
onChange={e => setUrl(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
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">
|
||||
{onRemove && initialUrl ? (
|
||||
<Button type="button" variant="outline" onClick={() => { onRemove(); onOpenChange(false); }}>
|
||||
{editing && onRemove ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="article-link-dialog__remove"
|
||||
onClick={() => {
|
||||
onRemove();
|
||||
onOpenChange(false);
|
||||
}}
|
||||
>
|
||||
移除链接
|
||||
</Button>
|
||||
) : null}
|
||||
@@ -67,7 +294,7 @@ export function ArticleLinkDialog({
|
||||
取消
|
||||
</Button>
|
||||
<Button type="button" onClick={handleConfirm}>
|
||||
确定
|
||||
{editing ? '更新链接' : '添加链接'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
|
||||
@@ -148,7 +148,10 @@ export default function MainLayout() {
|
||||
setSidebarOpen(false);
|
||||
}, [loc.pathname, loc.search]);
|
||||
useEffect(() => {
|
||||
if (!/^\/post\/\d+/.test(loc.pathname)) setPostOutline(null);
|
||||
const isArticleAside =
|
||||
(/^\/post\/\d+/.test(loc.pathname) && !/\/edit$/.test(loc.pathname))
|
||||
|| /^\/page\//.test(loc.pathname);
|
||||
if (!isArticleAside) setPostOutline(null);
|
||||
}, [loc.pathname]);
|
||||
useEffect(() => {
|
||||
if (!hideAside) setAsideOpen(false);
|
||||
@@ -477,6 +480,10 @@ export default function MainLayout() {
|
||||
const activeChipIndex = Math.max(0, boardChipIds.indexOf(mobileActiveBoard === -1 ? 0 : mobileActiveBoard));
|
||||
|
||||
const isPostDetail = /^\/post\/\d+/.test(loc.pathname) && !/\/edit$/.test(loc.pathname);
|
||||
const isSitePage = /^\/page\//.test(loc.pathname);
|
||||
const isArticleAside = isPostDetail || isSitePage;
|
||||
// 帖子有作者 →「作者与目录」;单页仅目录
|
||||
const articleAsideLabel = isPostDetail ? '作者与目录' : '文章目录';
|
||||
const setPostOutlineSafe = useCallback((outline: {
|
||||
headings: PostHeading[];
|
||||
scrollRoot: HTMLElement | null;
|
||||
@@ -632,10 +639,10 @@ export default function MainLayout() {
|
||||
type="button"
|
||||
className="header-icon-btn"
|
||||
onClick={openAside}
|
||||
aria-label={isPostDetail ? '打开作者与目录' : '打开社区动态'}
|
||||
aria-label={isArticleAside ? `打开${articleAsideLabel}` : '打开社区动态'}
|
||||
aria-expanded={asideOpen}
|
||||
aria-controls="aside-drawer"
|
||||
title={isPostDetail ? '作者与目录' : '社区动态'}
|
||||
title={isArticleAside ? articleAsideLabel : '社区动态'}
|
||||
>
|
||||
<PanelRight size={18} aria-hidden />
|
||||
</button>
|
||||
@@ -815,7 +822,7 @@ export default function MainLayout() {
|
||||
asideWidgets={asideWidgets}
|
||||
onPostClick={openPost}
|
||||
|
||||
postDetail={isPostDetail ? {
|
||||
postDetail={isArticleAside ? {
|
||||
author: postOutline?.author ?? null,
|
||||
publishedAt: postOutline?.publishedAt,
|
||||
viewCount: postOutline?.viewCount,
|
||||
@@ -879,7 +886,7 @@ export default function MainLayout() {
|
||||
onClick={() => { closeSidebar(); openAside(); }}
|
||||
>
|
||||
<PanelRight size={16} aria-hidden />
|
||||
{isPostDetail ? '作者与目录' : '社区动态'}
|
||||
{isArticleAside ? articleAsideLabel : '社区动态'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -910,10 +917,10 @@ export default function MainLayout() {
|
||||
className="aside-drawer"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={isPostDetail ? '作者与目录' : '社区动态'}
|
||||
aria-label={isArticleAside ? articleAsideLabel : '社区动态'}
|
||||
>
|
||||
<div className="aside-drawer-head">
|
||||
<span>{isPostDetail ? '作者与目录' : '社区动态'}</span>
|
||||
<span>{isArticleAside ? articleAsideLabel : '社区动态'}</span>
|
||||
<button
|
||||
ref={asideCloseRef}
|
||||
type="button"
|
||||
@@ -934,7 +941,7 @@ export default function MainLayout() {
|
||||
loading={asideLoading}
|
||||
asideWidgets={asideWidgets}
|
||||
onPostClick={openPost}
|
||||
postDetail={isPostDetail ? {
|
||||
postDetail={isArticleAside ? {
|
||||
author: postOutline?.author ?? null,
|
||||
publishedAt: postOutline?.publishedAt,
|
||||
viewCount: postOutline?.viewCount,
|
||||
|
||||
@@ -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 { ArrowLeft, ThumbsUp, Star, Lock, MessageSquare, MessageSquareOff, Flag, MoreHorizontal } from 'lucide-react';
|
||||
import FeaturedIcon from '@/components/FeaturedIcon';
|
||||
@@ -60,7 +60,8 @@ import { excerptFromHTML, firstImageFromHTML } from '../utils/seoText';
|
||||
import { canonicalRedirectPath, parsePermalinkID, postPath } from '../utils/permalink';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
import type { LayoutCtx } from '../layouts/MainLayout';
|
||||
import type { PostHeading } from '../utils/postHeadings';
|
||||
import { extractHeadingsFromHtml } from '../utils/postHeadings';
|
||||
import { renderPostContentHtml } from '../utils/postContent';
|
||||
import { InFlowSiteFooter } from '../components/SiteFooter';
|
||||
import NotFoundPage from './NotFoundPage';
|
||||
|
||||
@@ -132,7 +133,6 @@ export default function PostDetailPage() {
|
||||
const [deletingPost, setDeletingPost] = useState(false);
|
||||
const [deleteOpen, setDeleteOpen] = useState(false);
|
||||
const [composerOpen, setComposerOpen] = useState(false);
|
||||
const [headings, setHeadings] = useState<PostHeading[]>([]);
|
||||
const [reportOpen, setReportOpen] = useState(false);
|
||||
const [reportReason, setReportReason] = useState<ReportReason>('spam');
|
||||
const [reportDetail, setReportDetail] = useState('');
|
||||
@@ -173,6 +173,15 @@ export default function PostDetailPage() {
|
||||
|
||||
const brand = getCachedSiteBranding();
|
||||
const postContent = post?.content ?? '';
|
||||
const isLoggedIn = !!user;
|
||||
// 同步从正文派生目录,避免预取缓存命中后 setHeadings([]) 盖掉子组件上报且不再回调
|
||||
const headings = useMemo(() => {
|
||||
if (!postContent.trim()) return [];
|
||||
const rendered = renderPostContentHtml(postContent, isLoggedIn, {
|
||||
openLinksInNewTab: limits.open_content_links_in_new_tab,
|
||||
});
|
||||
return extractHeadingsFromHtml(rendered);
|
||||
}, [postContent, isLoggedIn, limits.open_content_links_in_new_tab]);
|
||||
const postSEO = post ? {
|
||||
title: post.title,
|
||||
description: excerptFromHTML(postContent),
|
||||
@@ -196,10 +205,6 @@ export default function PostDetailPage() {
|
||||
} : null;
|
||||
usePageSEO(postSEO);
|
||||
|
||||
const handleHeadingsChange = useCallback((next: PostHeading[]) => {
|
||||
setHeadings(next);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (loading || !post) {
|
||||
setPostOutline({ headings: [], scrollRoot: null, title: '文章目录' });
|
||||
@@ -263,7 +268,6 @@ export default function PostDetailPage() {
|
||||
setReplyTo(null);
|
||||
setEditingCommentId(null);
|
||||
setComposerOpen(false);
|
||||
setHeadings([]);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
@@ -272,7 +276,6 @@ export default function PostDetailPage() {
|
||||
setReplyTo(null);
|
||||
setEditingCommentId(null);
|
||||
setComposerOpen(false);
|
||||
setHeadings([]);
|
||||
if (!keep) {
|
||||
setLoading(true);
|
||||
setPost(null);
|
||||
@@ -1124,9 +1127,8 @@ export default function PostDetailPage() {
|
||||
|
||||
<PostContent
|
||||
html={post.content || ''}
|
||||
isLoggedIn={!!user}
|
||||
isLoggedIn={isLoggedIn}
|
||||
postId={post.id}
|
||||
onHeadingsChange={handleHeadingsChange}
|
||||
onRequestReply={scrollToCommentBox}
|
||||
onUnlocked={() => { void reloadPostContent(); }}
|
||||
/>
|
||||
|
||||
@@ -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 { api } from '../api/client';
|
||||
import type { SitePage } from '../api/types';
|
||||
import ArticleOutline from '../components/ArticleOutline';
|
||||
import PostContent from '../components/PostContent';
|
||||
import { usePageSEO } from '../hooks/usePageSEO';
|
||||
import { parsePermalinkSlug, pagePath } from '../utils/permalink';
|
||||
import { useForumLimits } from '../hooks/useForumLimits';
|
||||
import { useAuth } from '../hooks/useAuth';
|
||||
import { useSessionResource } from '../hooks/useSessionResource';
|
||||
import type { LayoutCtx } from '../layouts/MainLayout';
|
||||
import { extractHeadingsFromHtml } from '../utils/postHeadings';
|
||||
import { renderPostContentHtml } from '../utils/postContent';
|
||||
|
||||
/** 自定义单页(关于我们、版规等) */
|
||||
export default function SitePageView() {
|
||||
@@ -15,12 +20,25 @@ export default function SitePageView() {
|
||||
const slug = parsePermalinkSlug(rawSlug);
|
||||
const { limits } = useForumLimits();
|
||||
const { user } = useAuth();
|
||||
const { setPostOutline, isMobile } = useOutletContext<LayoutCtx>();
|
||||
const pageRef = useRef<HTMLDivElement>(null);
|
||||
const { data: page, loading } = useSessionResource<SitePage | null>(
|
||||
slug ? `sitepage:${slug}` : null,
|
||||
() => api.page(slug).then(d => d.page),
|
||||
{ enabled: !!slug },
|
||||
);
|
||||
const notFound = !slug || (!loading && !page);
|
||||
const isLoggedIn = !!user;
|
||||
const pageContent = page?.content ?? '';
|
||||
|
||||
// 同步从正文派生目录,与帖子详情共用右侧栏目录布局
|
||||
const headings = useMemo(() => {
|
||||
if (!pageContent.trim()) return [];
|
||||
const rendered = renderPostContentHtml(pageContent, isLoggedIn, {
|
||||
openLinksInNewTab: limits.open_content_links_in_new_tab,
|
||||
});
|
||||
return extractHeadingsFromHtml(rendered);
|
||||
}, [pageContent, isLoggedIn, limits.open_content_links_in_new_tab]);
|
||||
|
||||
usePageSEO({
|
||||
title: page?.title,
|
||||
@@ -29,19 +47,42 @@ export default function SitePageView() {
|
||||
ogType: 'article',
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (loading || !page) {
|
||||
setPostOutline({ headings: [], scrollRoot: null, title: '文章目录' });
|
||||
return () => setPostOutline(null);
|
||||
}
|
||||
setPostOutline({
|
||||
headings,
|
||||
scrollRoot: pageRef.current,
|
||||
title: '文章目录',
|
||||
});
|
||||
return () => setPostOutline(null);
|
||||
}, [headings, loading, page, setPostOutline]);
|
||||
|
||||
if (!slug) return <NotFoundPage title="页面不存在" />;
|
||||
if (loading) return null;
|
||||
if (notFound || !page) return <NotFoundPage title="页面不存在" description="该页面不存在或未发布" />;
|
||||
|
||||
return (
|
||||
<div className="page-wrap">
|
||||
<div className="page-wrap" ref={pageRef}>
|
||||
<article className="site-page">
|
||||
<header className="site-page__head">
|
||||
<h1>{page.title}</h1>
|
||||
</header>
|
||||
{isMobile && headings.length > 0 && (
|
||||
<details className="post-detail-toc-mobile">
|
||||
<summary>文章目录({headings.length})</summary>
|
||||
<ArticleOutline
|
||||
headings={headings}
|
||||
scrollRoot={pageRef.current}
|
||||
title="目录"
|
||||
/>
|
||||
</details>
|
||||
)}
|
||||
<PostContent
|
||||
html={page.content}
|
||||
isLoggedIn={!!user}
|
||||
isLoggedIn={isLoggedIn}
|
||||
className="site-page__body post-detail-content"
|
||||
/>
|
||||
</article>
|
||||
|
||||
@@ -952,7 +952,7 @@ export default function AdminSettingsPage() {
|
||||
<div className="admin-settings-subsection">
|
||||
<h4 className="admin-settings-subsection-title">首页排序标签</h4>
|
||||
<p className="admin-settings-subsection-desc">
|
||||
拖拽调整顺序;在「显示名称」框中改首页文案;右侧开关控制启停。第一个启用项为默认排序
|
||||
拖拽调整顺序;在「显示名称」框中改首页文案;右侧开关控制启停。第一个启用项为默认排序。「最新」按发帖与评论的最近时间混排
|
||||
</p>
|
||||
<FeedSortTabList
|
||||
tabs={normalizeFeedSortTabs(limits.feed_sort_tabs ?? DEFAULT_FEED_SORT_TABS)}
|
||||
|
||||
@@ -1977,6 +1977,69 @@ html.dark .ssr-theme-icon--sun {
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
/* 三栏主滚动区统一细绿色可拖滚动条 */
|
||||
.sidebar,
|
||||
.post-detail-page,
|
||||
.page-wrap,
|
||||
.post-list-scroll,
|
||||
.virtual-list-wrap,
|
||||
.aside-panel,
|
||||
.aside-drawer-body,
|
||||
.widget-outline-body {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: color-mix(in srgb, var(--j13-green) 45%, var(--j13-border)) transparent;
|
||||
-ms-overflow-style: auto;
|
||||
}
|
||||
|
||||
.sidebar::-webkit-scrollbar,
|
||||
.post-detail-page::-webkit-scrollbar,
|
||||
.page-wrap::-webkit-scrollbar,
|
||||
.post-list-scroll::-webkit-scrollbar,
|
||||
.virtual-list-wrap::-webkit-scrollbar,
|
||||
.aside-panel::-webkit-scrollbar,
|
||||
.aside-drawer-body::-webkit-scrollbar,
|
||||
.widget-outline-body::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.sidebar::-webkit-scrollbar-track,
|
||||
.post-detail-page::-webkit-scrollbar-track,
|
||||
.page-wrap::-webkit-scrollbar-track,
|
||||
.post-list-scroll::-webkit-scrollbar-track,
|
||||
.virtual-list-wrap::-webkit-scrollbar-track,
|
||||
.aside-panel::-webkit-scrollbar-track,
|
||||
.aside-drawer-body::-webkit-scrollbar-track,
|
||||
.widget-outline-body::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.sidebar::-webkit-scrollbar-thumb,
|
||||
.post-detail-page::-webkit-scrollbar-thumb,
|
||||
.page-wrap::-webkit-scrollbar-thumb,
|
||||
.post-list-scroll::-webkit-scrollbar-thumb,
|
||||
.virtual-list-wrap::-webkit-scrollbar-thumb,
|
||||
.aside-panel::-webkit-scrollbar-thumb,
|
||||
.aside-drawer-body::-webkit-scrollbar-thumb,
|
||||
.widget-outline-body::-webkit-scrollbar-thumb {
|
||||
background: color-mix(in srgb, var(--j13-green) 40%, var(--j13-border));
|
||||
border-radius: 999px;
|
||||
border: 2px solid transparent;
|
||||
background-clip: padding-box;
|
||||
}
|
||||
|
||||
.sidebar::-webkit-scrollbar-thumb:hover,
|
||||
.post-detail-page::-webkit-scrollbar-thumb:hover,
|
||||
.page-wrap::-webkit-scrollbar-thumb:hover,
|
||||
.post-list-scroll::-webkit-scrollbar-thumb:hover,
|
||||
.virtual-list-wrap::-webkit-scrollbar-thumb:hover,
|
||||
.aside-panel::-webkit-scrollbar-thumb:hover,
|
||||
.aside-drawer-body::-webkit-scrollbar-thumb:hover,
|
||||
.widget-outline-body::-webkit-scrollbar-thumb:hover {
|
||||
background: color-mix(in srgb, var(--j13-green) 65%, var(--j13-border));
|
||||
background-clip: padding-box;
|
||||
border: 2px solid transparent;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.aside-drawer,
|
||||
.sidebar-drawer { animation: none; }
|
||||
@@ -2088,8 +2151,6 @@ html.dark .ssr-theme-icon--sun {
|
||||
overflow-x: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
@@ -2259,17 +2320,11 @@ body:has(.admin-topbar) .ptr-indicator {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.page-wrap::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.virtual-list-wrap,
|
||||
.post-list-scroll {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
min-height: 0;
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
|
||||
/* 文档 SSR:静态列表(非 virtualizer absolute 行) */
|
||||
@@ -2296,11 +2351,6 @@ a.post-row {
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
|
||||
.virtual-list-wrap::-webkit-scrollbar,
|
||||
.post-list-scroll::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.feed-list-footer {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
@@ -4429,31 +4479,6 @@ a.post-title:visited {
|
||||
gap: 16px;
|
||||
padding: 16px 20px 24px;
|
||||
background: var(--j13-bg-workspace);
|
||||
/* 长文需要可拖拽定位;列表页仍隐藏滚动条保持干净 */
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: color-mix(in srgb, var(--j13-green) 45%, var(--j13-border)) transparent;
|
||||
-ms-overflow-style: auto;
|
||||
}
|
||||
|
||||
.post-detail-page::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.post-detail-page::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.post-detail-page::-webkit-scrollbar-thumb {
|
||||
background: color-mix(in srgb, var(--j13-green) 40%, var(--j13-border));
|
||||
border-radius: 999px;
|
||||
border: 2px solid transparent;
|
||||
background-clip: padding-box;
|
||||
}
|
||||
|
||||
.post-detail-page::-webkit-scrollbar-thumb:hover {
|
||||
background: color-mix(in srgb, var(--j13-green) 65%, var(--j13-border));
|
||||
background-clip: padding-box;
|
||||
border: 2px solid transparent;
|
||||
}
|
||||
|
||||
.post-detail-header {
|
||||
@@ -10931,8 +10956,302 @@ button.profile-stat:hover strong {
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
|
||||
.article-link-dialog {
|
||||
width: min(520px, 92vw);
|
||||
max-width: min(520px, 92vw);
|
||||
max-height: min(85vh, 720px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.article-link-dialog__section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 4px 0 16px;
|
||||
}
|
||||
.article-link-dialog__section + .article-link-dialog__section {
|
||||
border-top: 1px solid var(--j13-border-light);
|
||||
padding-top: 16px;
|
||||
}
|
||||
.article-link-dialog__section-title {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
.article-link-dialog__field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.article-link-dialog__field label {
|
||||
font-size: 12px;
|
||||
color: var(--color-text-2);
|
||||
}
|
||||
.article-link-dialog__advanced {
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
.article-link-dialog__advanced-toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-2);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
.article-link-dialog__advanced-toggle:hover {
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
.article-link-dialog__advanced-chevron {
|
||||
transition: transform 0.15s ease;
|
||||
}
|
||||
.article-link-dialog__advanced-toggle.is-open .article-link-dialog__advanced-chevron {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
.article-link-dialog__advanced-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.article-link-dialog__hits {
|
||||
position: relative;
|
||||
border: 1px solid var(--j13-border);
|
||||
border-radius: 10px;
|
||||
background: var(--j13-bg-block-muted, var(--color-fill-3));
|
||||
overflow: hidden;
|
||||
}
|
||||
.article-link-dialog__hits-hint {
|
||||
margin: 0;
|
||||
padding: 10px 12px 6px;
|
||||
font-size: 12px;
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
.article-link-dialog__hit-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0 0 6px;
|
||||
max-height: 220px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.article-link-dialog__hit {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
padding: 9px 12px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
color: var(--color-text-1);
|
||||
transition: background 0.12s;
|
||||
}
|
||||
.article-link-dialog__hit:hover {
|
||||
background: var(--j13-bg-surface, #fff);
|
||||
}
|
||||
.article-link-dialog__hit.is-selected {
|
||||
background: var(--j13-green-bg);
|
||||
}
|
||||
.article-link-dialog__hit-title {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 13px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.article-link-dialog__hit-kind {
|
||||
flex-shrink: 0;
|
||||
font-size: 11px;
|
||||
color: var(--color-text-3);
|
||||
padding: 2px 7px;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--j13-border) 55%, transparent);
|
||||
}
|
||||
.article-link-dialog__hits-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 88px;
|
||||
font-size: 13px;
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
.article-link-dialog__hits-loading {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
right: 12px;
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
.article-link-dialog__spin {
|
||||
animation: article-link-dialog-spin 0.8s linear infinite;
|
||||
}
|
||||
@keyframes article-link-dialog-spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
.article-link-dialog__footer {
|
||||
gap: 8px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.article-link-dialog__remove {
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.article-image-picker {
|
||||
width: min(520px, 92vw);
|
||||
max-width: min(520px, 92vw);
|
||||
}
|
||||
.article-image-picker__tabs {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 4px;
|
||||
margin: 4px 0 12px;
|
||||
padding: 4px;
|
||||
border: 1px solid var(--j13-border);
|
||||
border-radius: 10px;
|
||||
background: var(--j13-bg-block-muted, var(--color-fill-3));
|
||||
}
|
||||
.article-image-picker__tab {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
min-height: 36px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--color-text-2);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
line-height: 1.2;
|
||||
cursor: pointer;
|
||||
transition: background 0.12s, border-color 0.12s, color 0.12s, box-shadow 0.12s;
|
||||
}
|
||||
.article-image-picker__tab:hover:not(:disabled) {
|
||||
background: var(--j13-bg-surface, #fff);
|
||||
border-color: color-mix(in srgb, var(--j13-green) 22%, var(--j13-border));
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
.article-image-picker__tab.is-active {
|
||||
background: var(--j13-bg-surface, #fff);
|
||||
border-color: color-mix(in srgb, var(--j13-green) 40%, transparent);
|
||||
color: var(--j13-green-hover, var(--j13-green));
|
||||
font-weight: 600;
|
||||
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.06), 0 0 0 1px color-mix(in srgb, var(--j13-green) 18%, transparent);
|
||||
}
|
||||
.article-image-picker__tab:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.article-image-picker__panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
min-height: 160px;
|
||||
}
|
||||
.article-image-picker__drop {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 180px;
|
||||
padding: 24px 16px;
|
||||
border: 1.5px dashed var(--j13-border);
|
||||
border-radius: 10px;
|
||||
background: var(--j13-bg-block-muted, var(--color-fill-3));
|
||||
color: var(--color-text-2);
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.15s, background 0.15s;
|
||||
}
|
||||
.article-image-picker__drop p {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
.article-image-picker__drop span {
|
||||
font-size: 12px;
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
.article-image-picker__drop.is-dragover {
|
||||
border-color: var(--j13-green);
|
||||
background: var(--j13-green-bg);
|
||||
}
|
||||
.article-image-picker__drop.is-busy {
|
||||
cursor: wait;
|
||||
pointer-events: none;
|
||||
}
|
||||
.article-image-picker__hint {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
color: var(--color-text-3);
|
||||
}
|
||||
.article-image-picker__footer {
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
.article-image-picker__selected-count {
|
||||
margin-right: auto;
|
||||
font-size: 13px;
|
||||
color: var(--color-text-2);
|
||||
}
|
||||
.article-image-picker__grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 8px;
|
||||
max-height: 280px;
|
||||
overflow-y: auto;
|
||||
padding: 2px;
|
||||
}
|
||||
.article-image-picker__thumb {
|
||||
aspect-ratio: 1;
|
||||
padding: 0;
|
||||
border: 2px solid var(--j13-border);
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: var(--j13-bg-block-muted, var(--color-fill-3));
|
||||
cursor: pointer;
|
||||
transition: border-color 0.15s, box-shadow 0.15s;
|
||||
}
|
||||
.article-image-picker__thumb img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: block;
|
||||
}
|
||||
.article-image-picker__thumb.is-selected {
|
||||
border-color: var(--j13-green);
|
||||
box-shadow: 0 0 0 1px var(--j13-green);
|
||||
}
|
||||
.article-image-picker__empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
min-height: 140px;
|
||||
color: var(--color-text-3);
|
||||
font-size: 13px;
|
||||
}
|
||||
.article-image-picker__more {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
.article-image-picker__spin {
|
||||
animation: article-image-picker-spin 0.8s linear infinite;
|
||||
}
|
||||
@keyframes article-image-picker-spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* 代码块插入弹窗 */
|
||||
|
||||
@@ -4,7 +4,7 @@ import { DEFAULT_FEED_SORT_TABS } from '../api/types';
|
||||
const FEED_SORT_IDS: FeedSortId[] = ['reply', 'latest', 'hot'];
|
||||
|
||||
const DEFAULT_LABELS: Record<FeedSortId, string> = {
|
||||
reply: '新评论',
|
||||
reply: '最新',
|
||||
latest: '新帖子',
|
||||
hot: '推荐帖',
|
||||
};
|
||||
|
||||
@@ -122,9 +122,12 @@ export function insertMarkdownLink(
|
||||
value: string,
|
||||
url: string,
|
||||
onChange: ChangeHandler,
|
||||
opts?: { text?: string },
|
||||
) {
|
||||
const { selectionStart, selectionEnd } = textarea;
|
||||
const selected = value.slice(selectionStart, selectionEnd) || '链接文字';
|
||||
const selected = opts?.text?.trim()
|
||||
|| value.slice(selectionStart, selectionEnd)
|
||||
|| '链接文字';
|
||||
const insert = `[${selected}](${url})`;
|
||||
const next = value.slice(0, selectionStart) + insert + value.slice(selectionEnd);
|
||||
applyTextareaChange(
|
||||
|
||||
@@ -8,6 +8,27 @@ import (
|
||||
"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 列出媒体资源
|
||||
func (h *Handlers) APIAdminMedia(c *gin.Context) {
|
||||
if h.Store == nil {
|
||||
|
||||
@@ -553,7 +553,7 @@ func writeSSRFeed(b *strings.Builder, boot homeBootPayload, meta homeSSRMeta) {
|
||||
tabs := boot.Limits.FeedSortTabs
|
||||
if len(tabs) == 0 {
|
||||
tabs = []service.FeedSortTab{
|
||||
{ID: service.FeedSortReply, Label: "新评论", Enabled: true},
|
||||
{ID: service.FeedSortReply, Label: "最新", Enabled: true},
|
||||
{ID: service.FeedSortLatest, Label: "新帖子", Enabled: true},
|
||||
{ID: service.FeedSortHot, Label: "推荐帖", Enabled: true},
|
||||
}
|
||||
|
||||
@@ -177,6 +177,7 @@ func Setup(cfg *config.Config) (*gin.Engine, error) {
|
||||
api.POST("/profile/password", h.APIUpdatePassword)
|
||||
api.POST("/profile/avatar", h.APIUploadAvatar)
|
||||
api.POST("/uploads/image", h.APIUploadPostImage)
|
||||
api.GET("/uploads/images", h.APIMyPostImages)
|
||||
api.POST("/posts", middleware.RateLimitMiddleware(limiter, "post"), h.APICreatePost)
|
||||
api.PUT("/posts/:id", h.APIUpdatePost)
|
||||
api.DELETE("/posts/:id", h.APIDeletePost)
|
||||
|
||||
116
service/media.go
116
service/media.go
@@ -154,6 +154,122 @@ func (s *UploadStore) ListMedia(category, query string, page, size int) (*MediaL
|
||||
}, 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 批量删除媒体(含伴生扩展名与数据库索引)
|
||||
func (s *UploadStore) DeleteMedia(urls []string) (int, error) {
|
||||
if s == nil {
|
||||
|
||||
@@ -357,18 +357,12 @@ func (s *PostService) List(q PostListQuery) ([]model.Post, int64, error) {
|
||||
}
|
||||
switch sortKey {
|
||||
case "reply":
|
||||
// 有回复的帖子优先,按最后回复时间倒序;无回复的帖子沉底(仅计已公开评论)
|
||||
db = db.Order(`(
|
||||
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(`(
|
||||
// 最近活动:按最后公开评论时间与发帖时间的较晚者倒序(零回复新帖也能靠前)
|
||||
db = db.Order(`COALESCE((
|
||||
SELECT MAX(created_at) FROM comments
|
||||
WHERE comments.post_id = posts.id AND comments.deleted_at IS NULL
|
||||
AND comments.status = 'published'
|
||||
) DESC`)
|
||||
db = db.Order("posts.created_at DESC")
|
||||
), posts.created_at) DESC`)
|
||||
case "hot":
|
||||
// 仅推荐帖:按互动再按 id
|
||||
db = db.Order("like_count desc, view_count desc")
|
||||
@@ -384,7 +378,7 @@ func normalizePostSort(sort string) string {
|
||||
case "latest", "hot":
|
||||
return sort
|
||||
default:
|
||||
// 含空串 / reply:默认新评论
|
||||
// 含空串 / reply:默认最近活动
|
||||
return "reply"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,7 +206,7 @@ var feedSortTabDefaultOrder = []string{
|
||||
}
|
||||
|
||||
var feedSortTabDefaultLabels = map[string]string{
|
||||
FeedSortReply: "新评论",
|
||||
FeedSortReply: "最新",
|
||||
FeedSortLatest: "新帖子",
|
||||
FeedSortHot: "推荐帖",
|
||||
}
|
||||
@@ -287,7 +287,7 @@ var forumSettingDefs = []settingDef{
|
||||
|
||||
var feedSettingDefaults = map[string]string{
|
||||
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{
|
||||
|
||||
Reference in New Issue
Block a user