2016-02-17 00:49:27 +00:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2017-04-16 05:42:11 +00:00
|
|
|
let matches = autolinker.parseText(text);
|
|
|
|
|
|
|
|
if (matches.length === 0) {
|
|
|
|
return text;
|
|
|
|
}
|
|
|
|
|
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) {
|
|
|
|
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()}
|
2018-11-04 06:22:46 +00:00
|
|
|
key={i}
|
2018-04-05 23:46:22 +00:00
|
|
|
>
|
2017-04-16 04:08:45 +00:00
|
|
|
{match.matchedText}
|
|
|
|
</a>
|
|
|
|
);
|
2017-04-16 05:42:11 +00:00
|
|
|
} 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 {
|
2017-04-16 05:42:11 +00:00
|
|
|
result.push(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) {
|
2017-04-16 05:42:11 +00:00
|
|
|
if (typeof result[result.length - 1] === 'string') {
|
|
|
|
result[result.length - 1] += text.slice(pos);
|
|
|
|
} else {
|
|
|
|
result.push(text.slice(pos));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-21 09:04:06 +00:00
|
|
|
if (result.length === 1) {
|
|
|
|
return result[0];
|
2017-04-16 04:08:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
2016-02-17 00:49:27 +00:00
|
|
|
}
|