aboutsummaryrefslogtreecommitdiff
path: root/lib/html-generator.js
blob: 5f2befa47a10a63d9fe5029aac4cf789fb032082 (plain)
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
75
76
77
var util = require("util");

var _ = require("underscore");

exports.HtmlGenerator = HtmlGenerator;


function HtmlGenerator() {
    var stack = [];
    var fragments = [];
    
    function text(value) {
        fragments.push(escapeHtml(value))
    }
    
    function asString() {
        popAll();
        return fragments.join("");
    }
    
    function style(style) {
        var firstFreshPartIndex = findIndex(style, function(part) {
            return part.fresh;
        });
        
        var partIndex = 0;
        while (partIndex < firstFreshPartIndex && style[partIndex].tagName === stack[partIndex]) {
            partIndex++;
        }
        while (stack.length > partIndex) {
            pop();
        }
        for (; partIndex < style.length; partIndex++) {
            push(style[partIndex].tagName);
        }
    }
    
    function push(element) {
        stack.push(element);
        fragments.push(util.format("<%s>", element));
    }
    
    function pop() {
        var element = stack.pop();
        fragments.push(util.format("</%s>", element));
    }
    
    function popAll() {
        while (stack.length > 0) {
            pop();
        }
    }
    
    return {
        style: style,
        text: text,
        asString: asString
    };
}


function escapeHtml(value) {
    return value
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}

function findIndex(array, predicate) {
    for (var i = 0; i < array.length; i++) {
        if (predicate(array[i])) {
            return i;
        }
    }
    return -1;
}