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

1.42% Statements 2/140
3.09% Branches 3/97
2.08% Functions 1/48
1.48% Lines 2/135

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                                                                                        36x   2x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
<script>
import { GlTabs, GlTab } from '@gitlab/ui';
// eslint-disable-next-line no-restricted-imports
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 { createAlert } from '~/alert';
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 { markRaw } from '~/lib/utils/vue3compat/mark_raw';
import { readFileAsDataURL } from '~/lib/utils/file_utility';
import { hasCiConfigExtension } from '~/lib/utils/common_utils';
 
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, registerSchema, isTextFile } from '../utils';
import FileTemplatesBar from './file_templates/bar.vue';
 
const MARKDOWN_FILE_TYPE = 'markdown';
 
export default {
  name: 'RepoEditor',
  components: {
    GlTabs,
    GlTab,
    ContentViewer,
    DiffViewer,
    FileTemplatesBar,
  },
  props: {
    file: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      content: '',
      images: {},
      rules: {},
      globalEditor: null,
      modelManager: markRaw(new ModelManager()),
      isEditorLoading: true,
      unwatchCiYaml: null,
      SELivepreviewExtension: null,
      MarkdownLivePreview: null,
    };
  },
  computed: {
    ...mapState('rightPane', {
      rightPaneIsOpen: 'isOpen',
    }),
    ...mapState('editor', ['fileEditors']),
    ...mapState([
      'viewer',
      'panelResizing',
      'currentActivityView',
      'renderWhitespaceInCode',
      'editorTheme',
      'entries',
      'currentProjectId',
      'previewMarkdownPath',
    ]),
    ...mapGetters([
      'currentMergeRequest',
      'getStagedFile',
      'isEditModeActive',
      'isCommitModeActive',
      'currentBranch',
      'getJsonSchemaForPath',
    ]),
    ...mapGetters('fileTemplates', ['showFileTemplatesBar']),
    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;
    },
    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 || '';
    },
    showTabs() {
      return !this.shouldHideEditor && this.isEditModeActive && this.previewMode;
    },
    isCiConfigFile() {
      return (
        // For CI config schemas the filename must match '*.gitlab-ci.yml' regardless of project configuration.
        // https://gitlab.com/gitlab-org/gitlab/-/issues/293641
        hasCiConfigExtension(this.file.path) && this.editor?.getEditorType() === EDITOR_TYPE_CODE
      );
    },
  },
  watch: {
    file(newVal, oldVal) {
      Iif (oldVal.pending) {
        this.removePendingTab(oldVal);
      }
 
      // Compare key to allow for files opened in review mode to be cached differently
      Iif (oldVal.key !== this.file.key) {
        this.isEditorLoading = true;
        this.initEditor();
 
        Iif (this.currentActivityView !== leftSidebarViews.edit.name) {
          this.updateEditor({
            viewMode: FILE_VIEW_MODE_EDITOR,
          });
        }
      }
    },
    currentActivityView() {
      Iif (this.currentActivityView !== leftSidebarViews.edit.name) {
        this.updateEditor({
          viewMode: FILE_VIEW_MODE_EDITOR,
        });
      }
    },
    viewer() {
      this.isEditorLoading = false;
      Iif (!this.file.pending) {
        this.createEditorInstance();
      }
    },
    showContentViewer(val) {
      Iif (!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() {
    Iif (!this.globalEditor) {
      this.globalEditor = markRaw(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',
    ]),
    ...mapActions('editor', ['updateFileEditor']),
    initEditor() {
      performanceMarkAndMeasure({ mark: WEBIDE_MARK_REPO_EDITOR_START });
      Iif (this.shouldHideEditor && (this.file.content || this.file.raw)) {
        return;
      }
 
      Promise.all([this.fetchFileData(), this.fetchEditorconfigRules()])
        .then(() => {
          this.createEditorInstance();
        })
        .catch((err) => {
          createAlert({
            message: __('Error setting up editor. Please try again.'),
            fadeTransition: false,
            addBodyClass: true,
          });
          throw err;
        });
    },
    fetchFileData() {
      Iif (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() {
      Iif (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 {
        Iif (this.editor && shouldDisposeEditor) {
          this.editor.dispose();
        }
        const instanceOptions = isDiff ? defaultDiffEditorOptions : defaultEditorOptions;
        const method = isDiff ? EDITOR_DIFF_INSTANCE_FN : EDITOR_CODE_INSTANCE_FN;
 
        this.editor = markRaw(
          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,
            },
          },
        ]);
 
        this.$nextTick(() => {
          this.setupEditor();
        });
      }
    },
 
    setupEditor() {
      Iif (!this.file || !this.editor || this.file.loading) return;
 
      const useLivePreviewExtension = () => {
        this.SELivepreviewExtension = this.editor.use({
          definition: this.MarkdownLivePreview,
          setupOptions: { previewMarkdownPath: this.previewMarkdownPath },
        });
      };
      if (
        this.fileType === MARKDOWN_FILE_TYPE &&
        this.editor?.getEditorType() === EDITOR_TYPE_CODE &&
        this.previewMarkdownPath
      ) {
        if (this.MarkdownLivePreview) {
          useLivePreviewExtension();
        } else {
          import('~/editor/extensions/source_editor_markdown_livepreview_ext')
            .then(({ EditorMarkdownPreviewExtension }) => {
              this.MarkdownLivePreview = EditorMarkdownPreviewExtension;
              useLivePreviewExtension();
            })
            .catch((e) =>
              createAlert({
                message: e,
              }),
            );
        }
      } else Iif (this.SELivepreviewExtension) {
        this.editor.unuse(this.SELivepreviewExtension);
      }
 
      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,
      );
 
      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.registerSchemaForFile();
 
      this.model.onChange((model) => {
        const { file } = model;
        Iif (!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.$emit('editorSetup');
      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,
            },
          ],
        });
      }
    },
    fetchEditorconfigRules() {
      return getRulesWithTraversal(this.file.path, (path) => {
        const entry = this.entries[path];
        Iif (!entry) return Promise.resolve(null);
 
        const content = entry.content || entry.raw;
        Iif (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];
 
      Iif (
        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 registerExternalSchema = () => {
        const schema = this.getJsonSchemaForPath(this.file.path);
        return registerSchema(schema);
      };
      const registerLocalSchema = async () => {
        Iif (!this.CiSchemaExtension) {
          const { CiSchemaExtension } = await import(
            '~/editor/extensions/source_editor_ci_schema_ext'
          ).catch((e) =>
            createAlert({
              message: e,
            }),
          );
          this.CiSchemaExtension = CiSchemaExtension;
        }
        this.editor.use({ definition: this.CiSchemaExtension });
        this.editor.registerCiSchema();
      };
 
      if (this.isCiConfigFile) {
        registerLocalSchema();
      } else {
        Iif (this.CiSchemaExtension) {
          this.editor.unuse(this.CiSchemaExtension);
        }
        registerExternalSchema();
      }
    },
    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.
      Iif (!this.file.active) {
        return;
      }
 
      this.updateFileEditor({ path: this.file.path, data });
    },
  },
  viewerTypes,
  FILE_VIEW_MODE_EDITOR,
  FILE_VIEW_MODE_PREVIEW,
};
</script>
 
<template>
  <div id="ide" class="blob-viewer-container blob-editor-container">
    <gl-tabs v-if="showTabs" content-class="gl-display-none">
      <gl-tab
        :title="__('Edit')"
        data-testid="edit-tab"
        @click="updateEditor({ viewMode: $options.FILE_VIEW_MODE_EDITOR })"
      />
      <gl-tab
        :title="previewMode.previewTitle"
        data-testid="preview-tab"
        @click="updateEditor({ viewMode: $options.FILE_VIEW_MODE_PREVIEW })"
      />
    </gl-tabs>
    <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-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>