feat: 搜索结果持久化保存 + 结果数量可配置
- 新增 search_results 表,搜索结果按主题持久保存 - 搜索API自动保存结果到数据库,获取详情时更新raw_content - 页面加载时自动加载历史搜索结果,按搜索词分组显示 - 支持单条删除和清空所有搜索结果 - 搜索结果数量默认10条,可通过输入框调整(1-20) - 搜索面板标题显示结果计数badge
This commit is contained in:
@@ -221,14 +221,20 @@
|
||||
<!-- 搜索面板 -->
|
||||
<div class="search-panel mb-3">
|
||||
<div class="card-header d-flex justify-content-between align-items-center">
|
||||
<span class="section-title mb-0"><i class="bi bi-search text-accent"></i>网络搜索</span>
|
||||
<button class="btn btn-sm btn-link text-muted p-0" onclick="toggleSearchPanel()" title="折叠/展开">
|
||||
<i class="bi bi-chevron-down" id="searchPanelToggle"></i>
|
||||
</button>
|
||||
<span class="section-title mb-0"><i class="bi bi-search text-accent"></i>网络搜索 <span class="badge bg-secondary ms-1" id="searchCountBadge">0</span></span>
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<button class="btn btn-sm btn-link text-danger p-0" onclick="clearAllSearchResults()" title="清空所有搜索结果" id="clearSearchBtn" style="display:none;">
|
||||
<i class="bi bi-trash3 me-1"></i>清空
|
||||
</button>
|
||||
<button class="btn btn-sm btn-link text-muted p-0" onclick="toggleSearchPanel()" title="折叠/展开">
|
||||
<i class="bi bi-chevron-down" id="searchPanelToggle"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body" id="searchPanelBody">
|
||||
<div class="search-bar mb-3">
|
||||
<input type="text" class="form-control form-control-sm" id="searchQuery" placeholder="输入关键词搜索相关资料..." onkeydown="if(event.key==='Enter'){event.preventDefault();doSearch();}">
|
||||
<input type="number" class="form-control form-control-sm" id="searchMaxResults" value="10" min="1" max="20" title="结果数量" style="width:70px;">
|
||||
<select class="form-select form-select-sm" id="searchDepth" style="width:auto;min-width:90px;">
|
||||
<option value="basic">基础</option>
|
||||
<option value="advanced">深度</option>
|
||||
@@ -979,9 +985,10 @@
|
||||
// 初始化选择计数
|
||||
updateSelectCount();
|
||||
|
||||
// ===== 网络搜索 =====
|
||||
// ===== 网络搜索(持久化) =====
|
||||
let searchPanelCollapsed = false;
|
||||
let lastSearchQuery = '';
|
||||
// 搜索结果缓存(从数据库加载),key=result_id
|
||||
let searchResultsMap = {};
|
||||
|
||||
function toggleSearchPanel() {
|
||||
const body = document.getElementById('searchPanelBody');
|
||||
@@ -991,10 +998,84 @@
|
||||
icon.className = searchPanelCollapsed ? 'bi bi-chevron-right' : 'bi bi-chevron-down';
|
||||
}
|
||||
|
||||
function updateSearchCount() {
|
||||
const count = Object.keys(searchResultsMap).length;
|
||||
document.getElementById('searchCountBadge').textContent = count;
|
||||
document.getElementById('clearSearchBtn').style.display = count > 0 ? '' : 'none';
|
||||
}
|
||||
|
||||
// 页面加载时从数据库加载搜索结果
|
||||
async function loadSearchResults() {
|
||||
try {
|
||||
const res = await fetch(`/api/topics/${topicId}/search-results`);
|
||||
if (!res.ok) return;
|
||||
const results = await res.json();
|
||||
results.forEach(r => { searchResultsMap[r.id] = r; });
|
||||
renderAllSearchResults();
|
||||
updateSearchCount();
|
||||
} catch(e) {}
|
||||
}
|
||||
|
||||
function renderAllSearchResults() {
|
||||
const resultsEl = document.getElementById('searchResults');
|
||||
const results = Object.values(searchResultsMap);
|
||||
if (results.length === 0) {
|
||||
resultsEl.innerHTML = '<div class="search-empty"><i class="bi bi-globe2 d-block" style="font-size:2rem;opacity:0.3;"></i><small>搜索网络资料,结果可添加为素材</small></div>';
|
||||
return;
|
||||
}
|
||||
// 按时间倒序
|
||||
results.sort((a, b) => b.created_at.localeCompare(a.created_at));
|
||||
// 按query分组显示
|
||||
const groups = {};
|
||||
results.forEach(r => {
|
||||
if (!groups[r.query]) groups[r.query] = [];
|
||||
groups[r.query].push(r);
|
||||
});
|
||||
let html = '';
|
||||
for (const [query, items] of Object.entries(groups)) {
|
||||
html += `<div class="mb-3"><div class="small text-warning fw-bold mb-1"><i class="bi bi-search me-1"></i>${escapeHtml(query)} <span class="text-muted fw-normal">(${items.length}条)</span></div>`;
|
||||
items.forEach(r => { html += renderSearchResultFromDB(r); });
|
||||
html += '</div>';
|
||||
}
|
||||
resultsEl.innerHTML = html;
|
||||
}
|
||||
|
||||
function renderSearchResultFromDB(r) {
|
||||
const scorePercent = r.score ? Math.round(r.score * 100) : 0;
|
||||
const hasRaw = r.raw_content ? true : false;
|
||||
return `<div class="search-result-item" id="sr-${r.id}">
|
||||
<div class="d-flex justify-content-between align-items-start">
|
||||
<a class="result-title" href="${escapeHtml(r.url)}" target="_blank" rel="noopener">
|
||||
<i class="bi bi-box-arrow-up-right" style="font-size:0.8rem;"></i>
|
||||
${escapeHtml(r.title)}
|
||||
</a>
|
||||
<button class="btn btn-sm btn-link text-danger p-0" onclick="deleteSearchResult('${r.id}')" title="删除"><i class="bi bi-x-lg"></i></button>
|
||||
</div>
|
||||
<div class="result-url">${escapeHtml(r.url)}</div>
|
||||
<div class="result-snippet">${escapeHtml(r.snippet)}</div>
|
||||
<div class="result-score">相关度: ${scorePercent}%</div>
|
||||
<div class="result-actions">
|
||||
<button class="btn btn-sm btn-outline-accent" onclick="toggleSearchDetailDB('${r.id}')" id="detail-btn-${r.id}">
|
||||
<i class="bi bi-eye me-1"></i>${hasRaw ? '查看详情' : '获取详情'}
|
||||
</button>
|
||||
<button class="btn btn-sm btn-outline-success" onclick="addSearchResultAsMaterialDB('${r.id}')" id="add-btn-${r.id}" title="添加为文本素材">
|
||||
<i class="bi bi-plus-circle me-1"></i>添加为素材
|
||||
</button>
|
||||
<a class="btn btn-sm btn-secondary" href="${escapeHtml(r.url)}" target="_blank" rel="noopener" title="在新窗口打开">
|
||||
<i class="bi bi-box-arrow-up-right"></i>
|
||||
</a>
|
||||
</div>
|
||||
<div class="result-detail" id="search-detail-${r.id}">
|
||||
<div class="result-detail-content" id="search-detail-content-${r.id}">${hasRaw ? escapeHtml(r.raw_content) : ''}</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
async function doSearch() {
|
||||
const query = document.getElementById('searchQuery').value.trim();
|
||||
if (!query) return;
|
||||
|
||||
const maxResults = parseInt(document.getElementById('searchMaxResults').value) || 10;
|
||||
const depth = document.getElementById('searchDepth').value;
|
||||
const timeRange = document.getElementById('searchTimeRange').value;
|
||||
const btn = document.getElementById('searchBtn');
|
||||
@@ -1002,11 +1083,8 @@
|
||||
btn.innerHTML = '<span class="spinner-generate" style="width:14px;height:14px;border-width:2px;"></span>';
|
||||
btn.disabled = true;
|
||||
|
||||
const resultsEl = document.getElementById('searchResults');
|
||||
resultsEl.innerHTML = '<div class="search-loading"><span class="spinner-generate" style="width:20px;height:20px;"></span><br><small class="mt-2 d-block">搜索中...</small></div>';
|
||||
|
||||
try {
|
||||
const body = { query, search_depth: depth, max_results: 8 };
|
||||
const body = { query, search_depth: depth, max_results: maxResults, topic_id: topicId };
|
||||
if (timeRange) body.time_range = timeRange;
|
||||
|
||||
const res = await fetch('/api/search', {
|
||||
@@ -1016,69 +1094,57 @@
|
||||
});
|
||||
if (!res.ok) { const d = await res.json(); throw new Error(d.error || '搜索失败'); }
|
||||
const data = await res.json();
|
||||
lastSearchQuery = query;
|
||||
|
||||
const results = data.results || [];
|
||||
if (results.length === 0) {
|
||||
resultsEl.innerHTML = '<div class="search-empty"><i class="bi bi-search d-block" style="font-size:1.5rem;opacity:0.3;"></i><small>未找到相关结果</small></div>';
|
||||
} else {
|
||||
resultsEl.innerHTML = `<div class="small text-muted mb-2"><i class="bi bi-info-circle me-1"></i>找到 ${results.length} 条结果(耗时 ${data.response_time ? data.response_time.toFixed(1) : '-'}s)</div>` +
|
||||
results.map((r, i) => renderSearchResult(r, i, query)).join('');
|
||||
// 将保存的结果加入缓存
|
||||
if (data.saved_results) {
|
||||
data.saved_results.forEach(sr => {
|
||||
searchResultsMap[sr.id] = {
|
||||
id: sr.id,
|
||||
topic_id: topicId,
|
||||
query: query,
|
||||
title: sr.title,
|
||||
url: sr.url,
|
||||
snippet: sr.content,
|
||||
raw_content: '',
|
||||
score: sr.score,
|
||||
created_at: new Date().toLocaleString()
|
||||
};
|
||||
});
|
||||
}
|
||||
renderAllSearchResults();
|
||||
updateSearchCount();
|
||||
} catch(e) {
|
||||
resultsEl.innerHTML = `<div class="search-empty text-danger"><i class="bi bi-exclamation-triangle d-block" style="font-size:1.5rem;"></i><small>${escapeHtml(e.message)}</small></div>`;
|
||||
alert('搜索失败: ' + e.message);
|
||||
} finally {
|
||||
btn.innerHTML = origBtn;
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function renderSearchResult(r, index, query) {
|
||||
const scorePercent = r.score ? Math.round(r.score * 100) : 0;
|
||||
return `<div class="search-result-item" id="search-result-${index}">
|
||||
<a class="result-title" href="${escapeHtml(r.url)}" target="_blank" rel="noopener">
|
||||
<i class="bi bi-box-arrow-up-right" style="font-size:0.8rem;"></i>
|
||||
${escapeHtml(r.title)}
|
||||
</a>
|
||||
<div class="result-url">${escapeHtml(r.url)}</div>
|
||||
<div class="result-snippet">${escapeHtml(r.content)}</div>
|
||||
<div class="result-score">相关度: ${scorePercent}%</div>
|
||||
<div class="result-actions">
|
||||
<button class="btn btn-sm btn-outline-accent" onclick="toggleSearchDetail(${index}, '${escapeAttr(query)}', '${escapeAttr(r.url)}')" id="detail-btn-${index}">
|
||||
<i class="bi bi-eye me-1"></i>查看详情
|
||||
</button>
|
||||
<button class="btn btn-sm btn-outline-success" onclick="addSearchResultAsMaterial(${index})" title="添加为文本素材">
|
||||
<i class="bi bi-plus-circle me-1"></i>添加为素材
|
||||
</button>
|
||||
<a class="btn btn-sm btn-secondary" href="${escapeHtml(r.url)}" target="_blank" rel="noopener" title="在新窗口打开">
|
||||
<i class="bi bi-box-arrow-up-right"></i>
|
||||
</a>
|
||||
</div>
|
||||
<div class="result-detail" id="search-detail-${index}">
|
||||
<div class="result-detail-content" id="search-detail-content-${index}"></div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
async function toggleSearchDetail(index, query, url) {
|
||||
const detailEl = document.getElementById(`search-detail-${index}`);
|
||||
const btnEl = document.getElementById(`detail-btn-${index}`);
|
||||
const contentEl = document.getElementById(`search-detail-content-${index}`);
|
||||
async function toggleSearchDetailDB(resultId) {
|
||||
const detailEl = document.getElementById(`search-detail-${resultId}`);
|
||||
const btnEl = document.getElementById(`detail-btn-${resultId}`);
|
||||
const contentEl = document.getElementById(`search-detail-content-${resultId}`);
|
||||
if (!detailEl || !btnEl) return;
|
||||
|
||||
if (detailEl.classList.contains('show')) {
|
||||
detailEl.classList.remove('show');
|
||||
btnEl.innerHTML = '<i class="bi bi-eye me-1"></i>查看详情';
|
||||
const hasRaw = searchResultsMap[resultId] && searchResultsMap[resultId].raw_content;
|
||||
btnEl.innerHTML = `<i class="bi bi-eye me-1"></i>${hasRaw ? '查看详情' : '获取详情'}`;
|
||||
return;
|
||||
}
|
||||
|
||||
// 如果已经有内容,直接展示
|
||||
// 如果已有raw_content,直接展示
|
||||
if (contentEl.textContent.trim()) {
|
||||
detailEl.classList.add('show');
|
||||
btnEl.innerHTML = '<i class="bi bi-eye-slash me-1"></i>收起详情';
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取详细内容
|
||||
// 调用详情API获取
|
||||
const r = searchResultsMap[resultId];
|
||||
if (!r) return;
|
||||
|
||||
btnEl.innerHTML = '<span class="spinner-generate" style="width:12px;height:12px;border-width:2px;"></span>';
|
||||
btnEl.disabled = true;
|
||||
|
||||
@@ -1086,18 +1152,22 @@
|
||||
const res = await fetch('/api/search/detail', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({ query, url })
|
||||
body: JSON.stringify({ query: r.query, url: r.url, result_id: resultId })
|
||||
});
|
||||
if (!res.ok) { const d = await res.json(); throw new Error(d.error || '获取详情失败'); }
|
||||
const data = await res.json();
|
||||
const results = data.results || [];
|
||||
let detailText = '';
|
||||
if (results.length > 0 && results[0].raw_content) {
|
||||
contentEl.textContent = results[0].raw_content;
|
||||
detailText = results[0].raw_content;
|
||||
} else if (results.length > 0) {
|
||||
contentEl.textContent = results[0].content || '暂无详细内容';
|
||||
detailText = results[0].content || '暂无详细内容';
|
||||
} else {
|
||||
contentEl.textContent = '未能获取详细内容';
|
||||
detailText = '未能获取详细内容';
|
||||
}
|
||||
contentEl.textContent = detailText;
|
||||
// 更新缓存
|
||||
if (searchResultsMap[resultId]) searchResultsMap[resultId].raw_content = detailText;
|
||||
detailEl.classList.add('show');
|
||||
btnEl.innerHTML = '<i class="bi bi-eye-slash me-1"></i>收起详情';
|
||||
} catch(e) {
|
||||
@@ -1109,20 +1179,13 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function addSearchResultAsMaterial(index) {
|
||||
const item = document.querySelector(`#search-result-${index}`);
|
||||
if (!item) return;
|
||||
async function addSearchResultAsMaterialDB(resultId) {
|
||||
const r = searchResultsMap[resultId];
|
||||
if (!r) return;
|
||||
|
||||
const title = item.querySelector('.result-title').textContent.trim();
|
||||
const url = item.querySelector('.result-url').textContent.trim();
|
||||
const snippet = item.querySelector('.result-snippet').textContent.trim();
|
||||
const detailEl = document.getElementById(`search-detail-content-${index}`);
|
||||
const detailContent = detailEl ? detailEl.textContent.trim() : '';
|
||||
|
||||
// 构建素材内容:标题 + URL + 摘要 + 详细内容
|
||||
let content = `【${title}】\n来源: ${url}\n\n${snippet}`;
|
||||
if (detailContent) {
|
||||
content += `\n\n--- 详细内容 ---\n${detailContent}`;
|
||||
let content = `【${r.title}】\n来源: ${r.url}\n\n${r.snippet}`;
|
||||
if (r.raw_content) {
|
||||
content += `\n\n--- 详细内容 ---\n${r.raw_content}`;
|
||||
}
|
||||
|
||||
const fd = new FormData();
|
||||
@@ -1132,11 +1195,12 @@
|
||||
try {
|
||||
const res = await fetch(`/api/topics/${topicId}/materials`, {method: 'POST', body: fd});
|
||||
if (res.ok) {
|
||||
// 高亮提示
|
||||
const btn = item.querySelector('.btn-outline-success');
|
||||
btn.innerHTML = '<i class="bi bi-check-lg me-1"></i>已添加';
|
||||
btn.classList.replace('btn-outline-success', 'btn-success');
|
||||
btn.disabled = true;
|
||||
const btn = document.getElementById(`add-btn-${resultId}`);
|
||||
if (btn) {
|
||||
btn.innerHTML = '<i class="bi bi-check-lg me-1"></i>已添加';
|
||||
btn.classList.replace('btn-outline-success', 'btn-success');
|
||||
btn.disabled = true;
|
||||
}
|
||||
setTimeout(() => location.reload(), 800);
|
||||
} else {
|
||||
const d = await res.json(); alert(d.error || '添加失败');
|
||||
@@ -1145,6 +1209,28 @@
|
||||
alert('添加素材失败: ' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSearchResult(resultId) {
|
||||
if (!confirm('确定删除此搜索结果?')) return;
|
||||
await fetch(`/api/search-results/${resultId}`, {method: 'DELETE'});
|
||||
delete searchResultsMap[resultId];
|
||||
const el = document.getElementById(`sr-${resultId}`);
|
||||
if (el) el.remove();
|
||||
updateSearchCount();
|
||||
// 如果删完了重新渲染空状态
|
||||
if (Object.keys(searchResultsMap).length === 0) renderAllSearchResults();
|
||||
}
|
||||
|
||||
async function clearAllSearchResults() {
|
||||
if (!confirm('确定清空所有搜索结果?此操作不可恢复。')) return;
|
||||
await fetch(`/api/topics/${topicId}/search-results`, {method: 'DELETE'});
|
||||
searchResultsMap = {};
|
||||
renderAllSearchResults();
|
||||
updateSearchCount();
|
||||
}
|
||||
|
||||
// 加载搜索结果
|
||||
loadSearchResults();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user