-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
333 lines (277 loc) · 11.2 KB
/
index.js
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
"use strict";
(function(factory) {
if (typeof exports !== 'undefined') {
var React = require('react');
var jsdom = require('jsdom').jsdom;
var doc = jsdom('jsdom document');
module.exports = factory(React, doc);
} else {
window.Normalizer = { Normalizer: factory(window.React, window.document) }; // jshint ignore:line
}
}(function (React, doc) {
var defaultStyles = ["display"];
var defaultAttributes = ["style", "class"];
function normalizeHTML(node, attributesToConsider, attributesToExclude, stylesToConsider, classNamesToConsider) {
var html = "";
// An Element node such as <p> or <div>.
if (node.nodeType === 1) {
var tagName = node.tagName.toLowerCase();
html += "<"+tagName;
html += normalizeAttributes(node, attributesToConsider, attributesToExclude, stylesToConsider, classNamesToConsider);
html += ">";
if(node.hasChildNodes()){
Array.prototype.slice.call(node.childNodes,0).forEach(node => {html += normalizeHTML(node, attributesToConsider, attributesToExclude, stylesToConsider, classNamesToConsider);});
}
html += "</"+tagName+">";
}
// The actual Text of Element or Attr.
else if (node.nodeType === 3 && node.nodeName !== "#comment") {
var nodeValue = node.nodeValue.replace(/\s+/g, ' ');
if(nodeValue.trim()){
html += nodeValue;
}
}
return html;
}
function normalizeAttributes(node, attributesToConsider, attributesToExclude, stylesToConsider, classNamesToConsider) {
var attributes = "";
var attributeList = Array.prototype.slice.call(node.attributes, 0).reduce(((map, attribute) => {
map[attribute.nodeName] = attribute.nodeValue;
return map;
}),{});
Object.keys(attributeList).sort().forEach((attributeKey) => {
var value = attributeList[attributeKey];
var lowerCasedAttributeKey = attributeKey.toLowerCase();
if (!attributesToExclude[lowerCasedAttributeKey] && // checking blacklist
(!attributesToConsider || attributesToConsider[lowerCasedAttributeKey])) {
if(attributeKey === "style"){
attributes += normalizeStyle(value, stylesToConsider);
}
else if(classNamesToConsider && attributeKey === "class"){
attributes += normalizeClass(value, classNamesToConsider);
}
else if(attributeKey !== "data-reactid"){
attributes += " ";
attributes += attributeKey + "=\"" + value + "\"";
}
}
});
return attributes;
}
function normalizeClass(value, classNamesToConsider){
var retVal = "";
if(value && value.trim()){
var classNames = value.replace(/\s+/g, " ").split(" ").sort();
retVal = classNames.reduce((normalized, className) => {
//if classNamesToConsider is null use them all
if(!classNamesToConsider || classNamesToConsider[className]){
if(!normalized){
normalized = "class=\"";
}
normalized += className + " ";
}
return normalized;
}, "");
if(retVal){
retVal = retVal.trim();
retVal = " " + retVal + "\"";
}
}
return retVal;
}
function normalizeStyle(style, stylesToConsider){
var normalized = "";
var styleGroups = style.split(";");
var styleMap = styleGroups.filter(group => {return !!group;})
.reduce((map, group) => {
if(group.trim()){
var styleGroup = group.split(":");
var key = styleGroup[0].trim();
var value = styleGroup[1].trim();
//if styles to consider is null consider them all
if(!stylesToConsider || stylesToConsider[key.toLowerCase()]){
map[key] = value;
}
}
return map;
}, {});
var keys = Object.keys(styleMap);
var lastKeyIndex = keys.length-1;
keys.sort().forEach((key, i) => {
var value = styleMap[key];
if(!i){
normalized += " style=\"";
}
normalized += key + ":";
normalized += value;
if(i !== lastKeyIndex){
normalized += "; ";
}
else {
normalized += "\"";
}
});
return normalized;
}
function normalizedHTMLFromReactComponent(reactComponent, attributesToConsider, attributesToExclude, stylesToConsider, classNamesToConsider) {
var domString = React.renderToStaticMarkup(reactComponent);
return normalizeHTMLString(domString, attributesToConsider, attributesToExclude, stylesToConsider, classNamesToConsider);
}
function convertStringToDOM(html){
var wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
body: [0, "", ""],
_default: [ 1, "<div>", "</div>" ]
};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
var match = /<\s*\w.*?>/g.exec(html);
var node = doc.createElement('div');
if(match != null) {
var tag = match[0].replace(/</g, '').replace(/>/g, '').split(' ')[0];
if(tag.toLowerCase() === 'body') {
// var dom = doc.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
var body = doc.createElement("body");
// keeping the attributes
node.innerHTML = html.replace(/<body/g, '<div').replace(/<\/body>/g, '</div>');
var attrs = node.firstChild.attributes;
body.innerHTML = html;
for(var i=0; i<attrs.length; i++) {
body.setAttribute(attrs[i].name, attrs[i].value);
}
return body;
} else {
var map = wrapMap[tag] || wrapMap._default;
html = map[1] + html + map[2];
node.innerHTML = html;
// Descend through wrappers to the right content
var j = map[0]+1;
while(j--) {
return node.lastChild.childNodes;
}
}
} else {
node.innerHTML = html;
return node.childNodes;
}
}
function normalizeHTMLString(domString, attributesToConsider, attributesToExclude, stylesToConsider, classNamesToConsider) {
var domNodes = convertStringToDOM(domString);
return [].slice.call(domNodes).map(domNode =>
normalizeHTML(domNode, attributesToConsider, attributesToExclude, stylesToConsider, classNamesToConsider)
).join('');
}
function normalizeHTMLFromReactView(reactView, attributesToConsider, attributesToExclude, stylesToConsider, classNamesToConsider) {
var domNode;
try {
domNode = React.findDOMNode(reactView);
}
catch(e) {
domNode = reactView.getDOMNode();
}
return normalizeHTML(domNode, attributesToConsider, attributesToExclude, stylesToConsider, classNamesToConsider);
}
function toLowerMap(array){
return array.reduce((map, item) => {
map[item.toLowerCase()] = true;
return map;
}, {});
}
function toMap(array){
return array.reduce((map, item) => {
map[item] = true;
return map;
}, {});
}
function isReactComponent(component){
return component &&
typeof component === "object" &&
component.key !== undefined &&
component.props !== undefined &&
component.ref !== undefined;
}
function isReactView(view){
return view &&
typeof view === "object" &&
view.state !== undefined &&
view.props !== undefined &&
view.refs !== undefined;
}
return function(options) {
if(!options){
options = {};
}
if(!options.hasOwnProperty("attributes")){
options.attributes = defaultAttributes;
}
if (!options.hasOwnProperty("attributesExcluded") || options.attributesExcluded === null) {
options.attributesExcluded = [];
}
if(!options.hasOwnProperty("styles")){
options.styles = defaultStyles;
}
if(!options.hasOwnProperty("classNames")){
options.classNames = null; //consider all class names by default
}
var attributesToConsider = options.attributes ? toLowerMap(options.attributes) : null;
var attributesToExclude = options.attributesExcluded ? toLowerMap(options.attributesExcluded) : null;
var classNamesToConsider = options.classNames ? toMap(options.classNames) : null;
var stylesToConsider = options.styles ? toLowerMap(options.styles) : null;
return {
reactView(view){
if(isReactComponent(view)){
throw new Error("Looks like you passed in a react component. Try using .reactComponent instead of .reactView.");
}
else if(!isReactView(view)){
throw new Error("This function takes one argument. It must be a react view and can not be null.");
}
return normalizeHTMLFromReactView(view, attributesToConsider, attributesToExclude, stylesToConsider, classNamesToConsider);
},
reactComponent(component){
if(isReactView(component)){
throw new Error("Looks like you passed in a react view. Try using .reactView instead of .reactComponent.");
}
else if(!isReactComponent(component)){
throw new Error("This function takes one argument. It must be a react component and can not be null.");
}
return normalizedHTMLFromReactComponent(component, attributesToConsider, attributesToExclude, stylesToConsider, classNamesToConsider);
},
domNode(node){
if(!node || typeof node !== "object" || node.innerHTML === undefined){
throw new Error("This function takes one argument. It must be a dom node and can not be null.");
}
return normalizeHTML(node, attributesToConsider, attributesToExclude, stylesToConsider, classNamesToConsider);
},
domString(string){
if(!string || typeof string !== "string" ){
throw new Error("This function takes one argument. It must be a dom string and can not be empty.");
}
return normalizeHTMLString(string, attributesToConsider, attributesToExclude, stylesToConsider, classNamesToConsider);
},
normalize(objectWithHTML){
if(objectWithHTML && typeof objectWithHTML === "string" ){
return this.domString(objectWithHTML);
}else if(objectWithHTML && typeof objectWithHTML === "object" && objectWithHTML.innerHTML !== undefined){
return this.domNode(objectWithHTML);
}
else if(isReactComponent(objectWithHTML)){
return this.reactComponent(objectWithHTML);
}
else if(isReactView(objectWithHTML)){
return this.reactView(objectWithHTML);
}
else {
throw new Error("This function takes one argument. It must either be an HTML string, DOM node, react componenet or react element.");
}
}
};
};
}));