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