Browse Source

Removed singleton in linkify (thread safety)

pull/14/head
Vitaly Puzrin 10 years ago
parent
commit
6b69c9cbf1
  1. 39
      lib/rules_core/linkify.js

39
lib/rules_core/linkify.js

@ -1,6 +1,6 @@
// Replace link-like texts with link nodes.
//
// Currently restricted to http/https/ftp
// Currently restricted by `inline.validateLink()` to http/https/ftp
//
'use strict';
@ -10,8 +10,20 @@ var Autolinker = require('autolinker');
var LINK_SCAN_RE = /www|\:\/\//;
var links = [];
var autolinker = new Autolinker({
function isLinkOpen(str) {
return /^<a[>\s]/i.test(str);
}
function isLinkClose(str) {
return /^<\/a\s*>/i.test(str);
}
// Stupid fabric to avoid singletons, for thread safety.
// Required for engines like Nashorn.
//
function createLinkifier() {
var links = [];
var autolinker = new Autolinker({
stripPrefix: false,
replaceFn: function (autolinker, match) {
// Only collect matched strings but don't change anything.
@ -20,19 +32,19 @@ var autolinker = new Autolinker({
}
return false;
}
});
});
function isLinkOpen(str) {
return /^<a[>\s]/i.test(str);
}
function isLinkClose(str) {
return /^<\/a\s*>/i.test(str);
return {
links: links,
autolinker: autolinker
};
}
module.exports = function linkify(state) {
var i, j, l, tokens, token, text, nodes, ln, pos, level, htmlLinkLevel,
blockTokens = state.tokens;
blockTokens = state.tokens,
linkifier = null, links, autolinker;
if (!state.options.linkify) { return; }
@ -69,6 +81,13 @@ module.exports = function linkify(state) {
if (token.type === 'text' && LINK_SCAN_RE.test(token.content)) {
// Init linkifier in lazy manner, only if required.
if (!linkifier) {
linkifier = createLinkifier();
links = linkifier.links;
autolinker = linkifier.autolinker;
}
text = token.content;
links.length = 0;
autolinker.link(text);

Loading…
Cancel
Save