-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathsearch.html
83 lines (68 loc) · 2.8 KB
/
search.html
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
---
layout: default
hide_toc: true
---
<h1>Search Results</h1>
<ul id="search-results"></ul>
<script>
{% capture newline %}
{% endcapture %}
window.store = {
{%- for page in site.pages -%}
"{{ page.url | slugify }}": {
"title": "{{ page.title | xml_escape }}",
"content": {{ page.content | strip_html | replace: newline, " " | jsonify }},
"url": "{{ site.baseurl }}{{ page.url | xml_escape }}"
}{% unless forloop.last %}, {% endunless %}
{%- endfor -%}
};
</script>
<script src="https://unpkg.com/lunr/lunr.min.js"></script>
<script type="text/javascript">
(function () {
function displaySearchResults(results, store) {
var searchResults = document.getElementById('search-results');
if (results.length) { // Are there any results?
var appendString = '';
for (var i = 0; i < results.length; i++) { // Iterate over the results
var item = store[results[i].ref];
appendString += '<li><a href="' + item.url + '"><h3>' + item.title + '</h3></a>';
appendString += '<p>' + item.content.substring(0, 150) + '...</p></li>';
}
searchResults.innerHTML = appendString;
} else {
searchResults.innerHTML = '<li>No results found</li>';
}
}
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] === variable) {
return decodeURIComponent(pair[1].replace(/\+/g, '%20'));
}
}
}
var searchTerm = getQueryVariable('query');
if (searchTerm) {
document.getElementById('search-box').setAttribute("value", searchTerm);
// Initalize lunr with the fields it will be searching on. I've given title
// a boost of 10 to indicate matches on this field are more important.
var idx = lunr(function () {
this.field('id');
this.field('title', { boost: 10 });
this.field('content');
for (var key in window.store) { // Add the data to lunr
this.add({
'id': key,
'title': window.store[key].title,
'content': window.store[key].content
});
}
});
var results = idx.search('*' + searchTerm + '*'); // Get lunr to perform a search
displaySearchResults(results, window.store); // We'll write this in the next section
}
})();
</script>