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

Renderer.ts « js - github.com/icewind1991/files_markdown.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 833bdc0be693cfe5f6211cce7874a1c3ad329d54 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import MarkdownIt from 'markdown-it';
import Token from 'markdown-it/lib/token';
import iterator from 'markdown-it-for-inline';
import {CheckboxPlugin} from './CheckboxPlugin';
import AnchorPlugin from 'markdown-it-anchor';
import slugify from 'slugify';
import TOCPlugin from 'markdown-it-table-of-contents';
import VideoPlugin from './VideoPlugin';
import PreamblePlugin from 'markdown-it-github-preamble';
import morphdom from 'morphdom';

import 'katex/dist/katex.min.css';
import 'highlight.js/styles/github.css';

const slugifyHeading = name => 'editor/' + slugify(name).toLowerCase();

export type PluginChecker = (text: string) => boolean;

export interface PluginMap {
    [name: string]: {
        checker: PluginChecker;
        module: () => Promise<any>;
        loaded?: boolean
    }
}

function loadKaTeX() {
    return Promise.all([
        import('katex'),
        import('markdown-it-texmath'),
    ]).then(([katex, {default: texmath}]) => {
        texmath.use(katex);
        return texmath;
    });
}

function loadMermaid() {
    return import('./MermaidPlugin').then(module => module.MermaidPlugin);
}

function loadHighlight() {
    return import('markdown-it-highlightjs').then(module => module.default);
}

export class Renderer {
    md: MarkdownIt;

    plugins: PluginMap = {
        'mermaid': {
            checker: text => text.match(/(gantt|sequenceDiagram|graph (?:TB|BT|RL|LR|TD))/) !== null,
            module: loadMermaid
        },
        'highlight.js': {
            checker: text => text.indexOf('```') !== -1,
            module: loadHighlight
        },
        'katex': {
            checker: text => text.indexOf('$') !== -1,
            module: loadKaTeX
        }
    };

    constructor(readonly: boolean = false) {
        this.md = new MarkdownIt({
            linkify: true
        });
        this.md.use(CheckboxPlugin, {
            checkboxClass: 'checkbox',
            readonly: readonly
        });
        this.md.use(AnchorPlugin, {
            slugify: slugifyHeading
        });
        this.md.use(TOCPlugin, {
            slugify: slugifyHeading
        });
        this.md.use(PreamblePlugin);
        this.md.use(VideoPlugin);
        this.md.use(iterator, 'url_new_win', 'link_open', (tokens: Token[], idx: number) => {
            const href = tokens[idx].attrGet('href') as string;
            if (href[0] !== '#') {
                tokens[idx].attrPush(['target', '_blank']);
                tokens[idx].attrPush(['rel', 'noopener']);
            }
            tokens[idx].attrSet('href', this.getLinkUrl(href))
        });
        this.md.use(iterator, 'internal_image_link', 'image', (tokens: Token[], idx: number) => {
            tokens[idx].attrSet('src', this.getImageUrl(tokens[idx].attrGet('src') as string));
        });

        function injectLineNumbers(tokens, idx, options, env, slf) {
            if (tokens[idx].map && tokens[idx].level === 0) {
                const line = tokens[idx].map[0];
                tokens[idx].attrJoin('class', 'line');
                tokens[idx].attrSet('data-line', String(line));
            }
            return slf.renderToken(tokens, idx, options, env, slf);
        }

        this.md.renderer.rules.paragraph_open =
            this.md.renderer.rules.heading_open =
                this.md.renderer.rules.heading_open =
                    injectLineNumbers;
    }

    getLinkUrl(path: string): string {
        if (path[0] === '#') {
            return '#' + slugifyHeading(path.substr(1));
        }
        return path;
    }

    getImageUrl(path: string): string {
        if (!path || path.indexOf('.') === -1) {
            return path;
        }
        if (path.indexOf('://') !== -1) {
            return path;
        } else {
            if (path.substr(0, 1) !== '/') {
                if (OCA.Files_Texteditor.file && OCA.Files_Texteditor.file.dir) {
                    path = OCA.Files_Texteditor.file.dir + '/' + path;
                } else if (OCA.Files.App && OCA.Files.App.fileList._currentDirectory) {
                    path = OCA.Files.App.fileList._currentDirectory + '/' + path;
                }
            }
            return OC.linkToRemote('files' + path.replace(/\/\/+/g, '/'));
        }
    }

    renderText(text: string, element): Promise<void> {
        return this.loadPlugins(text).then(() => {
                const html = this.md.render(text);
                morphdom(element[0], `<div>${html}</div>`, {
                    childrenOnly: true
                });
            }
        );
    }

    loadPlugins(text: string) {
        return Promise.all(Object.keys(this.plugins)
            .map(pluginName => {
                const plugin = this.plugins[pluginName];
                if (!plugin.loaded && plugin.checker(text)) {
                    plugin.loaded = true;
                    return plugin.module().then(plugin => {
                        this.md.use(plugin);
                    });
                }
            })
        );
    }
}