search-lunr.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. require([
  2. 'gitbook',
  3. 'jquery'
  4. ], function(gitbook, $) {
  5. // Define global search engine
  6. function LunrSearchEngine() {
  7. this.index = null;
  8. this.store = {};
  9. this.name = 'LunrSearchEngine';
  10. }
  11. // Initialize lunr by fetching the search index
  12. LunrSearchEngine.prototype.init = function() {
  13. var that = this;
  14. var d = $.Deferred();
  15. $.getJSON(gitbook.state.basePath+'/search_index.json')
  16. .then(function(data) {
  17. // eslint-disable-next-line no-undef
  18. that.index = lunr.Index.load(data.index);
  19. that.store = data.store;
  20. d.resolve();
  21. });
  22. return d.promise();
  23. };
  24. // Search for a term and return results
  25. LunrSearchEngine.prototype.search = function(q, offset, length) {
  26. var that = this;
  27. var results = [];
  28. if (this.index) {
  29. results = $.map(this.index.search(q), function(result) {
  30. var doc = that.store[result.ref];
  31. return {
  32. title: doc.title,
  33. url: doc.url,
  34. body: doc.summary || doc.body
  35. };
  36. });
  37. }
  38. return $.Deferred().resolve({
  39. query: q,
  40. results: results.slice(0, length),
  41. count: results.length
  42. }).promise();
  43. };
  44. // Set gitbook research
  45. gitbook.events.bind('start', function(e, config) {
  46. var engine = gitbook.search.getEngine();
  47. if (!engine) {
  48. gitbook.search.setEngine(LunrSearchEngine, config);
  49. }
  50. });
  51. });