jazzy.search.js 2.1 KB

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