aboutsummaryrefslogtreecommitdiffstats
path: root/assets/js/search.js
blob: ab2256b79fb7b0a2bf6e08c72a5794fb931b09c9 (plain)
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
// 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(url, name) {
    const urlParams = new URLSearchParams(url)
    return urlParams.get(name)
}

function search(query, data){
    let fuse = new Fuse(data, fuseOptions)
    return fuse.search(query)
}

function unescapeText(input) {
    // Lifted from https://stackoverflow.com/posts/3700369/revisions
    var elem = document.createElement("textarea")
    elem.innerHTML = input
    return elem.value
}

function resultEntry(data, key) {
    // Pull template from hugo template definition
    let frag = document
        .getElementById("search-result-template")
        .content.cloneNode(true)

    // Replace values
    let { title, permalink, contents, date } = data
    frag.querySelector(".search_summary").setAttribute("id", "summary-" + key)
    frag.querySelector(".search_link").setAttribute("href", permalink)
    frag.querySelector(".search_title").textContent = title
    frag.querySelector(".search_snippet").textContent = unescapeText(contents)
    frag.querySelector(".search_time").textContent = date
    return frag
}


function executeSearch(searchQuery) {
    // Look for "index.json" in the same directory where this script is called.
    return fetch("index.json")
        .then((response) => response.json())
        .then((data) =>  search(searchQuery, data))
}

function renderResults(results) {
    let resultBox = document.getElementById("search-results")
    resultBox.innerHTML = ""

    // console.log("Results: ", results)
    if (results.length > 0) {
        results.forEach((value, key) => {
            resultBox.appendChild(resultEntry(value.item, key))
        })
    } else {
        resultBox.innerHTML = document.getElementById("no-match").innerHTML
    }
}

addEventListener("load", function () {
    let searchQuery = getUrlParameter(location.search, "q")
    if (searchQuery) {
        document.getElementById("search-query").value = searchQuery
        executeSearch(searchQuery).then(renderResults)
    }
}
)