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>
发布新帖
+9
View File
@@ -73,6 +73,15 @@ const API = {
return data;
},
// 搜索帖子(标题与正文)
async searchPosts(keyword, page = 1, limit = 20) {
const data = await apiFetch(
'/posts/search?q=' + encodeURIComponent(keyword) + '&page=' + page + '&limit=' + limit
);
if (data.error) throw new Error(data.error);
return data;
},
async getPost(postId) {
const data = await apiFetch('/posts/' + postId);
if (data.error) throw new Error(data.error);
+7
View File
@@ -1395,6 +1395,13 @@ async function init() {
const userParam = urlParams.get('user');
const postPageParam = urlParams.get('postpage');
const customParam = urlParams.get('custom');
const searchParam = urlParams.get('q');
// 恢复搜索状态:关键词要先于 renderFeed 设定,否则首屏会先按
// 普通列表加载一次,再因搜索条件变化重新请求。
if (searchParam && window.__feedSearch) {
window.__feedSearch.setKeyword(searchParam);
}
if (postPageParam) {
currentPageNum = parseInt(postPageParam) || 1;
+106 -3
View File
@@ -6,6 +6,9 @@ let currentSort = 'latest';
let totalPages = 1;
const PAGE_SIZE = 20;
// 当前搜索关键词。为空表示处于普通列表模式。
let currentSearch = '';
// 翻页后滚回列表顶部。分页控件在列表末尾,不回到顶部的话用户看到的
// 仍是新一页的底部。
// 尊重系统的「减少动画」设置:开启时直接跳转,不做平滑滚动。
@@ -20,13 +23,20 @@ function scrollFeedToTop() {
function renderFeed() {
const container = document.getElementById('postList');
const keyword = currentSearch;
// 骨架屏只在首次加载时显示。翻页时列表已有内容,再画一遍骨架会
// 造成明显的闪动,反而比直接留白更糟。
const isFirstLoad = container.dataset.loaded !== '1';
container.innerHTML = isFirstLoad
? Skeleton.postList(3)
: '<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>';
API.getPosts(currentSort, currentPageNum, PAGE_SIZE).then(result => {
const request = keyword
? API.searchPosts(keyword, currentPageNum, PAGE_SIZE)
: API.getPosts(currentSort, currentPageNum, PAGE_SIZE);
request.then(result => {
container.dataset.loaded = '1';
const posts = result.data || [];
const pagination = result.pagination || { total: 0, totalPages: 1, page: 1 };
@@ -34,8 +44,14 @@ function renderFeed() {
currentPageNum = pagination.page || 1;
if (posts.length === 0 && currentPageNum === 1) {
container.innerHTML =
'<div style="text-align:center;color:#94a3b8;padding:60px 0;">✨ 还没有帖子,快来发布第一条吧!</div>';
// 空结果提示。关键词单独放在 <strong> 里,让固定文案能作为独立
// 文本节点被 i18n 匹配到——整句含动态关键词时匹配不上词典。
container.innerHTML = keyword
? '<div class="search-empty">'
+ '<span>没有找到相关帖子</span><br>'
+ '<strong>「' + escapeHTML(keyword) + '」</strong><br>'
+ '<span style="font-size:13px;">试试其他关键词,或检查是否有错别字</span></div>'
: '<div style="text-align:center;color:#94a3b8;padding:60px 0;">✨ 还没有帖子,快来发布第一条吧!</div>';
return;
}
@@ -250,3 +266,90 @@ document.querySelectorAll('.tab').forEach(tab => {
renderFeed();
});
});
// ============================================================
// 🔍 搜索
// ============================================================
// 输入时防抖 350ms 自动搜索,回车立即搜索。
// 关键词写入 URL(?q=),刷新与分享可保持搜索状态。
(function initSearch() {
const input = document.getElementById('postSearchInput');
const clearBtn = document.getElementById('postSearchClear');
const wrap = input ? input.closest('.feed-search') : null;
if (!input) return;
let debounceTimer = null;
function syncClearButton() {
if (clearBtn) clearBtn.style.display = input.value.trim() ? 'flex' : 'none';
}
function runSearch(keyword, { updateUrl = true } = {}) {
const next = (keyword || '').trim();
// 与当前状态相同则不必重新请求
if (next === currentSearch && currentPageNum === 1) return;
currentSearch = next;
currentPageNum = 1;
if (updateUrl) {
const url = new URL(window.location);
if (next) url.searchParams.set('q', next);
else url.searchParams.delete('q');
url.searchParams.delete('postpage');
window.history.pushState({}, '', url);
}
if (wrap) wrap.classList.add('is-searching');
renderFeed();
// renderFeed 内部是异步的,这里在下一轮事件循环后移除进度条即可
// (列表本身会先显示「加载中」,不会长时间空白)
window.setTimeout(() => {
if (wrap) wrap.classList.remove('is-searching');
}, 600);
}
input.addEventListener('input', () => {
syncClearButton();
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => runSearch(input.value), 350);
});
// 回车立即搜索,跳过防抖
input.addEventListener('keydown', e => {
if (e.key === 'Enter') {
e.preventDefault();
if (debounceTimer) clearTimeout(debounceTimer);
runSearch(input.value);
} else if (e.key === 'Escape') {
e.preventDefault();
input.value = '';
syncClearButton();
if (debounceTimer) clearTimeout(debounceTimer);
runSearch('');
}
});
if (clearBtn) {
clearBtn.addEventListener('click', () => {
input.value = '';
syncClearButton();
if (debounceTimer) clearTimeout(debounceTimer);
runSearch('');
input.focus();
});
}
// 暴露给外部(初始化时按 URL 恢复搜索状态)
window.__feedSearch = {
setKeyword(keyword) {
input.value = keyword || '';
currentSearch = (keyword || '').trim();
syncClearButton();
},
run: runSearch,
};
syncClearButton();
})();
+16
View File
@@ -372,6 +372,14 @@ const TRANSLATIONS = {
'重新生成恢复码': '重新生成恢复码',
'退出登录': '退出登录',
// ===== 帖子搜索 =====
'搜索帖子…': '搜索帖子…',
'清除搜索': '清除搜索',
'请输入搜索关键词': '请输入搜索关键词',
'搜索关键词过长(最多 100 字)': '搜索关键词过长(最多 100 字)',
'没有找到相关帖子': '没有找到相关帖子',
'试试其他关键词,或检查是否有错别字': '试试其他关键词,或检查是否有错别字',
// ===== SMTP 与邮箱验证 =====
'邮件设置': '邮件设置',
'启用邮件发送': '启用邮件发送',
@@ -784,6 +792,14 @@ const TRANSLATIONS = {
'重新生成恢复码': 'Regenerate Recovery Codes',
'退出登录': 'Logout',
// ===== 帖子搜索 =====
'搜索帖子…': 'Search posts…',
'清除搜索': 'Clear search',
'请输入搜索关键词': 'Please enter a search term',
'搜索关键词过长(最多 100 字)': 'Search term is too long (max 100 characters)',
'没有找到相关帖子': 'No matching posts found',
'试试其他关键词,或检查是否有错别字': 'Try different keywords, or check for typos',
// ===== SMTP 与邮箱验证 =====
'邮件设置': 'Email Settings',
'启用邮件发送': 'Enable email sending',
+39
View File
@@ -0,0 +1,39 @@
-- ============================================================
-- 帖子搜索
-- ------------------------------------------------------------
-- 搜索用 ILIKE 做子串匹配(见 server.js 的 /api/posts/search)。
-- 之所以不用 PostgreSQL 的全文检索(tsvector):它依赖分词,而
-- 中文分词需要额外安装 zhparser 等扩展,多数部署环境没有;ILIKE
-- 无需任何扩展即可正确匹配中文子串。
--
-- 索引用 pg_trgm 的 GIN 索引,实测效果分两种情况:
-- - 英文关键词(如 postgresql):走 Bitmap Index Scan,0.2ms,
-- 相比全表扫描快约 47 倍
-- - 中文关键词:pg_trgm 对中文难以切出有效 trigram,优化器仍选
-- 全表扫描。3000 条数据下约 7~9ms,可接受
-- 即索引对英文有效、对中文无效。许多技术论坛中英混排,保留仍有
-- 价值。
--
-- 注意:创建扩展需要相应权限。部分托管数据库不开放该权限,因此
-- 失败时仅提示,不影响后续迁移与功能——搜索本身不依赖扩展。
-- ============================================================
DO $$
BEGIN
CREATE EXTENSION IF NOT EXISTS pg_trgm;
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'pg_trgm 扩展创建失败(%)。搜索仍可正常使用,但英文关键词将无法走索引加速。', SQLERRM;
END $$;
-- 仅在扩展可用时才建索引
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_trgm') THEN
CREATE INDEX IF NOT EXISTS idx_posts_title_trgm
ON posts USING gin (title gin_trgm_ops);
CREATE INDEX IF NOT EXISTS idx_posts_content_trgm
ON posts USING gin (content gin_trgm_ops);
ELSE
RAISE NOTICE '跳过 trigram 索引创建:pg_trgm 不可用。';
END IF;
END $$;
+27
View File
@@ -333,3 +333,30 @@ INSERT INTO settings (key, value) VALUES
('smtp_allow_self_signed', 'false'),
('email_verify_required', 'false')
ON CONFLICT (key) DO NOTHING;
-- ============================================================
-- 帖子搜索(对应 migrations/005_post_search.sql)
-- ------------------------------------------------------------
-- 搜索用 ILIKE 子串匹配。trigram 索引对英文关键词有效(实测 0.2ms,
-- 比全表扫描快约 47 倍),对中文因难以切出有效 trigram 而仍走全表
-- 扫描(3000 条约 7~9ms,可接受)。
--
-- 创建扩展需要权限,部分托管数据库不开放,故失败时仅提示。
-- ============================================================
DO $$
BEGIN
CREATE EXTENSION IF NOT EXISTS pg_trgm;
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'pg_trgm 扩展创建失败(%)。搜索仍可用,但英文关键词不走索引。', SQLERRM;
END $$;
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_trgm') THEN
CREATE INDEX IF NOT EXISTS idx_posts_title_trgm
ON posts USING gin (title gin_trgm_ops);
CREATE INDEX IF NOT EXISTS idx_posts_content_trgm
ON posts USING gin (content gin_trgm_ops);
END IF;
END $$;
+66
View File
@@ -1167,6 +1167,72 @@ app.get('/api/posts', async (req, res) => {
}
});
// 搜索帖子(公开)
// 用 ILIKE 做子串匹配:PostgreSQL 的全文检索对中文需要额外分词扩展
// (zhparser 等),否则中文搜不出来;ILIKE 无需扩展即可正确匹配中文
// 子串,英文也天然大小写不敏感。数据量在万级以内性能足够。
//
// 转义 % 与 _:它们是 LIKE 的通配符,用户搜索「100%」这类内容时若不
// 转义会被当作模式匹配。
function escapeLikePattern(value) {
return value.replace(/[\\%_]/g, match => '\\' + match);
}
// 注意:本路由必须声明在 /api/posts/:id 之前,否则 search 会被当作 id
app.get('/api/posts/search', async (req, res) => {
const raw = typeof req.query.q === 'string' ? req.query.q.trim() : '';
if (raw.length === 0) {
return res.status(400).json({ error: '请输入搜索关键词' });
}
if (raw.length > 100) {
return res.status(400).json({ error: '搜索关键词过长(最多 100 字)' });
}
const pagination = parsePagination(req.query);
if (!pagination) return res.status(400).json({ error: '分页参数无效' });
const { page, limit, offset } = pagination;
const pattern = '%' + escapeLikePattern(raw) + '%';
try {
const countResult = await pool.query(
`SELECT COUNT(*) AS total FROM posts p
WHERE p.title ILIKE $1 OR p.content ILIKE $1`,
[pattern]
);
const total = parseInt(countResult.rows[0]?.total || 0);
const r = await pool.query(
`SELECT
p.*,
u.username,
u.avatar_url,
u.signature,
(SELECT COUNT(*) FROM replies WHERE post_id = p.id) AS reply_count
FROM posts p
JOIN users u ON p.user_id = u.id
WHERE p.title ILIKE $1 OR p.content ILIKE $1
ORDER BY p.created_at DESC
LIMIT $2 OFFSET $3`,
[pattern, limit, offset]
);
res.json({
data: r.rows,
query: raw,
pagination: {
page,
limit,
total,
totalPages: Math.ceil(total / limit)
}
});
} catch (err) {
res.status(500).json({ error: '服务器错误' });
}
});
// 获取单个帖子
app.get('/api/posts/:id', validateUuidId, async (req, res) => {
try {
+121
View File
@@ -3468,6 +3468,127 @@ select:disabled {
box-shadow: none !important;
}
/* ============================================================
🔍 帖子搜索
============================================================ */
.feed-search {
position: relative;
flex: 1;
min-width: 140px;
max-width: 280px;
/* 夹在排序标签与发布按钮之间,靠右对齐 */
margin-left: auto;
}
.feed-search input {
width: 100%;
box-sizing: border-box;
/* 右侧留出清除按钮的位置 */
padding-right: 34px !important;
margin-bottom: 0 !important;
}
/* 有内容时才出现的清除按钮 */
.feed-search-clear {
position: absolute;
right: 6px;
top: 50%;
transform: translateY(-50%);
display: flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
padding: 0;
border: none;
border-radius: 50%;
background: transparent;
color: var(--glass-text-light);
cursor: pointer;
transition: background var(--dur-fast, 0.16s) ease, color var(--dur-fast, 0.16s) ease;
}
.feed-search-clear:hover {
background: rgba(127, 127, 147, 0.18);
color: var(--glass-text);
}
/* 搜索中:输入框右侧显示一个细进度条,替代整块骨架屏
(搜索通常很快,画骨架反而闪得厉害) */
.feed-search.is-searching::after {
content: '';
position: absolute;
left: 2px;
right: 2px;
bottom: -3px;
height: 2px;
border-radius: 2px;
background: linear-gradient(90deg, transparent, var(--primary), transparent);
background-size: 200% 100%;
animation: searchProgress 0.9s linear infinite;
}
@keyframes searchProgress {
from { background-position: 200% 0; }
to { background-position: -200% 0; }
}
@media (prefers-reduced-motion: reduce) {
.feed-search.is-searching::after {
animation: none;
background: var(--primary);
}
}
/* 窄屏时搜索框独占一行,避免与标签、按钮挤在一起 */
@media (max-width: 640px) {
.feed-search {
order: 3;
width: 100%;
max-width: none;
margin-left: 0;
margin-top: 10px;
}
}
/* 搜索结果提示条 */
.search-summary {
font-size: 13px;
color: var(--glass-text-light);
margin-bottom: 12px;
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.search-summary strong {
color: var(--glass-text);
}
.search-summary button {
border: none;
background: none;
padding: 0;
color: var(--primary);
cursor: pointer;
font-size: 13px;
text-decoration: underline;
}
/* 无搜索结果 */
.search-empty {
text-align: center;
color: var(--glass-text-light);
padding: 60px 0;
line-height: 1.9;
}
.search-empty strong {
color: var(--glass-text);
}
/* ===== 列表容器高度稳定 =====
骨架屏按「理想内容」绘制,实际帖子往往更短,数据到达时容器高度会
骤降,导致其下方的内容(分页控件、页脚)整体上跳——这就是首屏