aboutsummaryrefslogtreecommitdiff
path: root/assets/search.js
blob: 84e522a7fe493fc7bda68d7ce5df2d4c5de6f815 (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
addEventListener("load", function() {
  let input = document.querySelector("#book-search");
  let results = document.querySelector("#book-search-results");

  Promise.all([
    loadScript("{{ "lunr.min.js" | relURL }}"),
    loadScript("{{ "index.json" | relURL }}")
  ]).then(enableLunr);

  function enableLunr() {
    results.idx = lunr(function() { 
      this.ref('href')
      this.field('title')
      this.field('content')

      window.lunrData.forEach(function (page) {
        this.add(page)
      }, this)
    });
    input.addEventListener("keyup", search);
  }

  function search() {
    if (input.value) {
      var hits = results.idx.search(`${input.value}*`);
      results.innerHTML = JSON.stringify(hits);
    } else {
      results.innerHTML = '';
    }
  }

  function loadScript(src) {
    return new Promise(function(resolve, reject) {
      let script = document.createElement('script');
      script.src = src;
      script.onload = () => resolve(script);
  
      document.head.append(script);
    });
  }
});