-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathhtml_validator.js
686 lines (649 loc) · 30.6 KB
/
html_validator.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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
//HTML Validator By Peter West
//Original parser By John Resig (ejohn.org) http://ejohn.org/blog/pure-javascript-html-parser/
//and Erik Arvidsson (Mozilla Public License) http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
(function($) {
$.fn.outerHtml = function() {
if (this.length == 0) return false;
var elem = this[0], name = elem.tagName.toLowerCase();
if (elem.outerHTML) return elem.outerHTML;
var attrs = $.map(elem.attributes, function(i) { return i.name+'="'+i.value+'"'; });
return "<"+name+(attrs.length > 0 ? " "+attrs.join(" ") : "")+">"+elem.innerHTML+"</"+name+">";
};
})(jQuery);
(function($) {
var fn = {
englishList: function(conjunction) {
var last = this.length - 1;
return this.slice(0, last).join(", ")+(last > 0 ? (conjunction || " and ") : "")+(this[last] || "");
},
groupUnique: function() {
var last, different;
return this.call(select, function(item) { different = last != item; last = item; return different; });
},
draw: function(indent) {
var text = "";
if (this.unopened) text += (indent||"") + "</"+this.name+">\n";
else {
text += (indent||"")+(this.implicit ? "{<"+this.name+">}" : "<"+this.name+">")+"\n";
if (this.children) {
text += this.children.call(map, function(child) { return child.call(fn.draw, (indent||"")+" "); }).join("");
}
if (!this.unary && !this.selfClosed) {
text += (indent||"")+(this.closed ? "</"+this.name+">\n" : "{</"+this.name+">}\n");
}
}
return text;
},
reassemble: function() {
var innerHtml = (this.children || []).call(map, method, fn.reassemble).join("");
return (this.html || "")+innerHtml+(this.endHtml || "");
},
stack: function() { return this.parent ? this.parent.call(fn.stack).concat([this]) : [this]; },
combineLists: function(a,b) { return b ? (b.slice(0,1) == "+" ? a+","+b.slice(1) : b) : a.slice(0); },
countNewlines: function() { return (this.match(/(\r\n|\n|\r)/g) || []).length; },
htmlTags: function() {
return this.call(select, function(tag) { return tag.name != "#text" && tag.name != "#comment"; });
},
computedDescendents: function(tags) {
var allowed = {}, banned = {};
this.call(fn.stack).call(map, function(element) {
if (tags[element.name]) {
allowed.call(merge, tags[element.name].allowed_descendents || {});
banned.call(merge, tags[element.name].banned_descendents || {});
}
});
if (tags[this.name]) {
allowed = allowed.call(merge, tags[this.name].allowed_children || {});
}
banned.call(each, function(item, name) { if (allowed[name]) delete allowed[name]; });
return allowed;
},
expandList: function(groups) {
if (!is("String", this)) return this;
var list = this.split(",").call(hash, numbered);
list.call(each, function(value, name) {
if (groups[name]) {
delete list[name];
var group = groups[name].call(fn.expandList, groups);
group.call(each, function(item, tag) { this[tag] = value; });
list.call(merge, group);
}
});
return list;
},
formatMessage: function(data) {
var matchTag = /(<)(([^<>\s]+)[^<>]*)>/g;
var matchAttr = /(\[)(([^\[\]\s]+)[^\[\]]*)\]/g;
var inTag = function() { return "<"+this+">"; };
var insertItem = function(match, type, options, name, position, string) {
if (data[name] === undefined) return match;
var list = data[name].join;
var separator = (options.match(/\s+\S+\s+/) || [" and "])[0];
if (type == "<") {
return list ? data[name].call(map, method, inTag).call(fn.englishList, separator) : data[name].call(inTag);
}
if (type == "[") {
return list ? data[name].call(fn.englishList, separator) : data[name];
}
};
return this.replace(matchTag, insertItem).replace(matchAttr, insertItem);
},
contextualiseMessages: function() {
var messages = this.sort(function(a, b) { return a.line - b.line; });
return messages.call(map,
function(message) { return message.message+" on line "+message.line; }
).join("\n");
},
findLines: function(currentLine) {
this.line = currentLine;
if (this.html) { currentLine += this.html.call(fn.countNewlines); }
if (this.children) this.children.call(map,
function(child) { currentLine = child.call(fn.findLines, currentLine); }
);
if (this.endHtml) currentLine += this.endHtml.call(fn.countNewlines);
return currentLine;
},
runRegex: function(html, regex, fn) {
var obj = this;
html.replace(regex, function() {
fn.apply(obj, arguments);
});
}
};
$.htmlValidator = {
fn: fn,
doctypes: [],
doctype: function(name) {
return this.doctypes.call(select, function(doctype) {
return doctype.name == name;
})[0];
},
addSpec: function(spec) {
var doctypes = [];
(new spec(this.baseDoctype)).call(each, function(doctype) {
doctypes.push(doctype.compute());
});
this.doctypes = this.doctypes.concat(doctypes);
},
parseSettings: function(settings) {
settings = settings || {};
if (!settings.doctype || !settings.doctype.validate) {
settings.doctype = (this.doctype(settings.doctype) || this.doctypes[0]);
}
if (!settings.html || settings.html.jquery) {
settings.html = (settings.html || $("html")).outerHtml();
}
return settings;
},
parse: function(settings) {
settings = this.parseSettings(settings);
return this.parser.run(settings);
},
validate: function(settings) {
settings = this.parseSettings(settings);
return settings.doctype.validate(this.parse(settings));
},
baseDoctype: {
groups: {},
attrs: {},
rulesets: {},
extend: function(spec) {
this.extendGroups(spec);
this.extendAttrs(spec);
this.extendRulesets(spec);
return this.copyMethods(spec);
},
resetHashes: function() {
this.groups = {};
this.attrs = {};
this.rulesets = {};
},
extendGroups: function(spec) {
this.groups.call(each, function(groups, type) {
spec.groups[type] = spec.groups[type] || {};
groups.call(each, function(group, name) {
spec.groups[type][name] = fn.combineLists(group, spec.groups[type][name]);
});
});
},
extendAttrs: function(spec) {
spec.attrs = spec.attrs || {};
this.attrs.call(each, function(attrs, type) {
spec.attrs[type] = (attrs || []).concat(spec.attrs[type] || []);
});
},
extendRulesets: function(spec) {
spec.rulesets = spec.rulesets || {};
this.rulesets.call(each, function(rulesets, name) {
var cloned_rulesets = (rulesets.call(map, method, clone) || []);
spec.rulesets[name] = cloned_rulesets.concat(spec.rulesets[name] || []);
});
},
copyMethods: function(spec) {
return this.call(clone).call(merge, spec);
},
compute: function() {
if (this.computed) return;
this.computed = true;
//Expand groups
this.groups.call(each, function(groupType, type) {
groupType.call(each, function(group, name) {
groupType[name] = group.call(fn.expandList, groupType);
});
});
var groups = this.groups;
//Expand attrs
this.attrs.call(each, function(attrs) {
attrs.call(map, function(rule) {
rule.attrs = rule.attrs.call(fn.expandList, groups.attrs);
rule.attrs.call(each, function(attr, name) {
rule.attrs[name] = rule.values;
});
if (rule.include) rule.include = rule.include.call(fn.expandList, groups.tags);
if (rule.exclude) rule.exclude = rule.exclude.call(fn.expandList, groups.tags);
});
});
//Expand rulesets
this.rulesets.call(each, function(ruleset, name) {
ruleset.call(map, function(rules) {
rules.call(each, function(rule, type) {
rules[type] = rule.call(fn.expandList, groups.tags, true);
});
});
});
//Initialise tags
var tags = this.tags = groups.tags.all.call(clone);
tags.call(each, function(tag, name) {
tags[name] = {};
});
//Populate rules into tags, special case for allowed_children
this.rulesets.call(each, function(rules, ruleName) {
rules.call(map, function(rule, i) {
rule.tags.call(each, function(tag, name) {
tags[name][ruleName] = tags[name][ruleName] || {};
rule.innerTags.call(each, function(child, childName) {
tags[name][ruleName][childName] = child;
if (ruleName == "allowed_children" && tags[childName]) {
tags[childName].allowed_parents = tags[childName].allowed_parents || {};
tags[childName].allowed_parents[name] = true;
}
});
});
});
});
//Populate all, allowed and required attributes into tags
var attrGroups = this.attrs;
tags.call(each, function(tag, name) {
attrGroups.call(each, function(attrs, type) {
tag.attrs = tag.attrs || {};
tag.attrs[type] = tag.attrs[type] || {};
attrs.call(map, function(attr) {
if ((attr.include && attr.include[name]) || (attr.exclude && !attr.exclude[name])) {
tag.attrs[type] = tag.attrs[type].call(merge, attr.attrs);
}
});
});
tag.attrs["all"] = tag.attrs["optional"].call(merge, tag.attrs["required"]);
});
//Calculate implicit children
groups.tags.implicit.call(each, function(tag, name) {
if (tags[name].allowed_parents) {
tags[name].allowed_parents.call(each, function(parent, parentName) {
tags[parentName].implicit_children = tags[parentName].implicit_children || {};
var position = (tags[parentName].exact_children || tags[parentName].ordered_children)[name];
tags[parentName].implicit_children[position] = name;
});
}
});
return this
},
validate: function(doc) {
var doctype = this, errors = [];
doctype.rules.rules.call(each, function(rule, name) {
doc.all.call(map, function(tag) {
var tag_errors = tag.call(rule, doctype, doc, doctype.rulesets[name] || []);
tag_errors.call(map, function(error, i) {
tag_errors[i].message = doctype.rules.messages[name].call(fn.formatMessage, error);
});
errors = errors.concat(tag_errors);
});
});
return errors.call(fn.contextualiseMessages);
},
rules: {
attribute_values: {
formats: {
cdata: /^[\s\S]*$/,
number: /^\s*[0-9]+\s*$/,
length: /^\s*[0-9]+%?\s*/,
multi_length: /^\s*[0-9]+[%*]?\s*/,
name: /^\s*[a-z][a-z0-9-_:.]*\s*$/i,
names: /^\s*(([a-z][a-z0-9-_:.]*)|\s+)+$/i
},
messages: {
number: "an integer number",
length: "an integer number or percentage",
multi_length: "an integer number, percentage or relative length (e.g. 3*)",
name: "an start with a letter and can contain only letters, numbers and the following: .-_:",
names:
"a list of items separated with spaces. Each item must start with a letter and can contain only letters,"+
"numbers and the following: .-_:"
}
},
rules: {
allowed_attributes: function(doctype, doc) {
var tag = this, attrs = [];
var all = ((doctype.tags[tag.name] && doctype.tags[tag.name].attrs.all) || {});
(tag.attrs || []).call(map, function(attr) {
if (!all[attr.name]) attrs.push(attr.name);
});
if (attrs.length > 0) return [{tag: tag.name, attr: attrs, s: attrs.length > 1 ? "s" : "", line: tag.line}];
return [];
},
allowed_attribute_values: function(doctype, doc) {
var tag = this, errors = [], format, message, formatName;
var inQuote = function() { return "'"+this+"'"; };
(this.attrs || []).call(map, function(attr) {
if (!doctype.tags[tag.name]) return;
var values = (doctype.tags[tag.name].attrs.all[attr.name] || "");
if (values == "#self") {
format = attr.name;
message = attr.name.call(inQuote);
}
else if (values.match("#")) {
formatName = values.replace("#", "");
format = doctype.rules.attribute_values.formats[formatName];
message = doctype.rules.attribute_values.messages[formatName];
}
else if (values.match(/\S/)) {
values = values.split(",");
format = new RegExp("^("+values.join("|")+")$");
message = (values.length > 2 ? "one of " : "")+values.call(map, method, inQuote).call(fn.englishList, " or ");
}
if (format && !(attr.value || "").match(format)) {
errors.push({tag: tag.name, attr: attr.name, format: message, line: tag.line});
}
});
return errors;
},
allowed_tags: function(doctype, doc) {
if (doctype.groups.tags.all[this.name] || doctype.groups.tags.pseudo[this.name]) return [];
return [{ tag: this.name, line: this.line }];
},
allowed_children: function(doctype, doc) {
var tag = this, errors = [];
var allowedDescendents = tag.call(fn.computedDescendents, doctype.tags);
(tag.children || []).call(fn.htmlTags).call(map, function(child) {
if (!allowedDescendents[child.name]) errors.push({parent: tag.name, child: child.name, line: child.line});
});
return errors;
},
exact_children: function(doctype, doc, sets) {
var tag = this, errors = [], children = (tag.children || []).call(fn.htmlTags);
sets.call(map, function(set) {
if (set.tags[tag.name]) {
if (children.call(select, function(child, i) { return i != set.innerTags[child.name] - 1; }).length > 0) {
errors.push({
parent: tag.name, line: tag.line,
required: set.innerTags.call(keys),
child: tag.children.call(map, get, "name"),
});
}
}
});
return errors;
},
exclusive_children: function(doctype, doc, sets) {
var tag = this, errors = [], children = (tag.children || []).call(fn.htmlTags);
sets.call(map, function(set) {
if (set.tags[tag.name])
if (children.call(select, function(child) { return set.innerTags[child.name]; }).call(map, function(item) { return item.name; }).call(hash, numbered).call(keys).length > 1)
errors.push({parent: tag.name, child: set.innerTags.call(map, get, "name"), line: tag.line });
});
return errors;
},
not_empty: function(doctype, doc) {
return (doctype.groups.tags.not_empty[this.name] && (this.children || []).call(fn.htmlTags).length == 0) ? [{tag: this.name, line: this.line}] : [];
},
not_opened: function(doctype, doc) {
return (this.unopened) ? [{tag: this.name, line: this.line}] : [];
},
not_optionally_closed: function(doctype, doc) {
return (!doctype.groups.tags.close_optional[this.name] && !doctype.groups.tags.unary[this.name] && !this.closed) ? [{tag: this.name, line: this.line}] : [];
},
ordered_children: function(doctype, doc, sets) {
var tag = this, errors = [], position, error;
sets.call(map, function(set) {
if (set.tags[tag.name]) {
error = false;
position = 1;
(tag.children || []).call(fn.htmlTags).call(map, function(child, i) {
if (set.innerTags[child.name] >= position) position = set.innerTags[child.name];
else { error = true; }
});
if (error) errors.push({
tag: tag.name,
ordered: set.innerTags.call(keys),
child: tag.children.call(map, get, "name").call(fn.groupUnique),
line: tag.line
});
}
});
return errors;
},
required_attributes: function(doctype, doc) {
var tag = this, attrs = [];
((doctype.tags[tag.name] && doctype.tags[tag.name].attrs.required) || {}).call(each, function(required, name) {
if (!tag.attrs || !tag.attrs.call(map, function(item) { return item.name; }).call(hash, numbered)[name]) { attrs.push(name); }
});
if (attrs.length > 0) return [{
tag: tag.name,
attr: attrs.call(values),
s: attrs.call(values).length > 1 ? "s" : "",
line: tag.line
}];
return [];
},
required_first_child: function(doctype, doc, sets) {
var tag = this, errors = [];
sets.call(map, function(set) {
if (set.tags[tag.name]) {
if ((tag.children || []).call(fn.htmlTags).length > 0) {
tag.children.call(fn.htmlTags).call(map, function(child, i) {
if (i == 0 && !set.innerTags[child.name])
errors.push({tag: tag.name, child: set.innerTags.call(keys)[0], line: tag.line});
});
}
else errors.push({tag: tag.name, child: set.innerTags.call(keys)[0], line: tag.line});
}
});
return errors;
},
required_at_least_one_child: function(doctype, doc, sets) {
var tag = this, errors = [];
sets.call(map, function(set) {
if (set.tags[tag.name])
if ((tag.children || []).call(select, function(child) { return set.innerTags[child.name]; }).call(map, get, "name").call(hash, numbered).call(keys).length < 1)
errors.push({parent: tag, child: set.innerTags, line: tag.line});
});
return errors;
},
required_children: function(doctype, doc, sets) {
var tag = this, errors = [];
sets.call(map, function(set) {
if (set.tags[tag.name]) {
set.innerTags.call(each, function(innerTag, name) {
var count = 0;
(tag.children || []).call(map, function(child) {
if (child.name == name) count++;
});
if (count < 1) errors.push({parent: tag.name, child: name, count: count, line: tag.line});
});
}
});
return errors;
},
unary: function(doctype, doc) {
return (doctype.groups.tags.unary[this.name] && this.closed) ? [{tag: this.name, line: this.line}] : [];
},
unique_children: function(doctype, doc, sets) {
var tag = this, errors = [];
sets.call(map, function(set) {
if (set.tags[tag.name]) {
set.innerTags.call(each, function(innerTag, name) {
var count = 0;
(tag.children || []).call(map, function(child) {
if (child.name == name) count++;
});
if (count > 1) errors.push({parent: tag.name, child: name, count: count, line: tag.line});
});
}
});
return errors;
}
},
messages: {
allowed_attributes: "<tag> can't have attribute[s] [attr or attr]",
allowed_attribute_values: "<tag> element's attribute [attr] must be [format]",
allowed_tags: "<tag> isn't a valid element",
allowed_children: "<parent> can't contain <child>", //make this collect all invalid children
exact_children: "<parent> must contain exactly <required and required> but currently contains <child and child>",
exclusive_children: "<parent> can't contain both <child and child>",
not_empty: "<tag> can't be empty",
not_opened: "<tag> must have an opening tag",
not_optionally_closed: "<tag> must have a closing tag",
ordered_children: "The contents of <tag> must be ordered <ordered then ordered> but are currently ordered <child then child>",
required_attributes: "<tag> must have attribute[s] [attr and attr]",
required_first_child: "The contents of <tag> must start with <child>",
required_at_least_one_child: "<tag> must contain at least one of <child or child>",
required_children: "<parent> must contain <child>",
unary: "<tag> must not have a closing tag",
unique_children: "<parent> can't contain more than one <child>"
}
}
},
parser: {
regex: {
startTag: /<(\w+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,
endTag: /<\/(\w+)>/, //Removed "" from regex end, need to check with John Resig
attr: /(\w+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g
},
run: function(settings) {
var parser = this;
parser.doctype = settings.doctype;
var lastHtml = parser.html = settings.html;
parser.currentElement = parser.doc = { name: '#root', children: [], all: [], closed: true };
parser.doc.all.push(parser.doc);
var comment, startTag, endTag;
while (parser.html) {
if (parser.currentElement && parser.doctype.groups.tags.cdata_elements[parser.currentElement.name]) {
//Removed "[^>]*" from regex end, need to check with John Resig
parser.html = parser.html.replace(new RegExp("(.*)<\/"+parser.currentElement.name+">"), function(all, text) {
//Need more robust solution, and logging of whether cdata tag is used
text = text.replace(/<!--(.*?)-->/g, "$1").replace(/<!\[CDATA\[(.*?)]]>/g, "$1");
parser.currentElement.children.push({name: '#text', value: text, unary: true, html: all});
return "";
});
parser.parseEndTag("", parser.currentElement.name);
}
else if ((comment = parser.html.indexOf("<!--")) == 0) {
var end = parser.html.indexOf("-->");
parser.currentElement.children.push({ name: "#comment", value: parser.html.substring(4, end), html: parser.html.substring(0, end + 3), closed: end != -1 });
parser.html = end == -1 ? "" : parser.html.substring(end + 3);
}
else if ((endTag = parser.html.search(parser.regex.endTag)) == 0) {
parser.call(fn.runRegex, parser.html, parser.regex.endTag, parser.parseEndTag);
parser.html = parser.html.substring(parser.html.match(parser.regex.endTag)[0].length);
}
else if ((startTag = parser.html.search(parser.regex.startTag)) == 0) {
parser.call(fn.runRegex, parser.html, parser.regex.startTag, parser.parseStartTag);
parser.html = parser.html.substring(parser.html.match(parser.regex.startTag)[0].length);
}
//If no tag is immediately found, find the distance nearest tag, and take everything up to that point
else {
var index = ([comment, startTag, endTag].call(select, function(match) { return match >= 0; }) || []).call(min);
var text = index < 0 ? parser.html : parser.html.substring(0, index);
parser.currentElement.children.push({name: '#text', value: text, html: text, unary: true});
parser.html = index < 0 ? "" : parser.html.substring(index);
}
if (parser.html == lastHtml) throw "Parse Error: " + parser.html;
lastHtml = parser.html;
}
parser.parseEndTag("");
parser.doc.call(fn.findLines, 1);
return parser.doc;
},
parseStartTag: function(html, tag, rest, selfClosed) {
var parser = this;
var prev = parser.currentElement.children.call(fn.htmlTags).call(last);
//Checks for implicit child elements
if (parser.doctype.tags[parser.currentElement.name] && parser.doctype.tags[parser.currentElement.name].implicit_children) {
var implicit = false;
parser.doctype.tags[parser.currentElement.name].implicit_children.call(each, function(implicitChild, position) {
if (implicit) return;
//Looks for an implied child element with an exact position
if (parser.doctype.tags[parser.currentElement.name].exact_children) {
if (implicitChild != tag && parser.currentElement.children.call(fn.htmlTags).length + 1 == position) {
implicit = implicitChild;
}
}
//Looks for an implied child element within a specific order
else if (parser.doctype.tags[parser.currentElement.name].ordered_children) {
var orderedChildren = parser.doctype.tags[parser.currentElement.name].ordered_children;
var children = parser.currentElement.children.call(fn.htmlTags);
var invalidBeforeTags = children.call(select, function(child) { return orderedChildren[child] > position; }).length;
if (invalidBeforeTags == 0 && (!orderedChildren[tag] || orderedChildren[tag] > position)) {
implicit = implicitChild;
}
}
});
//Adds the implied element if one has been found, restarts the parseStartTag process for this element
if (implicit && (!prev || prev.name+"" != implicit || !prev.implicit)) {
var element = {name: implicit, implicit: true, attrs: [], parent: parser.currentElement, unary: false, children: [], html: ''};
parser.currentElement.children.push(element);
parser.doc.all.push(element);
parser.currentElement = element;
return parser.parseStartTag(html, tag, rest, selfClosed);
}
}
//Closes the current element if it is optionally closed and the new element doesn't belong inside it,
//restarts the parseStartTag process for this element
if (parser.doctype.groups.tags.close_optional[parser.currentElement.name]) {
if (!parser.currentElement.call(parser.allowedChildren, parser.doctype)[tag] && !parser.doctype.groups.tags.last_child[parser.currentElement.name]) {
parser.parseEndTag("", parser.currentElement.name);
return parser.parseStartTag(html, tag, rest, selfClosed);
}
}
var unary = parser.doctype.groups.tags.unary[tag] || !!selfClosed;
var attrs = [], values = [];
var value = "";
//Parse attributes and their values
rest.replace(parser.regex.attr, function(match, name) {
values = arguments.call([].slice, 2, 5).concat([parser.doctype.tags[tag].attrs.all[name] ? name : ""]);
value = values.call(select, function(value) { return value != null; })[0];
attrs.push({ name: name, value: value, escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') });
});
var element = {
name: tag, implicit: !html, attrs: attrs, parent: parser.currentElement,
unary: unary, selfClosed: !!selfClosed, children: [], html: html
};
parser.currentElement.children.push(element);
parser.doc.all.push(element);
if (!unary) parser.currentElement = element;
},
parseEndTag: function(html, tag) {
var parser = this;
var index = tag ? (parser.currentElement.call(fn.stack).call(map, get, "name").call(hash, numbered)[tag] - 1) : 0;
var endedTags = index >= 0 ? parser.currentElement.call(fn.stack).slice(index) : [];
//Deals with a number of existing elements being closed
if (endedTags.length > 0) {
var initial = parser.currentElement;
endedTags.call(each, function(tag) {
parser.currentElement = tag;
var parent = tag.parent;
//Checks for implicit elements which have not been added because they don't have any content
while (parser.currentElement !== parent) {
var currentTagRules = parser.doctype.tags[parser.currentElement.name];
if (currentTagRules && currentTagRules.implicit_children) {
var element = false;
currentTagRules.implicit_children.call(each, function(implicit) {
if (!element && parser.currentElement.children.call(select, function(c) { return c.name+"" == implicit; }).length == 0) {
element = { name: implicit, implicit: true, children: [], parent: parser.currentElement, html: '' };
parser.currentElement.children.push(element);
parser.doc.all.push(element);
parser.currentElement = element;
}
});
if (!element) parser.currentElement = parser.currentElement.parent;
}
else parser.currentElement = parser.currentElement.parent;
}
});
parser.currentElement = initial;
var endedTag = endedTags[0];
if (html) {
endedTag.closed = true;
endedTag.endHtml = html;
}
parser.currentElement = endedTag.parent;
}
//Deals with an unopened element being closed
else {
var element = {name: tag, unopened: true, closed: true, endHtml: html};
parser.currentElement.children.push(element);
parser.doc.all.push(element);
}
},
//Computes allowed child elements based on allowed_children and allowed_descendents rules,
//ignores banned descendents in order to parse more robustly
allowedChildren: function(doctype) {
var obj = {};
this.call(fn.stack).call(map, function(tag) {
obj.call(merge, doctype.tags[tag.name].allowed_descendents || {});
});
obj.call(merge, doctype.tags[this.name].allowed_children || {});
return obj;
}
}
};
})(jQuery);