/
Search.ts
297 lines (253 loc) · 7.93 KB
/
Search.ts
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import { debounce } from "../utils/debounce";
import { Index } from "lunr";
interface IDocument {
id: number;
kind: number;
name: string;
url: string;
classes?: string;
parent?: string;
boost?: number;
}
interface IData {
kinds: { [kind: number]: string };
rows: IDocument[];
index: object;
}
declare global {
interface Window {
searchData?: IData;
}
}
interface SearchState {
base: string;
data?: IData;
index?: Index;
}
export function initSearch() {
const searchEl = document.getElementById("tsd-search");
if (!searchEl) return;
const searchScript = document.getElementById(
"search-script"
) as HTMLScriptElement | null;
searchEl.classList.add("loading");
if (searchScript) {
searchScript.addEventListener("error", () => {
searchEl.classList.remove("loading");
searchEl.classList.add("failure");
});
searchScript.addEventListener("load", () => {
searchEl.classList.remove("loading");
searchEl.classList.add("ready");
});
if (window.searchData) {
searchEl.classList.remove("loading");
}
}
const field = document.querySelector<HTMLInputElement>("#tsd-search input");
const results = document.querySelector<HTMLElement>("#tsd-search .results");
if (!field || !results) {
throw new Error(
"The input field or the result list wrapper was not found"
);
}
let resultClicked = false;
results.addEventListener("mousedown", () => (resultClicked = true));
results.addEventListener("mouseup", () => {
resultClicked = false;
searchEl.classList.remove("has-focus");
});
field.addEventListener("focus", () => searchEl.classList.add("has-focus"));
field.addEventListener("blur", () => {
if (!resultClicked) {
resultClicked = false;
searchEl.classList.remove("has-focus");
}
});
const state: SearchState = {
base: searchEl.dataset["base"] + "/",
};
bindEvents(searchEl, results, field, state);
}
function bindEvents(
searchEl: HTMLElement,
results: HTMLElement,
field: HTMLInputElement,
state: SearchState
) {
field.addEventListener(
"input",
debounce(() => {
updateResults(searchEl, results, field, state);
}, 200)
);
let preventPress = false;
field.addEventListener("keydown", (e) => {
preventPress = true;
if (e.key == "Enter") {
gotoCurrentResult(results, field);
} else if (e.key == "Escape") {
field.blur();
} else if (e.key == "ArrowUp") {
setCurrentResult(results, -1);
} else if (e.key === "ArrowDown") {
setCurrentResult(results, 1);
} else {
preventPress = false;
}
});
field.addEventListener("keypress", (e) => {
if (preventPress) e.preventDefault();
});
/**
* Start searching by pressing slash.
*/
document.body.addEventListener("keydown", (e) => {
if (e.altKey || e.ctrlKey || e.metaKey) return;
if (!field.matches(":focus") && e.key === "/") {
field.focus();
e.preventDefault();
}
});
}
function checkIndex(state: SearchState, searchEl: HTMLElement) {
if (state.index) return;
if (window.searchData) {
searchEl.classList.remove("loading");
searchEl.classList.add("ready");
state.data = window.searchData;
state.index = Index.load(window.searchData.index);
}
}
function updateResults(
searchEl: HTMLElement,
results: HTMLElement,
query: HTMLInputElement,
state: SearchState
) {
checkIndex(state, searchEl);
// Don't clear results if loading state is not ready,
// because loading or error message can be removed.
if (!state.index || !state.data) return;
results.textContent = "";
const searchText = query.value.trim();
// Perform a wildcard search
// Set empty `res` to prevent getting random results with wildcard search
// when the `searchText` is empty.
let res = searchText ? state.index.search(`*${searchText}*`) : [];
for (let i = 0; i < res.length; i++) {
const item = res[i];
const row = state.data.rows[Number(item.ref)];
let boost = 1;
// boost by exact match on name
if (row.name.toLowerCase().startsWith(searchText.toLowerCase())) {
boost *=
1 + 1 / (Math.abs(row.name.length - searchText.length) * 10);
}
// boost by relevanceBoost
boost *= row.boost ?? 1;
item.score *= boost;
}
res.sort((a, b) => b.score - a.score);
for (let i = 0, c = Math.min(10, res.length); i < c; i++) {
const row = state.data.rows[Number(res[i].ref)];
// Bold the matched part of the query in the search results
let name = boldMatches(row.name, searchText);
if (row.parent) {
name = `<span class="parent">${boldMatches(
row.parent,
searchText
)}.</span>${name}`;
}
const item = document.createElement("li");
item.classList.value = row.classes ?? "";
const anchor = document.createElement("a");
anchor.href = state.base + row.url;
anchor.classList.add("tsd-kind-icon");
anchor.innerHTML = name;
item.append(anchor);
results.appendChild(item);
}
}
/**
* Move the highlight within the result set.
*/
function setCurrentResult(results: HTMLElement, dir: number) {
let current = results.querySelector(".current");
if (!current) {
current = results.querySelector(
dir == 1 ? "li:first-child" : "li:last-child"
);
if (current) {
current.classList.add("current");
}
} else {
let rel: Element | undefined = current;
// Tricky: We have to check that rel has an offsetParent so that users can't mark a hidden result as
// current with the arrow keys.
if (dir === 1) {
do {
rel = rel.nextElementSibling ?? undefined;
} while (rel instanceof HTMLElement && rel.offsetParent == null);
} else {
do {
rel = rel.previousElementSibling ?? undefined;
} while (rel instanceof HTMLElement && rel.offsetParent == null);
}
if (rel) {
current.classList.remove("current");
rel.classList.add("current");
}
}
}
/**
* Navigate to the highlighted result.
*/
function gotoCurrentResult(results: HTMLElement, field: HTMLInputElement) {
let current = results.querySelector(".current");
if (!current) {
current = results.querySelector("li:first-child");
}
if (current) {
const link = current.querySelector("a");
if (link) {
window.location.href = link.href;
}
field.blur();
}
}
function boldMatches(text: string, search: string) {
if (search === "") {
return text;
}
const lowerText = text.toLocaleLowerCase();
const lowerSearch = search.toLocaleLowerCase();
const parts = [];
let lastIndex = 0;
let index = lowerText.indexOf(lowerSearch);
while (index != -1) {
parts.push(
escapeHtml(text.substring(lastIndex, index)),
`<b>${escapeHtml(
text.substring(index, index + lowerSearch.length)
)}</b>`
);
lastIndex = index + lowerSearch.length;
index = lowerText.indexOf(lowerSearch, lastIndex);
}
parts.push(escapeHtml(text.substring(lastIndex)));
return parts.join("");
}
const SPECIAL_HTML = {
"&": "&",
"<": "<",
">": ">",
"'": "'",
'"': """,
} as const;
function escapeHtml(text: string) {
return text.replace(
/[&<>"'"]/g,
(match) => SPECIAL_HTML[match as keyof typeof SPECIAL_HTML]
);
}