forked from luzhenhua/NCE-Flow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.js
More file actions
236 lines (200 loc) · 7.72 KB
/
search.js
File metadata and controls
236 lines (200 loc) · 7.72 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
/**
* NCE Flow Search Module
* Implements global search with lazy loading index and client-side filtering.
*/
(() => {
const SEARCH_INDEX_URL = 'static/search_index.json';
let searchIndex = null;
let isLoading = false;
let debounceTimer = null;
// DOM Elements
const modal = document.getElementById('searchModal');
const trigger = document.getElementById('searchBtn');
const closeBtn = document.getElementById('searchClose');
const input = document.getElementById('searchInput');
const resultsContainer = document.getElementById('searchResults');
const clearBtn = document.getElementById('searchClear');
const emptyState = document.getElementById('searchEmpty');
const loadingState = document.getElementById('searchLoading');
if (!modal || !trigger) return;
// --------------------------
// Core Logic
// --------------------------
async function loadIndex() {
if (searchIndex) return;
if (isLoading) return;
isLoading = true;
try {
const res = await fetch(SEARCH_INDEX_URL);
if (!res.ok) throw new Error('Failed to load index');
searchIndex = await res.json();
} catch (e) {
console.error('Search index load failed:', e);
searchResults.innerHTML = '<div style="padding:20px;text-align:center;color:var(--muted)">搜索服务暂时不可用</div>';
} finally {
isLoading = false;
}
}
function toggleModal(show) {
if (show) {
modal.hidden = false;
document.body.style.overflow = 'hidden';
// Force repaint
modal.offsetHeight;
modal.classList.add('open');
input.focus();
setTimeout(() => input.focus(), 100);
loadIndex();
} else {
modal.classList.remove('open');
document.body.style.overflow = '';
// Wait for transition to finish
setTimeout(() => {
if (!modal.classList.contains('open')) {
modal.hidden = true;
}
}, 300);
}
}
function handleSearch(query) {
query = query.trim().toLowerCase();
if (!query) {
resultsContainer.innerHTML = '';
emptyState.hidden = true;
loadingState.hidden = true;
return;
}
if (!searchIndex) {
loadingState.hidden = false;
// Index loading is async, retry shortly
setTimeout(() => handleSearch(query), 100);
return;
}
loadingState.hidden = true;
const results = performSearch(query);
renderResults(results, query);
}
function performSearch(query) {
const matches = [];
const maxResults = 50; // Limit rendering for performance
// Search Strategy:
// 1. Title match (higher priority)
// 2. Content match (English or Chinese)
for (const lesson of searchIndex) {
if (matches.length >= maxResults) break;
// Title Match
if (lesson.t.toLowerCase().includes(query)) {
matches.push({
type: 'title',
book: lesson.b,
lessonId: lesson.l,
title: lesson.t,
matchText: lesson.t
});
continue; // Don't duplicate if content also matches (optional decision)
}
// Content Match
for (const [lineIdx, en, cn] of lesson.c) {
if (matches.length >= maxResults) break;
const enMatch = en.toLowerCase().includes(query);
const cnMatch = cn.includes(query);
if (enMatch || cnMatch) {
matches.push({
type: 'sentence',
book: lesson.b,
lessonId: lesson.l,
title: lesson.t,
lineIdx: lineIdx,
en: en,
cn: cn,
matchEn: enMatch, // boolean
matchCn: cnMatch // boolean
});
}
}
}
return matches;
}
function highlightText(text, query) {
if (!query) return text;
const regex = new RegExp(`(${escapeRegExp(query)})`, 'gi');
return text.replace(regex, '<span class="search-highlight">$1</span>');
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function renderResults(results, query) {
if (results.length === 0) {
resultsContainer.innerHTML = '';
emptyState.hidden = false;
return;
}
emptyState.hidden = true;
const html = results.map(item => {
const bookName = {
'NCE1': '第一册', 'NCE2': '第二册', 'NCE3': '第三册', 'NCE4': '第四册'
}[item.book] || item.book;
const link = `lesson.html#${item.book}/${item.lessonId}${item.type === 'sentence' ? '?line=' + item.lineIdx : ''}`;
let contentHtml = '';
if (item.type === 'sentence') {
const enHtml = item.matchEn ? highlightText(item.en, query) : item.en;
const cnHtml = item.matchCn ? highlightText(item.cn, query) : item.cn;
contentHtml = `
<div class="search-item-content">
<div style="margin-bottom:2px;color:var(--text)">${enHtml}</div>
<div style="font-size:13px">${cnHtml}</div>
</div>
`;
} else {
contentHtml = `<div class="search-item-content">包含匹配的标题</div>`;
}
const titleHtml = highlightText(item.title, item.type === 'title' ? query : '');
return `
<a href="${link}" class="search-item" onclick="document.getElementById('searchModal').click()"> <!-- Hack to close modal implicitly? No better add explicit handler -->
<div class="search-item-header">
<div class="search-item-tag">${bookName} · Lesson ${item.lessonId}</div>
</div>
<div class="search-item-title" style="margin-bottom:6px">${titleHtml}</div>
${contentHtml}
</a>
`;
}).join('');
resultsContainer.innerHTML = html;
}
// --------------------------
// Event Listeners
// --------------------------
trigger.addEventListener('click', () => toggleModal(true));
closeBtn.addEventListener('click', () => toggleModal(false));
// Close on backdrop click
modal.addEventListener('click', (e) => {
if (e.target === modal || e.target.classList.contains('search-container')) {
toggleModal(false);
}
});
// Close on Escape
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && !modal.hidden) {
toggleModal(false);
}
// Shortcut: Cmd+K or Ctrl+K to open
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault();
toggleModal(true);
}
});
input.addEventListener('input', (e) => {
const val = e.target.value;
clearBtn.hidden = !val;
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => handleSearch(val), 150);
});
clearBtn.addEventListener('click', () => {
input.value = '';
input.focus();
clearBtn.hidden = true;
handleSearch('');
});
// Handle link clicks inside modal to close it (though navigation happens anyway)
// Not strictly necessary if page reloads/navigates, but good for single page feel
})();