Blame view

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