github.com/mweagle/Sparta@v1.15.0/docs/js/search.js (about) 1 var lunrIndex, pagesIndex; 2 3 function endsWith(str, suffix) { 4 return str.indexOf(suffix, str.length - suffix.length) !== -1; 5 } 6 7 // Initialize lunrjs using our generated index file 8 function initLunr() { 9 if (!endsWith(baseurl,"/")){ 10 baseurl = baseurl+'/' 11 }; 12 13 // First retrieve the index file 14 $.getJSON(baseurl +"index.json") 15 .done(function(index) { 16 pagesIndex = index; 17 // Set up lunrjs by declaring the fields we use 18 // Also provide their boost level for the ranking 19 lunrIndex = lunr(function() { 20 this.ref("uri"); 21 this.field('title', { 22 boost: 15 23 }); 24 this.field('tags', { 25 boost: 10 26 }); 27 this.field("content", { 28 boost: 5 29 }); 30 31 this.pipeline.remove(lunr.stemmer); 32 this.searchPipeline.remove(lunr.stemmer); 33 34 // Feed lunr with each file and let lunr actually index them 35 pagesIndex.forEach(function(page) { 36 this.add(page); 37 }, this); 38 }) 39 }) 40 .fail(function(jqxhr, textStatus, error) { 41 var err = textStatus + ", " + error; 42 console.error("Error getting Hugo index file:", err); 43 }); 44 } 45 46 /** 47 * Trigger a search in lunr and transform the result 48 * 49 * @param {String} query 50 * @return {Array} results 51 */ 52 function search(queryTerm) { 53 // Find the item in our index corresponding to the lunr one to have more info 54 return lunrIndex.search(queryTerm+"^100"+" "+queryTerm+"*^10"+" "+"*"+queryTerm+"^10"+" "+queryTerm+"~2^1").map(function(result) { 55 return pagesIndex.filter(function(page) { 56 return page.uri === result.ref; 57 })[0]; 58 }); 59 } 60 61 // Let's get started 62 initLunr(); 63 $( document ).ready(function() { 64 var searchList = new autoComplete({ 65 /* selector for the search box element */ 66 selector: $("#search-by").get(0), 67 /* source is the callback to perform the search */ 68 source: function(term, response) { 69 response(search(term)); 70 }, 71 /* renderItem displays individual search results */ 72 renderItem: function(item, term) { 73 var numContextWords = 2; 74 var text = item.content.match( 75 "(?:\\s?(?:[\\w]+)\\s?){0,"+numContextWords+"}" + 76 term+"(?:\\s?(?:[\\w]+)\\s?){0,"+numContextWords+"}"); 77 item.context = text; 78 return '<div class="autocomplete-suggestion" ' + 79 'data-term="' + term + '" ' + 80 'data-title="' + item.title + '" ' + 81 'data-uri="'+ item.uri + '" ' + 82 'data-context="' + item.context + '">' + 83 'ยป ' + item.title + 84 '<div class="context">' + 85 (item.context || '') +'</div>' + 86 '</div>'; 87 }, 88 /* onSelect callback fires when a search suggestion is chosen */ 89 onSelect: function(e, term, item) { 90 location.href = item.getAttribute('data-uri'); 91 } 92 }); 93 });