diff --git a/docs/content/setup/feature.md b/docs/content/setup/feature.md index bd65099..02531b1 100644 --- a/docs/content/setup/feature.md +++ b/docs/content/setup/feature.md @@ -193,4 +193,16 @@ PageForge 支持 Dark Mode,需要启用后才能使用。 feature: darkMode: enable: true +``` + +## 搜索功能 + +--- + +PageForge 支持搜索功能,需要启用后才能使用。 + +```yaml +feature: + search: + enable: true ``` \ No newline at end of file diff --git a/templates/assets/js/pageforge-search.js b/templates/assets/js/pageforge-search.js index a36fcfb..2b7033c 100644 --- a/templates/assets/js/pageforge-search.js +++ b/templates/assets/js/pageforge-search.js @@ -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, `$1`); + }, + + // 获取包含匹配内容的摘要 + 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) { // 确保索引已加载 @@ -164,17 +203,23 @@ const Search = { this.els.searchResults.innerHTML = `