All files / app/assets/javascripts/notebook/cells markdown.vue

96.83% Statements 61/63
78.57% Branches 22/28
100% Functions 7/7
96.83% Lines 61/63

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191  3x 3x 3x 3x 3x 3x   3x                         3x                                         25x 25x     44x 44x   44x 44x       44x 44x 44x   44x 13x 13x 10x   10x 22x 22x 19x   3x   22x     3x 3x             44x   3x 40x 40x   3x 4x 4x   3x   3x 5x   5x 1x     1x           1x     4x 4x   4x 4x   4x 3x   3x 3x 3x 3x         4x 1x     3x     3x                                       50x 50x   50x             159x                                                      
<script>
import katex from 'katex';
import marked from 'marked';
import { GlSafeHtmlDirective as SafeHtml } from '@gitlab/ui';
import { sanitize } from '~/lib/dompurify';
import { hasContent, markdownConfig } from '~/lib/utils/text_utility';
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();
 
function deHTMLify(t) {
  // get some specific characters back, that are allowed for KaTex rendering
  const text = t.replace(/&#39;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>');
  return text;
}
function renderKatex(t) {
  let text = t;
  let numInline = 0; // number of successfull converted math formulas
 
E  if (typeof katex !== 'undefined') {
    const katexString = text
      .replace(/&amp;/g, '&')
      .replace(/&=&/g, '\\space=\\space') // eslint-disable-line @gitlab/require-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) {
      let matches = regex.exec(katexString);
      if (matchLocation > 0) {
        numInline += 1;
 
        while (matches !== null) {
          try {
            const renderedKatex = katex.renderToString(deHTMLify(matches[0].replace(/\$/g, '')));
            text = `${text.replace(matches[0], ` ${renderedKatex}`)}`;
          } catch {
            numInline -= 1;
          }
          matches = regex.exec(katexString);
        }
      } else {
        try {
          text = katex.renderToString(deHTMLify(matches[2]));
        } catch (error) {
          numInline -= 1;
        }
      }
    }
  }
  return [text, numInline > 0];
}
renderer.paragraph = (t) => {
  const [text, inline] = renderKatex(t);
  return `<p class="${inline ? 'inline-katex' : ''}">${text}</p>`;
};
renderer.listitem = (t) => {
  const [text, inline] = renderKatex(t);
  return `<li class="${inline ? 'inline-katex' : ''}">${text}</li>`;
};
renderer.originalImage = renderer.image;
 
renderer.image = function image(href, title, text) {
  const attachmentHeader = `attachment:`; // eslint-disable-line @gitlab/require-i18n-strings
 
  if (!this.attachments || !href.startsWith(attachmentHeader)) {
    let relativeHref = href;
 
    // eslint-disable-next-line @gitlab/require-i18n-strings
I    if (!(href.startsWith('http') || href.startsWith('data:'))) {
      // These are images within the repo. This will only work if the image
      // is relative to the path where the file is located
      relativeHref = this.relativeRawPath + href;
    }
 
    return this.originalImage(relativeHref, title, text);
  }
 
  let img = ``;
  const filename = href.substring(attachmentHeader.length);
 
E  if (hasContent(filename)) {
    const attachment = this.attachments[filename];
 
    if (attachment) {
      const imageType = Object.keys(attachment)[0];
 
E      if (hasContent(imageType)) {
        const data = attachment[imageType];
        const inlined = `data:${imageType};base64,${data}"`; // eslint-disable-line @gitlab/require-i18n-strings
        img = this.originalImage(inlined, title, text);
      }
    }
  }
 
  if (!hasContent(img)) {
    return this.originalImage(href, title, text);
  }
 
  return sanitize(img);
};
 
marked.setOptions({
  renderer,
});
 
export default {
  components: {
    prompt: Prompt,
  },
  directives: {
    SafeHtml,
  },
  inject: ['relativeRawPath'],
  props: {
    cell: {
      type: Object,
      required: true,
    },
  },
  computed: {
    markdown() {
      renderer.attachments = this.cell.attachments;
      renderer.relativeRawPath = this.relativeRawPath;
 
      return marked(this.cell.source.join('').replace(/\\/g, '\\\\'));
    },
  },
  markdownConfig,
};
</script>
 
<template>
  <div class="cell text-cell">
    <prompt />
    <div v-safe-html:[$options.markdownConfig]="markdown" class="markdown"></div>
  </div>
</template>
 
<style>
/*
  Importing the necessary katex stylesheet from the node_module folder rather
  than copying the stylesheet into `app/assets/stylesheets/vendors` for
  automatic importing via `app/assets/stylesheets/application.scss`. The reason
  is that the katex stylesheet depends on many fonts that are in node_module
  subfolders - moving all these fonts would make updating katex difficult.
 */
@import '~katex/dist/katex.min.css';
 
.markdown .katex {
  display: block;
  text-align: center;
}
 
.markdown .inline-katex .katex {
  display: inline;
  text-align: initial;
}
</style>