From 2e818b7beafe567a19447c81f9a033e32cc2022f Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Wed, 23 Mar 2016 00:11:16 +0000 Subject: Improve collapsing of elements when there are empty elements Specifically, strip out empty nodes before attempting to collapse. --- lib/html/simplify.js | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) (limited to 'lib/html') diff --git a/lib/html/simplify.js b/lib/html/simplify.js index 5b65034..24a3447 100644 --- a/lib/html/simplify.js +++ b/lib/html/simplify.js @@ -1,33 +1,37 @@ var ast = require("./ast"); function simplify(node) { - return removeEmpty(simplifiers[node.type](node)); + return collapse(removeEmpty(node)); } -var simplifiers = { - fragment: simplifyFragment, - element: simplifyElement, +function collapse(node) { + return collapsers[node.type](node); +} + +var collapsers = { + fragment: collapseFragment, + element: collapseElement, selfClosingElement: identity, text: identity, forceWrite: identity }; -function simplifyFragment(node) { - return ast.fragment(simplifyNodes(node.children)); +function collapseFragment(node) { + return ast.fragment(collapseNodes(node.children)); } -function simplifyElement(node) { - return ast.elementWithTag(node.tag, simplifyNodes(node.children)); +function collapseElement(node) { + return ast.elementWithTag(node.tag, collapseNodes(node.children)); } function identity(value) { return value; } -function simplifyNodes(nodes) { +function collapseNodes(nodes) { var children = []; - nodes.map(simplify).forEach(function(child) { + nodes.map(collapse).forEach(function(child) { appendChild(children, child, children.push.bind(children)); }); return children; @@ -58,15 +62,17 @@ var emptiers = { }; function fragmentEmptier(fragment) { - return ast.fragment(fragment.children.filter(function(child) { - return !child.isEmpty; - })); + return ast.fragment(listEmptier(fragment.children)); } function elementEmptier(element) { - return ast.elementWithTag(element.tag, element.children.filter(function(child) { + return ast.elementWithTag(element.tag, listEmptier(element.children)); +} + +function listEmptier(elements) { + return elements.map(removeEmpty).filter(function(child) { return !child.isEmpty; - })); + }); } -- cgit v1.2.3