fix(v2): linkify blog posts (#2326)

* fix(v2): linkify blog posts

* Fix tests
This commit is contained in:
Alexey Pyltsyn 2020-02-29 09:49:00 +03:00 committed by GitHub
parent 84eeb5120c
commit 36163773ec
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 161 additions and 12 deletions

View file

@ -88,7 +88,7 @@ export async function generateBlogPosts(
const {include, routeBasePath, truncateMarker} = options;
if (!fs.existsSync(blogDir)) {
return null;
return [];
}
const {baseUrl = ''} = siteConfig;
@ -156,3 +156,48 @@ export async function generateBlogPosts(
return blogPosts;
}
export function linkify(
fileContent: string,
siteDir: string,
blogPath: string,
blogPosts: BlogPost[],
) {
let fencedBlock = false;
const lines = fileContent.split('\n').map(line => {
if (line.trim().startsWith('```')) {
fencedBlock = !fencedBlock;
}
if (fencedBlock) return line;
let modifiedLine = line;
const mdRegex = /(?:(?:\]\()|(?:\]:\s?))(?!https)([^'")\]\s>]+\.mdx?)/g;
let mdMatch = mdRegex.exec(modifiedLine);
while (mdMatch !== null) {
const mdLink = mdMatch[1];
const aliasedPostSource = `@site/${path.relative(
siteDir,
path.resolve(blogPath, mdLink),
)}`;
let blogPostPermalink = null;
blogPosts.forEach(blogPost => {
if (blogPost.metadata.source === aliasedPostSource) {
blogPostPermalink = blogPost.metadata.permalink;
}
});
if (blogPostPermalink) {
modifiedLine = modifiedLine.replace(mdLink, blogPostPermalink);
}
mdMatch = mdRegex.exec(modifiedLine);
}
return modifiedLine;
});
return lines.join('\n');
}