All files / app/assets/javascripts/ide/lib editor.js

80.72% Statements 67/83
53.57% Branches 15/28
77.77% Functions 21/27
82.05% Lines 64/78

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                            29x 174x           64x 29x   64x       29x 29x 29x 29x 29x 29x 29x       29x       29x   29x 29x   29x           51x 51x   51x                   51x   51x         5x 5x   5x             5x   5x         10x       8x 1x         1x     7x 7x   7x   7x   7x 14x       7x       7x       1x         1x           1x 1x         67x       67x 67x   67x                                                                       1x               2x 2x             2x   2x 2x       11x       5x       56x 56x 224x   224x     56x 112x 112x     112x     112x                        
import { debounce } from 'lodash';
import { editor as monacoEditor, KeyCode, KeyMod, Range } from 'monaco-editor';
import { clearDomElement } from '~/editor/utils';
import { registerLanguages } from '../utils';
import Disposable from './common/disposable';
import ModelManager from './common/model_manager';
import DecorationsController from './decorations/controller';
import DirtyDiffController from './diff/controller';
import { editorOptions, defaultEditorOptions, defaultDiffEditorOptions } from './editor_options';
import keymap from './keymap.json';
import languages from './languages';
import { themes } from './themes';
 
function setupThemes() {
  themes.forEach((theme) => {
    monacoEditor.defineTheme(theme.name, theme.data);
  });
}
 
export default class Editor {
  static create(...args) {
    if (!this.editorInstance) {
      this.editorInstance = new Editor(...args);
    }
    return this.editorInstance;
  }
 
  constructor(store, options = {}) {
    this.currentModel = null;
    this.instance = null;
    this.dirtyDiffController = null;
    this.disposable = new Disposable();
    this.modelManager = new ModelManager();
    this.decorationsController = new DecorationsController(this);
    this.options = {
      ...defaultEditorOptions,
      ...options,
    };
    this.diffOptions = {
      ...defaultDiffEditorOptions,
      ...options,
    };
    this.store = store;
 
    setupThemes();
    registerLanguages(...languages);
 
    this.debouncedUpdate = debounce(() => {
      this.updateDimensions();
    }, 200);
  }
 
  createInstance(domElement) {
    Eif (!this.instance) {
      clearDomElement(domElement);
 
      this.disposable.add(
        (this.instance = monacoEditor.create(domElement, {
          ...this.options,
        })),
        (this.dirtyDiffController = new DirtyDiffController(
          this.modelManager,
          this.decorationsController,
        )),
      );
 
      this.addCommands();
 
      window.addEventListener('resize', this.debouncedUpdate, false);
    }
  }
 
  createDiffInstance(domElement) {
    Eif (!this.instance) {
      clearDomElement(domElement);
 
      this.disposable.add(
        (this.instance = monacoEditor.createDiffEditor(domElement, {
          ...this.diffOptions,
          renderSideBySide: Editor.renderSideBySide(domElement),
        })),
      );
 
      this.addCommands();
 
      window.addEventListener('resize', this.debouncedUpdate, false);
    }
  }
 
  createModel(file, head = null) {
    return this.modelManager.addModel(file, head);
  }
 
  attachModel(model) {
    if (this.isDiffEditorType) {
      this.instance.setModel({
        original: model.getOriginalModel(),
        modified: model.getModel(),
      });
 
      return;
    }
 
    this.instance.setModel(model.getModel());
    Eif (this.dirtyDiffController) this.dirtyDiffController.attachModel(model);
 
    this.currentModel = model;
 
    this.instance.updateOptions(
      editorOptions.reduce((acc, obj) => {
        Object.keys(obj).forEach((key) => {
          Object.assign(acc, {
            [key]: obj[key](model),
          });
        });
        return acc;
      }, {}),
    );
 
    Eif (this.dirtyDiffController) this.dirtyDiffController.reDecorate(model);
  }
 
  attachMergeRequestModel(model) {
    this.instance.setModel({
      original: model.getBaseModel(),
      modified: model.getModel(),
    });
 
    monacoEditor.createDiffNavigator(this.instance, {
      alwaysRevealFirst: true,
    });
  }
 
  clearEditor() {
    Eif (this.instance) {
      this.instance.setModel(null);
    }
  }
 
  dispose() {
    window.removeEventListener('resize', this.debouncedUpdate);
 
    // catch any potential errors with disposing the error
    // this is mainly for tests caused by elements not existing
    try {
      this.disposable.dispose();
 
      this.instance = null;
    } catch (e) {
      this.instance = null;
 
      if (process.env.NODE_ENV !== 'test') {
        // eslint-disable-next-line no-console
        console.error(e);
      }
    }
  }
 
  updateDimensions() {
    if (this.instance) {
      this.instance.layout();
      this.updateDiffView();
    }
  }
 
  setPosition({ lineNumber, column }) {
    this.instance.revealPositionInCenter({
      lineNumber,
      column,
    });
    this.instance.setPosition({
      lineNumber,
      column,
    });
  }
 
  onPositionChange(cb) {
    if (!this.instance.onDidChangeCursorPosition) return;
 
    this.disposable.add(this.instance.onDidChangeCursorPosition((e) => cb(this.instance, e)));
  }
 
  updateDiffView() {
    Eif (!this.isDiffEditorType) return;
 
    this.instance.updateOptions({
      renderSideBySide: Editor.renderSideBySide(this.instance.getDomNode()),
    });
  }
 
  replaceSelectedText(text) {
    let selection = this.instance.getSelection();
    const range = new Range(
      selection.startLineNumber,
      selection.startColumn,
      selection.endLineNumber,
      selection.endColumn,
    );
 
    this.instance.executeEdits('', [{ range, text }]);
 
    selection = this.instance.getSelection();
    this.instance.setPosition({ lineNumber: selection.endLineNumber, column: selection.endColumn });
  }
 
  get isDiffEditorType() {
    return this.instance.getEditorType() === 'vs.editor.IDiffEditor';
  }
 
  static renderSideBySide(domElement) {
    return domElement.offsetWidth >= 700;
  }
 
  addCommands() {
    const { store } = this;
    const getKeyCode = (key) => {
      const monacoKeyMod = key.indexOf('KEY_') === 0;
 
      return monacoKeyMod ? KeyCode[key] : KeyMod[key];
    };
 
    keymap.forEach((command) => {
      const keybindings = command.bindings.map((binding) => {
        const keys = binding.split('+');
 
        // eslint-disable-next-line no-bitwise
        return keys.length > 1 ? getKeyCode(keys[0]) | getKeyCode(keys[1]) : getKeyCode(keys[0]);
      });
 
      this.instance.addAction({
        id: command.id,
        label: command.label,
        keybindings,
        run() {
          store.dispatch(command.action.name, command.action.params);
          return null;
        },
      });
    });
  }
}