UNPKG

2.02 kBJavaScriptView Raw
1
2/*!
3 * Stylus - Renderer
4 * Copyright(c) 2010 LearnBoost <dev@learnboost.com>
5 * MIT Licensed
6 */
7
8/**
9 * Module dependencies.
10 */
11
12var Parser = require('./parser')
13 , Compiler = require('./visitor/compiler')
14 , Evaluator = require('./visitor/evaluator')
15 , utils = require('./utils')
16 , nodes = require('./nodes');
17
18/**
19 * Initialize a new `Renderer` with the given `str` and `options`.
20 *
21 * @param {String} str
22 * @param {Object} options
23 * @api public
24 */
25
26var Renderer = module.exports = function Renderer(str, options) {
27 options = options || {};
28 options.functions = {};
29 options.imports = [];
30 options.filename = options.filename || 'stylus';
31 this.str = str;
32 this.options = options;
33 this.parser = new Parser(str, options);
34};
35
36/**
37 * Parse and evaluate AST, then callback `fn(err, css)`.
38 *
39 * @param {Function} fn
40 * @api public
41 */
42
43Renderer.prototype.render = function(fn){
44 try {
45 var ast = this.parser.parse();
46 this.evaluator = new Evaluator(ast, this.options);
47 ast = this.evaluator.evaluate();
48 new Compiler(ast, this.options).compile(fn);
49 } catch (err) {
50 fn(utils.formatException(
51 this
52 , err
53 , this.options));
54 }
55 nodes.source = null;
56};
57
58/**
59 * Set option `key` to `val`.
60 *
61 * @param {String} key
62 * @param {Mixed} val
63 * @return {Renderer} for chaining
64 * @api public
65 */
66
67Renderer.prototype.set = function(key, val){
68 this.options[key] = val;
69 return this;
70};
71
72/**
73 * Define function with the given `name`. Optionally
74 * the function may accept full expressions, by setting `raw`
75 * to `true`.
76 *
77 * @param {String} name
78 * @param {Function} fn
79 * @return {Renderer} for chaining
80 * @api public
81 */
82
83Renderer.prototype.define = function(name, fn, raw){
84 this.options.functions[name] = fn;
85 fn.raw = raw;
86 return this;
87};
88
89/**
90 * Import the given `file`.
91 *
92 * @param {String} file
93 * @return {Renderer} for chaining
94 * @api public
95 */
96
97Renderer.prototype.import = function(file){
98 this.options.imports.push(file);
99 return this;
100};
101
102