generated from irfansofyana/til-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.html
270 lines (230 loc) · 10.9 KB
/
search.html
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
---
layout: default
title: Search
---
<div class="search-wrapper">
<div class="search-info">
<button onclick="window.history.back()" class="back-button">Back</button>
<h2>Search Features</h2>
<ul>
<li><strong>Smart Search:</strong> Search through titles, categories, and tags</li>
<li><strong>Navigation:</strong> Use ↑ and ↓ arrow keys to navigate results, Enter to select</li>
<li><strong>Instant Results:</strong> See matches as you type with highlighted search terms</li>
</ul>
</div>
<link rel="stylesheet" href="{{ '/assets/css/search.css' | relative_url }}">
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<div class="search-container">
<input type="text"
class="search-input"
id="search-input"
placeholder="Search for TILs..."
autocomplete="off"
autofocus>
<div id="search-results" class="search-results"></div>
</div>
<script>
// Pre-compute URLs
const tagsBaseUrl = "{{ '/tags' | relative_url }}";
// Initialize search data with lazy loading
let searchStore = null;
let fuse = null;
let debounceTimeout = null;
const DEBOUNCE_DELAY = 300; // milliseconds
// Lazy load search data
async function initializeSearchStore() {
if (searchStore === null) {
searchStore = {
{% for post in site.til %}
"{{ post.url | slugify }}": {
"title": "{{ post.title | xml_escape }}",
"content": {{ post.content | strip_html | strip_newlines | escape | jsonify }},
"url": "{{ post.url | xml_escape | relative_url }}",
"date": "{{ post.date | date: '%B %-d, %Y' }}",
"tags": "{{ post.tags | join: ', ' }}"
}{% unless forloop.last %},{% endunless %}
{% endfor %}
};
// Initialize Fuse.js with the loaded data
const documents = Object.values(searchStore);
fuse = new Fuse(documents, {
keys: [
{ name: 'title', weight: 0.7 },
{ name: 'content', weight: 0.3 },
{ name: 'tags', weight: 0.3 }
],
includeScore: true,
threshold: 0.4,
ignoreLocation: true
});
}
return searchStore;
}
let selectedIndex = -1;
// Initialize Fuse.js when the page loads
document.addEventListener('DOMContentLoaded', async () => {
// Check for URL parameters
const searchTerm = new URLSearchParams(window.location.search).get('q');
if (searchTerm) {
const searchInput = document.getElementById('search-input');
searchInput.value = searchTerm;
performSearch(searchTerm);
}
});
// Handle keyboard navigation
document.addEventListener('keydown', (e) => {
const results = document.querySelectorAll('.search-result');
if (!results.length) return;
if (e.key === 'ArrowDown') {
e.preventDefault();
selectedIndex = Math.min(selectedIndex + 1, results.length - 1);
updateSelection(results);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
selectedIndex = Math.max(selectedIndex - 1, -1);
updateSelection(results);
} else if (e.key === 'Enter' && selectedIndex >= 0) {
e.preventDefault();
const selectedResult = results[selectedIndex].querySelector('a');
if (selectedResult) selectedResult.click();
}
});
function updateSelection(results) {
results.forEach((result, index) => {
result.classList.toggle('selected', index === selectedIndex);
if (index === selectedIndex) {
result.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
});
}
// Handle search input with debouncing
document.getElementById('search-input').addEventListener('input', (e) => {
if (debounceTimeout) {
clearTimeout(debounceTimeout);
}
debounceTimeout = setTimeout(async () => {
// Ensure search store is initialized
if (!searchStore) {
await initializeSearchStore();
}
performSearch(e.target.value);
}, DEBOUNCE_DELAY);
});
function highlightText(text, searchTerm) {
if (!searchTerm) return text;
const regex = new RegExp(`(${searchTerm})`, 'gi');
return text.replace(regex, '<mark class="search-highlight">$1</mark>');
}
function getContentSnippet(content, searchTerm) {
if (!content || !searchTerm) return '';
const searchTermLower = searchTerm.toLowerCase();
const contentLower = content.toLowerCase();
const matchIndex = contentLower.indexOf(searchTermLower);
if (matchIndex === -1) return '';
const snippetStart = Math.max(0, matchIndex - 100);
const snippetEnd = Math.min(content.length, matchIndex + searchTerm.length + 100);
let snippet = content.slice(snippetStart, snippetEnd);
// Add ellipsis
if (snippetStart > 0) snippet = '...' + snippet;
if (snippetEnd < content.length) snippet += '...';
return highlightText(snippet, searchTerm);
}
function hasExactMatch(text, searchTerm) {
if (!text || !searchTerm) return false;
return text.toLowerCase().includes(searchTerm.toLowerCase());
}
function createResultElement(item, searchTerm) {
const resultDiv = document.createElement('div');
resultDiv.className = 'search-result';
// Create and append title
const title = document.createElement('h2');
const titleLink = document.createElement('a');
titleLink.href = item.url;
titleLink.innerHTML = highlightText(item.title, searchTerm);
title.appendChild(titleLink);
resultDiv.appendChild(title);
// Create and append content snippet if exists
const contentSnippet = getContentSnippet(item.content, searchTerm);
if (contentSnippet && (hasExactMatch(item.title, searchTerm) || hasExactMatch(item.content, searchTerm) || hasExactMatch(item.tags, searchTerm))) {
const snippetDiv = document.createElement('div');
snippetDiv.className = 'search-snippet';
const snippetP = document.createElement('p');
snippetP.innerHTML = contentSnippet;
snippetDiv.appendChild(snippetP);
resultDiv.appendChild(snippetDiv);
}
// Create and append meta information
const metaDiv = document.createElement('div');
metaDiv.className = 'search-result-meta';
// Add date
const timeElement = document.createElement('time');
timeElement.textContent = item.date;
metaDiv.appendChild(timeElement);
// Add tags if they exist
if (item.tags) {
const tagsDiv = document.createElement('div');
tagsDiv.className = 'tags';
item.tags.split(', ').forEach(tag => {
const tagLink = document.createElement('a');
tagLink.href = `${tagsBaseUrl}#${tag.toLowerCase()}`;
tagLink.className = 'tag';
tagLink.innerHTML = highlightText(tag, searchTerm);
tagsDiv.appendChild(tagLink);
});
metaDiv.appendChild(tagsDiv);
}
resultDiv.appendChild(metaDiv);
return resultDiv;
}
async function performSearch(searchTerm) {
const searchResults = document.getElementById('search-results');
selectedIndex = -1;
if (!searchTerm) {
searchResults.innerHTML = '';
return;
}
try {
// Ensure search store is initialized
if (!searchStore) {
await initializeSearchStore();
}
const results = fuse.search(searchTerm)
.filter(result => {
const item = result.item;
return hasExactMatch(item.title, searchTerm) ||
hasExactMatch(item.content, searchTerm) ||
hasExactMatch(item.tags, searchTerm);
});
// Create document fragment for batch DOM updates
const fragment = document.createDocumentFragment();
if (results.length > 0) {
// Create all result elements in memory first
results.forEach(result => {
const resultElement = createResultElement(result.item, searchTerm);
fragment.appendChild(resultElement);
});
// Clear previous results and append new ones in a single operation
searchResults.textContent = '';
searchResults.appendChild(fragment);
} else {
const noResultsDiv = document.createElement('div');
noResultsDiv.className = 'search-no-results';
const message = document.createElement('p');
message.textContent = `No results found for "${searchTerm}"`;
noResultsDiv.appendChild(message);
fragment.appendChild(noResultsDiv);
searchResults.textContent = '';
searchResults.appendChild(fragment);
}
} catch (e) {
const errorDiv = document.createElement('div');
errorDiv.className = 'search-no-results';
const errorMessage = document.createElement('p');
errorMessage.textContent = 'An error occurred while searching. Please try a different search term.';
errorDiv.appendChild(errorMessage);
searchResults.textContent = '';
searchResults.appendChild(errorDiv);
}
}
</script>
</div>