summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/blob/blob_line_permalink_updater.js
blob: c8f68860fbdd4f4f53da53d30ffe30060161a317 (plain)
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
const lineNumberRe = /^L[0-9]+/;

const updateLineNumbersOnBlobPermalinks = (linksToUpdate) => {
  const hash = gl.utils.getLocationHash();
  if (hash && lineNumberRe.test(hash)) {
    const hashUrlString = `#${hash}`;

    [].concat(Array.prototype.slice.call(linksToUpdate)).forEach((permalinkButton) => {
      const baseHref = permalinkButton.getAttribute('data-original-href') || (() => {
        const href = permalinkButton.getAttribute('href');
        permalinkButton.setAttribute('data-original-href', href);
        return href;
      })();
      permalinkButton.setAttribute('href', `${baseHref}${hashUrlString}`);
    });
  }
};

function BlobLinePermalinkUpdater(blobContentHolder, lineNumberSelector, elementsToUpdate) {
  const updateBlameAndBlobPermalinkCb = () => {
    // Wait for the hash to update from the LineHighlighter callback
    setTimeout(() => {
      updateLineNumbersOnBlobPermalinks(elementsToUpdate);
    }, 0);
  };

  blobContentHolder.addEventListener('click', (e) => {
    if (e.target.matches(lineNumberSelector)) {
      updateBlameAndBlobPermalinkCb();
    }
  });
  updateBlameAndBlobPermalinkCb();
}

export default BlobLinePermalinkUpdater;