-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy pathsearch-worker.js
80 lines (65 loc) · 1.98 KB
/
search-worker.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
(function () {
importScripts('lunr.min.js');
var lunrIndex;
var stopWords = null;
var searchData = {};
lunr.tokenizer.separator = /[\s\-\.\(\)]+/;
var stopWordsRequest = new XMLHttpRequest();
stopWordsRequest.open('GET', '../search-stopwords.json');
stopWordsRequest.onload = function () {
if (this.status != 200) {
return;
}
stopWords = JSON.parse(this.responseText);
buildIndex();
}
stopWordsRequest.send();
var searchDataRequest = new XMLHttpRequest();
searchDataRequest.open('GET', '../index.json');
searchDataRequest.onload = function () {
if (this.status != 200) {
return;
}
searchData = JSON.parse(this.responseText);
buildIndex();
postMessage({ e: 'index-ready' });
}
searchDataRequest.send();
onmessage = function (oEvent) {
var q = oEvent.data.q;
var hits = lunrIndex.search(q);
var results = [];
hits.forEach(function (hit) {
var item = searchData[hit.ref];
results.push({ 'href': item.href, 'title': item.title, 'keywords': item.keywords });
});
postMessage({ e: 'query-ready', q: q, d: results });
}
function buildIndex() {
if (stopWords !== null && !isEmpty(searchData)) {
lunrIndex = lunr(function () {
this.pipeline.remove(lunr.stopWordFilter);
this.ref('href');
this.field('title', { boost: 50 });
this.field('keywords', { boost: 20 });
for (var prop in searchData) {
if (searchData.hasOwnProperty(prop)) {
this.add(searchData[prop]);
}
}
var docfxStopWordFilter = lunr.generateStopWordFilter(stopWords);
lunr.Pipeline.registerFunction(docfxStopWordFilter, 'docfxStopWordFilter');
this.pipeline.add(docfxStopWordFilter);
this.searchPipeline.add(docfxStopWordFilter);
});
}
}
function isEmpty(obj) {
if(!obj) return true;
for (var prop in obj) {
if (obj.hasOwnProperty(prop))
return false;
}
return true;
}
})();