Skip to main content

max / makenotwork

1.6 KB · 60 lines History Blame Raw
1 (function () {
2 "use strict";
3
4 var index = null;
5 var input = document.querySelector(".docs-search-input");
6 var results = document.querySelector(".docs-search-results");
7 if (!input || !results) return;
8
9 var timer = null;
10
11 fetch("/docs/search.json")
12 .then(function (r) { return r.json(); })
13 .then(function (data) { index = data; });
14
15 input.addEventListener("input", function () {
16 clearTimeout(timer);
17 timer = setTimeout(doSearch, 150);
18 });
19
20 function doSearch() {
21 var q = input.value.trim().toLowerCase();
22 results.innerHTML = "";
23
24 if (!q || !index) {
25 results.classList.add("hidden");
26 return;
27 }
28
29 var matches = index.filter(function (entry) {
30 return (
31 entry.title.toLowerCase().indexOf(q) !== -1 ||
32 entry.body_text.toLowerCase().indexOf(q) !== -1
33 );
34 });
35
36 if (matches.length === 0) {
37 results.classList.remove("hidden");
38 results.innerHTML = '<div class="empty-state empty-state--compact">No results found.</div>';
39 return;
40 }
41
42 results.classList.remove("hidden");
43 matches.slice(0, 15).forEach(function (entry) {
44 var a = document.createElement("a");
45 a.href = "/docs/" + entry.slug;
46 a.className = "docs-search-result";
47 a.innerHTML =
48 '<span class="docs-search-result-title">' + esc(entry.title) + "</span>" +
49 '<span class="docs-search-result-section">' + esc(entry.section) + "</span>";
50 results.appendChild(a);
51 });
52 }
53
54 function esc(s) {
55 var d = document.createElement("span");
56 d.textContent = s;
57 return d.innerHTML;
58 }
59 })();
60