injects.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. 'use strict';
  2. const fs = require('fs');
  3. const path = require('path');
  4. const points = require('./injects-point');
  5. const defaultExtname = '.swig';
  6. // Defining stylus types
  7. class StylusInject {
  8. constructor(base_dir) {
  9. this.base_dir = base_dir;
  10. this.files = [];
  11. }
  12. push(file) {
  13. // Get absolute path base on hexo dir
  14. this.files.push(path.resolve(this.base_dir, file));
  15. }
  16. }
  17. // Defining view types
  18. class ViewInject {
  19. constructor(base_dir) {
  20. this.base_dir = base_dir;
  21. this.raws = [];
  22. }
  23. raw(name, raw, ...args) {
  24. // Set default extname
  25. if (path.extname(name) === '') {
  26. name += defaultExtname;
  27. }
  28. this.raws.push({name, raw, args});
  29. }
  30. file(name, file, ...args) {
  31. // Set default extname from file's extname
  32. if (path.extname(name) === '') {
  33. name += path.extname(file);
  34. }
  35. // Get absolute path base on hexo dir
  36. this.raw(name, fs.readFileSync(path.resolve(this.base_dir, file), 'utf8'), ...args);
  37. }
  38. }
  39. // Init injects
  40. function initInject(base_dir) {
  41. let injects = {};
  42. points.styles.forEach(item => {
  43. injects[item] = new StylusInject(base_dir);
  44. });
  45. points.views.forEach(item => {
  46. injects[item] = new ViewInject(base_dir);
  47. });
  48. return injects;
  49. }
  50. module.exports = hexo => {
  51. // Exec theme_inject filter
  52. let injects = initInject(hexo.base_dir);
  53. hexo.execFilterSync('theme_inject', injects);
  54. hexo.theme.config.injects = {};
  55. // Inject stylus
  56. points.styles.forEach(type => {
  57. hexo.theme.config.injects[type] = injects[type].files;
  58. });
  59. // Inject views
  60. points.views.forEach(type => {
  61. let configs = Object.create(null);
  62. hexo.theme.config.injects[type] = [];
  63. // Add or override view.
  64. injects[type].raws.forEach((injectObj, index) => {
  65. let name = `inject/${type}/${injectObj.name}`;
  66. hexo.theme.setView(name, injectObj.raw);
  67. configs[name] = {
  68. layout : name,
  69. locals : injectObj.args[0],
  70. options: injectObj.args[1],
  71. order : injectObj.args[2] || index
  72. };
  73. });
  74. // Views sort.
  75. hexo.theme.config.injects[type] = Object.values(configs)
  76. .sort((x, y) => x.order - y.order);
  77. });
  78. };