Skip to content

Commit

Permalink
feat: init mdx plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
JulianCataldo committed Jul 31, 2022
1 parent 1b4f0b4 commit f1f17ae
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 2 deletions.
49 changes: 49 additions & 0 deletions components/Diagram/mdx-mermaid.ts
@@ -0,0 +1,49 @@
// TODO: Proper TypeScript rehaul for this file.

/**
* Some bits of code are from https://github.com/sjwall/mdx-mermaid
*
* Using Parcel to bundle this plugin because
* Astro uses MJS for its config file.
* (It seems that it support TS too, but it breaks some third-parties)
*
*/

// eslint-disable-next-line import/no-extraneous-dependencies
import { visit } from 'unist-util-visit';
import renderDiagram from './render-diagram';

const style = `display: flex; justify-content: center; width: 100%;`;

function plugin() {
return async function transformer(ast) {
// Find all the mermaid diagram code blocks. i.e. ```mermaid
const instances = [];
visit(ast, { type: 'code', lang: 'mermaid' }, (node, index, parent) => {
instances.push([node, index, parent]);
});
// Replace each Mermaid code block with the server-side rendered SVG
await Promise.all(
instances.map(async ([node, index, parent]) => {
// MDX rendering seems to be already cached.
// or this keep running puppeeter ?
// Also, disabling it prevent a bug which doesn't
// occur in the regular component.
const html = await renderDiagram({
config: {},
code: node.value,
}).then((diagram) => diagram.result);
parent.children.splice(index, 1, {
type: 'html',
// TODO: put CSS elsewhere
value: `<div style="${style}">${html}</div>`,
position: node.position,
});
}),
);

return ast;
};
}

export default plugin;
5 changes: 3 additions & 2 deletions components/Diagram/package.json
Expand Up @@ -2,7 +2,7 @@
"name": "@julian_cataldo/astro-diagram",
"version": "0.10.0",
"description": "Embed you Mermaid diagrams in no time inside your Astro templates. Features server-side rendering and smart caching.",
"main": "index.js",
"main": "dist/index.js",
"type": "module",
"publishConfig": {
"access": "public"
Expand Down Expand Up @@ -35,7 +35,8 @@
"license": "ISC",
"dependencies": {
"@wbmnky/license-report-generator": "^2.1.3",
"headless-mermaid": "^1.3.0"
"headless-mermaid": "^1.3.0",
"unist-util-visit": "^4.1.0"
},
"devDependencies": {
"@types/mermaid": "^8.2.9"
Expand Down
25 changes: 25 additions & 0 deletions components/Diagram/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit f1f17ae

Please sign in to comment.