Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsearch-enhanced.js
More file actions
483 lines (430 loc) · 13.4 KB
/
Copy pathsearch-enhanced.js
File metadata and controls
483 lines (430 loc) · 13.4 KB
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
/**
* 增强搜索功能
* 支持搜索历史、自动建议和智能搜索
*/
class EnhancedSearch {
constructor() {
this.searchHistoryKey = 'search-history';
this.maxHistoryItems = 10;
this.searchHistory = this.loadSearchHistory();
this.suggestionsCache = {};
this.searchData = [];
this.init();
}
/**
* 初始化
*/
init() {
this.loadSearchData();
this.setupSearchUI();
this.setupKeyboardShortcuts();
}
/**
* 加载搜索数据
*/
async loadSearchData() {
try {
// 从 JSON 数据加载
const response = await fetch('./data/search-index.json');
if (response.ok) {
this.searchData = await response.json();
console.log(`加载了 ${this.searchData.length} 条搜索数据`);
} else {
// 如果没有搜索索引,使用导航数据
const navResponse = await fetch('./data/nav.json');
const navData = await navResponse.json();
this.searchData = this.extractSearchData(navData);
console.log(`从导航数据提取了 ${this.searchData.length} 条搜索数据`);
}
} catch (error) {
console.error('加载搜索数据失败:', error);
}
}
/**
* 从导航数据提取搜索数据
*/
extractSearchData(navData) {
const results = [];
if (navData.categories) {
navData.categories.forEach((category) => {
if (category.links) {
category.links.forEach((link) => {
results.push({
title: link.name,
url: link.url,
category: category.name,
description: link.description || `来自 ${category.name}`,
keywords: [link.name, category.name].join(' '),
type: 'link',
});
});
}
});
}
return results;
}
/**
* 加载搜索历史
*/
loadSearchHistory() {
try {
const history = localStorage.getItem(this.searchHistoryKey);
return history ? JSON.parse(history) : [];
} catch (error) {
console.error('加载搜索历史失败:', error);
return [];
}
}
/**
* 保存搜索历史
*/
saveSearchHistory() {
try {
localStorage.setItem(this.searchHistoryKey, JSON.stringify(this.searchHistory));
} catch (error) {
console.error('保存搜索历史失败:', error);
}
}
/**
* 添加搜索历史
*/
addSearchHistory(query) {
const trimmedQuery = query.trim();
if (!trimmedQuery) return;
// 移除重复项
this.searchHistory = this.searchHistory.filter((item) => item !== trimmedQuery);
// 添加到开头
this.searchHistory.unshift(trimmedQuery);
// 限制数量
if (this.searchHistory.length > this.maxHistoryItems) {
this.searchHistory = this.searchHistory.slice(0, this.maxHistoryItems);
}
this.saveSearchHistory();
}
/**
* 清除搜索历史
*/
clearSearchHistory() {
this.searchHistory = [];
this.saveSearchHistory();
}
/**
* 设置搜索 UI
*/
setupSearchUI() {
// 查找或创建搜索框
const searchInput =
document.getElementById('search-input') || document.querySelector('.search-input');
if (searchInput) {
this.setupSearchInput(searchInput);
}
// 创建搜索建议容器
this.createSuggestionsContainer();
}
/**
* 设置搜索输入框
*/
setupSearchInput(input) {
this.searchInput = input;
// 输入事件
input.addEventListener('input', (e) => {
this.handleInput(e.target.value);
});
// 焦点事件
input.addEventListener('focus', () => {
this.showSuggestions();
});
// 失去焦点事件(延迟隐藏)
input.addEventListener('blur', () => {
setTimeout(() => this.hideSuggestions(), 200);
});
// 键盘事件
input.addEventListener('keydown', (e) => {
this.handleKeydown(e);
});
}
/**
* 创建建议容器
*/
createSuggestionsContainer() {
const container = document.createElement('div');
container.className = 'search-suggestions-container';
container.id = 'search-suggestions';
document.body.appendChild(container);
this.suggestionsContainer = container;
}
/**
* 处理输入
*/
handleInput(value) {
if (value.trim()) {
this.showSuggestions(value);
} else {
this.showSuggestions();
}
}
/**
* 显示建议
*/
showSuggestions(query = '') {
if (!this.suggestionsContainer) return;
let suggestionsHTML = '';
// 搜索建议
if (query.trim()) {
const suggestions = this.getSuggestions(query);
if (suggestions.length > 0) {
suggestionsHTML += `
<div class="suggestions-section">
<div class="suggestions-header">搜索建议</div>
<div class="suggestions-list">
${suggestions.map((item) => this.renderSuggestionItem(item)).join('')}
</div>
</div>
`;
}
}
// 搜索历史
if (this.searchHistory.length > 0 && !query.trim()) {
suggestionsHTML += `
<div class="suggestions-section">
<div class="suggestions-header">
<span>搜索历史</span>
<button class="clear-history-btn" onclick="enhancedSearch.clearSearchHistory()">
<i class="fa fa-trash-o"></i> 清除
</button>
</div>
<div class="suggestions-list history-list">
${this.searchHistory.map((item) => this.renderHistoryItem(item)).join('')}
</div>
</div>
`;
}
// 热门搜索
if (!query.trim()) {
const popularSearches = this.getPopularSearches();
if (popularSearches.length > 0) {
suggestionsHTML += `
<div class="suggestions-section">
<div class="suggestions-header">热门搜索</div>
<div class="suggestions-list popular-list">
${popularSearches.map((item) => this.renderPopularItem(item)).join('')}
</div>
</div>
`;
}
}
this.suggestionsContainer.innerHTML = suggestionsHTML;
this.suggestionsContainer.style.display = 'block';
}
/**
* 隐藏建议
*/
hideSuggestions() {
if (this.suggestionsContainer) {
this.suggestionsContainer.style.display = 'none';
}
}
/**
* 获取搜索建议
*/
getSuggestions(query) {
const lowerQuery = query.toLowerCase();
return this.searchData
.filter(
(item) =>
item.title.toLowerCase().includes(lowerQuery) ||
(item.description && item.description.toLowerCase().includes(lowerQuery)) ||
(item.keywords && item.keywords.toLowerCase().includes(lowerQuery))
)
.slice(0, 5);
}
/**
* 获取热门搜索
*/
getPopularSearches() {
return [
{ title: 'Python', url: '#' },
{ title: 'JavaScript', url: '#' },
{ title: 'React', url: '#' },
{ title: 'Vue.js', url: '#' },
{ title: 'Docker', url: '#' },
];
}
/**
* 渲染建议项
*/
renderSuggestionItem(item) {
return `
<a href="${item.url}" class="suggestion-item" onclick="enhancedSearch.performSearch('${item.title}')">
<div class="suggestion-icon">
<i class="fa fa-${item.type === 'link' ? 'link' : 'search'}"></i>
</div>
<div class="suggestion-content">
<div class="suggestion-title">${this.highlightMatch(item.title)}</div>
<div class="suggestion-description">${item.description || ''}</div>
</div>
</a>
`;
}
/**
* 渲染历史项
*/
renderHistoryItem(query) {
return `
<div class="suggestion-item history-item" onclick="enhancedSearch.performSearch('${query}')">
<div class="suggestion-icon">
<i class="fa fa-clock-o"></i>
</div>
<div class="suggestion-content">
<div class="suggestion-title">${query}</div>
</div>
</div>
`;
}
/**
* 渲染热门项
*/
renderPopularItem(item) {
return `
<a href="${item.url}" class="suggestion-item popular-item">
<div class="suggestion-icon">
<i class="fa fa-fire"></i>
</div>
<div class="suggestion-content">
<div class="suggestion-title">${item.title}</div>
</div>
</a>
`;
}
/**
* 高亮匹配文本
*/
highlightMatch(text, query) {
if (!this.searchInput) return text;
const queryText = this.searchInput.value.trim();
if (!queryText) return text;
const regex = new RegExp(`(${queryText})`, 'gi');
return text.replace(regex, '<mark>$1</mark>');
}
/**
* 执行搜索
*/
performSearch(query) {
if (!query) return;
// 添加到搜索历史
this.addSearchHistory(query);
// 更新搜索框
if (this.searchInput) {
this.searchInput.value = query;
}
// 隐藏建议
this.hideSuggestions();
// 执行实际搜索
this.executeSearch(query);
}
/**
* 执行搜索
*/
executeSearch(query) {
// 调用原有的搜索功能
if (window.performSearch) {
window.performSearch(query);
} else {
// 默认搜索行为
const results = this.searchData.filter(
(item) =>
item.title.toLowerCase().includes(query.toLowerCase()) ||
(item.description &&
item.description.toLowerCase().includes(query.toLowerCase()))
);
console.log(`搜索 "${query}" 找到 ${results.length} 个结果`);
this.displaySearchResults(results);
}
}
/**
* 显示搜索结果
*/
displaySearchResults(results) {
const resultsContainer =
document.getElementById('search-results') || document.querySelector('.search-results');
if (resultsContainer) {
if (results.length === 0) {
resultsContainer.innerHTML = '<div class="no-results">未找到相关结果</div>';
} else {
resultsContainer.innerHTML = `
<div class="results-count">找到 ${results.length} 个结果</div>
<div class="results-list">
${results
.map(
(item) => `
<a href="${item.url}" class="result-item">
<div class="result-title">${item.title}</div>
<div class="result-description">${item.description || ''}</div>
<div class="result-category">${item.category || ''}</div>
</a>
`
)
.join('')}
</div>
`;
}
}
}
/**
* 处理键盘事件
*/
handleKeydown(e) {
const suggestions = this.suggestionsContainer?.querySelectorAll('.suggestion-item');
if (!suggestions || suggestions.length === 0) return;
if (e.key === 'ArrowDown') {
e.preventDefault();
// 移动到下一个建议
} else if (e.key === 'ArrowUp') {
e.preventDefault();
// 移动到上一个建议
} else if (e.key === 'Enter') {
e.preventDefault();
// 执行搜索
this.performSearch(this.searchInput.value);
} else if (e.key === 'Escape') {
// 隐藏建议
this.hideSuggestions();
}
}
/**
* 设置键盘快捷键
*/
setupKeyboardShortcuts() {
document.addEventListener('keydown', (e) => {
// Cmd/Ctrl + K 打开搜索
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault();
if (this.searchInput) {
this.searchInput.focus();
this.showSuggestions();
}
}
// Escape 关闭搜索
if (e.key === 'Escape' && this.searchInput === document.activeElement) {
this.searchInput.blur();
this.hideSuggestions();
}
});
}
/**
* 获取搜索统计
*/
getSearchStats() {
return {
totalSearches: this.searchHistory.length,
recentSearches: this.searchHistory.slice(0, 5),
dataCount: this.searchData.length,
};
}
}
// 创建全局实例
const enhancedSearch = new EnhancedSearch();
// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
module.exports = EnhancedSearch;
}
You can’t perform that action at this time.
