forked from frega/WunderWay
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.js
More file actions
92 lines (81 loc) · 2.13 KB
/
search.js
File metadata and controls
92 lines (81 loc) · 2.13 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
---
---
require([
'/public/js/jquery-2.1.1.min.js',
'/public/js/lunr.min.js',
], function (_, lunr) {
var docs =
[
{% for page in site.pages %}
{% unless page.exclude_from_search %}
{% include page.json %},
{% endunless %}
{% endfor %}
];
// init lunr
var idx = lunr(function () {
this.field('title', {boost: 10});
this.field('content');
this.ref('id');
});
// add each document to be index
for(var index in docs) {
idx.add(docs[index]);
}
var originalContent = {
selector : '.page',
};
originalContent.content = $(originalContent.selector).html();
originalContent.reset = function() {
$(originalContent.selector).html(originalContent.content);
};
var debounce = function (fn) {
var timeout;
return function () {
var args = Array.prototype.slice.call(arguments),
ctx = this;
clearTimeout(timeout);
timeout = setTimeout(function () {
fn.apply(ctx, args);
}, 100);
};
};
// Run a query as the user types
$('#search').bind('input', debounce(function (e) {
var query = $(this).val();
if (query < 1) {
originalContent.reset();
return;
}
render( prepare( query ) );
}))
// Load the top result if the user hits enter
$('.search-form').bind('submit', function(e) {
window.location.href = idx.latestEntries[0].id;
e.preventDefault();
});
function prepare( query ) {
var entries = idx.search(query).map(function (result) {
return docs.filter(function (q) { return q.id === result.ref })[0]
})
idx.latestEntries = entries;
return entries;
}
function render( entries ) {
var output = '';
if (entries.length == 0) {
output = '<h2 class="minor-text">Nothing found</h2>';
}
for(var index in entries) {
entry = entries[index];
output += '<div class="search-result">';
output += '<a href="' + entry.id + '">';
output += '<h2 class="search-result__title">';
output += entry.title;
output += '</h2>';
output += '</a>';
output += '</div>';
}
$(originalContent.selector).html( output );
}
});