All files / app/assets/javascripts/ide/components repo_editor.vue

93.41% Statements 156/167
87.5% Branches 98/112
94.44% Functions 51/54
93.33% Lines 154/165

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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559    2x 2x           2x 2x 2x 2x 2x 2x 2x 2x             2x 2x 2x 2x 2x           2x 2x 2x 2x 2x 2x 2x 2x   2x                                 50x                                                                       57x     100x     61x     70x     124x           72x     104x     104x     102x         28x         124x     48x           7x     55x     53x           54x   54x             5x 1x       5x 4x 4x   4x               2x 2x           1x 1x 1x       3x 1x       2x   6x 6x   2x       7x   5x 3x 3x 3x   2x 2x         50x     50x 50x   50x     50x     50x                         54x 54x 54x 3x     51x   51x   51x                     51x 51x 44x     7x       7x           52x 52x       52x 52x   52x 3x   49x 1x   49x 49x   49x               49x                             49x         11x   11x                       49x 49x         58x 59x   57x   57x         57x     57x     57x   57x   57x 12x 12x   12x 12x 12x       57x 24x           57x           57x       57x 57x     57x 57x     57x                       4x 4x     51x 51x 68x 117x   19x 34x   4x       51x     3x 3x 3x 3x   3x           2x 2x   2x 2x 2x   2x         2x           1x     51x 51x           84x 3x     81x                 54x                       410x                                                                                                                              
<script>
import { debounce } from 'lodash';
import { mapState, mapGetters, mapActions } from 'vuex';
import {
  EDITOR_TYPE_DIFF,
  EDITOR_TYPE_CODE,
  EDITOR_CODE_INSTANCE_FN,
  EDITOR_DIFF_INSTANCE_FN,
} from '~/editor/constants';
import { SourceEditorExtension } from '~/editor/extensions/source_editor_extension_base';
import { EditorWebIdeExtension } from '~/editor/extensions/source_editor_webide_ext';
import SourceEditor from '~/editor/source_editor';
import createFlash from '~/flash';
import ModelManager from '~/ide/lib/common/model_manager';
import { defaultDiffEditorOptions, defaultEditorOptions } from '~/ide/lib/editor_options';
import { __ } from '~/locale';
import {
  WEBIDE_MARK_FILE_CLICKED,
  WEBIDE_MARK_REPO_EDITOR_START,
  WEBIDE_MARK_REPO_EDITOR_FINISH,
  WEBIDE_MEASURE_REPO_EDITOR,
  WEBIDE_MEASURE_FILE_AFTER_INTERACTION,
} from '~/performance/constants';
import { performanceMarkAndMeasure } from '~/performance/utils';
import ContentViewer from '~/vue_shared/components/content_viewer/content_viewer.vue';
import { viewerInformationForPath } from '~/vue_shared/components/content_viewer/lib/viewer_utils';
import DiffViewer from '~/vue_shared/components/diff_viewer/diff_viewer.vue';
import {
  leftSidebarViews,
  viewerTypes,
  FILE_VIEW_MODE_EDITOR,
  FILE_VIEW_MODE_PREVIEW,
} from '../constants';
import eventHub from '../eventhub';
import { getRulesWithTraversal } from '../lib/editorconfig/parser';
import mapRulesToMonaco from '../lib/editorconfig/rules_mapper';
import { getFileEditorOrDefault } from '../stores/modules/editor/utils';
import { extractMarkdownImagesFromEntries } from '../stores/utils';
import { getPathParent, readFileAsDataURL, registerSchema, isTextFile } from '../utils';
import FileAlert from './file_alert.vue';
import FileTemplatesBar from './file_templates/bar.vue';
 
const MARKDOWN_FILE_TYPE = 'markdown';
 
