• 安知鱼主题原本自带本地搜索预览图,但是检索的是文章内容图片
  • 文章内容的图片各种各样,而且有的有有的没导致搜索显示十分不统一
  • 所以我就直接把文章封面当作预览图使用

配置本地搜索

  • 安装插件
  • Hexo配置文件_config.yml
  • 增加本地搜索配置
1
2
3
4
5
6
# 本地搜索
search:
path: search.xml
field: post
content: true # 文章内容
template: source/_data/search.xml # 自定义模板
  • 主题配置文件_config.anzhiyu.yml
  • 开启本地搜索
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Local search
local_search:
enable: true
preload: false
CDN:

# CDN
# Don't modify the following settings unless you know how they work
# 非必要请不要修改
CDN:
# The CDN provider of internal scripts (主题内部 js 的 cdn 配置)
# option: local/elemecdn/jsdelivr/unpkg/cdnjs/onmicrosoft/cbd/anheyu/custom
# Dev version can only choose. ( dev版的主题只能设置为 local )
internal_provider: local

# The CDN provider of third party scripts (第三方 js 的 cdn 配置)
# option: elemecdn/jsdelivr/unpkg/cdnjs/onmicrosoft/cbd/anheyu/custom
third_party_provider: cbd

# Add version number to CDN, true or false
version: true

# Custom format
# For example: https://cdn.staticfile.org/${cdnjs_name}/${version}/${min_cdnjs_file}
custom_format: # https://npm.elemecdn.com/${name}@latest/${file}

option:
local_search: https://cdn.cbd.int/hexo-naokuo-search@0.0.2/dist/local-search.js
  • 自定义本地搜索模板
  • 路径source/_data/search.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?xml version="1.0" encoding="utf-8"?>
<search>
{% if posts %}
{% for post in posts.toArray() %}
{% if post.indexing == undefined or post.indexing %}
<entry>
<title>{{ post.title }}</title>
<link href="{{ (url + post.path) | uriencode }}"/>
<url>{{ (url + post.path) | uriencode }}</url>
<cover>{{ post.cover | uriencode }}</cover>
<date>{{ post.date }}</date>
{% if content %}
<content type="html"><![CDATA[{{ post.content | noControlChars | safe }}]]></content>
{% endif %}
{% if post.categories and post.categories.length>0 %}
<categories>
{% for cate in post.categories.toArray() %}
<category> {{ cate.name }} </category>
{% endfor %}
</categories>
{% endif %}
{% if post.tags and post.tags.length>0 %}
<tags>
{% for tag in post.tags.toArray() %}
<tag> {{ tag.name }} </tag>
{% endfor %}
</tags>
{% endif %}
</entry>
{% endif %}
{% endfor %}
{% endif %}
{% if pages %}
{% for page in pages.toArray() %}
{% if post.indexing == undefined or post.indexing %}
<entry>
<title>{{ page.title }}</title>
<link href="{{ (url + page.path) | uriencode }}"/>
<url>{{ (url + page.path) | uriencode }}</url>
<cover>{{ post.cover | uriencode }}</cover>
<date>{{ post.date }}</date>
{% if content %}
<content type="html"><![CDATA[{{ page.content | noControlChars | safe }}]]></content>
{% endif %}
</entry>
{% endif %}
{% endfor %}
{% endif %}
</search>

CSS(可选)

  • 小修改,以及移动端不显示预览图
  • 路径themes/anzhiyu/source/css/_extra/local_search/local_search.css 替换
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#local-search .search-dialog .local-search__hit-item:before {
content: none !important;
}

#local-search .search-dialog .local-search__hit-item {
padding: 10px !important;
border-radius: 8px;
border: var(--style-border);
margin-bottom: 10px;
display: flex;
justify-content: space-between;
align-items: center;
}

#local-search .search-dialog .local-search__hit-item .search-left {
width: 35%;
padding: 1rem;
}

#local-search .search-dialog .local-search__hit-item .search-right {
width: 60%;
}

#local-search .search-dialog .local-search__hit-item .search-left img {
object-fit: cover;
width: 100%;
background: var(--anzhiyu-secondbg);
border-radius: 8px;
transition: all 0.6s ease 0s;
}

