2016-02-17 00:49:27 +00:00
|
|
|
import Autolinker from 'autolinker';
|
|
|
|
|
|
|
|
const autolinker = new Autolinker({
|
|
|
|
stripPrefix: false,
|
2017-04-16 04:08:45 +00:00
|
|
|
stripTrailingSlash: false
|
|
|
|
});
|
|
|
|
|
2020-06-30 11:24:23 +00:00
|
|
|
function pushText(arr, text) {
|
|
|
|
const last = arr[arr.length - 1];
|
|
|
|
if (last?.type === 'text') {
|
|
|
|
last.text += text;
|
|
|
|
} else {
|
|
|
|
arr.push({
|
|
|
|
type: 'text',
|
|
|
|
text
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function pushLink(arr, url, text) {
|
|
|
|
arr.push({
|
|
|
|
type: 'link',
|
|
|
|
url,
|
|
|
|
text
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-04-16 04:08:45 +00:00
|
|
|
export default function linkify(text) {
|
2020-06-30 11:24:23 +00:00
|
|
|
if (typeof text !== 'string') {
|
2019-01-23 07:52:17 +00:00
|
|
|
return text;
|
|
|
|
}
|
|
|
|
|
2017-04-16 05:42:11 +00:00
|
|
|
let matches = autolinker.parseText(text);
|
|
|
|
|
|
|
|
if (matches.length === 0) {
|
2020-06-30 11:24:23 +00:00
|
|
|
return [
|
|
|
|
{
|
|
|
|
type: 'text',
|
|
|
|
text
|
|
|
|
}
|
|
|
|
];
|
2017-04-16 05:42:11 +00:00
|
|
|
}
|
|
|
|
|
2017-04-16 04:08:45 +00:00
|
|
|
const result = [];
|
|
|
|
let pos = 0;
|
2017-04-16 05:42:11 +00:00
|
|
|
matches = autolinker.compactMatches(matches);
|
2017-04-16 04:08:45 +00:00
|
|
|
|
|
|
|
for (let i = 0; i < matches.length; i++) {
|
|
|
|
const match = matches[i];
|
|
|
|
|
2016-02-17 00:49:27 +00:00
|
|
|
if (match.getType() === 'url') {
|
2017-04-16 05:42:11 +00:00
|
|
|
if (match.offset > pos) {
|
2020-06-30 11:24:23 +00:00
|
|
|
pushText(result, text.slice(pos, match.offset));
|
2017-04-16 05:42:11 +00:00
|
|
|
}
|
|
|
|
|
2020-06-30 11:24:23 +00:00
|
|
|
pushLink(result, match.getAnchorHref(), match.matchedText);
|
2017-04-16 04:08:45 +00:00
|
|
|
} else {
|
2020-06-30 11:24:23 +00:00
|
|
|
pushText(
|
|
|
|
result,
|
|
|
|
text.slice(pos, match.offset + match.matchedText.length)
|
|
|
|
);
|
2016-02-17 00:49:27 +00:00
|
|
|
}
|
2016-03-14 22:22:24 +00:00
|
|
|
|
2017-04-16 05:42:11 +00:00
|
|
|
pos = match.offset + match.matchedText.length;
|
2017-04-16 04:08:45 +00:00
|
|
|
}
|
2016-02-17 00:49:27 +00:00
|
|
|
|
2017-04-16 04:08:45 +00:00
|
|
|
if (pos < text.length) {
|
2020-06-30 11:24:23 +00:00
|
|
|
if (result[result.length - 1]?.type === 'text') {
|
|
|
|
result[result.length - 1].text += text.slice(pos);
|
2017-04-16 05:42:11 +00:00
|
|
|
} else {
|
2020-06-30 11:24:23 +00:00
|
|
|
pushText(result, text.slice(pos));
|
2017-04-16 05:42:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-16 04:08:45 +00:00
|
|
|
return result;
|
2016-02-17 00:49:27 +00:00
|
|
|
}
|