-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathlocal-search.js
More file actions
341 lines (318 loc) · 10.8 KB
/
local-search.js
File metadata and controls
341 lines (318 loc) · 10.8 KB
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/* global CONFIG */
'use strict';
$(document).ready(function() {
// Popup Window
var isfetched = false;
var datas;
var isXml = true;
// Search DB path
var searchPath = CONFIG.search.path;
if (searchPath.length === 0) {
searchPath = 'search.xml';
} else if (/json$/i.test(searchPath)) {
isXml = false;
}
var path = CONFIG.search.root + searchPath;
var input = document.getElementById('local-search-input');
var resultContent = document.getElementById('local-search-result');
// Ref: https://github.com/ForbesLindesay/unescape-html
function unescapeHtml(html) {
return String(html)
.replace(/"/g, '"')
.replace(/'/g, '\'')
.replace(/:/g, ':')
// Replace all the other &#x; chars
.replace(/&#(\d+);/g, function(m, p) {
return String.fromCharCode(p);
})
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&');
}
function getIndexByWord(word, text, caseSensitive) {
var wordLen = word.length;
if (wordLen === 0) {
return [];
}
var startPosition = 0, position = [], index = [];
if (!caseSensitive) {
text = text.toLowerCase();
word = word.toLowerCase();
}
while ((position = text.indexOf(word, startPosition)) > -1) {
index.push({
position: position,
word: word
});
startPosition = position + wordLen;
}
return index;
}
// Merge hits into slices
function mergeIntoSlice(text, start, end, index, searchText) {
var item = index[index.length - 1];
var position = item.position;
var word = item.word;
var hits = [];
var searchTextCountInSlice = 0;
while (position + word.length <= end && index.length !== 0) {
if (word === searchText) {
searchTextCountInSlice++;
}
hits.push({
position: position,
length: word.length
});
var wordEnd = position + word.length;
// Move to next position of hit
index.pop();
while (index.length !== 0) {
item = index[index.length - 1];
position = item.position;
word = item.word;
if (wordEnd > position) {
index.pop();
} else {
break;
}
}
}
return {
hits: hits,
start: start,
end: end,
searchTextCount: searchTextCountInSlice
};
}
// Highlight title and content
function highlightKeyword(text, slice) {
var result = '';
var prevEnd = slice.start;
slice.hits.forEach(function(hit) {
result += text.substring(prevEnd, hit.position);
var end = hit.position + hit.length;
result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
prevEnd = end;
});
result += text.substring(prevEnd, slice.end);
return result;
}
function inputEventFunction() {
var searchText = input.value.trim().toLowerCase();
var keywords = searchText.split(/[-\s]+/);
if (keywords.length > 1) {
keywords.push(searchText);
}
var resultItems = [];
if (searchText.length > 0) {
// Perform local searching
datas.forEach(function(data) {
// Only match articles with not empty titles
if (!data.title) {
return;
}
var searchTextCount = 0;
var title = data.title.trim();
var titleInLowerCase = title.toLowerCase();
var content = data.content ? data.content.trim().replace(/<[^>]+>/g, '') : '';
if (CONFIG.localsearch.unescape) {
content = unescapeHtml(content);
}
var contentInLowerCase = content.toLowerCase();
var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
var indexOfTitle = [];
var indexOfContent = [];
keywords.forEach(function(keyword) {
indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
});
// Show search results
if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
var hitCount = indexOfTitle.length + indexOfContent.length;
// Sort index by position of keyword
[indexOfTitle, indexOfContent].forEach(function(index) {
index.sort(function(itemLeft, itemRight) {
if (itemRight.position !== itemLeft.position) {
return itemRight.position - itemLeft.position;
} else {
return itemLeft.word.length - itemRight.word.length;
}
});
});
var slicesOfTitle = [];
if (indexOfTitle.length !== 0) {
var tmp = mergeIntoSlice(title, 0, title.length, indexOfTitle, searchText);
searchTextCount += tmp.searchTextCountInSlice;
slicesOfTitle.push(tmp);
}
var slicesOfContent = [];
while (indexOfContent.length !== 0) {
var item = indexOfContent[indexOfContent.length - 1];
var position = item.position;
var word = item.word;
// Cut out 100 characters
var start = position - 20;
var end = position + 80;
if (start < 0) {
start = 0;
}
if (end < position + word.length) {
end = position + word.length;
}
if (end > content.length) {
end = content.length;
}
var tmp = mergeIntoSlice(content, start, end, indexOfContent, searchText);
searchTextCount += tmp.searchTextCountInSlice;
slicesOfContent.push(tmp);
}
// Sort slices in content by search text's count and hits' count
slicesOfContent.sort(function(sliceLeft, sliceRight) {
if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
return sliceRight.searchTextCount - sliceLeft.searchTextCount;
} else if (sliceLeft.hits.length !== sliceRight.hits.length) {
return sliceRight.hits.length - sliceLeft.hits.length;
} else {
return sliceLeft.start - sliceRight.start;
}
});
// Select top N slices in content
var upperBound = parseInt(CONFIG.localsearch.top_n_per_article, 10);
if (upperBound >= 0) {
slicesOfContent = slicesOfContent.slice(0, upperBound);
}
var resultItem = '';
if (slicesOfTitle.length !== 0) {
resultItem += '<li><a href="' + articleUrl + '" class="search-result-title">' + highlightKeyword(title, slicesOfTitle[0]) + '</a>';
} else {
resultItem += '<li><a href="' + articleUrl + '" class="search-result-title">' + title + '</a>';
}
slicesOfContent.forEach(function(slice) {
resultItem += '<a href="' + articleUrl + '">'
+ '<p class="search-result">' + highlightKeyword(content, slice)
+ '...</p></a>';
});
resultItem += '</li>';
resultItems.push({
item: resultItem,
searchTextCount: searchTextCount,
hitCount: hitCount,
id: resultItems.length
});
}
});
}
if (keywords.length === 1 && keywords[0] === '') {
resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>';
} else if (resultItems.length === 0) {
resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>';
} else {
resultItems.sort(function(resultLeft, resultRight) {
if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
return resultRight.searchTextCount - resultLeft.searchTextCount;
} else if (resultLeft.hitCount !== resultRight.hitCount) {
return resultRight.hitCount - resultLeft.hitCount;
} else {
return resultRight.id - resultLeft.id;
}
});
var searchResultList = '<ul class="search-result-list">';
resultItems.forEach(function(result) {
searchResultList += result.item;
});
searchResultList += '</ul>';
resultContent.innerHTML = searchResultList;
}
}
function fetchData(callback) {
$.ajax({
url: path,
dataType: isXml ? 'xml' : 'json',
success: function(res) {
// Get the contents from search data
isfetched = true;
datas = isXml ? $('entry', res).map(function() {
return {
title: $('title', this).text(),
content: $('content', this).text(),
url: $('url', this).text()
};
}).get() : res;
// Remove loading animation
$('.local-search-pop-overlay').remove();
$('body').css('overflow', '');
if (callback) {
callback();
}
}
});
}
if (CONFIG.localsearch.preload) {
fetchData();
}
// Monitor main search box
function onPopupClose() {
$('.popup').hide();
$('#local-search-input').val('');
$('.search-result-list').remove();
$('#no-result').remove();
$('.local-search-pop-overlay').remove();
$('body').css('overflow', '');
}
function proceedSearch() {
$('body')
.append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
.css('overflow', 'hidden');
$('.search-popup-overlay').click(onPopupClose);
$('.popup').toggle();
var $localSearchInput = $('#local-search-input');
$localSearchInput.attr('autocapitalize', 'none');
$localSearchInput.attr('autocorrect', 'off');
$localSearchInput.focus();
}
// Search function
function searchFunc() {
// Start loading animation
$('body')
.append('<div class="search-popup-overlay local-search-pop-overlay">'
+ '<div id="search-loading-icon">'
+ '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>'
+ '</div>'
+ '</div>')
.css('overflow', 'hidden');
$('#search-loading-icon').css({
margin: '20% auto 0 auto',
'text-align': 'center'
});
fetchData(proceedSearch);
}
if (CONFIG.localsearch.trigger === 'auto') {
input.addEventListener('input', inputEventFunction);
} else {
$('.search-icon').click(inputEventFunction);
input.addEventListener('keypress', function(event) {
if (event.keyCode === 13) {
inputEventFunction();
}
});
}
// Handle and trigger popup window
$('.popup-trigger').click(function(e) {
e.stopPropagation();
if (isfetched === false) {
searchFunc();
} else {
proceedSearch();
}
});
$('.popup-btn-close').click(onPopupClose);
$('.popup').click(function(e) {
e.stopPropagation();
});
$(document).on('keyup', function(event) {
var shouldDismissSearchPopup = event.which === 27 && $('.search-popup').is(':visible');
if (shouldDismissSearchPopup) {
onPopupClose();
}
});
});