summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/notebook/cells/markdown.vue
blob: 9e4a92426ee3b9ef5c07089ca036e91bc826831c (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
<script>
/* global katex */
import marked from 'marked';
import sanitize from 'sanitize-html';
import Prompt from './prompt.vue';

const renderer = new marked.Renderer();

/*
    Regex to match KaTex blocks.

    Supports the following:

    \begin{equation}<math>\end{equation}
    $$<math>$$
    inline $<math>$

    The matched text then goes through the KaTex renderer & then outputs the HTML
  */
const katexRegexString = `(
    ^\\\\begin{[a-zA-Z]+}\\s
    |
    ^\\$\\$
    |
    \\s\\$(?!\\$)
  )
    ((.|\\n)+?)
  (
    \\s\\\\end{[a-zA-Z]+}$
    |
    \\$\\$$
    |
    \\$
  )
  `
  .replace(/\s/g, '')
  .trim();

renderer.paragraph = t => {
  let text = t;
  let inline = false;

  if (typeof katex !== 'undefined') {
    const katexString = text
      .replace(/&amp;/g, '&')
      .replace(/&=&/g, '\\space=\\space') // eslint-disable-line @gitlab/i18n/no-non-i18n-strings
      .replace(/<(\/?)em>/g, '_');
    const regex = new RegExp(katexRegexString, 'gi');
    const matchLocation = katexString.search(regex);
    const numberOfMatches = katexString.match(regex);

    if (numberOfMatches && numberOfMatches.length !== 0) {
      if (matchLocation > 0) {
        let matches = regex.exec(katexString);
        inline = true;

        while (matches !== null) {
          const renderedKatex = katex.renderToString(matches[0].replace(/\$/g, ''));
          text = `${text.replace(matches[0], ` ${renderedKatex}`)}`;
          matches = regex.exec(katexString);
        }
      } else {
        const matches = regex.exec(katexString);
        text = katex.renderToString(matches[2]);
      }
    }
  }

  return `<p class="${inline ? 'inline-katex' : ''}">${text}</p>`;
};

marked.setOptions({
  sanitize: true,
  renderer,
});

export default {
  components: {
    prompt: Prompt,
  },
  props: {
    cell: {
      type: Object,
      required: true,
    },
  },
  computed: {
    markdown() {
      return sanitize(marked(this.cell.source.join('').replace(/\\/g, '\\\\')), {
        allowedTags: false,
        allowedAttributes: {
          '*': ['class'],
        },
      });
    },
  },
};
</script>

<template>
  <div class="cell text-cell">
    <prompt />
    <div class="markdown" v-html="markdown"></div>
  </div>
</template>

<style>
.markdown .katex {
  display: block;
  text-align: center;
}

.markdown .inline-katex .katex {
  display: inline;
  text-align: initial;
}
</style>