summaryrefslogtreecommitdiff
path: root/lib/html/ast.js
blob: 30e65c7dd662085d28c7c51b6b4a241d45803b19 (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
var _ = require("underscore");

var htmlPaths = require("../html-paths");


function fragment(children) {
    return {
        type: "fragment",
        children: collapseFragments(children)
    };
}

function nonFreshElement(tagName, attributes, children) {
    return elementWithTag(
        htmlPaths.element(tagName, attributes, {fresh: false}),
        children);
}

function freshElement(tagName, attributes, children) {
    return elementWithTag(
        htmlPaths.element(tagName, attributes, {fresh: true}),
        children);
}

function elementWithTag(tag, children) {
    return {
        type: "element",
        tag: tag,
        children: collapseFragments(children),
        isEmpty: _.all(children, function(child) {
            return child.isEmpty;
        }),
        appendChild: appendChild
    };
}
    
function appendChild(child) {
    this.children.push(child);
    this.isEmpty = this.isEmpty && child.isEmpty;
}

function selfClosingElement(tagName, attributes) {
    return {
        type: "selfClosingElement",
        tagName: tagName,
        attributes: attributes
    };
}

function text(value) {
    return {
        type: "text",
        value: value,
        isEmpty: !value
    };
}

var forceWrite = {
    type: "forceWrite",
    isEmpty: false
};

function collapseFragments(elements) {
    return _.flatten((elements || []).map(function(element) {
        return element.type === "fragment" ? element.children : [element];
    }), true);
}

exports.fragment = fragment;
exports.freshElement = freshElement;
exports.nonFreshElement = nonFreshElement;
exports.elementWithTag = elementWithTag;
exports.selfClosingElement = selfClosingElement;
exports.text = text;
exports.forceWrite = forceWrite;