|
| 1 | + |
| 2 | +function getQueryParams(k){ |
| 3 | + var p={}; |
| 4 | + location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){p[k]=v}) |
| 5 | + return k?p[k]:p; |
| 6 | +} |
| 7 | + |
| 8 | +function doSearch(index){ |
| 9 | + // Initalize lunr with the fields it will be searching on. I've given title |
| 10 | + // a boost of 10 to indicate matches on this field are more important. |
| 11 | + var idx = lunr(function () { |
| 12 | + this.ref('id'); |
| 13 | + this.field('title', { boost: 10 }); |
| 14 | + this.field('keywords'); |
| 15 | + this.field('tags'); |
| 16 | + this.field('body'); |
| 17 | + |
| 18 | + for (var key in index) { // Add the data to lunr |
| 19 | + this.add({ |
| 20 | + 'id': key, |
| 21 | + 'title': index[key].title, |
| 22 | + 'keywords': index[key].keywords, |
| 23 | + 'tags': index[key].tags, |
| 24 | + 'body': index[key].content |
| 25 | + }); |
| 26 | + } |
| 27 | + }); |
| 28 | + |
| 29 | + var results = idx.search("*"+searchTerm+"*"); // Get lunr to perform a search |
| 30 | + displaySearchResults(results, index); // We'll write this in the next section |
| 31 | +} |
| 32 | + |
| 33 | +function displaySearchResults(results, index) { |
| 34 | + var searchResults = document.getElementById('search-results'); |
| 35 | + |
| 36 | + if (results.length) { // Are there any results? |
| 37 | + var appendString = ''; |
| 38 | + |
| 39 | + for (var i = 0; i < results.length; i++) { // Iterate over the results |
| 40 | + var item = index[results[i].ref]; |
| 41 | + appendString += '<li><a href="' + item.url + '"><h3>' + item.title + '</h3></a>'; |
| 42 | + if (item.tags != "") { |
| 43 | + appendString += '<span class="search-tag">' + item.tags + '</span>'; |
| 44 | + } |
| 45 | + appendString += '<p>' + item.content.substring(0, 150) + '...</p></li>'; |
| 46 | + } |
| 47 | + |
| 48 | + searchResults.innerHTML = appendString; |
| 49 | + } else { |
| 50 | + searchResults.innerHTML = '<li>No results found</li>'; |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +var searchTerm = getQueryParams('q'); |
| 55 | + |
| 56 | +if (searchTerm) { |
| 57 | + document.getElementById('search-box-full').setAttribute("value", searchTerm); |
| 58 | + document.getElementById('search-box').setAttribute("value", searchTerm); |
| 59 | + |
| 60 | +$.getJSON('/search.json', function(data) { |
| 61 | + doSearch(data); |
| 62 | +}); |
| 63 | +} |
0 commit comments