-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathmodify.js
More file actions
93 lines (82 loc) · 3.01 KB
/
modify.js
File metadata and controls
93 lines (82 loc) · 3.01 KB
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
88
89
90
91
92
93
var SimpleApiParser = require('parse5').SimpleApiParser,
serialize = require('./serialize'),
utils = require('./utils');
/**
* Parses the given HTML and modifies it according to the given options
* @param {String} value
* @param {Object} [options]
* @param {String[]} [options.ignoreAttributes]
* @param {String[]} [options.compareAttributesAsJSON]
* @param {Boolean} [options.ignoreWhitespaces=true]
* @param {Boolean} [options.ignoreComments=true]
* @param {Boolean} [options.ignoreEndTags=false]
* @param {Boolean} [options.ignoreDuplicateAttributes=false]
* @param {Boolean} [options.ignoreEmptyAttributes=false]
* returns {String}
*/
function modify(value, options) {
var modifiedValue = '',
parser;
parser = new SimpleApiParser({
/**
* @param {String} name
* @param {String} publicId
* @param {String} systemId
*/
doctype: function (name, publicId, systemId) {
modifiedValue += serialize.doctype(name, publicId, systemId);
},
/**
* @param {String} tagName
* @param {Array} attrs
* @param {Boolean} selfClosing
*/
startTag: function (tagName, attrs, selfClosing) {
if (options.ignoreDuplicateAttributes) {
attrs = utils.removeDuplicateAttributes(attrs);
}
attrs = utils.sortAttrs(attrs) &&
utils.sortCssClasses(attrs) &&
utils.sortAttrsValues(attrs, options.compareAttributesAsJSON) &&
utils.removeAttrsValues(attrs, options.ignoreAttributes);
if (options.ignoreEmptyAttributes) {
attrs = utils.removeEmptyAttributes(attrs);
}
modifiedValue += serialize.startTag(tagName, attrs, selfClosing);
},
/**
* @param {String} tagName
*/
endTag: function (tagName) {
!options.ignoreEndTags && (modifiedValue += serialize.endTag(tagName));
},
/**
* @param {String} text
*/
text: function (text) {
options.ignoreWhitespaces && (text = utils.removeWhitespaces(text));
modifiedValue += serialize.text(text);
},
/**
* @param {String} comment
*/
comment: function (comment) {
var conditionalComment = utils.getConditionalComment(comment, modify, options);
if (conditionalComment) {
modifiedValue += serialize.comment(conditionalComment);
} else if (!options.ignoreComments) {
modifiedValue += serialize.comment(comment);
}
}
});
// Makes 'parse5' handle duplicate attributes
parser._reset = function (html) {
SimpleApiParser.prototype._reset.call(this, html);
this.tokenizerProxy.tokenizer._isDuplicateAttr = function () {
return false;
};
};
parser.parse(value);
return modifiedValue;
}
module.exports = modify;