-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathsearch.js
More file actions
270 lines (231 loc) · 9.74 KB
/
search.js
File metadata and controls
270 lines (231 loc) · 9.74 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
(function() {
var totalPages = {{ total_pages }};
var searchBox = document.getElementById('search-box');
var searchInput = document.getElementById('search-input');
var searchBtn = document.getElementById('search-btn');
var modal = document.getElementById('search-modal');
var modalInput = document.getElementById('modal-search-input');
var modalSearchBtn = document.getElementById('modal-search-btn');
var modalCloseBtn = document.getElementById('modal-close-btn');
var searchStatus = document.getElementById('search-status');
var searchResults = document.getElementById('search-results');
if (!searchBox || !modal) return;
// Hide search on file:// protocol (doesn't work due to CORS restrictions)
if (window.location.protocol === 'file:') return;
// Show search box (progressive enhancement)
searchBox.style.display = 'flex';
// Gist preview support - detect by query string pattern: ?<hex-gist-id>/...
var gistMatch = window.location.search.match(/^\?([a-f0-9]{20,})(\/|$)/i);
var isGistPreview = !!gistMatch;
var gistId = gistMatch ? gistMatch[1] : null;
var gistOwner = null;
var gistInfoLoaded = false;
async function loadGistInfo() {
if (!isGistPreview || !gistId || gistInfoLoaded) return;
try {
var response = await fetch('https://api.github.com/gists/' + gistId);
if (response.ok) {
var info = await response.json();
gistOwner = info.owner.login;
gistInfoLoaded = true;
}
} catch (e) {
console.error('Failed to load gist info:', e);
}
}
function getPageFetchUrl(pageFile) {
if (isGistPreview && gistOwner && gistId) {
// Use raw gist URL for fetching content
return 'https://gist.githubusercontent.com/' + gistOwner + '/' + gistId + '/raw/' + pageFile;
}
return pageFile;
}
function getPageLinkUrl(pageFile) {
if (isGistPreview && gistId) {
// Use gistpreview URL format for navigation links
return '?' + gistId + '/' + pageFile;
}
return pageFile;
}
function escapeHtml(text) {
var div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function escapeRegex(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function openModal(query) {
modalInput.value = query || '';
searchResults.innerHTML = '';
searchStatus.textContent = '';
modal.showModal();
modalInput.focus();
if (query) {
performSearch(query);
}
}
function closeModal() {
modal.close();
// Update URL to remove search fragment, preserving path and query string
if (window.location.hash.startsWith('#search=')) {
history.replaceState(null, '', window.location.pathname + window.location.search);
}
}
function updateUrlHash(query) {
if (query) {
// Preserve path and query string when adding hash
history.replaceState(null, '', window.location.pathname + window.location.search + '#search=' + encodeURIComponent(query));
}
}
function highlightTextNodes(element, searchTerm) {
var walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, null, false);
var nodesToReplace = [];
while (walker.nextNode()) {
var node = walker.currentNode;
if (node.nodeValue.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1) {
nodesToReplace.push(node);
}
}
nodesToReplace.forEach(function(node) {
var text = node.nodeValue;
var regex = new RegExp('(' + escapeRegex(searchTerm) + ')', 'gi');
var parts = text.split(regex);
if (parts.length > 1) {
var span = document.createElement('span');
parts.forEach(function(part) {
if (part.toLowerCase() === searchTerm.toLowerCase()) {
var mark = document.createElement('mark');
mark.textContent = part;
span.appendChild(mark);
} else {
span.appendChild(document.createTextNode(part));
}
});
node.parentNode.replaceChild(span, node);
}
});
}
function fixInternalLinks(element, pageFile) {
// Update all internal anchor links to include the page file
var links = element.querySelectorAll('a[href^="#"]');
links.forEach(function(link) {
var href = link.getAttribute('href');
link.setAttribute('href', pageFile + href);
});
}
function processPage(pageFile, html, query) {
var parser = new DOMParser();
var doc = parser.parseFromString(html, 'text/html');
var resultsFromPage = 0;
// Find all message blocks
var messages = doc.querySelectorAll('.message');
messages.forEach(function(msg) {
var text = msg.textContent || '';
if (text.toLowerCase().indexOf(query.toLowerCase()) !== -1) {
resultsFromPage++;
// Get the message ID for linking
var msgId = msg.id || '';
var pageLinkUrl = getPageLinkUrl(pageFile);
var link = pageLinkUrl + (msgId ? '#' + msgId : '');
// Clone the message HTML and highlight matches
var clone = msg.cloneNode(true);
// Fix internal links to include the page file
fixInternalLinks(clone, pageLinkUrl);
highlightTextNodes(clone, query);
var resultDiv = document.createElement('div');
resultDiv.className = 'search-result';
resultDiv.innerHTML = '<a href="' + link + '">' +
'<div class="search-result-page">' + escapeHtml(pageFile) + '</div>' +
'<div class="search-result-content">' + clone.innerHTML + '</div>' +
'</a>';
searchResults.appendChild(resultDiv);
}
});
return resultsFromPage;
}
async function performSearch(query) {
if (!query.trim()) {
searchStatus.textContent = 'Enter a search term';
return;
}
updateUrlHash(query);
searchResults.innerHTML = '';
searchStatus.textContent = 'Searching...';
// Load gist info if on gistpreview (needed for constructing URLs)
if (isGistPreview && !gistInfoLoaded) {
searchStatus.textContent = 'Loading gist info...';
await loadGistInfo();
if (!gistOwner) {
searchStatus.textContent = 'Failed to load gist info. Search unavailable.';
return;
}
}
var resultsFound = 0;
var pagesSearched = 0;
// Build list of pages to fetch
var pagesToFetch = [];
for (var i = 1; i <= totalPages; i++) {
pagesToFetch.push('page-' + String(i).padStart(3, '0') + '.html');
}
searchStatus.textContent = 'Searching...';
// Process pages in batches of 3, but show results immediately as each completes
var batchSize = 3;
for (var i = 0; i < pagesToFetch.length; i += batchSize) {
var batch = pagesToFetch.slice(i, i + batchSize);
// Create promises that process results immediately when each fetch completes
var promises = batch.map(function(pageFile) {
return fetch(getPageFetchUrl(pageFile))
.then(function(response) {
if (!response.ok) throw new Error('Failed to fetch');
return response.text();
})
.then(function(html) {
// Process and display results immediately
var count = processPage(pageFile, html, query);
resultsFound += count;
pagesSearched++;
searchStatus.textContent = 'Found ' + resultsFound + ' result(s) in ' + pagesSearched + '/' + totalPages + ' pages...';
})
.catch(function() {
pagesSearched++;
searchStatus.textContent = 'Found ' + resultsFound + ' result(s) in ' + pagesSearched + '/' + totalPages + ' pages...';
});
});
// Wait for this batch to complete before starting the next
await Promise.all(promises);
}
searchStatus.textContent = 'Found ' + resultsFound + ' result(s) in ' + totalPages + ' pages';
}
// Event listeners
searchBtn.addEventListener('click', function() {
openModal(searchInput.value);
});
searchInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter') {
openModal(searchInput.value);
}
});
modalSearchBtn.addEventListener('click', function() {
performSearch(modalInput.value);
});
modalInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter') {
performSearch(modalInput.value);
}
});
modalCloseBtn.addEventListener('click', closeModal);
modal.addEventListener('click', function(e) {
if (e.target === modal) {
closeModal();
}
});
// Check for #search= in URL on page load
if (window.location.hash.startsWith('#search=')) {
var query = decodeURIComponent(window.location.hash.substring(8));
if (query) {
searchInput.value = query;
openModal(query);
}
}
})();