Welcome to mirror list, hosted at ThFree Co, Russian Federation.

MermaidPlugin.ts « js - github.com/icewind1991/files_markdown.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 70e1de4c1f0b06304ded5b807d57ec0743327100 (plain)
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// based on https://github.com/tylingsoft/markdown-it-mermaid

import MarkdownIt from "markdown-it";
import Token from 'markdown-it/lib/token';
import mermaid from 'mermaid';

// workaround missing import in dependency
// see: https://github.com/tylingsoft/dagre-d3-renderer/pull/1
import * as d3 from 'd3';
window['d3'] = d3;

mermaid.mermaidAPI.initialize({
    startOnLoad: true,
    logLevel: 3,
    theme: 'forest'
});

let chartCounter = 0;

const mermaidChart = (code: string): string => {
    let mermaidError: string | null = null;
    mermaid.parseError = (error: string) => {
        mermaidError = error
    };
    if (mermaid.parse(code) || mermaidError === null) {
        const tempElement = document.createElement('div');
        // tempElement.classList.add('hidden');
        document.body.appendChild(tempElement);
        const graph = mermaid.mermaidAPI.render(`chart_${chartCounter++}`, code, () => {
        }, tempElement);
        document.body.removeChild(tempElement);
        if (!graph) {
            return `<pre>Error creating graph</pre>`
        }
        return `<div class="mermaid">${graph}</div>`
    } else {
        return `<pre>${mermaidError}</pre>`
    }
};

export const MermaidPlugin = (md: MarkdownIt) => {
    if (md.renderer.rules.fence) {
        const originalRenderer = md.renderer.rules.fence.bind(md.renderer.rules);
        md.renderer.rules.fence = (tokens: Token[], idx: number, options, env, slf) => {
            const token = tokens[idx];
            const code = token.content.trim();
            if (token.info === 'mermaid') {
                return mermaidChart(code);
            }
            const firstLine = code.split(/\n/)[0].trim();
            if (firstLine === 'gantt' || firstLine === 'sequenceDiagram' || firstLine.match(/^graph (?:TB|BT|RL|LR|TD);?$/)) {
                return mermaidChart(code);
            }
            return originalRenderer(tokens, idx, options, env, slf);
        }
    }
};