export default {
  name: 'RepoEditor',
  components: {
    FileAlert,
    ContentViewer,
    DiffViewer,
    FileTemplatesBar,
  },
  props: {
    file: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      content: '',
      images: {},
      rules: {},
      globalEditor: null,
      modelManager: new ModelManager(),
      isEditorLoading: true,
      unwatchCiYaml: null,
    };
  },
  computed: {
    ...mapState('rightPane', {
      rightPaneIsOpen: 'isOpen',
    }),
    ...mapState('editor', ['fileEditors']),
    ...mapState([
      'viewer',
      'panelResizing',
      'currentActivityView',
      'renderWhitespaceInCode',
      'editorTheme',
      'entries',
      'currentProjectId',
      'previewMarkdownPath',
    ]),
    ...mapGetters([
      'getAlert',
      'currentMergeRequest',
      'getStagedFile',
      'isEditModeActive',
      'isCommitModeActive',
      'currentBranch',
      'getJsonSchemaForPath',
    ]),
    ...mapGetters('fileTemplates', ['showFileTemplatesBar']),
    alertKey() {
      return this.getAlert(this.file);
    },
    fileEditor() {
      return getFileEditorOrDefault(this.fileEditors, this.file.path);
    },
    isBinaryFile() {
      return !isTextFile(this.file);
    },
    shouldHideEditor() {
      return this.file && !this.file.loading && this.isBinaryFile;
    },
    showContentViewer() {
      return (
        (this.shouldHideEditor || this.isPreviewViewMode) &&
        (this.viewer !== viewerTypes.mr || !this.file.mrChange)
      );
    },
    showDiffViewer() {
      return this.shouldHideEditor && this.file.mrChange && this.viewer === viewerTypes.mr;
    },
    isEditorViewMode() {
      return this.fileEditor.viewMode === FILE_VIEW_MODE_EDITOR;
    },
    isPreviewViewMode() {
      return this.fileEditor.viewMode === FILE_VIEW_MODE_PREVIEW;
    },
    editTabCSS() {
      return {
        active: this.isEditorViewMode,
      };
    },
    previewTabCSS() {
      return {
        active: this.isPreviewViewMode,
      };
    },
    showEditor() {
      return !this.shouldHideEditor && this.isEditorViewMode;
    },
    editorOptions() {
      return {
        renderWhitespace: this.renderWhitespaceInCode ? 'all' : 'none',
        theme: this.editorTheme,
      };
    },
    currentBranchCommit() {
      return this.currentBranch?.commit.id;
    },
    previewMode() {
      return viewerInformationForPath(this.file.path);
    },
    fileType() {
      return this.previewMode?.id || '';
    },
  },
  watch: {
    'file.name': {
      handler() {
        this.stopWatchingCiYaml();
 
I        if (this.file.name === '.gitlab-ci.yml') {
          this.startWatchingCiYaml();
        }
      },
      immediate: true,
    },
    file(newVal, oldVal) {
      if (oldVal.pending) {
        this.removePendingTab(oldVal);
      }
 
      // Compare key to allow for files opened in review mode to be cached differently
      if (oldVal.key !== this.file.key) {
        this.isEditorLoading = true;
        this.initEditor();
 
I        if (this.currentActivityView !== leftSidebarViews.edit.name) {
          this.updateEditor({
            viewMode: FILE_VIEW_MODE_EDITOR,
          });
        }
      }
    },
    currentActivityView() {
E      if (this.currentActivityView !== leftSidebarViews.edit.name) {
        this.updateEditor({
          viewMode: FILE_VIEW_MODE_EDITOR,
        });
      }
    },
    viewer() {
      this.isEditorLoading = false;
E      if (!this.file.pending) {
        this.createEditorInstance();
      }
    },
    panelResizing() {
      if (!this.panelResizing) {
        this.refreshEditorDimensions();
      }
    },
    rightPaneIsOpen() {
      this.refreshEditorDimensions();
    },
    showEditor(val) {
      if (val) {
        // We need to wait for the editor to actually be rendered.
        this.$nextTick(() => this.refreshEditorDimensions());
      }
    },
    showContentViewer(val) {
      if (!val) return;
 
      if (this.fileType === MARKDOWN_FILE_TYPE) {
        const { content, images } = extractMarkdownImagesFromEntries(this.file, this.entries);
        this.content = content;
        this.images = images;
      } else {
        this.content = this.file.content || this.file.raw;
        this.images = {};
      }
    },
  },
  beforeDestroy() {
    this.globalEditor.dispose();
  },
  mounted() {
E    if (!this.globalEditor) {
      this.globalEditor = new SourceEditor();
    }
    this.initEditor();
 
    // listen in capture phase to be able to override Monaco's behaviour.
    window.addEventListener('paste', this.onPaste, true);
  },
  destroyed() {
    window.removeEventListener('paste', this.onPaste, true);
  },
  methods: {
    ...mapActions([
      'getFileData',
      'getRawFileData',
      'changeFileContent',
      'removePendingTab',
      'triggerFilesChange',
      'addTempImage',
      'detectGitlabCiFileAlerts',
    ]),
    ...mapActions('editor', ['updateFileEditor']),
    initEditor() {
      performanceMarkAndMeasure({ mark: WEBIDE_MARK_REPO_EDITOR_START });
      if (this.shouldHideEditor && (this.file.content || this.file.raw)) {
        return;
      }
 
      this.registerSchemaForFile();
 
      Promise.all([this.fetchFileData(), this.fetchEditorconfigRules()])
        .then(() => {
          this.createEditorInstance();
        })
        .catch((err) => {
          createFlash({
            message: __('Error setting up editor. Please try again.'),
            fadeTransition: false,
            addBodyClass: true,
          });
          throw err;
        });
    },
    fetchFileData() {
      if (this.file.tempFile) {
        return Promise.resolve();
      }
 
      return this.getFileData({
        path: this.file.path,
        makeFileActive: false,
        toggleLoading: false,
      }).then(() =>
        this.getRawFileData({
          path: this.file.path,
        }),
      );
    },
    createEditorInstance() {
I      if (this.isBinaryFile) {
        return;
      }
 
      const isDiff = this.viewer !== viewerTypes.edit;
      const shouldDisposeEditor = isDiff !== (this.editor?.getEditorType() === EDITOR_TYPE_DIFF);
 
      if (this.editor && !shouldDisposeEditor) {
        this.setupEditor();
      } else {
        if (this.editor && shouldDisposeEditor) {
          this.editor.dispose();
        }
        const instanceOptions = isDiff ? defaultDiffEditorOptions : defaultEditorOptions;
        const method = isDiff ? EDITOR_DIFF_INSTANCE_FN : EDITOR_CODE_INSTANCE_FN;
 
        this.editor = this.globalEditor[method]({
          el: this.$refs.editor,
          blobPath: this.file.path,
          blobGlobalId: this.file.key,
          blobContent: this.content || this.file.content,
          ...instanceOptions,
          ...this.editorOptions,
        });
        this.editor.use([
          {
            definition: SourceEditorExtension,
          },
          {
            definition: EditorWebIdeExtension,
            setupOptions: {
              modelManager: this.modelManager,
              store: this.$store,
              file: this.file,
              options: this.editorOptions,
            },
          },
        ]);
 
        if (
          this.fileType === MARKDOWN_FILE_TYPE &&
          this.editor?.getEditorType() === EDITOR_TYPE_CODE &&
          this.previewMarkdownPath
        ) {
          import('~/editor/extensions/source_editor_markdown_livepreview_ext')
            .then(({ EditorMarkdownPreviewExtension: MarkdownLivePreview }) => {
              this.editor.use({
                definition: MarkdownLivePreview,
                setupOptions: { previewMarkdownPath: this.previewMarkdownPath },
              });
            })
            .catch((e) =>
              createFlash({
                message: e,
              }),
            );
        }
 
        this.$nextTick(() => {
          this.setupEditor();
        });
      }
    },
 
    setupEditor() {
      if (!this.file || !this.editor || this.file.loading) return;
 
      const head = this.getStagedFile(this.file.path);
 
      this.model = this.editor.createModel(
        this.file,
        this.file.staged && this.file.key.indexOf('unstaged-') === 0 ? head : null,
      );
 
I      if (this.viewer === viewerTypes.mr && this.file.mrChange) {
        this.editor.attachMergeRequestModel(this.model);
      } else {
        this.editor.attachModel(this.model);
      }
 
      this.isEditorLoading = false;
 
      this.model.updateOptions(this.rules);
 
      this.model.onChange((model) => {
        const { file } = model;
I        if (!file.active) return;
 
        const monacoModel = model.getModel();
        const content = monacoModel.getValue();
        this.changeFileContent({ path: file.path, content });
      });
 
      // Handle Cursor Position
      this.editor.onPositionChange((instance, e) => {
        this.updateEditor({
          editorRow: e.position.lineNumber,
          editorColumn: e.position.column,
        });
      });
 
      this.editor.setPos({
        lineNumber: this.fileEditor.editorRow,
        column: this.fileEditor.editorColumn,
      });
 
      // Handle File Language
      this.updateEditor({
        fileLanguage: this.model.language,
      });
 
      this.$nextTick(() => {
        this.editor.updateDimensions();
      });
 
      this.$emit('editorSetup');
I      if (performance.getEntriesByName(WEBIDE_MARK_FILE_CLICKED).length) {
        eventHub.$emit(WEBIDE_MEASURE_FILE_AFTER_INTERACTION);
      } else {
        performanceMarkAndMeasure({
          mark: WEBIDE_MARK_REPO_EDITOR_FINISH,
          measures: [
            {
              name: WEBIDE_MEASURE_REPO_EDITOR,
              start: WEBIDE_MARK_REPO_EDITOR_START,
            },
          ],
        });
      }
    },
    refreshEditorDimensions() {
E      if (this.showEditor) {
        this.editor.updateDimensions();
      }
    },
    fetchEditorconfigRules() {
      return getRulesWithTraversal(this.file.path, (path) => {
        const entry = this.entries[path];
        if (!entry) return Promise.resolve(null);
 
        const content = entry.content || entry.raw;
        if (content) return Promise.resolve(content);
 
        return this.getFileData({ path: entry.path, makeFileActive: false }).then(() =>
          this.getRawFileData({ path: entry.path }),
        );
      }).then((rules) => {
        this.rules = mapRulesToMonaco(rules);
      });
    },
    onPaste(event) {
      const { editor } = this;
      const reImage = /^image\/(png|jpg|jpeg|gif)$/;
      const file = event.clipboardData.files[0];
 
      if (
        editor.hasTextFocus() &&
        this.fileType === MARKDOWN_FILE_TYPE &&
        reImage.test(file?.type)
      ) {
        // don't let the event be passed on to Monaco.
        event.preventDefault();
        event.stopImmediatePropagation();
 
        return readFileAsDataURL(file).then((content) => {
          const parentPath = getPathParent(this.file.path);
          const path = `${parentPath ? `${parentPath}/` : ''}${file.name}`;
 
          return this.addTempImage({
            name: path,
            rawPath: URL.createObjectURL(file),
            content: atob(content.split('base64,')[1]),
          }).then(({ name: fileName }) => {
            this.editor.replaceSelectedText(`![${fileName}](./${fileName})`);
          });
        });
      }
 
      // do nothing if no image is found in the clipboard
      return Promise.resolve();
    },
    registerSchemaForFile() {
      const schema = this.getJsonSchemaForPath(this.file.path);
      registerSchema(schema);
    },
    updateEditor(data) {
      // Looks like our model wrapper `.dispose` causes the monaco editor to emit some position changes after
      // when disposing. We want to ignore these by only capturing editor changes that happen to the currently active
      // file.
      if (!this.file.active) {
        return;
      }
 
      this.updateFileEditor({ path: this.file.path, data });
    },
    startWatchingCiYaml() {
      this.unwatchCiYaml = this.$watch(
        'file.content',
        debounce(this.detectGitlabCiFileAlerts, 500),
      );
    },
    stopWatchingCiYaml() {
I      if (this.unwatchCiYaml) {
        this.unwatchCiYaml();
        this.unwatchCiYaml = null;
      }
    },
  },
  viewerTypes,
  FILE_VIEW_MODE_EDITOR,
  FILE_VIEW_MODE_PREVIEW,
};
</script>
 
