Skip to content

Commit 21290d4

Browse files
mjwwitlunny
authored andcommitted
Optimize and fix autolink function (#1442) (#1444)
* Optimize and fix autolink function (#1442) * Fix bug in autolink recursive fallback function
1 parent 2229594 commit 21290d4

File tree

1 file changed

+45
-15
lines changed

1 file changed

+45
-15
lines changed

public/js/libs/autolink.js

+45-15
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,45 @@
1-
jQuery.fn.autolink = function() {
2-
var re = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-]*)?\??(?:[\-\+:=&;%@\.\w]*)#?(?:[\.\!\/\\\w]*))?)/g;
3-
return this.find('*').contents()
4-
.filter(function () { return this.nodeType === 3; })
5-
.each(function() {
6-
$(this).each(function() {
7-
if (re.test($(this).text()))
8-
$(this).replaceWith(
9-
$("<span />").html(
10-
this.nodeValue.replace(re, "<a href='$1'>$1</a>")
11-
)
12-
);
13-
});
14-
});
15-
};
1+
(function () {
2+
var re = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-]*)?\??(?:[\-\+:=&;%@\.\w]*)#?(?:[\.\!\/\\\w]*))?)/g;
3+
function textNodesUnder(node) {
4+
var textNodes = [];
5+
if(typeof document.createTreeWalker === 'function') {
6+
// Efficient TreeWalker
7+
var currentNode, walker;
8+
walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT, null, false);
9+
while(currentNode = walker.nextNode()) {
10+
textNodes.push(currentNode);
11+
}
12+
} else {
13+
// Less efficient recursive function
14+
for(node = node.firstChild; node; node = node.nextSibling) {
15+
if(node.nodeType === 3) {
16+
textNodes.push(node);
17+
} else {
18+
textNodes = textNodes.concat(textNodesUnder(node));
19+
}
20+
}
21+
}
22+
return textNodes;
23+
}
24+
25+
function processNode(node) {
26+
re.lastIndex = 0;
27+
var results = re.exec(node.textContent);
28+
if(results !== null) {
29+
if($(node).parents().filter('pre>code').length === 0) {
30+
$(node).replaceWith(
31+
$('<span />').html(
32+
node.nodeValue.replace(re, '<a href="$1">$1</a>')
33+
)
34+
);
35+
}
36+
}
37+
}
38+
39+
jQuery.fn.autolink = function () {
40+
this.each(function () {
41+
textNodesUnder(this).forEach(processNode);
42+
});
43+
return this;
44+
};
45+
})();

0 commit comments

Comments
 (0)