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

refactor(jqLite): make HTML-parsing constructor more robust (v1.2.x) #6963

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/.jshintrc
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@
"JQLitePrototype": false,
"addEventListenerFn": false,
"removeEventListenerFn": false,
"jqLiteIsTextNode": false,

/* apis.js */
"hashKey": false,
Expand Down
78 changes: 71 additions & 7 deletions src/jqLite.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,75 @@ function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArgu
}
}

var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
var HTML_REGEXP = /<|&#?\w+;/;
var TAG_NAME_REGEXP = /<([\w:]+)/;
var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;

var wrapMap = {
'option': [1, '<select multiple="multiple">', '</select>'],

'thead': [1, '<table>', '</table>'],
'col': [2, '<table><colgroup>', '</colgroup></table>'],
'tr': [2, '<table><tbody>', '</tbody></table>'],
'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
'_default': [0, "", ""]
};

wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;

function jqLiteIsTextNode(html) {
return !HTML_REGEXP.test(html);
}

function jqLiteBuildFragment(html, context) {
var elem, tmp, tag, wrap,
fragment = context.createDocumentFragment(),
nodes = [], i, j, jj;

if (jqLiteIsTextNode(html)) {
// Convert non-html into a text node
nodes.push(context.createTextNode(html));
} else {
tmp = fragment.appendChild(context.createElement('div'));
// Convert html into DOM nodes
tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
wrap = wrapMap[tag] || wrapMap._default;
tmp.innerHTML = '<div>&#160;</div>' +
wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
tmp.removeChild(tmp.firstChild);

// Descend through wrappers to the right content
i = wrap[0];
while (i--) {
tmp = tmp.lastChild;
}

for (j=0, jj=tmp.childNodes.length; j<jj; ++j) nodes.push(tmp.childNodes[j]);

tmp = fragment.firstChild;
tmp.textContent = "";
}

// Remove wrapper from fragment
fragment.textContent = "";
fragment.innerHTML = ""; // Clear inner HTML
return nodes;
}

function jqLiteParseHTML(html, context) {
context = context || document;
var parsed;

if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
return [context.createElement(parsed[1])];
}

return jqLiteBuildFragment(html, context);
}

/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
Expand All @@ -195,14 +264,9 @@ function JQLite(element) {
}

if (isString(element)) {
var div = document.createElement('div');
// Read about the NoScope elements here:
// http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
div.innerHTML = '<div>&#160;</div>' + element; // IE insanity to make NoScope elements work!
div.removeChild(div.firstChild); // remove the superfluous div
jqLiteAddNodes(this, div.childNodes);
jqLiteAddNodes(this, jqLiteParseHTML(element));
var fragment = jqLite(document.createDocumentFragment());
fragment.append(this); // detach the elements from the temporary DOM div.
fragment.append(this);
} else {
jqLiteAddNodes(this, element);
}
Expand Down
36 changes: 11 additions & 25 deletions src/ng/compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -513,8 +513,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
var hasDirectives = {},
Suffix = 'Directive',
COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/,
TABLE_CONTENT_REGEXP = /^<\s*(tr|th|td|thead|tbody|tfoot)(\s+[^>]*)?>/i;
CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/;

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

if (directive.replace) {
replaceDirective = directive;
$template = directiveTemplateContents(directiveValue);
if (jqLiteIsTextNode(directiveValue)) {
$template = [];
} else {
$template = jqLite(directiveValue);
}
compileNode = $template[0];

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


function directiveTemplateContents(template) {
var type;
template = trim(template);
if ((type = TABLE_CONTENT_REGEXP.exec(template))) {
type = type[1].toLowerCase();
var table = jqLite('<table>' + template + '</table>');
if (/(thead|tbody|tfoot)/.test(type)) {
return table.children(type);
}
table = table.children('tbody');
if (type === 'tr') {
return table.children('tr');
}
return table.children('tr').contents();
}
return jqLite('<div>' +
template +
'</div>').contents();
}


function compileTemplateUrl(directives, $compileNode, tAttrs,
$rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
var linkQueue = [],
Expand All @@ -1700,7 +1682,11 @@ function $CompileProvider($provide, $$sanitizeUriProvider) {
content = denormalizeTemplate(content);

if (origAsyncDirective.replace) {
$template = directiveTemplateContents(content);
if (jqLiteIsTextNode(content)) {
$template = [];
} else {
$template = jqLite(content);
}
compileNode = $template[0];

if ($template.length != 1 || compileNode.nodeType !== 1) {
Expand Down
30 changes: 30 additions & 0 deletions test/jqLiteSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,36 @@ describe('jqLite', function() {
expect(fragment.length).toBe(1);
expect(fragment[0].nodeType).toBe(11);
});


it('should allow construction of <option> elements', function() {
var nodes = jqLite('<option>');
expect(nodes.length).toBe(1);
expect(nodes[0].nodeName.toLowerCase()).toBe('option');
});


// Special tests for the construction of elements which are restricted (in the HTML5 spec) to
// being children of specific nodes.
forEach([
'caption',
'colgroup',
'col',
'optgroup',
'opt',
'tbody',
'td',
'tfoot',
'th',
'thead',
'tr'
], function(name) {
it('should allow construction of <$NAME$> elements'.replace('$NAME$', name), function() {
var nodes = jqLite('<$NAME$>'.replace('$NAME$', name));
expect(nodes.length).toBe(1);
expect(nodes[0].nodeName.toLowerCase()).toBe(name);
});
});
});

describe('_data', function() {
Expand Down
48 changes: 48 additions & 0 deletions test/ng/compileSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,14 @@ describe('$compile', function() {
replace: true,
template: '<tfoot><tr><td>TD</td></tr></tfoot>'
}));
directive('replaceWithOption', valueFn({
replace: true,
template: '<option>OPTION</option>'
}));
directive('replaceWithOptgroup', valueFn({
replace: true,
template: '<optgroup>OPTGROUP</optgroup>'
}));
}));


Expand Down Expand Up @@ -746,6 +754,20 @@ describe('$compile', function() {
}).not.toThrow();
expect(nodeName_(element)).toMatch(/tfoot/i);
}));

it('should support templates with root <option> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-option></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/option/i);
}));

it('should support templates with root <optgroup> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-optgroup></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/optgroup/i);
}));
});


Expand Down Expand Up @@ -867,6 +889,14 @@ describe('$compile', function() {
replace: true,
templateUrl: 'tfoot.html'
}));
directive('replaceWithOption', valueFn({
replace: true,
templateUrl: 'option.html'
}));
directive('replaceWithOptgroup', valueFn({
replace: true,
templateUrl: 'optgroup.html'
}));
}
));

Expand Down Expand Up @@ -1556,6 +1586,24 @@ describe('$compile', function() {
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/tfoot/i);
}));

it('should support templates with root <option> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('option.html', '<option>OPTION</option>');
expect(function() {
element = $compile('<div replace-with-option></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/option/i);
}));

it('should support templates with root <optgroup> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('optgroup.html', '<optgroup>OPTGROUP</optgroup>');
expect(function() {
element = $compile('<div replace-with-optgroup></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/optgroup/i);
}));
});


Expand Down