{{ .Title }}
-{{.Page.Summary}}
+{{.Page.Summary | plainify}}
-Last modified
Last modified
Edit this page
diff --git a/assets/scripts/search.js b/assets/scripts/search.js new file mode 100644 index 0000000..e8dc3ef --- /dev/null +++ b/assets/scripts/search.js @@ -0,0 +1,225 @@ +/* +tutorials used: +- https://aaronluna.dev/blog/add-search-to-static-site-lunrjs-hugo-vanillajs/#codepen-with-final-code +- https://victoria.dev/blog/add-search-to-hugo-static-sites-with-lunr/ +*/ + +let pagesIndex, searchIndex +const MAX_SUMMARY_LENGTH = 30 +const SENTENCE_BOUNDARY_REGEX = /\b\.\s/gm +const WORD_REGEX = /\b(\w*)[\W|\s|\b]?/gm + +async function initSearch() { + try { + const response = await fetch("/index.json"); + pagesIndex = await response.json(); + searchIndex = lunr(function () { + this.field("title"); + this.field("content"); + this.ref("href"); + pagesIndex.forEach((page) => this.add(page)); + }); + } catch (e) { + console.log(e); + } + console.log("Search index initialized") + // Get the query parameter(s) + const params = new URLSearchParams(window.location.search) + const query = params.get('query') + + // Perform a search if there is a query + if (query) { + // Retain the search input in the form when displaying results + document.getElementById('search-input').setAttribute('value', query) + + // Update the list with results + console.log("search performed") + let results = searchSite(query) + renderSearchResults(query, results) + } +} + +initSearch(); + +function searchSite(query) { + const originalQuery = query; + query = getLunrSearchQuery(query); + let results = getSearchResults(query); + return results.length + ? results + : query !== originalQuery + ? getSearchResults(originalQuery) + : []; +} + +function getLunrSearchQuery(query) { + const searchTerms = query.split(" "); + if (searchTerms.length === 1) { + return query; + } + query = ""; + for (const term of searchTerms) { + query += `+${term} `; + } + return query.trim(); +} + +function getSearchResults(query) { + return searchIndex.search(query).flatMap((hit) => { + if (hit.ref == "undefined") return []; + let pageMatch = pagesIndex.filter((page) => page.href === hit.ref)[0]; + pageMatch.score = hit.score; + return [pageMatch]; + }); +} + +function renderSearchResults(query, results) { + clearSearchResults(); + updateSearchResults(query, results); +} + +function clearSearchResults() { + const results = document.querySelector("#search-results"); + while (results.firstChild) results.removeChild(results.firstChild); +} + +function updateSearchResults(query, results) { + document.getElementById("results-query").innerHTML = query; + document.querySelector("#search-results").innerHTML = results + .map( + (hit) => ` +
${createSearchResultBlurb(query, hit.content)}
+{{.Page.Summary}}
+{{.Page.Summary | plainify}}
-Last modified
Last modified
Edit this page
Last modified
Last modified
Edit this page
{{.Site.Params.title}}