summaryrefslogtreecommitdiff
path: root/lib/html-generator.js
blob: de0749cd309c92648cbfbe9ab259254b66a3c1c5 (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
var _ = require("underscore");

var htmlWriter = require("./html-writer");

exports.HtmlGenerator = HtmlGenerator;


function HtmlGenerator(options) {
    var stack = [];
    var writer = htmlWriter.writer(options);
    
    function text(value) {
        if (value.length > 0) {
            writeAll();
            writer.text(value);
        }
    }
    
    function asString() {
        return writer.asString();
    }
    
    function append(otherHtmlGenerator) {
        var otherString = otherHtmlGenerator.asString();
        if (otherString.length > 0) {
            writeAll();
        }
        writer.append(otherString);
    }
    
    function satisfyPath(style) {
        var firstFreshPartIndex = findIndex(style, function(part) {
            return part.fresh;
        });
        
        var partIndex = 0;
        while (partIndex < firstFreshPartIndex && stylePartMatchesStackElement(style[partIndex], stack[partIndex])) {
            partIndex++;
        }
        while (stack.length > partIndex) {
            close();
        }
        for (; partIndex < style.length; partIndex++) {
            open(style[partIndex]);
        }
    }
    
    function stylePartMatchesStackElement(stylePart, stackElement) {
        return stackElement && stylePart.matchesElement(stackElement);
    }
    
    function open(htmlPathElement) {
        var stackElement = Object.create(htmlPathElement);
        stackElement.written = false;
        stack.push(stackElement);
    }
    
    function close() {
        var element = stack.pop();
        if (element.written) {
            writer.close(element.tagName);
        }
    }
    
    function closeAll() {
        while (stack.length > 0) {
            close();
        }
    }
    
    function writeAll() {
        stack.filter(function(element) {
            return !element.written;
        }).forEach(writeElement);
    }
    
    function writeElement(element) {
        element.written = true;
        writer.open(element.tagName, element.attributes);
    }
    
    function selfClosing(element) {
        writer.selfClosing(element.tagName, element.attributes);
    }
    
    return {
        satisfyPath: satisfyPath,
        text: text,
        open: open,
        close: close,
        closeAll: closeAll,
        asString: asString,
        append: append,
        selfClosing: selfClosing
    };
}

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