<template>
  <div id="ide" class="blob-viewer-container blob-editor-container">
    <div v-if="!shouldHideEditor && isEditModeActive" class="ide-mode-tabs clearfix">
      <ul class="nav-links float-left border-bottom-0">
        <li :class="editTabCSS">
          <a
            href="javascript:void(0);"
            role="button"
            data-testid="edit-tab"
            @click.prevent="updateEditor({ viewMode: $options.FILE_VIEW_MODE_EDITOR })"
            >{{ __('Edit') }}</a
          >
        </li>
        <li v-if="previewMode" :class="previewTabCSS">
          <a
            href="javascript:void(0);"
            role="button"
            data-testid="preview-tab"
            @click.prevent="updateEditor({ viewMode: $options.FILE_VIEW_MODE_PREVIEW })"
            >{{ previewMode.previewTitle }}</a
          >
        </li>
      </ul>
    </div>
    <file-alert v-if="alertKey" :alert-key="alertKey" />
    <file-templates-bar v-else-if="showFileTemplatesBar(file.name)" />
    <div
      v-show="showEditor"
      ref="editor"
      :key="`content-editor`"
      :class="{
        'is-readonly': isCommitModeActive,
        'is-deleted': file.deleted,
        'is-added': file.tempFile,
      }"
      class="multi-file-editor-holder"
      data-qa-selector="editor_container"
      data-testid="editor-container"
      :data-editor-loading="isEditorLoading"
      @focusout="triggerFilesChange"
    ></div>
    <content-viewer
      v-if="showContentViewer"
      :content="content"
      :images="images"
      :path="file.rawPath || file.path"
      :file-path="file.path"
      :file-size="file.size"
      :project-path="currentProjectId"
      :commit-sha="currentBranchCommit"
      :type="fileType"
    />
    <diff-viewer
      v-if="showDiffViewer"
      :diff-mode="file.mrChange.diffMode"
      :new-path="file.mrChange.new_path"
      :new-sha="currentMergeRequest.sha"
      :old-path="file.mrChange.old_path"
      :old-sha="currentMergeRequest.baseCommitSha"
      :project-path="currentProjectId"
    />
  </div>
</template>