search-lunr.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. (function(compodoc) {
  2. function LunrSearchEngine() {
  3. this.index = null;
  4. this.store = {};
  5. this.name = 'LunrSearchEngine';
  6. }
  7. LunrSearchEngine.prototype.init = function() {
  8. var that = this,
  9. d = new promise.Promise();
  10. that.index = lunr.Index.load(COMPODOC_SEARCH_INDEX.index);
  11. that.store = COMPODOC_SEARCH_INDEX.store;
  12. d.done();
  13. return d;
  14. };
  15. LunrSearchEngine.prototype.search = function(q, offset, length) {
  16. var that = this,
  17. results = [],
  18. d = new promise.Promise();
  19. if (this.index) {
  20. results = $.map(this.index.search(q), function(result) {
  21. var doc = that.store[result.ref];
  22. return {
  23. title: doc.title,
  24. url: doc.url,
  25. body: doc.summary || doc.body
  26. };
  27. });
  28. }
  29. d.done({
  30. query: q,
  31. results: results.slice(0, length),
  32. count: results.length
  33. });
  34. return d;
  35. };
  36. compodoc.addEventListener(compodoc.EVENTS.READY, function(event) {
  37. console.log('compodoc ready');
  38. var engine = new LunrSearchEngine(),
  39. initialized = false;
  40. engine.init()
  41. .then(function() {
  42. initialized = true;
  43. compodoc.dispatchEvent({
  44. type: compodoc.EVENTS.SEARCH_READY
  45. });
  46. });
  47. function query(q, offset, length) {
  48. if (!initialized) throw new Error('Search has not been initialized');
  49. return engine.search(q, offset, length);
  50. }
  51. compodoc.search = {
  52. query: query
  53. };
  54. });
  55. })(compodoc);