aboutsummaryrefslogtreecommitdiff
path: root/assets/search.js
blob: c91baf221b02ed8a69c8f73c0ed58ad7b178f1b4 (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
{{- $searchData := resources.Get "search-data.js" | resources.ExecuteAsTemplate "search-data.js" . | resources.Minify | resources.Fingerprint }}

(function() {
  const input = document.querySelector("#book-search-input");
  const results = document.querySelector("#book-search-results");
  const dummy = document.querySelector("#book-search-dummy");

  input.addEventListener("focus", init);

  function init() {
    loadScript("{{ $searchData.RelPermalink }}", function() {
      input.disabled = false;
      input.addEventListener("keyup", search);
      search();
    });
    input.removeEventListener("focus", init);
  }

  function search() {
    while (results.firstChild) {
      results.removeChild(results.firstChild);
    }

    if (input.value) {
      const hits = window.bookSearch.idx.search(`${input.value}*`);
      hits.slice(0, 10).forEach(function(hit) {
        const page = window.bookSearch.pages[hit.ref];
        const li = dummy.querySelector("li").cloneNode(true),
              a = li.querySelector("a");

        a.href = page.href;
        a.textContent = page.title;

        results.appendChild(li);
      });
    }
  }

  function loadScript(src, callback) {
    const script = document.createElement("script");
    script.defer = true;
    script.src = src;
    script.onload = callback;

    document.head.append(script);
  }
})();