2018-04-10 17:33:46 +00:00
|
|
|
|
// Fork of https://github.com/uiureo/link-text with HTML escaping disabled as we leverage
|
|
|
|
|
// jQuery’s escaping mechanism:
|
|
|
|
|
|
2018-04-10 19:00:55 +00:00
|
|
|
|
const linkify = require('linkify-it')();
|
|
|
|
|
|
|
|
|
|
function createLink(url, text, attrs = {}) {
|
|
|
|
|
const html = [];
|
|
|
|
|
html.push('<a ');
|
|
|
|
|
html.push(`href="${url}"`);
|
|
|
|
|
Object.keys(attrs).forEach((key) => {
|
|
|
|
|
html.push(` ${key}="${attrs[key]}"`);
|
|
|
|
|
});
|
|
|
|
|
html.push('>');
|
|
|
|
|
html.push(decodeURIComponent(text));
|
|
|
|
|
html.push('</a>');
|
|
|
|
|
|
|
|
|
|
return html.join('');
|
2018-04-10 17:33:46 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-04-10 19:00:55 +00:00
|
|
|
|
module.exports = (text, attrs = {}) => {
|
|
|
|
|
const matchData = linkify.match(text) || [];
|
2018-04-10 17:33:46 +00:00
|
|
|
|
|
2018-04-10 19:00:55 +00:00
|
|
|
|
const result = [];
|
|
|
|
|
let last = 0;
|
2018-04-10 17:33:46 +00:00
|
|
|
|
|
2018-04-10 19:00:55 +00:00
|
|
|
|
matchData.forEach((match) => {
|
2018-04-10 17:33:46 +00:00
|
|
|
|
if (last < match.index) {
|
2018-04-10 19:00:55 +00:00
|
|
|
|
result.push(text.slice(last, match.index));
|
2018-04-10 17:33:46 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-04-10 19:00:55 +00:00
|
|
|
|
result.push(createLink(match.url, match.text, attrs));
|
2018-04-10 17:33:46 +00:00
|
|
|
|
|
2018-04-10 19:00:55 +00:00
|
|
|
|
last = match.lastIndex;
|
|
|
|
|
});
|
2018-04-10 17:33:46 +00:00
|
|
|
|
|
2018-04-10 19:00:55 +00:00
|
|
|
|
result.push(text.slice(last));
|
2018-04-10 17:33:46 +00:00
|
|
|
|
|
2018-04-10 19:00:55 +00:00
|
|
|
|
return result.join('');
|
|
|
|
|
};
|