-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsearch.js
More file actions
686 lines (583 loc) · 19.5 KB
/
Copy pathsearch.js
File metadata and controls
686 lines (583 loc) · 19.5 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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
/**
* 全站搜索功能
* 支持 URL 搜索、文章搜索、Wiki 搜索
*/
(function () {
'use strict';
// 搜索数据
let searchData = {
urls: [],
articles: [],
wiki: [],
};
// 搜索配置
const config = {
minQueryLength: 2,
maxResults: 10,
debounceDelay: 300,
};
// DOM 元素
let searchOverlay = null;
let searchInput = null;
let searchResults = null;
let searchSpinner = null;
let isSearchOpen = false;
// 初始化搜索
function init() {
if (document.querySelector('.search-overlay')) {
return; // 已经初始化过
}
createSearchOverlay();
loadSearchData();
bindEvents();
}
// 创建搜索覆盖层
function createSearchOverlay() {
const overlay = document.createElement('div');
overlay.className = 'search-overlay';
overlay.innerHTML = `
<div class="search-container">
<div class="search-header">
<input type="text" class="search-input" placeholder="搜索网站内容..." autocomplete="off">
<button class="search-close" aria-label="关闭搜索">×</button>
</div>
<div class="search-spinner">
<div class="spinner"></div>
</div>
<div class="search-results">
<div class="search-empty">
<i class="fas fa-search"></i>
<p>输入关键词开始搜索</p>
</div>
</div>
<div class="search-footer">
<span class="search-shortcut">按 ESC 关闭</span>
<span class="search-hint">↑↓ 选择结果</span>
</div>
</div>
`;
document.body.appendChild(overlay);
searchOverlay = overlay;
searchInput = overlay.querySelector('.search-input');
searchResults = overlay.querySelector('.search-results');
searchSpinner = overlay.querySelector('.search-spinner');
// 添加样式
addSearchStyles();
}
// 添加搜索样式
function addSearchStyles() {
if (document.querySelector('#search-styles')) {
return;
}
const style = document.createElement('style');
style.id = 'search-styles';
style.textContent = `
.search-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.8);
z-index: 10000;
display: none;
align-items: flex-start;
justify-content: center;
padding-top: 10vh;
animation: fadeIn 0.2s ease;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.search-overlay.active {
display: flex;
}
.search-container {
width: 90%;
max-width: 700px;
background: white;
border-radius: 12px;
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.3);
overflow: hidden;
animation: slideDown 0.3s ease;
}
@keyframes slideDown {
from {
transform: translateY(-50px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.search-header {
display: flex;
align-items: center;
padding: 20px;
border-bottom: 1px solid #e5e7eb;
gap: 12px;
}
.search-input {
flex: 1;
padding: 12px 16px;
font-size: 16px;
border: 2px solid #e5e7eb;
border-radius: 8px;
outline: none;
transition: border-color 0.2s;
}
.search-input:focus {
border-color: #3b82f6;
}
.search-close {
width: 40px;
height: 40px;
border: none;
background: #f3f4f6;
border-radius: 8px;
font-size: 24px;
cursor: pointer;
color: #6b7280;
transition: all 0.2s;
}
.search-close:hover {
background: #e5e7eb;
color: #1f2937;
}
.search-spinner {
display: none;
padding: 40px;
text-align: center;
}
.search-spinner.active {
display: block;
}
.spinner {
width: 40px;
height: 40px;
border: 4px solid #e5e7eb;
border-top-color: #3b82f6;
border-radius: 50%;
animation: spin 0.8s linear infinite;
margin: 0 auto;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.search-results {
max-height: 400px;
overflow-y: auto;
padding: 0;
}
.search-empty {
text-align: center;
padding: 40px 20px;
color: #9ca3af;
}
.search-empty i {
font-size: 48px;
margin-bottom: 12px;
opacity: 0.5;
}
.search-item {
padding: 16px 20px;
border-bottom: 1px solid #f3f4f6;
cursor: pointer;
transition: background 0.2s;
text-decoration: none;
color: inherit;
display: block;
}
.search-item:hover,
.search-item.active {
background: #f9fafb;
}
.search-item-title {
font-weight: 600;
color: #1f2937;
margin-bottom: 4px;
}
.search-item-url {
color: #6b7280;
font-size: 13px;
margin-bottom: 4px;
}
.search-item-desc {
color: #9ca3af;
font-size: 14px;
}
.search-item-highlight {
background: #fef3c7;
padding: 0 2px;
border-radius: 2px;
}
.search-category {
padding: 12px 20px;
font-weight: 600;
color: #6b7280;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.5px;
background: #f9fafb;
}
.search-footer {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 20px;
background: #f9fafb;
border-top: 1px solid #e5e7eb;
font-size: 13px;
color: #6b7280;
}
.dark-mode .search-overlay {
background: rgba(0, 0, 0, 0.9);
}
.dark-mode .search-container {
background: #1f2937;
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5);
}
.dark-mode .search-header {
border-bottom-color: #374151;
}
.dark-mode .search-input {
background: #374151;
border-color: #4b5563;
color: #f9fafb;
}
.dark-mode .search-input:focus {
border-color: #3b82f6;
}
.dark-mode .search-close {
background: #374151;
color: #9ca3af;
}
.dark-mode .search-close:hover {
background: #4b5563;
color: #f9fafb;
}
.dark-mode .search-item {
border-bottom-color: #374151;
}
.dark-mode .search-item:hover,
.dark-mode .search-item.active {
background: #374151;
}
.dark-mode .search-item-title {
color: #f9fafb;
}
.dark-mode .search-item-url {
color: #9ca3af;
}
.dark-mode .search-item-desc {
color: #6b7280;
}
.dark-mode .search-item-highlight {
background: #92400e;
}
.dark-mode .search-category {
background: #374151;
color: #9ca3af;
}
.dark-mode .search-footer {
background: #374151;
border-top-color: #4b5563;
}
/* 移动端适配 */
@media (max-width: 768px) {
.search-container {
width: 95%;
margin-top: 10vh;
}
.search-input {
font-size: 14px;
}
.search-results {
max-height: 50vh;
}
}
`;
document.head.appendChild(style);
}
// 加载搜索数据
function loadSearchData() {
// 加载导航数据
fetch('/data/nav.json')
.then((response) => response.json())
.then((data) => {
data.categories.forEach((category) => {
category.links.forEach((link) => {
searchData.urls.push({
title: link.name,
url: link.url,
category: category.name,
type: 'url',
});
});
});
})
.catch((error) => {
console.error('加载导航数据失败:', error);
});
// 加载文章数据(这里可以扩展为实际的文章搜索)
const articles = document.querySelectorAll('.post-card');
articles.forEach((article) => {
const title = article.querySelector('.post-title')?.textContent || '';
const url = article.getAttribute('href') || '';
const desc = article.querySelector('.post-excerpt')?.textContent || '';
if (title && url) {
searchData.articles.push({
title: title,
url: url,
description: desc,
type: 'article',
});
}
});
}
// 绑定事件
function bindEvents() {
// 键盘快捷键
document.addEventListener('keydown', handleKeydown);
// 搜索输入
if (searchInput) {
searchInput.addEventListener('input', debounce(handleSearch, config.debounceDelay));
searchInput.addEventListener('keydown', handleSearchKeydown);
}
// 关闭按钮
const closeBtn = searchOverlay?.querySelector('.search-close');
if (closeBtn) {
closeBtn.addEventListener('click', closeSearch);
}
// 点击覆盖层关闭
searchOverlay?.addEventListener('click', (e) => {
if (e.target === searchOverlay) {
closeSearch();
}
});
}
// 处理键盘事件
function handleKeydown(e) {
// Cmd/Ctrl + K 打开搜索
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault();
toggleSearch();
}
// ESC 关闭搜索
if (e.key === 'Escape' && isSearchOpen) {
closeSearch();
}
}
// 处理搜索输入
function handleSearchKeydown(e) {
const items = searchResults?.querySelectorAll('.search-item');
if (!items.length) return;
const activeItem = searchResults.querySelector('.search-item.active');
const currentIndex = Array.from(items).indexOf(activeItem);
// 向下箭头
if (e.key === 'ArrowDown') {
e.preventDefault();
const nextIndex = currentIndex < items.length - 1 ? currentIndex + 1 : 0;
setActiveItem(items[nextIndex]);
}
// 向上箭头
if (e.key === 'ArrowUp') {
e.preventDefault();
const prevIndex = currentIndex > 0 ? currentIndex - 1 : items.length - 1;
setActiveItem(items[prevIndex]);
}
// Enter 选择结果
if (e.key === 'Enter' && activeItem) {
e.preventDefault();
activeItem.click();
}
}
// 设置激活项
function setActiveItem(item) {
searchResults.querySelectorAll('.search-item').forEach((i) => {
i.classList.remove('active');
});
item.classList.add('active');
item.scrollIntoView({ block: 'nearest' });
}
// 执行搜索
function handleSearch() {
const query = searchInput.value.trim();
if (!query || query.length < config.minQueryLength) {
showEmptyState();
return;
}
showSpinner();
// 模拟搜索延迟
setTimeout(() => {
const results = performSearch(query);
displayResults(results);
hideSpinner();
}, 300);
}
// 执行搜索
function performSearch(query) {
const results = [];
const lowerQuery = query.toLowerCase();
// 搜索 URL
const urlResults = searchData.urls
.filter(
(item) =>
item.title.toLowerCase().includes(lowerQuery) ||
item.category.toLowerCase().includes(lowerQuery)
)
.slice(0, config.maxResults);
if (urlResults.length > 0) {
results.push({
category: '网址导航',
items: urlResults,
});
}
// 搜索文章
const articleResults = searchData.articles
.filter(
(item) =>
item.title.toLowerCase().includes(lowerQuery) ||
(item.description && item.description.toLowerCase().includes(lowerQuery))
)
.slice(0, config.maxResults);
if (articleResults.length > 0) {
results.push({
category: '文章',
items: articleResults,
});
}
return results;
}
// 显示搜索结果
function displayResults(results) {
if (!results.length) {
searchResults.innerHTML = `
<div class="search-empty">
<i class="fas fa-search-minus"></i>
<p>未找到匹配 "${escapeHtml(searchInput.value)}" 的结果</p>
</div>
`;
return;
}
let html = '';
results.forEach((category) => {
html += `<div class="search-category">${category.category}</div>`;
category.items.forEach((item) => {
const highlightedTitle = highlightText(item.title, searchInput.value);
const highlightedDesc = item.description
? highlightText(item.description, searchInput.value)
: '';
html += `
<a href="${escapeHtml(item.url)}" class="search-item" target="${item.type === 'url' ? '_blank' : '_self'}">
<div class="search-item-title">${highlightedTitle}</div>
${item.type === 'url' ? `<div class="search-item-url">${escapeHtml(item.category)}</div>` : ''}
${highlightedDesc ? `<div class="search-item-desc">${highlightedDesc}</div>` : ''}
</a>
`;
});
});
searchResults.innerHTML = html;
}
// 高亮搜索词
function highlightText(text, query) {
if (!query) return escapeHtml(text);
const regex = new RegExp(`(${escapeRegExp(query)})`, 'gi');
return escapeHtml(text).replace(regex, '<span class="search-item-highlight">$1</span>');
}
// 转义正则表达式
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
// 显示空状态
function showEmptyState() {
searchResults.innerHTML = `
<div class="search-empty">
<i class="fas fa-search"></i>
<p>输入关键词开始搜索</p>
<p style="font-size: 13px; margin-top: 8px;">至少输入 ${config.minQueryLength} 个字符</p>
</div>
`;
}
// 显示/隐藏加载动画
function showSpinner() {
if (searchSpinner) {
searchSpinner.classList.add('active');
}
}
function hideSpinner() {
if (searchSpinner) {
searchSpinner.classList.remove('active');
}
}
// 打开搜索
function openSearch() {
if (searchOverlay) {
searchOverlay.classList.add('active');
isSearchOpen = true;
if (searchInput) {
setTimeout(() => searchInput.focus(), 100);
}
document.body.style.overflow = 'hidden';
}
}
// 关闭搜索
function closeSearch() {
if (searchOverlay) {
searchOverlay.classList.remove('active');
isSearchOpen = false;
if (searchInput) {
searchInput.value = '';
showEmptyState();
}
document.body.style.overflow = '';
}
}
// 切换搜索
function toggleSearch() {
if (isSearchOpen) {
closeSearch();
} else {
openSearch();
}
}
// 防抖函数
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// HTML 转义
function escapeHtml(text) {
if (typeof text !== 'string') {
return '';
}
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// 暴露全局方法
window.SiteSearch = {
init: init,
open: openSearch,
close: closeSearch,
toggle: toggleSearch,
};
// 自动初始化
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();