edit_blob.js 2.2 KB
Newer Older
1
/* global ace */
2

3
import TemplateSelectorMediator from '../blob/file_template_mediator';
4 5

export default class EditBlob {
6
  constructor(assetsPath, aceMode, currentAction) {
7 8 9
    this.configureAceEditor(aceMode, assetsPath);
    this.initModePanesAndLinks();
    this.initSoftWrap();
10
    this.initFileSelectors(currentAction);
11 12 13 14 15 16 17
  }

  configureAceEditor(aceMode, assetsPath) {
    ace.config.set('modePath', `${assetsPath}/ace`);
    ace.config.loadModule('ace/ext/searchbox');

    this.editor = ace.edit('editor');
18 19 20 21

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

22 23 24 25 26 27 28
    this.editor.focus();

    if (aceMode) {
      this.editor.getSession().setMode(`ace/mode/${aceMode}`);
    }
  }

29 30 31 32
  initFileSelectors(currentAction) {
    this.fileTemplateMediator = new TemplateSelectorMediator({
      currentAction,
      editor: this.editor,
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
    });
  }

  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();
      return $.post(currentLink.data('preview-url'), {
        content: this.editor.getValue(),
      }, (response) => {
        currentPane.empty().append(response);
        return currentPane.renderGFM();
L
Luke "Jared" Bennett 已提交
64
      });
F
Fatih Acet 已提交
65 66
    }

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
    this.$toggleButton.show();

    return this.editor.focus();
  }

  initSoftWrap() {
    this.isSoftWrapped = false;
    this.$toggleButton = $('.soft-wrap-toggle');
    this.$toggleButton.on('click', () => this.toggleSoftWrap());
  }

  toggleSoftWrap() {
    this.isSoftWrapped = !this.isSoftWrapped;
    this.$toggleButton.toggleClass('soft-wrap-active', this.isSoftWrapped);
    this.editor.getSession().setUseWrapMode(this.isSoftWrapped);
  }
}