-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
78 lines (64 loc) · 2.25 KB
/
index.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
const searchTermElem = document.querySelector('#searchTerm');
const searchResultElem = document.querySelector('#searchResult');
searchTermElem.select();
searchTermElem.addEventListener('input', function (event) {
search(event.target.value);
});
let timeoutId;
const debounce = (fn, delay=500) => {
let timeoutId;
return (...args) => {
// cancel the previous timer
if (timeoutId) {
clearTimeout(timeoutId);
}
// setup a new timer
timeoutId = setTimeout(() => {
fn.apply(null, args);
}, delay);
};
};
const stripHtml = (html) => {
let div = document.createElement('div');
div.textContent = html;
return div.textContent;
};
const highlight = (str, keyword, className = "highlight") => {
const hl = `<span class="${className}">${keyword}</span>`;
return str.replace(new RegExp(keyword, 'gi'), hl);
};
const generateSearchResultHTML= (results, searchTerm) => {
return results
.map(result => {
const title = highlight(stripHtml(result.title), searchTerm);
const snippet = highlight(stripHtml(result.snippet), searchTerm);
return `<article>
<a href="https://en.wikipedia.org/?curid=${result.pageid}">
<h2>${title}</h2>
</a>
<div class="summary">${snippet}...</div>
</article>`;
})
.join('');
}
const search = debounce(async (searchTerm) => {
// if the search term is removed,
// reset the search result
if (!searchTerm) {
// reset the search result
searchResultElem.innerHTML = '';
return;
}
try {
// make an API request
const url = `https://en.wikipedia.org/w/api.php?action=query&list=search&prop=info|extracts&inprop=url&utf8=&format=json&origin=*&srlimit=10&srsearch=${searchTerm}`;
const response = await fetch(url);
const searchResults = await response.json();
// render search result
const searchResultHtml = generateSearchResultHTML(searchResults.query.search, searchTerm);
// add the search result to the searchResultElem
searchResultElem.innerHTML = searchResultHtml;
} catch (error) {
console.log(error);
}
});