summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/content_editor/extensions/diagram.js
blob: 7c4a56468eb03a70110bf1c5443a8d0e1546247f (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
import { lowlight } from 'lowlight/lib/core';
import { textblockTypeInputRule } from '@tiptap/core';
import { base64DecodeUnicode } from '~/lib/utils/text_utility';
import { PARSE_HTML_PRIORITY_HIGHEST } from '../constants';
import languageLoader from '../services/code_block_language_loader';
import CodeBlockHighlight from './code_block_highlight';

const backtickInputRegex = /^```(mermaid|plantuml)[\s\n]$/;

export default CodeBlockHighlight.extend({
  name: 'diagram',

  isolating: true,

  addOptions() {
    return {
      lowlight,
    };
  },

  addAttributes() {
    return {
      language: {
        default: null,
        parseHTML: (element) => {
          return element.dataset.diagram;
        },
      },
      isDiagram: {
        default: true,
      },
      showPreview: {
        default: true,
      },
    };
  },

  parseHTML() {
    return [
      {
        priority: PARSE_HTML_PRIORITY_HIGHEST,
        tag: 'pre[lang="mermaid"]',
        getAttrs: () => ({ language: 'mermaid' }),
      },
      {
        priority: PARSE_HTML_PRIORITY_HIGHEST,
        tag: '[data-diagram]',
        getContent(element, schema) {
          const source = base64DecodeUnicode(
            element.dataset.diagramSrc.replace('data:text/plain;base64,', ''),
          );
          const node = schema.node('paragraph', {}, [schema.text(source)]);
          return node.content;
        },
      },
    ];
  },

  renderHTML({ HTMLAttributes: { language, ...HTMLAttributes } }) {
    return [
      'div',
      [
        'pre',
        {
          language,
          class: `content-editor-code-block code highlight`,
          ...HTMLAttributes,
        },
        ['code', {}, 0],
      ],
    ];
  },

  addCommands() {
    return {};
  },

  addInputRules() {
    const getAttributes = (match) => languageLoader?.loadLanguageFromInputRule(match) || {};

    return [
      textblockTypeInputRule({
        find: backtickInputRegex,
        type: this.type,
        getAttributes,
      }),
    ];
  },
});