#local-search .search-dialog .local-search__hit-item .search-left:hover img {
filter: brightness(0.82) !important;
transform: scale(1.06) !important;
transition: 0.3s ease-in-out;
}

#local-search .search-dialog .local-search__hit-item .search-result {
cursor: pointer;
}

#local-search .tag-list {
padding: 4px 8px;
border-radius: 8px;
margin-right: 0.5rem;
margin-top: 0.5rem;
border: var(--style-border);
cursor: pointer;
}

#local-search .search-dialog .local-search__hit-item .tag-list {
display: inline;
}

#local-search .search-dialog .local-search__hit-item .tag-list:hover {
background: var(--anzhiyu-main);
color: var(--anzhiyu-white);
}

#local-search .search-dialog .search-right .search-result-tags {
display: flex;
flex-wrap: wrap;
justify-content: flex-start;
}

@media screen and (max-width: 768px) {
#local-search .search-dialog .local-search__hit-item .search-right {
width: 100%;
padding: 0.8rem;
}

#local-search .search-dialog .local-search__hit-item .search-left {
display: none;
}
}
  • 个人喜好
  • 想像本博客本地搜索一样的显示大小
  • 就修改以下CSS
  • 路径themes/anzhiyu/source/css/_search/index.styl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
- .search-dialog
- position: fixed
- top: 5rem
- left: 50%
- z-index: 1001
- display: none
- margin-left: -18.75rem;
- padding: 1.25rem;
- width: 37.5rem;
- border-radius: 8px
- background: var(--search-bg)
- border-radius: 12px;
- box-shadow: var(--anzhiyu-shadow-lightblack);
- background: var(--anzhiyu-card-bg);
- border: var(--style-border);
- transition: .3s;
+ .search-dialog
+ position: fixed
+ top: 5rem
+ left: 0
+ right: 0
+ z-index: 1001
+ display: none
+ // margin-left: -18.75rem;
+ margin: auto;
+ padding: 1.25rem;
+ max-width: 70rem;
+ width: 100%;
+ border-radius: 8px
+ background: var(--search-bg)
+ border-radius: 12px;
+ box-shadow: var(--anzhiyu-shadow-lightblack);
+ background: var(--anzhiyu-card-bg);
+ border: var(--style-border);
+ transition: .3s;

注意请检查文章链接是否带.html后缀(可能会影响评论数据获取)

  • 已知Twikoo是区分https://www.naokuo.top/posts/39270d2bhttps://www.naokuo.top/posts/39270d2b.html
  • 访问它们时会获取不同的评论数据
  • 本文章介绍了的本地搜索默认生成的链接不包含 .html后缀
  • 所以如果你以前文章链接包含 .html后缀的可以使用以下本地搜索javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
