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

Commit ddb8081

Browse files
committedApr 2, 2014
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 ccfa72d commit ddb8081

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
@@ -138,6 +138,7 @@
138138
"JQLitePrototype": false,
139139
"addEventListenerFn": false,
140140
"removeEventListenerFn": false,
141+
"jqLiteIsTextNode": false,
141142

142143
/* apis.js */
143144
"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
@@ -1259,7 +1258,11 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
12591258

12601259
if (directive.replace) {
12611260
replaceDirective = directive;
1262-
$template = directiveTemplateContents(directiveValue);
1261+
if (jqLiteIsTextNode(directiveValue)) {
1262+
$template = [];
1263+
} else {
1264+
$template = jqLite(directiveValue);
1265+
}
12631266
compileNode = $template[0];
12641267

12651268
if ($template.length != 1 || compileNode.nodeType !== 1) {
@@ -1658,27 +1661,6 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
16581661
}
16591662

16601663

1661-
function directiveTemplateContents(template) {
1662-
var type;
1663-
template = trim(template);
1664-
if ((type = TABLE_CONTENT_REGEXP.exec(template))) {
1665-
type = type[1].toLowerCase();
1666-
var table = jqLite('<table>' + template + '</table>');
1667-
if (/(thead|tbody|tfoot)/.test(type)) {
1668-
return table.children(type);
1669-
}
1670-
table = table.children('tbody');
1671-
if (type === 'tr') {
1672-
return table.children('tr');
1673-
}
1674-
return table.children('tr').contents();
1675-
}
1676-
return jqLite('<div>' +
1677-
template +
1678-
'</div>').contents();
1679-
}
1680-
1681-
16821664
function compileTemplateUrl(directives, $compileNode, tAttrs,
16831665
$rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
16841666
var linkQueue = [],
@@ -1703,7 +1685,11 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
17031685
content = denormalizeTemplate(content);
17041686

17051687
if (origAsyncDirective.replace) {
1706-
$template = directiveTemplateContents(content);
1688+
if (jqLiteIsTextNode(content)) {
1689+
$template = [];
1690+
} else {
1691+
$template = jqLite(content);
1692+
}
17071693
compileNode = $template[0];
17081694

17091695
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)