jazzy.search.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. $(function(){
  2. var $typeahead = $('[data-typeahead]');
  3. var $form = $typeahead.parents('form');
  4. var searchURL = $form.attr('action');
  5. function displayTemplate(result) {
  6. return result.name;
  7. }
  8. function suggestionTemplate(result) {
  9. var t = '<div class="list-group-item clearfix">';
  10. t += '<span class="doc-name">' + result.name + '</span>';
  11. if (result.parent_name) {
  12. t += '<span class="doc-parent-name label">' + result.parent_name + '</span>';
  13. }
  14. t += '</div>';
  15. return t;
  16. }
  17. $typeahead.one('focus', function() {
  18. $form.addClass('loading');
  19. $.getJSON(searchURL).then(function(searchData) {
  20. const searchIndex = lunr(function() {
  21. this.ref('url');
  22. this.field('name');
  23. this.field('abstract');
  24. for (const [url, doc] of Object.entries(searchData)) {
  25. this.add({url: url, name: doc.name, abstract: doc.abstract});
  26. }
  27. });
  28. $typeahead.typeahead(
  29. {
  30. highlight: true,
  31. minLength: 3,
  32. autoselect: true
  33. },
  34. {
  35. limit: 10,
  36. display: displayTemplate,
  37. templates: { suggestion: suggestionTemplate },
  38. source: function(query, sync) {
  39. const lcSearch = query.toLowerCase();
  40. const results = searchIndex.query(function(q) {
  41. q.term(lcSearch, { boost: 100 });
  42. q.term(lcSearch, {
  43. boost: 10,
  44. wildcard: lunr.Query.wildcard.TRAILING
  45. });
  46. }).map(function(result) {
  47. var doc = searchData[result.ref];
  48. doc.url = result.ref;
  49. return doc;
  50. });
  51. sync(results);
  52. }
  53. }
  54. );
  55. $form.removeClass('loading');
  56. $typeahead.trigger('focus');
  57. });
  58. });
  59. var baseURL = searchURL.slice(0, -"search.json".length);
  60. $typeahead.on('typeahead:select', function(e, result) {
  61. window.location = baseURL + result.url;
  62. });
  63. });