Call autolinker.compactMatches() and minimize textnode count returned from linkify()

This commit is contained in:
Ken-Håvard Lieng 2017-04-16 07:42:11 +02:00
parent 305c1fa08f
commit 12fbca8110
2 changed files with 47 additions and 28 deletions

File diff suppressed because one or more lines are too long

View File

@ -7,34 +7,53 @@ const autolinker = new Autolinker({
});
export default function linkify(text) {
const matches = autolinker.parseText(text);
let matches = autolinker.parseText(text);
if (matches.length === 0) {
return text;
}
const result = [];
let pos = 0;
matches = autolinker.compactMatches(matches);
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));
pos = match.offset;
}
}
if (match.getType() === 'url') {
result.push(
<a target="_blank" rel="noopener noreferrer" href={match.getAnchorHref()}>
{match.matchedText}
</a>
);
} else if (typeof result[result.length - 1] === 'string') {
result[result.length - 1] += text.slice(pos, match.offset + match.matchedText.length);
} else {
result.push(match.matchedText);
result.push(text.slice(pos, match.offset + match.matchedText.length));
}
pos += match.matchedText.length;
pos = match.offset + match.matchedText.length;
}
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 && typeof result[0] === 'string') {
return text;
}
return result;
}