dispatch/client/js/utils/linkify.js

72 lines
1.6 KiB
JavaScript
Raw Normal View History

import Autolinker from 'autolinker';
import React from 'react';
const autolinker = new Autolinker({
stripPrefix: false,
2017-04-16 04:08:45 +00:00
stripTrailingSlash: false
});
export default function linkify(text) {
2019-01-23 07:52:17 +00:00
if (!text) {
return text;
}
let matches = autolinker.parseText(text);
if (matches.length === 0) {
return text;
}
2017-04-16 04:08:45 +00:00
const result = [];
let pos = 0;
matches = autolinker.compactMatches(matches);
2017-04-16 04:08:45 +00:00
for (let i = 0; i < matches.length; i++) {
const match = matches[i];
if (match.getType() === 'url') {
if (match.offset > pos) {
if (typeof result[result.length - 1] === 'string') {
result[result.length - 1] += text.slice(pos, match.offset);
} else {
result.push(text.slice(pos, match.offset));
}
}
2017-04-16 04:08:45 +00:00
result.push(
2018-04-05 23:46:22 +00:00
<a
target="_blank"
rel="noopener noreferrer"
href={match.getAnchorHref()}
key={i}
2018-04-05 23:46:22 +00:00
>
2017-04-16 04:08:45 +00:00
{match.matchedText}
</a>
);
} else if (typeof result[result.length - 1] === 'string') {
2018-04-05 23:46:22 +00:00
result[result.length - 1] += text.slice(
pos,
match.offset + match.matchedText.length
);
2017-04-16 04:08:45 +00:00
} else {
result.push(text.slice(pos, match.offset + match.matchedText.length));
}
2016-03-14 22:22:24 +00:00
pos = match.offset + match.matchedText.length;
2017-04-16 04:08:45 +00:00
}
2017-04-16 04:08:45 +00:00
if (pos < text.length) {
if (typeof result[result.length - 1] === 'string') {
result[result.length - 1] += text.slice(pos);
} else {
result.push(text.slice(pos));
}
}
if (result.length === 1) {
return result[0];
2017-04-16 04:08:45 +00:00
}
return result;
}