local-search.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* global hexo */
  2. 'use strict';
  3. hexo.extend.generator.register('_hexo_generator_search', function(locals) {
  4. const config = this.theme.config;
  5. if (!config.search.enable) {
  6. return;
  7. }
  8. const nunjucks = require('nunjucks');
  9. const env = new nunjucks.Environment();
  10. const pathFn = require('path');
  11. const fs = require('fs');
  12. env.addFilter('uriencode', function(str) {
  13. return encodeURI(str);
  14. });
  15. env.addFilter('noControlChars', function(str) {
  16. // eslint-disable-next-line no-control-regex
  17. return str && str.replace(/[\x00-\x1F\x7F]/g, '').replace(/<figure class="highlight.*?<\/figure>/ig, '').replace(/(<([^>]+)>)/ig, '').replace(/(https?:\/\/[^\s]+)/ig, '');
  18. });
  19. env.addFilter('urlJoin', function(str) {
  20. const base = str[0];
  21. const relative = str[1].replace(/\.html$/g, '');
  22. return relative
  23. ? base.replace(/\/+$/, '') + '/' + relative.replace(/^\/+/, '')
  24. : base;
  25. });
  26. const searchTmplSrc = pathFn.join(hexo.theme_dir, './source/xml/local-search.xml');
  27. const searchTmpl = nunjucks.compile(fs.readFileSync(searchTmplSrc, 'utf8'), env);
  28. const searchConfig = config.search;
  29. let searchField = searchConfig.field;
  30. const content = searchConfig.content && true;
  31. let posts, pages;
  32. if (searchField.trim() !== '') {
  33. searchField = searchField.trim();
  34. if (searchField === 'post') {
  35. posts = locals.posts.sort('-date');
  36. } else if (searchField === 'page') {
  37. pages = locals.pages;
  38. } else {
  39. posts = locals.posts.sort('-date');
  40. pages = locals.pages;
  41. }
  42. } else {
  43. posts = locals.posts.sort('-date');
  44. }
  45. const xml = searchTmpl.render({
  46. config : config,
  47. posts : posts,
  48. pages : pages,
  49. content: content,
  50. url : hexo.config.root
  51. });
  52. return {
  53. path: searchConfig.generate_path || '/local-search.xml',
  54. data: xml
  55. };
  56. });