aboutsummaryrefslogtreecommitdiff
path: root/lib/html/simplify.js
blob: 291e5d49ffc28098221c94ec20e5a93c917bd335 (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
var _ = require("underscore");

var ast = require("./ast");

function simplify(node) {
    return simplifiers[node.type](node);
};

var simplifiers = {
    fragment: simplifyFragment,
    element: simplifyElement,
    text: simplifyText
};

function simplifyFragment(node) {
    return ast.fragment(simplifyNodes(node.children));
}

function simplifyElement(node) {
    return ast.elementWithTag(node.tag, simplifyNodes(node.children));
}

function simplifyText(node) {
    return node;
}

function simplifyNodes(nodes) {
    var children = [];
    
    nodes.map(simplify).forEach(function(child) {
        var lastChild = children[children.length - 1];
        if (child.type === "element" && !child.tag.fresh && lastChild && child.tag.matchesElement(lastChild.tag)) {
            child.children.forEach(function(grandChild) {
                // Mutation is fine since simplifying elements create a copy of the children.
                lastChild.children.push(grandChild);
            });
        } else {
            children.push(child);
        }
    });
    return children;
}

module.exports = simplify;