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: 4e150c1223b32fa5f861f851c13d89de58a69d39 (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
// based on https://github.com/tylingsoft/markdown-it-mermaid

import MarkdownIt = require("markdown-it");
import * as 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,
});

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.MarkdownIt) => {
    const originalRenderer = md.renderer.rules.fence.bind(md.renderer.rules);
    md.renderer.rules.fence = (tokens: MarkdownIt.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);
    }
};