Skip to content

Commit

Permalink
添加搜索结果高亮
Browse files Browse the repository at this point in the history
  • Loading branch information
qianmoQ committed Feb 7, 2025
1 parent 92c27f3 commit d25ec32
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 11 deletions.
12 changes: 12 additions & 0 deletions docs/content/setup/feature.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,4 +193,16 @@ PageForge 支持 Dark Mode,需要启用后才能使用。
feature:
darkMode:
enable: true
```

## 搜索功能

---

PageForge 支持搜索功能,需要启用后才能使用。

```yaml
feature:
search:
enable: true
```
67 changes: 56 additions & 11 deletions templates/assets/js/pageforge-search.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,45 @@ const Search = {
}
},

// 高亮文本
highlightText(text, query) {
if (!text || !query) {
return text;
}

// 转义正则表达式特殊字符
const escapedQuery = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(`(${escapedQuery})`, 'gi');

return text.replace(regex, `<mark class="bg-yellow-200 dark:bg-yellow-800 dark:text-gray-100">$1</mark>`);
},

// 获取包含匹配内容的摘要
getContentExcerpt(content, query, maxLength = 160) {
if (!content || !query) {
return content;
}

const lowerContent = content.toLowerCase();
const lowerQuery = query.toLowerCase();
const matchIndex = lowerContent.indexOf(lowerQuery);

if (matchIndex === -1) {
return content.substring(0, maxLength);
}

// 确定摘要的起始和结束位置
let start = Math.max(0, matchIndex - 60);
let end = Math.min(content.length, matchIndex + 100);

// 如果摘要不是从开头开始,添加省略号
let excerpt = (start > 0 ? '...' : '') +
content.substring(start, end) +
(end < content.length ? '...' : '');

return excerpt;
},

// 执行搜索
async performSearch(query) {
// 确保索引已加载
Expand Down Expand Up @@ -164,17 +203,23 @@ const Search = {

this.els.searchResults.innerHTML = `
<div class="divide-y divide-gray-100 dark:divide-gray-800">
${results.map(result => `
<a href="${result.url}"
class="block px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-700/50">
<div class="text-sm font-medium text-gray-900 dark:text-gray-100">
${result.title}
</div>
<div class="mt-1 text-sm text-gray-500 dark:text-gray-400 line-clamp-2">
${result.content.substring(0, 160)}...
</div>
</a>
`).join('')}
${results.map(result => {
const highlightedTitle = this.highlightText(result.title, query);
const contentExcerpt = this.getContentExcerpt(result.content, query);
const highlightedContent = this.highlightText(contentExcerpt, query);
return `
<a href="${result.url}"
class="block px-4 py-3 hover:bg-gray-50 dark:hover:bg-gray-700/50">
<div class="text-sm font-medium text-gray-900 dark:text-gray-100">
${highlightedTitle}
</div>
<div class="mt-1 text-sm text-gray-500 dark:text-gray-400 line-clamp-2">
${highlightedContent}
</div>
</a>
`;
}).join('')}
</div>
`;
}
Expand Down

0 comments on commit d25ec32

Please sign in to comment.