Skip to content

Commit

Permalink
feat: Add support for mermaid diagrams in markdown (asyncapi#712)
Browse files Browse the repository at this point in the history
  • Loading branch information
j-h-a committed Apr 12, 2023
1 parent 505304d commit e2fd448
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
25 changes: 23 additions & 2 deletions library/src/helpers/marked.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ hljs.registerLanguage('yaml', yaml);
import bash from 'highlight.js/lib/languages/bash';
hljs.registerLanguage('bash', bash);

const markedOptions: marked.MarkedOptions = {
const codeHighlightOptions: marked.MarkedOptions = {
langPrefix: 'hljs language-',
highlight: (code, language) => {
if (!hljs.getLanguage(language)) {
Expand All @@ -28,9 +28,30 @@ const markedOptions: marked.MarkedOptions = {
}
},
};
const codeHighlightRenderer = new marked.Renderer(codeHighlightOptions);
const markdownRenderer = new marked.Renderer();
markdownRenderer.code = (code, language, isEscaped) => {
if (language === 'mermaid') {
addMermaidIfNeeded();
return '<pre class="mermaid">' + code + '</pre>';
}
return codeHighlightRenderer.code(code, language, isEscaped);
};

let gotMermaidAlready = false;
function addMermaidIfNeeded() {
if (gotMermaidAlready) {
return;
}
gotMermaidAlready = true;
const script = document.createElement('script');
script.type = 'module';
script.text = `import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';`;
document.body.appendChild(script);
}

export function renderMarkdown(content: string): string {
return marked(content, markedOptions);
return marked(content, { renderer: markdownRenderer });
}

export { hljs };
9 changes: 9 additions & 0 deletions playground/src/specs/streetlights.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ info:
* Dim a specific streetlight 😎
* Receive real-time information about environmental lighting conditions 📈
### We got mermaids 🧜‍♀️
\`\`\`mermaid
graph LR
Mermaid --> Graph --> Looks --> Cool
Graph --> Works["Works!"]
Works --> Cool
\`\`\`
termsOfService: http://asyncapi.org/terms/
contact:
name: API Support
Expand Down

0 comments on commit e2fd448

Please sign in to comment.