search-lunr.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. (function(compodoc) {
  2. function LunrSearchEngine() {
  3. this.index = undefined;
  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: length === 0 ? results : results.slice(0, length),
  32. count: results.length
  33. });
  34. return d;
  35. };
  36. compodoc.addEventListener(compodoc.EVENTS.READY, function(event) {
  37. var engine = new LunrSearchEngine(),
  38. initialized = false;
  39. function query(q, offset, length) {
  40. if (!initialized) throw new Error('Search has not been initialized');
  41. return engine.search(q, offset, length);
  42. }
  43. compodoc.search = {
  44. query: query
  45. };
  46. engine.init()
  47. .then(function() {
  48. initialized = true;
  49. compodoc.dispatchEvent({
  50. type: compodoc.EVENTS.SEARCH_READY
  51. });
  52. });
  53. });
  54. })(compodoc);