Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 4ea57e7

Browse files
committed
refactor(jqLite): make HTML-parsing constructor more robust
Previously, the jqLite constructor was limited and would be unable to circumvent many of the HTML5 spec's "allowed content" policies for various nodes. This led to complicated and gross hacks around this in the HTML compiler. This change refactors these hacks by simplifying them, and placing them in jqLite rather than in $compile, in order to better support these things, and simplify code. While the new jqLite constructor is still not even close to as robust as jQuery, it should be more than suitable enough for the needs of the framework, while adding minimal code. Closes #6941 Closes #6958
1 parent 6e420ff commit 4ea57e7

File tree

4 files changed

+118
-33
lines changed

4 files changed

+118
-33
lines changed

src/.jshintrc

+1
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@
135135
"JQLitePrototype": false,
136136
"addEventListenerFn": false,
137137
"removeEventListenerFn": false,
138+
"jqLiteIsTextNode": false,
138139

139140
/* apis.js */
140141
"hashKey": false,

src/jqLite.js

+76-8
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,81 @@ function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArgu
179179
}
180180
}
181181

182+
var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
183+
var HTML_REGEXP = /<|&#?\w+;/;
184+
var TAG_NAME_REGEXP = /<([\w:]+)/;
185+
var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
186+
187+
var wrapMap = {
188+
'option': [1, '<select multiple="multiple">', '</select>'],
189+
190+
'thead': [1, '<table>', '</table>'],
191+
'col': [2, '<table><colgroup>', '</colgroup></table>'],
192+
'tr': [2, '<table><tbody>', '</tbody></table>'],
193+
'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
194+
'_default': [0, "", ""]
195+
};
196+
197+
wrapMap.optgroup = wrapMap.option;
198+
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
199+
wrapMap.th = wrapMap.td;
200+
201+
function jqLiteIsTextNode(html) {
202+
return !HTML_REGEXP.test(html);
203+
}
204+
205+
function jqLiteBuildFragment(html, context) {
206+
var elem, tmp, tag, wrap,
207+
fragment = context.createDocumentFragment(),
208+
nodes = [], i;
209+
210+
if (jqLiteIsTextNode(html)) {
211+
// Convert non-html into a text node
212+
nodes.push(context.createTextNode(html));
213+
} else {
214+
// Convert html into DOM nodes
215+
tmp = tmp || fragment.appendChild(context.createElement("div"));
216+
tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
217+
wrap = wrapMap[tag] || wrapMap._default;
218+
tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
219+
220+
// Descend through wrappers to the right content
221+
i = wrap[0];
222+
while (i--) {
223+
tmp = tmp.lastChild;
224+
}
225+
226+
nodes = concat(nodes, tmp.childNodes);
227+
228+
tmp = fragment.firstChild;
229+
tmp.textContent = "";
230+
}
231+
232+
// Remove wrapper from fragment
233+
fragment.textContent = "";
234+
fragment.innerHTML = ""; // Clear inner HTML
235+
forEach(nodes, function(node) {
236+
fragment.appendChild(node);
237+
});
238+
239+
return fragment;
240+
}
241+
242+
function jqLiteParseHTML(html, context) {
243+
context = context || document;
244+
var parsed;
245+
246+
if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
247+
return [context.createElement(parsed[1])];
248+
}
249+
250+
if ((parsed = jqLiteBuildFragment(html, context))) {
251+
return parsed.childNodes;
252+
}
253+
254+
return [];
255+
}
256+
182257
/////////////////////////////////////////////
183258
function JQLite(element) {
184259
if (element instanceof JQLite) {
@@ -195,14 +270,7 @@ function JQLite(element) {
195270
}
196271

197272
if (isString(element)) {
198-
var div = document.createElement('div');
199-
// Read about the NoScope elements here:
200-
// http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
201-
div.innerHTML = '<div>&#160;</div>' + element; // IE insanity to make NoScope elements work!
202-
div.removeChild(div.firstChild); // remove the superfluous div
203-
jqLiteAddNodes(this, div.childNodes);
204-
var fragment = jqLite(document.createDocumentFragment());
205-
fragment.append(this); // detach the elements from the temporary DOM div.
273+
jqLiteAddNodes(this, jqLiteParseHTML(element));
206274
} else {
207275
jqLiteAddNodes(this, element);
208276
}

src/ng/compile.js

+11-25
Original file line numberDiff line numberDiff line change
@@ -513,8 +513,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
513513
var hasDirectives = {},
514514
Suffix = 'Directive',
515515
COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
516-
CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/,
517-
TABLE_CONTENT_REGEXP = /^<\s*(tr|th|td|thead|tbody|tfoot)(\s+[^>]*)?>/i;
516+
CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/;
518517

519518
// Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
520519
// The assumption is that future DOM event attribute names will begin with
@@ -1256,7 +1255,11 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
12561255

12571256
if (directive.replace) {
12581257
replaceDirective = directive;
1259-
$template = directiveTemplateContents(directiveValue);
1258+
if (jqLiteIsTextNode(directiveValue)) {
1259+
$template = [];
1260+
} else {
1261+
$template = jqLite(directiveValue);
1262+
}
12601263
compileNode = $template[0];
12611264

12621265
if ($template.length != 1 || compileNode.nodeType !== 1) {
@@ -1655,27 +1658,6 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
16551658
}
16561659

16571660

1658-
function directiveTemplateContents(template) {
1659-
var type;
1660-
template = trim(template);
1661-
if ((type = TABLE_CONTENT_REGEXP.exec(template))) {
1662-
type = type[1].toLowerCase();
1663-
var table = jqLite('<table>' + template + '</table>');
1664-
if (/(thead|tbody|tfoot)/.test(type)) {
1665-
return table.children(type);
1666-
}
1667-
table = table.children('tbody');
1668-
if (type === 'tr') {
1669-
return table.children('tr');
1670-
}
1671-
return table.children('tr').contents();
1672-
}
1673-
return jqLite('<div>' +
1674-
template +
1675-
'</div>').contents();
1676-
}
1677-
1678-
16791661
function compileTemplateUrl(directives, $compileNode, tAttrs,
16801662
$rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
16811663
var linkQueue = [],
@@ -1700,7 +1682,11 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
17001682
content = denormalizeTemplate(content);
17011683

17021684
if (origAsyncDirective.replace) {
1703-
$template = directiveTemplateContents(content);
1685+
if (jqLiteIsTextNode(content)) {
1686+
$template = [];
1687+
} else {
1688+
$template = jqLite(content);
1689+
}
17041690
compileNode = $template[0];
17051691

17061692
if ($template.length != 1 || compileNode.nodeType !== 1) {

test/jqLiteSpec.js

+30
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,36 @@ describe('jqLite', function() {
9595
expect(fragment.length).toBe(1);
9696
expect(fragment[0].nodeType).toBe(11);
9797
});
98+
99+
100+
it('should allow construction of <option> elements', function() {
101+
var nodes = jqLite('<option>');
102+
expect(nodes.length).toBe(1);
103+
expect(nodes[0].nodeName.toLowerCase()).toBe('option');
104+
});
105+
106+
107+
// Special tests for the construction of elements which are restricted (in the HTML5 spec) to
108+
// being children of specific nodes.
109+
forEach([
110+
'caption',
111+
'colgroup',
112+
'col',
113+
'optgroup',
114+
'opt',
115+
'tbody',
116+
'td',
117+
'tfoot',
118+
'th',
119+
'thead',
120+
'tr'
121+
], function(name) {
122+
it('should allow construction of <$NAME$> elements'.replace('$NAME$', name), function() {
123+
var nodes = jqLite('<$NAME$>'.replace('$NAME$', name));
124+
expect(nodes.length).toBe(1);
125+
expect(nodes[0].nodeName.toLowerCase()).toBe(name);
126+
});
127+
});
98128
});
99129

100130
describe('_data', function() {

0 commit comments

Comments
 (0)