dispatch/client/js/utils/linkify.js

77 lines
1.4 KiB
JavaScript
Raw Normal View History

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;
}
let matches = autolinker.parseText(text);
if (matches.length === 0) {
2020-06-30 11:24:23 +00:00
return [
{
type: 'text',
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) {
2020-06-30 11:24:23 +00:00
pushText(result, text.slice(pos, match.offset));
}
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-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) {
2020-06-30 11:24:23 +00:00
if (result[result.length - 1]?.type === 'text') {
result[result.length - 1].text += text.slice(pos);
} else {
2020-06-30 11:24:23 +00:00
pushText(result, text.slice(pos));
}
}
2017-04-16 04:08:45 +00:00
return result;
}