mirror of
https://github.com/facebook/docusaurus.git
synced 2025-05-18 11:36:53 +02:00
fix(v2): linkify blog posts (#2326)
* fix(v2): linkify blog posts * Fix tests
This commit is contained in:
parent
84eeb5120c
commit
36163773ec
8 changed files with 161 additions and 12 deletions
|
@ -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');
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue