4ec66b9eb2175216800bd027f34ee19dae1a7ab1
[framework/web/web-ui-fw.git] / build-tools / lib / less / tree / javascript.js
1 (function (tree) {
2
3 tree.JavaScript = function (string, index, escaped) {
4     this.escaped = escaped;
5     this.expression = string;
6     this.index = index;
7 };
8 tree.JavaScript.prototype = {
9     eval: function (env) {
10         var result,
11             that = this,
12             context = {};
13
14         var expression = this.expression.replace(/@\{([\w-]+)\}/g, function (_, name) {
15             return tree.jsify(new(tree.Variable)('@' + name, that.index).eval(env));
16         });
17
18         try {
19             expression = new(Function)('return (' + expression + ')');
20         } catch (e) {
21             throw { message: "JavaScript evaluation error: `" + expression + "`" ,
22                     index: this.index };
23         }
24
25         for (var k in env.frames[0].variables()) {
26             context[k.slice(1)] = {
27                 value: env.frames[0].variables()[k].value,
28                 toJS: function () {
29                     return this.value.eval(env).toCSS();
30                 }
31             };
32         }
33
34         try {
35             result = expression.call(context);
36         } catch (e) {
37             throw { message: "JavaScript evaluation error: '" + e.name + ': ' + e.message + "'" ,
38                     index: this.index };
39         }
40         if (typeof(result) === 'string') {
41             return new(tree.Quoted)('"' + result + '"', result, this.escaped, this.index);
42         } else if (Array.isArray(result)) {
43             return new(tree.Anonymous)(result.join(', '));
44         } else {
45             return new(tree.Anonymous)(result);
46         }
47     }
48 };
49
50 })(require('less/tree'));
51