renderer.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. const stylus = require('stylus');
  3. function getProperty(obj, name) {
  4. name = name.replace(/\[(\w+)\]/g, '.$1').replace(/^\./, '');
  5. const split = name.split('.');
  6. let key = split.shift();
  7. if (!Object.prototype.hasOwnProperty.call(obj, key)) return '';
  8. let result = obj[key];
  9. const len = split.length;
  10. if (!len) return result || '';
  11. if (typeof result !== 'object') return '';
  12. for (let i = 0; i < len; i++) {
  13. key = split[i];
  14. if (!Object.prototype.hasOwnProperty.call(result, key)) return '';
  15. result = result[split[i]];
  16. if (typeof result !== 'object') return result;
  17. }
  18. return result;
  19. }
  20. function applyPlugins(stylusConfig, plugins) {
  21. plugins.forEach(plugin => {
  22. const factoryFn = require(plugin.trim());
  23. stylusConfig.use(factoryFn());
  24. });
  25. }
  26. function stylusFn(data, options, callback) {
  27. const config = this.config.stylus || {};
  28. const self = this;
  29. const plugins = ['nib'].concat(config.plugins || []);
  30. function defineConfig(style) {
  31. style.define('hexo-config', data => {
  32. return getProperty(self.theme.config, data.val);
  33. });
  34. }
  35. const stylusConfig = stylus(data.text);
  36. applyPlugins(stylusConfig, plugins);
  37. stylusConfig
  38. .use(defineConfig)
  39. .use(style => this.execFilterSync('stylus:renderer', style, {context: this}))
  40. .set('filename', data.path)
  41. .set('sourcemap', config.sourcemaps)
  42. .set('compress', config.compress)
  43. .set('include css', true)
  44. .render(callback);
  45. }
  46. stylusFn.disableNunjucks = true;
  47. module.exports = stylusFn;