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

code_block_highlight.js « extensions « content_editor « javascripts « assets « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 74f620b57b6927230d38e0f2169f235c99dfc7c7 (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
import { CodeBlockLowlight } from '@tiptap/extension-code-block-lowlight';
import { textblockTypeInputRule } from '@tiptap/core';
import { isFunction } from 'lodash';

const extractLanguage = (element) => element.getAttribute('lang');
const backtickInputRegex = /^```([a-z]+)?[\s\n]$/;
const tildeInputRegex = /^~~~([a-z]+)?[\s\n]$/;

const loadLanguageFromInputRule = (languageLoader) => (match) => {
  const language = match[1];

  if (isFunction(languageLoader?.loadLanguages)) {
    languageLoader.loadLanguages([language]);
  }

  return {
    language,
  };
};

export default CodeBlockLowlight.extend({
  isolating: true,

  addOptions() {
    return {
      ...this.parent?.(),
      languageLoader: {},
    };
  },

  addAttributes() {
    return {
      language: {
        default: null,
        parseHTML: (element) => extractLanguage(element),
      },
      class: {
        // eslint-disable-next-line @gitlab/require-i18n-strings
        default: 'code highlight',
      },
    };
  },
  addInputRules() {
    const { languageLoader } = this.options;

    return [
      textblockTypeInputRule({
        find: backtickInputRegex,
        type: this.type,
        getAttributes: loadLanguageFromInputRule(languageLoader),
      }),
      textblockTypeInputRule({
        find: tildeInputRegex,
        type: this.type,
        getAttributes: loadLanguageFromInputRule(languageLoader),
      }),
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return [
      'pre',
      {
        ...HTMLAttributes,
        class: `content-editor-code-block ${HTMLAttributes.class}`,
      },
      ['code', {}, 0],
    ];
  },
});