Optimize and fix autolink function (#1442) (#1444)

* Optimize and fix autolink function (#1442)

* Fix bug in autolink recursive fallback function
This commit is contained in:
Michael de Wit 2017-04-12 10:01:08 +02:00 committed by Lunny Xiao
parent 22295944df
commit 21290d4e80

@ -1,15 +1,45 @@
jQuery.fn.autolink = function() { (function () {
var re = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-]*)?\??(?:[\-\+:=&;%@\.\w]*)#?(?:[\.\!\/\\\w]*))?)/g; var re = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-]*)?\??(?:[\-\+:=&;%@\.\w]*)#?(?:[\.\!\/\\\w]*))?)/g;
return this.find('*').contents() function textNodesUnder(node) {
.filter(function () { return this.nodeType === 3; }) var textNodes = [];
.each(function() { if(typeof document.createTreeWalker === 'function') {
$(this).each(function() { // Efficient TreeWalker
if (re.test($(this).text())) var currentNode, walker;
$(this).replaceWith( walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT, null, false);
$("<span />").html( while(currentNode = walker.nextNode()) {
this.nodeValue.replace(re, "<a href='$1'>$1</a>") textNodes.push(currentNode);
) }
); } else {
}); // Less efficient recursive function
}); for(node = node.firstChild; node; node = node.nextSibling) {
}; if(node.nodeType === 3) {
textNodes.push(node);
} else {
textNodes = textNodes.concat(textNodesUnder(node));
}
}
}
return textNodes;
}
function processNode(node) {
re.lastIndex = 0;
var results = re.exec(node.textContent);
if(results !== null) {
if($(node).parents().filter('pre>code').length === 0) {
$(node).replaceWith(
$('<span />').html(
node.nodeValue.replace(re, '<a href="$1">$1</a>')
)
);
}
}
}
jQuery.fn.autolink = function () {
this.each(function () {
textNodesUnder(this).forEach(processNode);
});
return this;
};
})();