aboutsummaryrefslogtreecommitdiff
path: root/static/js/fixedsearch.ts
blob: 04d318bb56df4e4922df62570d64980c4aaf554b (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/*
 * Fixed Search Copyright (C) 2020 Heracles Papatheodorou
 * Copyright (C) Craig Mod, Eddie Webb, and Matthew Daly
 * https://gist.github.com/Arty2/8b0c43581013753438a3d35c15091a9f#file-license-md
 * Licence: MIT | https://mit-license.org/
*/

(function () {
  ["DOMContentLoaded", "URLChangedCustomEvent"].forEach(function (event) {
  self.addEventListener(event, function () {
    const container = document.querySelector("search-box");
    const dropdown  = document.querySelector("search-box ul");
    const form      = document.querySelector("search-box form");
    const query     = document.querySelector("search-box input");
    const submit    = document.querySelector("search-box button");

    function first(element) {
      if (element.firstChild.nextElementSibling) {
      return element.firstChild.nextElementSibling.firstChild
        .nextElementSibling;
      }
    }

    function last(element) {
      return element.lastElementChild.firstChild.nextElementSibling;
    }

    function next(element) {
      return element.activeElement.parentElement.nextElementSibling.firstChild
        .nextElementSibling.focus();
    }

    function previous(element) {
      return element.activeElement.parentElement.previousElementSibling
        .firstChild
        .nextElementSibling.focus();
    }

    function press(keyname) {
      document.dispatchEvent(new KeyboardEvent("keydown", { "key": keyname }));
    }

    let selected;

    if (submit === null) return;

    submit.addEventListener("click", function (event) {
      if (selected) {
        event.preventDefault();
        selected.focus();
        return selected.click();
      }
      first(dropdown).focus();
      press("ArrowDown");
      document.activeElement.click();
    });

    ["keyup", "click"].forEach(function (event) {
      form.addEventListener(event, function () {
        if (document.activeElement.nodeName === "A") {
          return selected = document.activeElement;
        }
        selected = undefined;
      });
    });

    form.addEventListener("focusin", function () {
      container.setAttribute("data-focus", "");
      initialize();
    });

    form.addEventListener("submit", function (event) {
      event.preventDefault();
      return false;
    });

    form.addEventListener("keydown", function (event) {
      // ESC (27)
      if (form.contains(event.target)) {
        if (event.keyCode == 27) {
          document.activeElement.blur();
          dropdown.setAttribute("hidden", "");
          container.removeAttribute("data-focus");
        }
      }

      // BACKSPACE (8)
      if (event.keyCode == 8) {
        if (document.activeElement != query) {
          event.preventDefault();
          query.focus();
        }
      }

      const head = first(dropdown);
      const tail = last(dropdown);

      // DOWN (40)
      if (event.keyCode == 40) {
        event.preventDefault();
        if (document.activeElement == query) head.focus();
        else if (document.activeElement == tail) query.focus();
        else next(document);
      }

      // UP (38)
      if (event.keyCode == 38) {
        event.preventDefault();
        if (document.activeElement == query) tail.focus();
        else if (document.activeElement == head) query.focus();
        else previous(document);
      }

      // ENTER (13)
      if (event.keyCode == 13) {
        if (dropdown && document.activeElement == query) {
          event.preventDefault();
          head.focus();
          head.click();
        }
      }
    });

    let scrolls = 0;

    self.addEventListener("scroll", function () {
      if (scrolls > 3) {
        scrolls = 0;
        document.activeElement.blur();
        dropdown.setAttribute("hidden", "");
        container.removeAttribute("data-focus");
      }
      scrolls++;
    });

    self.addEventListener("click", function (event) {
      if (
        !form.contains(event.target) &&
        !(document.activeElement === query) &&
        !(document.activeElement === submit)
      ) {
        dropdown.setAttribute("hidden", "");
        container.removeAttribute("data-focus");
      }
    });

    function fetch(url, callback) {
      const http = new XMLHttpRequest();
      http.onreadystatechange = function () {
        if (http.readyState === 4 && http.status === 200 && callback) {
          callback(http);
        }
      };
      http.open("GET", url);
      http.send();
    }

    /* Load script based on https://stackoverflow.com/a/55451823 */

    function script(url) {
      return new Promise(function (resolve, reject) {
        const script = document.createElement("script");
        script.onerror = reject;
        script.onload = resolve;
        if (document.currentScript) {
          document.currentScript.parentNode.insertBefore(
            script,
            document.currentScript,
          );
        } else document.head.appendChild(script);
        script.src = url;
      });
    }

    let data = {};
    let boot = true;

    const options = { key: ["title"] };

    function isEmpty(obj) { return Object.keys(obj).length === 0; }

    function appendItemsTo(local, remote) {
      const paginated = Object.keys(remote).includes("next_url");
      if (isEmpty(local)) {
        local = remote;
      } else {
        local.items = local.items.concat(remote.items);
      }
      if (paginated) {
        fetch(remote.next_url, function (request) {
          appendItemsTo(local, JSON.parse(request.responseText));
        });
      } else search(query.value, data.items, options);
      data = local;
    }

    function initialize() {
      if (boot) {
        script(window.location.origin + "/js/fuzzysort.js")
          .then(function () {

            fetch("/index.json", function (request) {
              appendItemsTo({}, JSON.parse(request.responseText));
              search("", data.items, options);
              boot = false;
            });


            ["keyup", "focusin"].forEach(function (event) {
              query.addEventListener(event, function () {
                if (data.items) search(query.value, data.items, options);
                else { boot = true; initialize(); }
              });
            });

          }).catch(function (error) {
            console.error("ERROR: Failed to load fuzzy search", error);
          });
      }
    }

    function escape(text) {
      const escaped = document.createElement("textarea");
      escaped.textContent = text;
      return escaped.innerHTML;
    }

    function search(term, data, options) {
      const results = fuzzysort.go(term, data, options);
      let items = "";

      if (results.length === 0 && term.length >= 0) {
        let separator = "—";
        if (term.length === 0) separator = "";
        items = '<li><a tabindex="0">'.concat(
          escape(term),
          " ",
        ).concat(separator, " No Results Found</a></li>");
        dropdown.removeAttribute("hidden");
        container.setAttribute("data-focus", "");
      } else {
        dropdown.removeAttribute("hidden");
        for (var string in results.slice(0, 10)) {
          const title = results[string].obj.title;
          let highlight = fuzzysort.highlight(
            fuzzysort.single(escape(term), escape(title)),
            "<span>",
            "</span>",
          );

          if (highlight === null) highlight = title;

          items = items +
            '\n<li>\n<a href="'.concat(
              results[string].obj.url,
              '" tabindex="0">',
            ).concat(highlight, "</a>\n</li>\n");
        }
      }
      dropdown.innerHTML = items;
    }
  });
  });
})();