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