summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/blob_edit/edit_blob.js
blob: 2a4ab4b882758936ed08b212e4a4e9fc11b6af02 (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
/* global ace */

import $ from 'jquery';
import axios from '~/lib/utils/axios_utils';
import { deprecatedCreateFlash as createFlash } from '~/flash';
import { BLOB_EDITOR_ERROR, BLOB_PREVIEW_ERROR } from './constants';
import TemplateSelectorMediator from '../blob/file_template_mediator';
import getModeByFileExtension from '~/lib/utils/ace_utils';
import { addEditorMarkdownListeners } from '~/lib/utils/text_markdown';

const monacoEnabledGlobally = window.gon.features?.monacoBlobs;

export default class EditBlob {
  // The options object has:
  // assetsPath, filePath, currentAction, projectId, isMarkdown
  constructor(options) {
    this.options = options;
    this.options.monacoEnabled = this.options.monacoEnabled ?? monacoEnabledGlobally;
    const { isMarkdown, monacoEnabled } = this.options;
    return Promise.resolve()
      .then(() => {
        return monacoEnabled ? this.configureMonacoEditor() : this.configureAceEditor();
      })
      .then(() => {
        this.initModePanesAndLinks();
        this.initFileSelectors();
        this.initSoftWrap();
        if (isMarkdown) {
          addEditorMarkdownListeners(this.editor);
        }
        this.editor.focus();
      })
      .catch(() => createFlash(BLOB_EDITOR_ERROR));
  }

  configureMonacoEditor() {
    const EditorPromise = import(
      /* webpackChunkName: 'monaco_editor_lite' */ '~/editor/editor_lite'
    );
    const MarkdownExtensionPromise = this.options.isMarkdown
      ? import('~/editor/editor_markdown_ext')
      : Promise.resolve(false);
    const FileTemplateExtensionPromise = import('~/editor/editor_file_template_ext');

    return Promise.all([EditorPromise, MarkdownExtensionPromise, FileTemplateExtensionPromise])
      .then(([EditorModule, MarkdownExtension, FileTemplateExtension]) => {
        const EditorLite = EditorModule.default;
        const editorEl = document.getElementById('editor');
        const fileNameEl =
          document.getElementById('file_path') || document.getElementById('file_name');
        const fileContentEl = document.getElementById('file-content');
        const form = document.querySelector('.js-edit-blob-form');

        const rootEditor = new EditorLite();

        this.editor = rootEditor.createInstance({
          el: editorEl,
          blobPath: fileNameEl.value,
          blobContent: editorEl.innerText,
        });

        rootEditor.use([MarkdownExtension.default, FileTemplateExtension.default], this.editor);

        fileNameEl.addEventListener('change', () => {
          this.editor.updateModelLanguage(fileNameEl.value);
        });

        form.addEventListener('submit', () => {
          fileContentEl.value = this.editor.getValue();
        });
      })
      .catch(() => createFlash(BLOB_EDITOR_ERROR));
  }

  configureAceEditor() {
    const { filePath, assetsPath } = this.options;
    ace.config.set('modePath', `${assetsPath}/ace`);
    ace.config.loadModule('ace/ext/searchbox');
    ace.config.loadModule('ace/ext/modelist');

    this.editor = ace.edit('editor');

    // This prevents warnings re: automatic scrolling being logged
    this.editor.$blockScrolling = Infinity;

    if (filePath) {
      this.editor.getSession().setMode(getModeByFileExtension(filePath));
    }
  }

  initFileSelectors() {
    const { currentAction, projectId } = this.options;
    this.fileTemplateMediator = new TemplateSelectorMediator({
      currentAction,
      editor: this.editor,
      projectId,
    });
  }

  initModePanesAndLinks() {
    this.$editModePanes = $('.js-edit-mode-pane');
    this.$editModeLinks = $('.js-edit-mode a');
    this.$editModeLinks.on('click', e => this.editModeLinkClickHandler(e));
  }

  editModeLinkClickHandler(e) {
    e.preventDefault();

    const currentLink = $(e.target);
    const paneId = currentLink.attr('href');
    const currentPane = this.$editModePanes.filter(paneId);

    this.$editModeLinks.parent().removeClass('active hover');

    currentLink.parent().addClass('active hover');

    this.$editModePanes.hide();

    currentPane.fadeIn(200);

    if (paneId === '#preview') {
      this.$toggleButton.hide();
      axios
        .post(currentLink.data('previewUrl'), {
          content: this.editor.getValue(),
        })
        .then(({ data }) => {
          currentPane.empty().append(data);
          currentPane.renderGFM();
        })
        .catch(() => createFlash(BLOB_PREVIEW_ERROR));
    }

    this.$toggleButton.show();

    return this.editor.focus();
  }

  initSoftWrap() {
    this.isSoftWrapped = Boolean(this.options.monacoEnabled);
    this.$toggleButton = $('.soft-wrap-toggle');
    this.$toggleButton.toggleClass('soft-wrap-active', this.isSoftWrapped);
    this.$toggleButton.on('click', () => this.toggleSoftWrap());
  }

  toggleSoftWrap() {
    this.isSoftWrapped = !this.isSoftWrapped;
    this.$toggleButton.toggleClass('soft-wrap-active', this.isSoftWrapped);
    if (this.options.monacoEnabled) {
      this.editor.updateOptions({ wordWrap: this.isSoftWrapped ? 'on' : 'off' });
    } else {
      this.editor.getSession().setUseWrapMode(this.isSoftWrapped);
    }
  }
}