All files / app/assets/javascripts/behaviors/shortcuts shortcuts_blob.js

4.76% Statements 1/21
0% Branches 0/15
0% Functions 0/5
4.76% Lines 1/21

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                    1x                                                                                                            
import { PROJECT_FILES_GO_TO_PERMALINK } from '~/behaviors/shortcuts/keybindings';
import {
  getLocationHash,
  updateHistory,
  urlIsDifferent,
  urlContainsSha,
  getShaFromUrl,
} from '~/lib/utils/url_utility';
import { updateRefPortionOfTitle } from '~/repository/utils/title';
 
const defaults = {
  fileBlobPermalinkUrl: null,
  fileBlobPermalinkUrlElement: null,
};
 
function eventHasModifierKeys(event) {
  // We ignore alt because I don't think alt clicks normally do anything special?
  return event.ctrlKey || event.metaKey || event.shiftKey;
}
 
export default class ShortcutsBlob {
  constructor(shortcuts, opts) {
    const options = { ...defaults, ...opts };
    this.options = options;
 
    this.shortcircuitPermalinkButton();
 
    shortcuts.add(PROJECT_FILES_GO_TO_PERMALINK, this.moveToFilePermalink.bind(this));
  }
 
  moveToFilePermalink() {
    const permalink = this.options.fileBlobPermalinkUrl;
 
    if (permalink) {
      const hash = getLocationHash();
      const hashUrlString = hash ? `#${hash}` : '';
 
      if (urlIsDifferent(permalink)) {
        updateHistory({
          url: `${permalink}${hashUrlString}`,
          title: document.title,
        });
      }
 
      if (urlContainsSha({ url: permalink })) {
        updateRefPortionOfTitle(getShaFromUrl({ url: permalink }));
      }
    }
  }
 
  shortcircuitPermalinkButton() {
    const button = this.options.fileBlobPermalinkUrlElement;
    const handleButton = (e) => {
      if (!eventHasModifierKeys(e)) {
        e.preventDefault();
        this.moveToFilePermalink();
      }
    };
 
    if (button) {
      button.addEventListener('click', handleButton);
    }
  }
}