aboutsummaryrefslogtreecommitdiffstats
path: root/assets/js
diff options
context:
space:
mode:
authorOscar Najera <hi@oscarnajera.com>2023-11-09 17:49:27 +0100
committerOscar Najera <hi@oscarnajera.com>2023-11-09 17:49:27 +0100
commit4a826ff2748eafdbf63dd0547706ed7dc7ed3d76 (patch)
tree17b3f45d8b750d7fbd1de718e87fdcbfa44e7e5a /assets/js
parent76b72515b6d8078268077bd9d96db493fb7bd6f8 (diff)
downloadhugo-minimalist-theme-4a826ff2748eafdbf63dd0547706ed7dc7ed3d76.tar.gz
hugo-minimalist-theme-4a826ff2748eafdbf63dd0547706ed7dc7ed3d76.tar.bz2
hugo-minimalist-theme-4a826ff2748eafdbf63dd0547706ed7dc7ed3d76.zip
Search page
Diffstat (limited to 'assets/js')
-rw-r--r--assets/js/search.js65
1 files changed, 65 insertions, 0 deletions
diff --git a/assets/js/search.js b/assets/js/search.js
new file mode 100644
index 0000000..2dd397a
--- /dev/null
+++ b/assets/js/search.js
@@ -0,0 +1,65 @@
+// Options for fuse.js
+let fuseOptions = {
+ includeMatches: true,
+ includeScore: true,
+ ignoreLocation: true,
+ minMatchCharLength: 3,
+ keys: [
+ { name: "title", weight: 0.8 },
+ { name: "contents", weight: 0.4 },
+ { name: "tags", weight: 0.5 },
+ { name: "categories", weight: 0.5 },
+ ],
+}
+
+function getUrlParameter(name) {
+ const urlParams = new URLSearchParams(location.search)
+ return urlParams.get(name)
+}
+
+let searchQuery = getUrlParameter("q")
+if (searchQuery) {
+ document.getElementById("search-query").value = searchQuery
+ executeSearch(searchQuery)
+} else {
+ document.getElementById("search-results").innerHTML = ""
+}
+
+function executeSearch(searchQuery) {
+ // Look for "index.json" in the same directory where this script is called.
+ fetch("index.json")
+ .then((response) => response.json())
+ .then(function (data) {
+ let fuse = new Fuse(data, fuseOptions)
+ let result = fuse.search(searchQuery)
+ // console.log("Results: ", result)
+ if (result.length > 0) {
+ populateResults(result)
+ } else {
+ document.getElementById("search-results").innerHTML =
+ "<p class=\"bg-washed-red pa3 dark-red f4 fw6 tc br2 b--light-red ba\">No matches found</p>"
+ }
+ })
+}
+
+function populateResults(result) {
+ result.forEach(function (value, key) {
+ // Lifted from https://stackoverflow.com/posts/3700369/revisions
+ var elem = document.createElement("textarea")
+ elem.innerHTML = value.item.contents
+ var decoded = elem.value
+
+ // Pull template from hugo template definition
+ let frag = document
+ .getElementById("search-result-template")
+ .content.cloneNode(true)
+ // Replace values
+ frag.querySelector(".search_summary").setAttribute("id", "summary-" + key)
+ frag.querySelector(".search_link")
+ .setAttribute("href", value.item.permalink)
+ frag.querySelector(".search_title").textContent = value.item.title
+ frag.querySelector(".search_snippet").textContent = decoded
+ frag.querySelector(".search_time").textContent = value.item.date
+ document.getElementById("search-results").appendChild(frag)
+ })
+}