feat: 新增帖子搜索功能

支持按标题与正文搜索帖子,入口在首页排序标签与发布按钮之间。

实现方式选择 ILIKE 子串匹配而非 PostgreSQL 全文检索:后者依赖分词,
中文分词需额外安装 zhparser 等扩展,多数部署环境没有;ILIKE 无需任何
扩展即可正确匹配中文子串,英文也天然大小写不敏感。

后端(GET /api/posts/search)
- 关键词长度限制 100 字,超长或为空返回 400
- 转义 % 与 _:它们是 LIKE 的通配符,若不过滤,搜索「%」会匹配全部
  帖子
- 复用 parsePagination,响应结构与 /api/posts 一致
- 路由必须声明在 /api/posts/:id 之前,否则 search 会被当作 id 匹配
- 新增迁移 005:创建 pg_trgm 扩展与 trigram 索引。
  实测索引效果分两种情况——英文关键词(postgresql)走 Bitmap Index
  Scan,0.2ms,比全表扫描快约 47 倍;中文因 pg_trgm 难以切出有效
  trigram,仍走全表扫描,3000 条数据约 7~9ms。即索引对英文有效、
  对中文无效,考虑到许多论坛中英混排,予以保留。
  创建扩展需要权限,部分托管数据库不开放,故失败时仅提示,不影响
  搜索功能本身。

前端
- 首页新增搜索框,含清除按钮;输入防抖 350ms 自动搜索,回车立即搜索,
  Esc 清空
- 关键词写入 URL(?q=),刷新与分享可保持搜索状态;初始化时先于
  renderFeed 设定关键词,避免首屏先按普通列表加载一次
- 搜索时输入框下方显示细进度条,而非整块骨架屏——搜索通常很快,
  画骨架反而闪得厉害
- 无结果时给出明确提示与改进建议
- 移动端搜索框独占一行,避免与标签、按钮挤压
- 补充 6 条 i18n 文案;空结果提示中的关键词单独放在 <strong> 内,
  使固定文案能作为独立文本节点被词典匹配

实测(Puppeteer + 接口直测):
- 中文「论坛」「分词」、英文 resend/RESEND 均正确命中
- 空关键词与超长关键词正确返回 400
- 搜索 % 与 _ 返回 0 条,确认通配符已转义
- 输入「分词」后列表由 5 条筛为 1 条,URL 同步为 ?q=分词
- 清除按钮恢复全部列表并移除 URL 参数
- 通过 ?q=论坛 直接访问时,输入框自动填入且结果为 2 条

完整测试套件 25/25 通过。
This commit is contained in:
Furrium Network committed 2026-09-22 21:58:21 +08:00
1 parent 9844988cf2
commit fdf90f4b1d
9 files changed
+397 -3

No files matched your search

+6
View File
@@ -101,6 +101,12 @@
<button class="tab active" data-sort="latest">最新发布</button>
<button class="tab" data-sort="hot">最新回复</button>
</div>
<div class="feed-search">
<input type="search" id="postSearchInput" placeholder="搜索帖子…" autocomplete="off" />
<button id="postSearchClear" class="feed-search-clear" type="button" title="清除搜索" style="display:none;">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>
</div>
<button id="fab" class="btn-primary fab-btn">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
发布新帖