Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(external_link): optimize external link filter #5598

Merged
merged 3 commits into from
Jan 9, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 26 additions & 10 deletions lib/plugins/filter/after_render/external_link.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { isExternalLink } from 'hexo-util';
import Hexo from '../../../hexo';
import type Hexo from '../../../hexo';

let EXTERNAL_LINK_SITE_ENABLED = true;
const rATag = /<a(?:\s+?|\s+?[^<>]+?\s+?)href=["']((?:https?:|\/\/)[^<>"']+)["'][^<>]*>/gi;
const rTargetAttr = /target=/i;
const rRelAttr = /rel=/i;
const rRelStrAttr = /rel=["']([^<>"']*)["']/i;

const addNoopener = (relStr: string, rel: string) => {
return rel.includes('noopenner') ? relStr : `rel="${rel} noopener"`;
};

function externalLinkFilter(this: Hexo, data: string): string {
if (!EXTERNAL_LINK_SITE_ENABLED) return;

Expand All @@ -17,18 +21,30 @@ function externalLinkFilter(this: Hexo, data: string): string {
return;
}

return data.replace(rATag, (str, href) => {
if (!isExternalLink(href, url, external_link.exclude as any) || rTargetAttr.test(str)) return str;
let result = '';
let lastIndex = 0;
let match;

while ((match = rATag.exec(data)) !== null) {
result += data.slice(lastIndex, match.index);

if (rRelAttr.test(str)) {
str = str.replace(rRelStrAttr, (relStr, rel) => {
return rel.includes('noopenner') ? relStr : `rel="${rel} noopener"`;
});
return str.replace('href=', 'target="_blank" href=');
const str = match[0];
const href = match[1];

if (!isExternalLink(href, url, external_link.exclude as any) || rTargetAttr.test(str)) {
result += str;
} else {
if (rRelAttr.test(str)) {
result += str.replace(rRelStrAttr, addNoopener).replace('href=', 'target="_blank" href=');
} else {
result += str.replace('href=', 'target="_blank" rel="noopener" href=');
}
}
lastIndex = rATag.lastIndex;
}
result += data.slice(lastIndex);

return str.replace('href=', 'target="_blank" rel="noopener" href=');
});
return result;
}

export = externalLinkFilter;
Loading