-
Notifications
You must be signed in to change notification settings - Fork 9
/
search.html
119 lines (109 loc) · 4.67 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
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
---
layout: search
---
<script src="/js/custom-tile.js"></script>
<script>
const language = '{{site.active_lang}}';
const jsonPath = language === 'en' ? '/en/json/posts.json' : '/json/posts.json';
fetch(jsonPath)
.then(response => response.json())
.then(store => {
(function () {
function displaySearchResults(results) {
const searchResults = document.getElementById('search-results');
if (results.length) {
results.forEach(result => {
const item = store[result.ref];
if (item.lang === language) {
searchResults.innerHTML += `
<custom-tile
title="${item.title}"
url="${item.url}"
author-name="${item.author}"
author-image="${'/assets/img/authors/' + item.image}"
author-url="${item.authorUrl}"
image="${item.highlight}"
date="${getFormattedDate(item.date)}"
content="${item.content.split(' ').slice(0, 30).join(' ') + '...'}"
></custom-tile>
`
}
});
} else {
notifyAboutNoResults(searchResults);
return;
}
if (searchResults.innerHTML === '') {
notifyAboutNoResults()
}
}
function getQueryVariable(variable) {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(variable);
}
function notifyAboutNoResults(container) {
container.innerHTML = `
<h1>
{{ site.data.translations['noResults'][site.active_lang] }}
</h1>`;
}
function getFormattedDate(date) {
const dateAsArray = date.split('-');
let months;
if (language === 'pl') {
months = {
'01': 'stycznia',
'02': 'lutego',
'03': 'marca',
'04': 'kwietnia',
'05': 'maja',
'06': 'czerwca',
'07': 'lipca',
'08': 'sierpnia',
'09': 'września',
'10': 'października',
'11': 'listopada',
'12': 'grudnia'
};
} else {
months = {
'01': 'Jan',
'02': 'Feb',
'03': 'Mar',
'04': 'Apr',
'05': 'May',
'06': 'Jun',
'07': 'Jul',
'08': 'Aug',
'09': 'Sep',
'10': 'Oct',
'11': 'Nov',
'12': 'Dec'
};
}
return dateAsArray[0] + " " + months[dateAsArray[1]] + " " + dateAsArray[2];
}
const searchTerm = getQueryVariable('query');
if (searchTerm) {
document.getElementById('search-box').setAttribute("value", searchTerm);
const idx = lunr(function () {
this.field('id');
this.field('title', {boost: 10});
this.field('tags');
this.field('content');
for (let key in store) {
this.add({
'id': key,
'title': store[key].title,
'tags': store[key].tags,
'content': store[key].content,
'path': store[key].path
});
}
});
const results = idx.search(searchTerm);
displaySearchResults(results);
}
})();
});
</script>