aboutsummaryrefslogtreecommitdiff
path: root/lib/html/simplify.js
diff options
context:
space:
mode:
authorMichael Williamson <mike@zwobble.org>2015-10-13 23:29:41 +0100
committerMichael Williamson <mike@zwobble.org>2015-10-13 23:49:31 +0100
commit7b7ce0d563ddc07172b0f241a5c3baf344f256e8 (patch)
tree43f5fddf920d47e281a30139bde99da5a689d667 /lib/html/simplify.js
parente04d054a1b414e843fa6d6f5ee1ae75c0df533b1 (diff)
Collapse similar HTML elements
Diffstat (limited to 'lib/html/simplify.js')
-rw-r--r--lib/html/simplify.js43
1 files changed, 34 insertions, 9 deletions
diff --git a/lib/html/simplify.js b/lib/html/simplify.js
index 291e5d4..8ab4a1f 100644
--- a/lib/html/simplify.js
+++ b/lib/html/simplify.js
@@ -1,15 +1,15 @@
-var _ = require("underscore");
-
var ast = require("./ast");
function simplify(node) {
- return simplifiers[node.type](node);
-};
+ return removeEmpty(simplifiers[node.type](node));
+}
var simplifiers = {
fragment: simplifyFragment,
element: simplifyElement,
- text: simplifyText
+ selfClosingElement: identity,
+ text: identity,
+ forceWrite: identity
};
function simplifyFragment(node) {
@@ -20,8 +20,8 @@ function simplifyElement(node) {
return ast.elementWithTag(node.tag, simplifyNodes(node.children));
}
-function simplifyText(node) {
- return node;
+function identity(value) {
+ return value;
}
function simplifyNodes(nodes) {
@@ -29,10 +29,10 @@ function simplifyNodes(nodes) {
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)) {
+ 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.
- lastChild.children.push(grandChild);
+ lastChild.appendChild(grandChild);
});
} else {
children.push(child);
@@ -41,4 +41,29 @@ function simplifyNodes(nodes) {
return children;
}
+function removeEmpty(node) {
+ return emptiers[node.type](node);
+}
+
+var emptiers = {
+ fragment: fragmentEmptier,
+ element: elementEmptier,
+ selfClosingElement: identity,
+ text: identity,
+ forceWrite: identity
+};
+
+function fragmentEmptier(fragment) {
+ return ast.fragment(fragment.children.filter(function(child) {
+ return !child.isEmpty;
+ }));
+}
+
+function elementEmptier(element) {
+ return ast.elementWithTag(element.tag, element.children.filter(function(child) {
+ return !child.isEmpty;
+ }));
+}
+
+
module.exports = simplify;