Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update ignore whitespace option #66

Merged
merged 2 commits into from
Jul 24, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 38 additions & 29 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ var utils = require('./utils'),
* @param {Object} options
* @returns {AST}
*/
function htmlToAST(HTMLDoc, options) {
function htmlToAST(HTMLDoc) {
var parser,
parserHandler;

parserHandler = new htmlParser.DomHandler(function(err) {
if (err) console.log(err);
}, options);
});

parser = new htmlParser.Parser(parserHandler);
parser.parseComplete(HTMLDoc);
Expand All @@ -26,45 +26,54 @@ function htmlToAST(HTMLDoc, options) {
}

/**
* Recursively sorts arttibutes' values of the AST leafs
* Recursively modifies the tree depending on the given options
* @param {AST} tree
* @param {Object} options
* @returns {AST}
*/
function modifyASTTree(tree, options) {
_.each(tree, function(node) {
Object.keys(node).forEach(function(leaf) {
if (leaf === 'attribs') {
var attrs = utils.sortObj(node[leaf]);
_.forEach(tree, function(node) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем lodash для таких случаев? Можно же tree.forEach(function(node) {...}).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно конечно, у меня так и было раньше! это сделал изменения в своем пул реквесте @shuhrat!

/cc @shuhrat

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

есть мнение, что лодашовский each работает быстрее чем нативный

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Хорошо! только я заглянул в доку лодаша и там пишут о переходе each на forEach, поэтому я и изменил у себя!

if (options.ignoreWhitespace && node.type === 'text') {

if (attrs.hasOwnProperty('class')) {
attrs['class'] = utils.sortCssClasses(attrs['class']);
}
node.data = node.data
.replace(/(\n|\r|\t|\v|\f)+/g, '')
.replace(/\s+/g, ' ')
.trim();

_.each(options.compareHtmlAttrsAsJSON, function(attr) {
var attrValue,
isFunction = (attr === 'onclick' || attr === 'ondblclick'); // @FIXME: should be configurable
return;
}

if (attrs.hasOwnProperty(attr)) {
if (node.hasOwnProperty('attribs')) {
var attrs = utils.sortObj(node['attribs']);

attrValue = utils.parseAttr(attrs[attr].replace(/"/g, '"'), isFunction);
attrValue = utils.sortObj(attrValue);
attrValue = JSON.stringify(attrValue);
if (attrs.hasOwnProperty('class')) {
attrs['class'] = utils.sortCssClasses(attrs['class']);
}

attrs[attr] = (isFunction ? 'return ' : '') + attrValue.replace(/"/g, '"')
}
});
_.forEach(options.compareHtmlAttrsAsJSON, function(attr) {
var attrValue,
isFunction = (attr === 'onclick' || attr === 'ondblclick'); // @FIXME: should be configurable

_.each(options.ignoreHtmlAttrs, function(attr) {
attrs.hasOwnProperty(attr) && (attrs[attr] = '');
});
if (attrs.hasOwnProperty(attr)) {

node[leaf] = attrs;
}
else if (leaf === 'children') {
modifyASTTree(node.children, options);
}
});
attrValue = utils.parseAttr(attrs[attr].replace(/"/g, '"'), isFunction);
attrValue = utils.sortObj(attrValue);
attrValue = JSON.stringify(attrValue);

attrs[attr] = (isFunction ? 'return ' : '') + attrValue.replace(/"/g, '"')
}
});

_.forEach(options.ignoreHtmlAttrs, function(attr) {
attrs.hasOwnProperty(attr) && (attrs[attr] = '');
});

node['attribs'] = attrs;
}

if (node.hasOwnProperty('children')) {
modifyASTTree(node.children, options);
}
});

return tree;
Expand Down
2 changes: 1 addition & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ exports.sortObj = function sortObj(obj) {
var keys = _.keys(obj).sort(),
sortedObj = {};

_.each(keys, function(key) {
_.forEach(keys, function(key) {
var objValue = obj[key];

if(_.isPlainObject(objValue)) {
Expand Down
2 changes: 1 addition & 1 deletion test/diffHtml.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ describe('\'diffHtml\'', function () {
files = readFiles('3.html', '_3.html'),

res = [ {
value: '<html> <head> <title>Test</title> </head> <body> <label for="">label for input</label> <input id=""> </body> </html> ',
value: '<html><head><title>Test</title></head><body><label for="">label for input</label><input id=""></body></html>',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему тест изменился?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

У htmlparser2 опция ignoreWhitespace работает не так как у htmlparser!

Я считаю, что эта опция у htmlparser продумана более корректно! Я писал об этом автору htmlparser2, но он не особо хочет это чинить, то есть не чинить, а делать ее такой же как у htmlparser, поэтому я при переходе на htmlparser2 подогнал тест таким образом, чтобы при использовании этой опции не падали тесты! А в этом пул реквесте игнорирование происходит нужным мне образом (как это было в htmlparser), поэтому тест и изменился!

added: undefined,
removed: undefined
} ];
Expand Down
12 changes: 12 additions & 0 deletions test/fixtures/10.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<!-- comments1 -->
<html>
<head lang="en">
<meta charset="UTF-8">
<title><!-- comments2 --></title>
</head>
<body>
Text<!-- comments3 -->
</body>
</html>
<!-- comments4 -->
1 change: 1 addition & 0 deletions test/fixtures/7.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<!DOCTYPE html>
<html>
Text Text
<head lang="en">
<meta charset="UTF-8">
<title></title>
Expand Down
10 changes: 10 additions & 0 deletions test/fixtures/_10.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
Text
</body>
</html>
21 changes: 14 additions & 7 deletions test/fixtures/_7.html
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
<!DOCTYPE html>
<html>
<html>
Text Text
<head lang = "en">
<meta charset="UTF-8">
<title > </title>

<head lang="en">
<meta charset="UTF-8">
<title ></title>
</head>

</head>

<body>
Text
</body>
Text

</body>




</html>


Expand Down