forked from krux/postscribe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
htmlParser.js
395 lines (333 loc) · 10.6 KB
/
htmlParser.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
// An html parser written in JavaScript
// Based on http://ejohn.org/blog/pure-javascript-html-parser/
//TODO(#39)
/*globals console:false*/
(function() {
var supports = (function() {
var supports = {};
var html;
var work = this.document.createElement('div');
html = '<P><I></P></I>';
work.innerHTML = html;
supports.tagSoup = work.innerHTML !== html;
work.innerHTML = '<P><i><P></P></i></P>';
supports.selfClose = work.childNodes.length === 2;
return supports;
})();
// Regular Expressions for parsing tags and attributes
var startTag = /^<([\-A-Za-z0-9_]+)((?:\s+[\w\-]+(?:\s*=?\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
var endTag = /^<\/([\-A-Za-z0-9_]+)[^>]*>/;
var attr = /(?:([\-A-Za-z0-9_]+)\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))|(?:([\-A-Za-z0-9_]+)(\s|$)+)/g;
var fillAttr = /^(checked|compact|declare|defer|disabled|ismap|multiple|nohref|noresize|noshade|nowrap|readonly|selected)$/i;
var DEBUG = false;
function htmlParser(stream, options) {
stream = stream || '';
// Options
options = options || {};
for(var key in supports) {
if(supports.hasOwnProperty(key)) {
if(options.autoFix) {
options['fix_'+key] = true;//!supports[key];
}
options.fix = options.fix || options['fix_'+key];
}
}
var stack = [];
// Cache div element for unescaping html entities
var el = document.createElement('div');
var unescapeHTMLEntities = function(html) {
if ( (typeof html === 'string') && (html.indexOf('&') !== -1) ) {
el.innerHTML = html;
// ie and ff differ
return el.textContent || el.innerText || html;
}
else {
return html;
}
};
var append = function(str) {
stream += str;
};
var prepend = function(str) {
stream = str + stream;
};
// Order of detection matters: detection of one can only
// succeed if detection of previous didn't
var detect = {
comment: /^<!--/,
endTag: /^<\//,
atomicTag: /^<\s*(script|style|noscript|iframe|textarea)[\s\/>]/i,
startTag: /^</,
chars: /^[^<]/
};
// Detection has already happened when a reader is called.
var reader = {
comment: function() {
var index = stream.indexOf('-->');
if ( index >= 0 ) {
return {
content: stream.substr(4, index-1),
length: index + 3
};
}
},
endTag: function() {
var match = stream.match( endTag );
if ( match ) {
return {
tagName: match[1],
length: match[0].length
};
}
},
atomicTag: function() {
var start = reader.startTag();
if(start) {
var rest = stream.slice(start.length);
// for optimization, we check first just for the end tag
if(rest.match(new RegExp('<\/\\s*' + start.tagName + '\\s*>', 'i'))) {
// capturing the content is inefficient, so we do it inside the if
var match = rest.match(new RegExp('([\\s\\S]*?)<\/\\s*' + start.tagName + '\\s*>', 'i'));
if(match) {
// good to go
return {
tagName: start.tagName,
attrs: start.attrs,
content: match[1],
length: match[0].length + start.length
};
}
}
}
},
startTag: function() {
var endTagIndex = stream.indexOf('>');
if(endTagIndex === -1) {
return null; //avoid the match statement if there will be no match
}
var match = stream.match( startTag );
if ( match ) {
var attrs = {};
var booleanAttrs = {};
var rest = match[2];
match[2].replace(attr, function(match, name) {
if (!(arguments[2] || arguments[3] || arguments[4] || arguments[5])) {
attrs[name] = null;
} else if (arguments[5]) {
attrs[arguments[5]] = '';
booleanAttrs[name] = true;
} else {
var value = arguments[2] || arguments[3] || arguments[4] ||
fillAttr.test(name) && name || '';
attrs[name] = unescapeHTMLEntities(value);
}
rest = rest.replace(match, '');
});
return {
tagName: match[1],
attrs: attrs,
booleanAttrs: booleanAttrs,
rest: rest,
unary: !!match[3],
length: match[0].length
};
}
},
chars: function() {
var index = stream.indexOf('<');
return {
length: index >= 0 ? index : stream.length
};
}
};
var readToken = function() {
// Enumerate detects in order
for (var type in detect) {
if(detect[type].test(stream)) {
if(DEBUG) { console.log('suspected ' + type); }
var token = reader[type]();
if(token) {
if(DEBUG) { console.log('parsed ' + type, token); }
// Type
token.type = token.type || type;
// Entire text
token.text = stream.substr(0, token.length);
// Update the stream
stream = stream.slice(token.length);
return token;
}
return null;
}
}
};
var readTokens = function(handlers) {
var tok;
while((tok = readToken())) {
// continue until we get an explicit "false" return
if(handlers[tok.type] && handlers[tok.type](tok) === false) {
return;
}
}
};
var clear = function() {
var rest = stream;
stream = '';
return rest;
};
var rest = function() {
return stream;
};
if(options.fix) {
(function() {
// Empty Elements - HTML 4.01
var EMPTY = /^(AREA|BASE|BASEFONT|BR|COL|FRAME|HR|IMG|INPUT|ISINDEX|LINK|META|PARAM|EMBED)$/i;
// Elements that you can| intentionally| leave open
// (and which close themselves)
var CLOSESELF = /^(COLGROUP|DD|DT|LI|OPTIONS|P|TD|TFOOT|TH|THEAD|TR)$/i;
var stack = [];
stack.last = function() {
return this[this.length - 1];
};
stack.lastTagNameEq = function(tagName) {
var last = this.last();
return last && last.tagName &&
last.tagName.toUpperCase() === tagName.toUpperCase();
};
stack.containsTagName = function(tagName) {
for(var i = 0, tok; (tok = this[i]); i++) {
if(tok.tagName === tagName) {
return true;
}
}
return false;
};
var correct = function(tok) {
if(tok && tok.type === 'startTag') {
// unary
tok.unary = EMPTY.test(tok.tagName) || tok.unary;
tok.html5Unary = !/\/>$/.test(tok.text);
}
return tok;
};
var readTokenImpl = readToken;
var peekToken = function() {
var tmp = stream;
var tok = correct(readTokenImpl());
stream = tmp;
return tok;
};
var closeLast = function() {
var tok = stack.pop();
// prepend close tag to stream.
prepend('</'+tok.tagName+'>');
};
var handlers = {
startTag: function(tok) {
var tagName = tok.tagName;
// Fix tbody
if(tagName.toUpperCase() === 'TR' && stack.lastTagNameEq('TABLE')) {
prepend('<TBODY>');
prepareNextToken();
} else if(options.fix_selfClose && CLOSESELF.test(tagName) && stack.containsTagName(tagName)) {
if(stack.lastTagNameEq(tagName)) {
closeLast();
} else {
prepend('</'+tok.tagName+'>');
prepareNextToken();
}
} else if (!tok.unary) {
stack.push(tok);
}
},
endTag: function(tok) {
var last = stack.last();
if(last) {
if(options.fix_tagSoup && !stack.lastTagNameEq(tok.tagName)) {
// cleanup tag soup
closeLast();
} else {
stack.pop();
}
} else if (options.fix_tagSoup) {
// cleanup tag soup part 2: skip this token
skipToken();
}
}
};
var skipToken = function() {
// shift the next token
readTokenImpl();
prepareNextToken();
};
var prepareNextToken = function() {
var tok = peekToken();
if(tok && handlers[tok.type]) {
handlers[tok.type](tok);
}
};
// redefine readToken
readToken = function() {
prepareNextToken();
return correct(readTokenImpl());
};
})();
}
return {
append: append,
readToken: readToken,
readTokens: readTokens,
clear: clear,
rest: rest,
stack: stack
};
}
htmlParser.supports = supports;
htmlParser.tokenToString = function(tok) {
var handler = {
comment: function(tok) {
return '<!--' + tok.content;
},
endTag: function(tok) {
return '</'+tok.tagName+'>';
},
atomicTag: function(tok) {
if(DEBUG) { console.log(tok); }
return handler.startTag(tok) +
tok.content +
handler.endTag(tok);
},
startTag: function(tok) {
var str = '<'+tok.tagName;
for (var key in tok.attrs) {
str += ' '+key;
var val = tok.attrs[key];
if (typeof tok.booleanAttrs == 'undefined' || typeof tok.booleanAttrs[key] == 'undefined') {
// escape quotes
str += '="'+(val ? val.replace(/(^|[^\\])"/g, '$1\\\"') : '')+'"';
}
}
if (tok.rest) {
str += tok.rest;
}
return str + (tok.unary && !tok.html5Unary ? '/>' : '>');
},
chars: function(tok) {
return tok.text;
}
};
return handler[tok.type](tok);
};
htmlParser.escapeAttributes = function(attrs) {
var escapedAttrs = {};
// escape double-quotes for writing html as a string
for(var name in attrs) {
var value = attrs[name];
escapedAttrs[name] = value && value.replace(/(^|[^\\])"/g, '$1\\\"');
}
return escapedAttrs;
};
for(var key in supports) {
htmlParser.browserHasFlaw = htmlParser.browserHasFlaw || (!supports[key]) && key;
}
this.htmlParser = htmlParser;
})();