-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsearch.js
224 lines (201 loc) · 6.37 KB
/
search.js
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
import lunr from "lunr";
import Mustache from "mustache";
import scrollIntoView from "scroll-into-view-if-needed";
import Mark from "mark.js";
import truncate from "truncate-html";
const Pitchfork = {
init: function (settings) {
this.input = settings.input;
this.indexURL = settings.indexURL || "/search-index.json";
this.resultsNode = settings.resultsNode;
this.highlightedResultNode;
this.loadTemplate();
this.addListeners();
},
loadTemplate: function () {
// Get the template then remove it
if (
this.resultsNode.children.length === 1 &&
this.resultsNode.children[0].nodeName === "SCRIPT"
) {
this.resultsTemplate = this.resultsNode.children[0].innerHTML;
} else {
this.resultsTemplate = this.resultsNode.innerHTML;
}
this.resultsNode.innerHTML = "";
},
addListeners: function () {
this.input.addEventListener("keydown", (e) => {
if (e.keyCode === 38 && e.metaKey) {
// Cmd + up
e.preventDefault();
this.setNodeActive(this.resultsNode.firstElementChild);
} else if (e.keyCode === 38) {
// Up
e.preventDefault();
this.highlightPrevResult();
} else if (e.keyCode === 40 && e.metaKey) {
// Cmd + down
e.preventDefault();
this.setNodeActive(this.resultsNode.lastElementChild);
} else if (e.keyCode === 40) {
// Down
e.preventDefault();
this.highlightNextResult();
} else if (e.keyCode === 27) {
// Escape
this.hideResults();
} else if (e.keyCode === 13) {
// Enter
this.selectHighlighted();
}
});
this.input.addEventListener("keyup", (e) => {
// Ignore all arrows (no change in text), escape and enter
if ([37, 38, 39, 40, 27, 13].includes(e.keyCode)) return;
this.onSearchInputChange(e);
});
this.input.addEventListener("focusout", (e) => {
// If a link was clicked, ignore this
if (e.relatedTarget && e.relatedTarget.nodeName === "A") return;
this.hideResults();
});
this.input.addEventListener("focusin", (e) => {
if (!this.index) {
this.loadIndex();
}
});
},
loadIndex: function () {
const pf = this;
// TODO catch 404 or fetch error
fetch(this.indexURL)
.then((response) => response.json())
.then((data) => {
pf.searchContent = data.pages;
pf.index = lunr.Index.load(data.lunr);
});
},
hideResults: function () {
this.resultsNode.style.display = "none";
},
showResults: function () {
this.resultsNode.style.display = "";
},
onSearchInputChange: function () {
this.renderResults([]);
// Empty search stops here
if (!this.input.value) {
this.hideResults();
return;
}
this.showResults();
const searchResults = this.index.search(this.input.value);
if (searchResults.length < 1) {
this.renderResults([]);
this.highlightedResultNode = null;
return;
}
this.renderResults([]);
const truncateLength = parseInt(
this.resultsNode.getAttribute("data-pitchfork-truncate") || 100
);
const highlightClass =
this.resultsNode.getAttribute("data-pitchfork-highlight-class") ||
"highlight";
const pf = this;
const results = searchResults.map(function (res) {
const url = res.ref;
var contentData = pf.searchContent[url];
const highlights = {};
pf.index.fields.forEach((f) => {
let text = contentData[f];
if (!text) return;
const ranges = [];
let startIndex = 99999;
Object.values(res.matchData.metadata).forEach((matchMetadata) => {
if (
!matchMetadata ||
!matchMetadata[f] ||
!matchMetadata[f].position
) {
return;
}
matchMetadata[f].position.forEach((position) => {
startIndex = Math.min(position[0], startIndex);
ranges.push({ start: position[0], length: position[1] });
});
});
const el = document.createElement("div");
el.innerHTML = text;
const instance = new Mark(el);
instance.markRanges(ranges, {
className: highlightClass,
});
let final = el.innerHTML;
if (contentData[f].length > truncateLength) {
if (startIndex > truncateLength / 3) {
// Only trim the beginning if there is a lot
final = final.substr(startIndex);
}
final = truncate(final, truncateLength);
}
highlights[f] = final;
});
return {
url,
highlights,
...contentData,
};
});
this.renderResults(results);
this.setNodeActive(this.resultsNode.firstElementChild);
},
setNodeActive: function (node) {
const activeClass =
this.resultsNode.getAttribute("data-pitchfork-active-class") || "active";
if (!activeClass) return;
const activeClasses = activeClass.split(" ");
// Remove the previous highlight
if (this.highlightedResultNode) {
this.highlightedResultNode.classList.remove(...activeClasses);
}
// Highlight the new one
node.classList.add(...activeClasses);
this.highlightedResultNode = node;
scrollIntoView(this.highlightedResultNode, {
behavior: "smooth",
scrollMode: "if-needed",
});
},
highlightNextResult: function () {
const n = this.highlightedResultNode.nextElementSibling;
if (n) this.setNodeActive(n);
},
highlightPrevResult: function () {
const n = this.highlightedResultNode.previousElementSibling;
if (n) this.setNodeActive(n);
},
selectHighlighted: function () {
if (this.highlightedResultNode)
window.location = this.highlightedResultNode.href;
},
renderResults: function (results) {
this.resultsNode.innerHTML = Mustache.render(this.resultsTemplate, {
results: results,
});
},
};
window.Pitchfork = Pitchfork;
window.addEventListener("DOMContentLoaded", (event) => {
const input = document.querySelector("[data-pitchfork-input]");
if (input) {
const index = document.querySelector("[data-pitchfork-index-url]"); // can be on search, results, script
const results = document.querySelector("[data-pitchfork-results]");
window.Pitchfork.init({
input: input,
indexURL: index ? index.getAttribute("data-pitchfork-index-url") : null,
resultsNode: results,
});
}
});