-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathrender.ts
More file actions
40 lines (37 loc) · 1.16 KB
/
Copy pathrender.ts
File metadata and controls
40 lines (37 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import {
type MermaidRenderer,
type RenderResult,
createMermaidRenderer,
} from "mermaid-isomorphic";
// Cache the renderer to avoid creating a new one every time.
let renderer: MermaidRenderer;
/**
* Ref:
* - https://github.com/mermaid-js/mermaid-cli/blob/master/src/index.js
* - https://github.com/remcohaszing/mermaid-isomorphic
* @returns
*/
export async function renderMermaid(
mermaid: string,
theme = "default",
backgroundColor = "white",
): Promise<RenderResult> {
if (!renderer) renderer = createMermaidRenderer();
const cssContent = `svg { background: ${backgroundColor}; }`;
const cssTmpPath = path.join(os.tmpdir(), "mermaid-tmp-css.css");
fs.writeFileSync(cssTmpPath, cssContent);
const r = await renderer([mermaid], {
// Image is needed.
screenshot: true,
css: cssTmpPath,
mermaidConfig: {
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
theme: theme as any,
},
});
const r0 = r[0] as PromiseSettledResult<RenderResult>;
return r0.status === "fulfilled" ? r0.value : Promise.reject(r0.reason);
}