window.addEventListener("load", () => {
let loadFlag = false;
let dataObj = [];
const $searchMask = document.getElementById("search-mask");

const openSearch = () => {
const bodyStyle = document.body.style;
bodyStyle.width = "100%";
bodyStyle.overflow = "hidden";
anzhiyu.animateIn($searchMask, "to_show 0.5s");
anzhiyu.animateIn(document.querySelector("#local-search .search-dialog"), "titleScale 0.5s");
setTimeout(() => {
document.querySelector("#local-search-input input").focus();
}, 100);
if (!loadFlag) {
search();
loadFlag = true;
}
// shortcut: ESC
document.addEventListener("keydown", function f(event) {
if (event.code === "Escape") {
closeSearch();
document.removeEventListener("keydown", f);
}
});
};

const closeSearch = () => {
const bodyStyle = document.body.style;
bodyStyle.width = "";
bodyStyle.overflow = "";
anzhiyu.animateOut(document.querySelector("#local-search .search-dialog"), "search_close .5s");
anzhiyu.animateOut($searchMask, "to_hide 0.5s");
};

const searchClickFn = () => {
document.querySelector("#search-button > .search").addEventListener("click", openSearch);
document.querySelector("#menu-search").addEventListener("click", openSearch);
};

const searchClickFnOnce = () => {
document.querySelector("#local-search .search-close-button").addEventListener("click", closeSearch);
$searchMask.addEventListener("click", closeSearch);
if (GLOBAL_CONFIG.localSearch.preload) dataObj = fetchData(GLOBAL_CONFIG.localSearch.path);
};

// check url is json or not
const isJson = url => {
const reg = /\.json$/;
return reg.test(url);
};

const fetchData = async path => {
let data = [];
const response = await fetch(path);
if (isJson(path)) {
data = await response.json();
} else {
const res = await response.text();
const t = await new window.DOMParser().parseFromString(res, "text/xml");
const a = await t;

data = [...a.querySelectorAll("entry")].map(item => {
let tagsArr = [];
if (item.querySelector("tags") && item.querySelector("tags").getElementsByTagName("tag")) {
Array.prototype.forEach.call(item.querySelector("tags").getElementsByTagName("tag"), function (item, index) {
tagsArr.push(item.textContent);
});
}
let content = item.querySelector("content") && item.querySelector("content").textContent;
let imgUrl = item.querySelector("cover") && item.querySelector("cover").textContent;
let dateText = item.querySelector("date") && item.querySelector("date").textContent;
let postsUrl = item.querySelector("url") && item.querySelector("url").textContent;
let dateMatch = null
let dateUrl = null
// 解码和匹配日期部分...
const decodedDate = decodeURIComponent(dateText);
const dateRegex = /^([a-zA-Z]{3})\s+([a-zA-Z]{3})\s+(\d{1,2})\s+(\d{4})/;
const date_match = dateRegex.exec(decodedDate);
const monthToNumber = {
'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4,
'May': 5, 'Jun': 6, 'Jul': 7, 'Aug': 8,
'Sep': 9, 'Sept': 9, // 注意:有时候会使用全拼"September"
'Oct': 10, 'Nov': 11, 'Dec': 12
};
if (date_match) {
const day = parseInt(date_match[3], 10);
const monthName = date_match[2];
const year = parseInt(date_match[4], 10);
// 映射英文月份到数字月份
const monthNumber = monthToNumber[monthName];

dateMatch = year + "-" + (monthNumber < 10 ? "0" + monthNumber : monthNumber) + "-" + (day < 10 ? "0" + day : day);
dateUrl = "/archives/" + year + "/" + (monthNumber < 10 ? "0" + monthNumber : monthNumber) + "/";
}

// let postsregex = /(.*)\.html$/; // 匹配任何字符直到遇到".html"结尾
// postsUrl = postsUrl.match(postsregex);
// if (postsUrl) {
// postsUrl = postsUrl[1];
// }
return {
title: item.querySelector("title").textContent,
content: content,
url: postsUrl,
tags: tagsArr,
oneImage: imgUrl,
dateText: dateMatch,
dateUrl: dateUrl,
};
});
}
if (response.ok) {
const $loadDataItem = document.getElementById("loading-database");
$loadDataItem.nextElementSibling.style.display = "block";
$loadDataItem.remove();
}
return data;
};

const search = () => {
if (!GLOBAL_CONFIG.localSearch.preload) {
dataObj = fetchData(GLOBAL_CONFIG.localSearch.path);
}
const $input = document.querySelector("#local-search-input input");
const $resultContent = document.getElementById("local-search-results");
const $loadingStatus = document.getElementById("loading-status");

$input.addEventListener("input", function () {
const keywords = this.value.trim().toLowerCase().split(/[\s]+/);
if (keywords[0] !== "")
$loadingStatus.innerHTML = '<i class="naokuofont naokuo-icon-spinner anzhiyu-pulse-icon"></i>';

$resultContent.innerHTML = "";
let str = '<div class="search-result-list">';
if (keywords.length <= 0) return;
let count = 0;
// perform local searching
dataObj.then(data => {
data.forEach(data => {
let isMatch = true;
let dataTitle = data.title ? data.title.trim().toLowerCase() : "";
let dataTags = data.tags;
let oneImage = data.oneImage ?? "";
let dateText = data.dateText;
let dateUrl = data.dateUrl;
const dataContent = data.content
? data.content
.trim()
.replace(/<[^>]+>/g, "")
.toLowerCase()
: "";
const dataUrl = data.url.startsWith("/") ? data.url : GLOBAL_CONFIG.root + data.url;
let indexTitle = -1;
let indexContent = -1;
let firstOccur = -1;
// only match articles with not empty titles and contents
if (dataTitle !== "" || dataContent !== "") {
keywords.forEach((keyword, i) => {
indexTitle = dataTitle.indexOf(keyword);
indexContent = dataContent.indexOf(keyword);
if (indexTitle < 0 && indexContent < 0) {
isMatch = false;
} else {
if (indexContent < 0) {
indexContent = 0;
}
if (i === 0) {
firstOccur = indexContent;
}
}
});
} else {
isMatch = false;
}

// show search results
if (isMatch) {
if (firstOccur >= 0) {
// cut out 130 characters
// let start = firstOccur - 30 < 0 ? 0 : firstOccur - 30
// let end = firstOccur + 50 > dataContent.length ? dataContent.length : firstOccur + 50
let start = firstOccur - 30;
let end = firstOccur + 100;
let pre = "";
let post = "";

if (start < 0) {
start = 0;
}

if (start === 0) {
end = 100;
} else {
pre = "...";
}

if (end > dataContent.length) {
end = dataContent.length;
} else {
post = "...";
}

let matchContent = dataContent.substring(start, end);

// highlight all keywords
keywords.forEach(keyword => {
const regS = new RegExp(keyword, "gi");
matchContent = matchContent.replace(regS, `<span class="search-keyword">${keyword}</span>`);
dataTitle = dataTitle.replace(regS, `<span class="search-keyword">${keyword}</span>`);
});

str += '<div class="local-search__hit-item">';
if (oneImage) {
str += `<div class="search-left"><a href="javascript:;" onclick="pjax.loadUrl('${dataUrl}')" title="${data.title ? data.title.trim().toLowerCase() : ''}" data-pjax-state=""><img src="${oneImage}" alt="${data.title ? data.title.trim().toLowerCase() : ''}"></a>`;
} else {
str += '<div class="search-left" style="width:0">';
}

str += "</div>";

if (oneImage) {
str += `<div class="search-right"><a class="search-result-title" href="javascript:;" onclick="pjax.loadUrl('${dataUrl}')" title="${data.title ? data.title.trim().toLowerCase() : ''}" data-pjax-state="">${dataTitle}</a>`;
} else {
str += `<div class="search-right" style="width: 100%"><a class="search-result-title" href="javascript:;" onclick="pjax.loadUrl('${dataUrl}')" title="${data.title ? data.title.trim().toLowerCase() : ''}" data-pjax-state="">${dataTitle}</a>`;
}

count += 1;

if (dataContent !== "") {
str += `<p class="search-result" onclick="pjax.loadUrl('${dataUrl}')" data-pjax-state="">${pre}${matchContent}${post}</p>`;
}
if (dataTags.length) {
str += '<div class="search-result-tags">';

for (let i = 0; i < dataTags.length; i++) {
const element = dataTags[i].trim();

str += `<a class="tag-list" href="javascript:;" onclick="pjax.loadUrl('/tags/${element}/')" one-link-mark="yes" title="#${element}" data-pjax-state="">#${element}</a>`;
}
}
if (dateText.length && dateUrl.length) {
str += `<a class="tag-list" href="javascript:;" onclick="pjax.loadUrl('${dateUrl}')" title="发表于${dateText}" data-pjax-state=""><i class="naokuofont naokuo-icon-calendar-days" style="font-size: 15px;"></i><span> 发表于 ${dateText}</span></a></div>`;
} else {
str += `</div>`;
}
}
str += "</div></div>";
}
});
if (count === 0) {
str +=
'<div id="local-search__hits-empty">' +
GLOBAL_CONFIG.localSearch.languages.hits_empty.replace(/\$\{query}/, this.value.trim()) +
"</div>";
}
str += "</div>";
$resultContent.innerHTML = str;
if (keywords[0] !== "") $loadingStatus.innerHTML = "";
window.pjax && window.pjax.refresh($resultContent);
});
});
};

searchClickFn();
searchClickFnOnce();

// pjax
window.addEventListener("pjax:complete", () => {
!anzhiyu.isHidden($searchMask) && closeSearch();
searchClickFn();
});
});