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

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

function simplify(nodes) {
    return collapse(removeEmpty(nodes));
}

function collapse(nodes) {
    var children = [];
    
    nodes.map(collapseNode).forEach(function(child) {
        appendChild(children, child);
    });
    return children;
}

function collapseNode(node) {
    return collapsers[node.type](node);
}

var collapsers = {
    element: collapseElement,
    selfClosingElement: identity,
    text: identity,
    forceWrite: identity
};

function collapseElement(node) {
    return ast.elementWithTag(node.tag, collapse(node.children));
}

function identity(value) {
    return value;
}

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

function removeEmpty(nodes) {
    return flatMap(nodes, function(node) {
        return emptiers[node.type](node);
    });
}

function flatMap(values, func) {
    return _.flatten(_.map(values, func), true);
}

var emptiers = {
    element: elementEmptier,
    selfClosingElement: neverEmpty,
    text: textEmptier,
    forceWrite: neverEmpty
};

function neverEmpty(node) {
    return [node];
}

function elementEmptier(element) {
    var children = removeEmpty(element.children);
    if (children.length === 0) {
        return [];
    } else {
        return ast.elementWithTag(element.tag, children);
    }
}

function textEmptier(node) {
    if (node.value.length === 0) {
        return [];
    } else {
        return [node];
    }
}

module.exports = simplify;