-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.html
181 lines (159 loc) · 6.21 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
---
layout: default
title: Search
---
<div class="search-info">
<h2>Search Features</h2>
<ul>
<li><strong>Smart Search:</strong> Search through titles, content, 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
const searchStore = {
{% for post in site.til %}
"{{ post.url | slugify }}": {
"title": "{{ post.title | xml_escape }}",
"content": {{ post.content | strip_html | strip_newlines | jsonify }},
"url": "{{ post.url | xml_escape | relative_url }}",
"date": "{{ post.date | date: '%B %-d, %Y' }}",
"tags": "{{ post.tags | join: ', ' }}"
}{% unless forloop.last %},{% endunless %}
{% endfor %}
};
// Convert store to array for Fuse.js
const searchData = Object.entries(searchStore).map(([id, item]) => ({
id,
...item
}));
// Fuse.js options
const fuseOptions = {
includeScore: true,
threshold: 0.3,
keys: [
{ name: 'title', weight: 0.7 },
{ name: 'content', weight: 0.3 },
{ name: 'tags', weight: 0.5 }
],
shouldSort: true,
minMatchCharLength: 2
};
let fuse;
let selectedIndex = -1;
// Initialize Fuse.js when the page loads
document.addEventListener('DOMContentLoaded', () => {
fuse = new Fuse(searchData, fuseOptions);
// 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);
}
// Global keyboard shortcut
document.addEventListener('keydown', (e) => {
if (e.key === '/' && document.activeElement !== searchInput) {
e.preventDefault();
searchInput.focus();
}
});
});
// 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
document.getElementById('search-input').addEventListener('input', (e) => {
performSearch(e.target.value);
});
function highlightText(text, searchTerm) {
if (!searchTerm) return text;
const regex = new RegExp(`(${searchTerm})`, 'gi');
return text.replace(regex, '<span class="search-highlight">$1</span>');
}
function performSearch(searchTerm) {
const searchResults = document.getElementById('search-results');
selectedIndex = -1;
if (!searchTerm) {
searchResults.innerHTML = '';
return;
}
try {
const results = fuse.search(searchTerm);
if (results.length > 0) {
const resultList = results.map(result => {
const item = result.item;
const title = highlightText(item.title, searchTerm);
const tags = item.tags ? item.tags.split(', ') : [];
return `
<div class="search-result">
<h2><a href="${item.url}">${title}</a></h2>
<div class="search-result-meta">
<time>${item.date}</time>
${tags.length ? `
<div class="tags">
${tags.map(tag => `
<a href="${tagsBaseUrl}#${tag.toLowerCase()}"
class="tag">${tag}</a>
`).join('')}
</div>
` : ''}
</div>
</div>
`;
}).join('');
searchResults.innerHTML = resultList;
} else {
searchResults.innerHTML = `
<div class="search-no-results">
<p>No results found for "${searchTerm}"</p>
</div>
`;
}
} catch (e) {
console.error('Search error:', e);
searchResults.innerHTML = `
<div class="search-no-results">
<p>An error occurred while searching. Please try a different search term.</p>
</div>
`;
}
}
</script>