-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
* Optimize and fix autolink function (#1442) * Fix bug in autolink recursive fallback function
- Loading branch information
Showing
1 changed file
with
45 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,45 @@ | ||
jQuery.fn.autolink = function() { | ||
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() | ||
.filter(function () { return this.nodeType === 3; }) | ||
.each(function() { | ||
$(this).each(function() { | ||
if (re.test($(this).text())) | ||
$(this).replaceWith( | ||
$("<span />").html( | ||
this.nodeValue.replace(re, "<a href='$1'>$1</a>") | ||
) | ||
); | ||
}); | ||
}); | ||
}; | ||
(function () { | ||
var re = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-]*)?\??(?:[\-\+:=&;%@\.\w]*)#?(?:[\.\!\/\\\w]*))?)/g; | ||
function textNodesUnder(node) { | ||
var textNodes = []; | ||
if(typeof document.createTreeWalker === 'function') { | ||
// Efficient TreeWalker | ||
var currentNode, walker; | ||
walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT, null, false); | ||
while(currentNode = walker.nextNode()) { | ||
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; | ||
}; | ||
})(); |