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
106
107
108
109
110
111
112
113
114
115
116
|
var util = require("util");
var _ = require("underscore");
exports.HtmlGenerator = HtmlGenerator;
function HtmlGenerator() {
var stack = [];
var fragments = [];
function text(value) {
if (value.length > 0) {
writeAll();
fragments.push(escapeHtml(value))
}
}
function asString() {
return fragments.join("");
}
function append(otherHtmlGenerator) {
if (otherHtmlGenerator._fragments.length > 0) {
writeAll();
}
otherHtmlGenerator._fragments.forEach(function(fragment) {
fragments.push(fragment);
});
}
function style(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) {
pop();
}
for (; partIndex < style.length; partIndex++) {
push(style[partIndex]);
}
}
function stylePartMatchesStackElement(stylePart, stackElement) {
return stackElement && stylePart.tagName === stackElement.element.tagName;
}
function push(element) {
stack.push({
element: element,
written: false
});
}
function pop() {
var stackElement = stack.pop();
if (stackElement.written) {
fragments.push(util.format("</%s>", stackElement.element.tagName));
}
}
function popAll() {
while (stack.length > 0) {
pop();
}
}
function writeAll() {
stack.filter(function(element) {
return !element.written;
}).forEach(writeElement);
}
function writeElement(stackElement) {
stackElement.written = true;
var element = stackElement.element;
var attributeString = _.map(element.attributes, function(value, key) {
return util.format(' %s="%s"', key, value);
}).join("");
fragments.push(util.format("<%s%s>", element.tagName, attributeString));
}
return {
style: style,
text: text,
closeAll: popAll,
asString: asString,
append: append,
push: push,
pop: pop,
_fragments: fragments
};
}
function escapeHtml(value) {
return value
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function findIndex(array, predicate) {
for (var i = 0; i < array.length; i++) {
if (predicate(array[i])) {
return i;
}
}
return -1;
}
|