Skip to content

Commit

Permalink
Avoid race condition when rendering graphs
Browse files Browse the repository at this point in the history
  • Loading branch information
lukastaegert committed Mar 9, 2023
1 parent b3ad789 commit 9a2c241
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions docs/.vitepress/mermaid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export function renderMermaidGraphsPlugin(): Plugin {
const existingGraphFileNamesPromise = mkdir(graphsDirectory, { recursive: true })
.then(() => getFilesInDirectory(graphsDirectory))
.then(files => new Set(files.filter(name => name.endsWith('.svg'))));
const existingGraphsByName = new Map<string, string>();
const existingGraphsByName = new Map<string, Promise<string>>();

async function renderGraph(codeBlock: string, outFile: string) {
const existingGraphFileNames = await existingGraphFileNamesPromise;
Expand All @@ -46,6 +46,7 @@ export function renderMermaidGraphsPlugin(): Plugin {
extractedStyles.push(styleTag);
return '';
});
console.log('Extracted styles from mermaid chart:', extractedStyles.length);
return `${extractedStyles.join('')}\n${baseGraph}`;
}

Expand All @@ -64,9 +65,9 @@ export function renderMermaidGraphsPlugin(): Plugin {
mermaidCodeBlocks.map(async (codeBlock, index) => {
const outFile = `${createHash('sha256').update(codeBlock).digest('base64url')}.svg`;
if (!existingGraphsByName.has(outFile)) {
existingGraphsByName.set(outFile, await renderGraph(codeBlock, outFile));
existingGraphsByName.set(outFile, renderGraph(codeBlock, outFile));
}
renderedGraphs[index] = existingGraphsByName.get(outFile)!;
renderedGraphs[index] = await existingGraphsByName.get(outFile)!;
})
);
return code.replace(mermaidRegExp, () => renderedGraphs.shift()!);
Expand Down

0 comments on commit 9a2c241

Please sign in to comment.