runtimeterror/assets/js/search.js

46 lines
1.3 KiB
JavaScript
Raw Permalink Normal View History

2024-01-16 18:03:24 +00:00
// based on https://victoria.dev/blog/add-search-to-hugo-static-sites-with-lunr/
2024-01-15 22:02:30 +00:00
function displayResults (results, store) {
const searchResults = document.getElementById('results');
if (results.length) {
let resultList = '';
for (const n in results) {
const item = store[results[n].ref];
resultList += '<li><a href="' + item.url + '">' + item.title + '</a></li>'
2024-01-16 00:12:56 +00:00
if (item.description)
resultList += '<p>' + item.description + '</p>'
else
resultList += '<p>' + item.content.substring(0, 150) + '...</p>'
2024-01-15 22:02:30 +00:00
}
searchResults.innerHTML = resultList;
} else {
searchResults.innerHTML = 'No results found.';
}
}
const searchParams = new URLSearchParams(window.location.search);
const query = searchParams.get('query');
2024-01-15 22:02:30 +00:00
if (query) {
2024-01-15 23:07:23 +00:00
document.getElementById('search-query').setAttribute('value', query);
2024-01-15 22:02:30 +00:00
const idx = lunr(function () {
this.ref('id')
this.field('title', {
boost: 15
})
this.field('tags')
this.field('content', {
boost: 10
})
for (const key in window.store) {
this.add({
id: key,
title: window.store[key].title,
tags: window.store[key].tags,
content: window.store[key].content
})
}
})
const results = idx.search(query);
displayResults(results, window.store)
}