search-engine.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. require([
  2. 'gitbook',
  3. 'jquery'
  4. ], function(gitbook, $) {
  5. // Global search objects
  6. var engine = null;
  7. var initialized = false;
  8. // Set a new search engine
  9. function setEngine(Engine, config) {
  10. initialized = false;
  11. engine = new Engine(config);
  12. init(config);
  13. }
  14. // Initialize search engine with config
  15. function init(config) {
  16. if (!engine) throw new Error('No engine set for research. Set an engine using gitbook.research.setEngine(Engine).');
  17. return engine.init(config)
  18. .then(function() {
  19. initialized = true;
  20. gitbook.events.trigger('search.ready');
  21. });
  22. }
  23. // Launch search for query q
  24. function query(q, offset, length) {
  25. if (!initialized) throw new Error('Search has not been initialized');
  26. return engine.search(q, offset, length);
  27. }
  28. // Get stats about search
  29. function getEngine() {
  30. return engine? engine.name : null;
  31. }
  32. function isInitialized() {
  33. return initialized;
  34. }
  35. // Initialize gitbook.search
  36. gitbook.search = {
  37. setEngine: setEngine,
  38. getEngine: getEngine,
  39. query: query,
  40. isInitialized: isInitialized
  41. };
  42. });