All files / app/assets/javascripts/editor/extensions source_editor_extension_base.js

98.21% Statements 55/56
92.1% Branches 35/38
94.44% Functions 17/18
98.18% Lines 54/55

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                    10x   10x 7x 7x 7x 7x 7x 7x 1x   7x         250x       125x 125x 16x           124x 124x 99x         2x 2x 1x         16x                           16x       9x 9x 8x 8x 8x 8x 7x 7x           103x 103x 2x     2x 1x   1x 1x             146x     146x 146x 146x 1x   146x 17x 17x 17x                           199x           1x                         22x       5x 5x 5x 5x     5x            
import { Range } from 'monaco-editor';
import { __ } from '~/locale';
import {
  EDITOR_TYPE_CODE,
  EXTENSION_BASE_LINE_LINK_ANCHOR_CLASS,
  EXTENSION_BASE_LINE_NUMBERS_CLASS,
  EDITOR_TOOLBAR_BUTTON_GROUPS,
  EXTENSION_SOFTWRAP_ID,
} from '../constants';
 
const hashRegexp = /#?L/g;
 
const createAnchor = (href) => {
  const fragment = new DocumentFragment();
  const el = document.createElement('a');
  el.classList.add(EXTENSION_BASE_LINE_LINK_ANCHOR_CLASS);
  el.href = href;
  fragment.appendChild(el);
  el.addEventListener('contextmenu', (e) => {
    e.stopPropagation();
  });
  return fragment;
};
 
export class SourceEditorExtension {
  static get extensionName() {
    return 'BaseExtension';
  }
 
  onSetup(instance) {
    this.toolbarButtons = [];
    if (instance.toolbar) {
      this.setupToolbar(instance);
    }
  }
 
  // eslint-disable-next-line class-methods-use-this
  onUse(instance) {
    SourceEditorExtension.highlightLines(instance);
    if (instance.getEditorType && instance.getEditorType() === EDITOR_TYPE_CODE) {
      SourceEditorExtension.setupLineLinking(instance);
    }
  }
 
  onBeforeUnuse(instance) {
    const ids = this.toolbarButtons.map((item) => item.id);
    if (instance.toolbar) {
      instance.toolbar.removeItems(ids);
    }
  }
 
  setupToolbar(instance) {
    this.toolbarButtons = [
      {
        id: EXTENSION_SOFTWRAP_ID,
        label: __('Soft wrap'),
        icon: 'soft-wrap',
        selected: instance.getOption(116) === 'on',
        group: EDITOR_TOOLBAR_BUTTON_GROUPS.settings,
        category: 'primary',
        selectedLabel: __('No wrap'),
        selectedIcon: 'soft-unwrap',
        class: 'soft-wrap-toggle',
        onClick: () => instance.toggleSoftwrap(),
      },
    ];
    instance.toolbar.addItems(this.toolbarButtons);
  }
 
  static onMouseMoveHandler(e) {
    const target = e.target.element;
    if (target.classList.contains(EXTENSION_BASE_LINE_NUMBERS_CLASS)) {
      const lineNum = e.target.position.lineNumber;
      const hrefAttr = `#L${lineNum}`;
      let lineLink = target.querySelector('a');
      if (!lineLink) {
        lineLink = createAnchor(hrefAttr);
        target.appendChild(lineLink);
      }
    }
  }
 
  static setupLineLinking(instance) {
    instance.onMouseMove(SourceEditorExtension.onMouseMoveHandler);
    instance.onMouseDown((e) => {
      const isCorrectAnchor = e.target.element.classList.contains(
        EXTENSION_BASE_LINE_LINK_ANCHOR_CLASS,
      );
      if (!isCorrectAnchor) {
        return;
      }
      Eif (instance.lineDecorations) {
        instance.deltaDecorations(instance.lineDecorations, []);
      }
    });
  }
 
  static highlightLines(instance, bounds = null) {
    const [start, end] =
      bounds && Array.isArray(bounds)
        ? bounds
        : window.location.hash.replace(hashRegexp, '').split('-');
    let startLine = start ? parseInt(start, 10) : null;
    let endLine = end ? parseInt(end, 10) : startLine;
    if (endLine < startLine) {
      [startLine, endLine] = [endLine, startLine];
    }
    if (startLine) {
      window.requestAnimationFrame(() => {
        instance.revealLineInCenter(startLine);
        Object.assign(instance, {
          lineDecorations: instance.deltaDecorations(instance.lineDecorations || [], [
            {
              range: new Range(startLine, 1, endLine, 1),
              options: { isWholeLine: true, className: 'active-line-text' },
            },
          ]),
        });
      });
    }
  }
 
  // eslint-disable-next-line class-methods-use-this
  provides() {
    return {
      /**
       * Removes existing line decorations and updates the reference on the instance
       * @param {module:source_editor_instance~EditorInstance} instance - The Source Editor instance
       */
      removeHighlights: (instance) => {
        Object.assign(instance, {
          lineDecorations: instance.deltaDecorations(instance.lineDecorations || [], []),
        });
      },
 
      /**
       * Returns a function that can only be invoked once between
       * each browser screen repaint.
       * @param {Array} bounds - The [start, end] array with start
       * @param {module:source_editor_instance~EditorInstance} instance - The Source Editor instance
       * and end coordinates for highlighting
       */
      highlightLines(instance, bounds = null) {
        SourceEditorExtension.highlightLines(instance, bounds);
      },
 
      toggleSoftwrap(instance) {
        const isSoftWrapped = instance.getOption(116) === 'on';
        instance.updateOptions({ wordWrap: isSoftWrapped ? 'off' : 'on' });
        Eif (instance.toolbar) {
          instance.toolbar.updateItem(EXTENSION_SOFTWRAP_ID, {
            selected: !isSoftWrapped,
          });
          document.querySelector('.soft-wrap-toggle')?.blur();
        }
      },
    };
  }
}