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: 1e0041a97f7e5346dc41bde8d8125ca450c4f84c (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
155
156
157
158
159
160
161
162
163
164
165
166
import * as MarkdownIt from 'markdown-it';
import * as iterator from 'markdown-it-for-inline';
import {CheckboxPlugin} from './CheckboxPlugin';
import * as AnchorPlugin from 'markdown-it-anchor';
import * as slugify from 'slugify';
import * as TOCPlugin from 'markdown-it-table-of-contents';
import VideoPlugin from './VideoPlugin';
import * as PreamblePlugin from 'markdown-it-github-preamble';
import * as morphdom from 'morphdom';

import 'katex/dist/katex.min.css';
import 'highlight.js/styles/github.css';
import 'mermaid/dist/mermaid.forest.min.css';
import Thenable = JQuery.Thenable;

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() {
    const deferred = $.Deferred();
    require.ensure([
        'katex',
        'markdown-it-texmath'
    ], () => {
        deferred.resolve(require('markdown-it-texmath').use(require('katex')));
    }, 'katex');
    return deferred.promise();
}

function loadMermaid() {
    const deferred = $.Deferred();
    require.ensure([
        './MermaidPlugin'
    ], () => {
        deferred.resolve(require('./MermaidPlugin').MermaidPlugin);
    }, 'mermaid');
    return deferred.promise();
}

function loadHighlight() {
    const deferred = $.Deferred();
    require.ensure([
        'markdown-it-highlightjs'
    ], () => {
        deferred.resolve(require('markdown-it-highlightjs'));
    }, 'highlight');
    return deferred.promise();
}

export class Renderer {
    md: MarkdownIt.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() {
        this.md = new MarkdownIt({
            linkify: true
        });
        this.md.use(CheckboxPlugin, {
            checkboxClass: 'checkbox',
            readonly: false
        });
        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: MarkdownIt.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: MarkdownIt.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): Thenable<void> {
        return this.loadPlugins(text).then(() => {
                const html = this.md.render(text);
                morphdom(element[0], `<div>${html}</div>`, {
                    childrenOnly: true
                });
            }
        );
    }

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