UNPKG

1.52 kBJavaScriptView Raw
1var Node = require('./node'),
2 stringifiers = {},
3 styleStack = Array(1),
4 toString,
5 set,
6 get;
7
8// return string representation of a class
9toString = function (style) {
10 var stringifier, string = '';
11
12 styleStack.unshift(style || styleStack[0]);
13 stringifier = get(this.type, styleStack[0]);
14 if (stringifier) {
15 string = stringifier.call(this, styleStack[0]);
16 }
17 styleStack.shift();
18
19 return string;
20};
21
22get = function (type, style) {
23 if (stringifiers[type]) {
24 if (style && stringifiers[type].styles[style]) {
25 return stringifiers[type].styles[style];
26 } else {
27 return stringifiers[type].main;
28 }
29 }
30};
31
32set = function (type, func, style, main) {
33 var i;
34 if (!Node.isSet(type)) {
35 throw 'Unknown type `' + type + '`';
36 }
37
38 // first stringifier for this type
39 if (!stringifiers[type]) {
40 stringifiers[type] = {
41 // set first stringifier as main by default
42 main: func,
43 styles: {}
44 };
45
46 Node.getTypeClass(type).prototype.toString = toString;
47 }
48 // main stringifier
49 else if (main) {
50 stringifiers[type].main = func;
51 }
52
53 // link stringifier to its name
54 if (typeof style === 'string') {
55 stringifiers[type].styles[style] = func;
56 } else if(style instanceof Array) {
57 for (i = 0; i < style.length; i++) {
58 stringifiers[type].styles[style[i]] = func;
59 }
60 }
61};
62
63exports.set = set;
64exports.get = get;
65
66// return indent string
67exports.getIndent = function (n) {
68 return Array(n + 1).join(' ');
69}
\No newline at end of file