use.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. var utils = require('../utils')
  2. , path = require('path');
  3. /**
  4. * Use the given `plugin`
  5. *
  6. * Examples:
  7. *
  8. * use("plugins/add.js")
  9. *
  10. * width add(10, 100)
  11. * // => width: 110
  12. */
  13. function use(plugin, options){
  14. utils.assertString(plugin, 'plugin');
  15. if (options) {
  16. utils.assertType(options, 'object', 'options');
  17. options = parseObject(options);
  18. }
  19. // lookup
  20. plugin = plugin.string;
  21. var found = utils.lookup(plugin, this.options.paths, this.options.filename);
  22. if (!found) throw new Error('failed to locate plugin file "' + plugin + '"');
  23. // use
  24. var fn = require(path.resolve(found));
  25. if ('function' != typeof fn) {
  26. throw new Error('plugin "' + plugin + '" does not export a function');
  27. }
  28. this.renderer.use(fn(options || this.options));
  29. }
  30. use.params = ['plugin', 'options'];
  31. module.exports = use;
  32. /**
  33. * Attempt to parse object node to the javascript object.
  34. *
  35. * @param {Object} obj
  36. * @return {Object}
  37. * @api private
  38. */
  39. function parseObject(obj){
  40. obj = obj.vals;
  41. for (var key in obj) {
  42. var nodes = obj[key].nodes[0].nodes;
  43. if (nodes && nodes.length) {
  44. obj[key] = [];
  45. for (var i = 0, len = nodes.length; i < len; ++i) {
  46. obj[key].push(convert(nodes[i]));
  47. }
  48. } else {
  49. obj[key] = convert(obj[key].first);
  50. }
  51. }
  52. return obj;
  53. function convert(node){
  54. switch (node.nodeName) {
  55. case 'object':
  56. return parseObject(node);
  57. case 'boolean':
  58. return node.isTrue;
  59. case 'unit':
  60. return node.type ? node.toString() : +node.val;
  61. case 'string':
  62. case 'literal':
  63. return node.val;
  64. default:
  65. return node.toString();
  66. }
  67. }
  68. }