summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/blob/blob_line_permalink_updater.js
blob: df38c5400e2d62b6181eaddc240f62177133c666 (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
36
37
38
39
40
41
import { getLocationHash } from '../lib/utils/url_utility';

const lineNumberRe = /^(L|LC)[0-9]+/;

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

    [].concat(Array.prototype.slice.call(linksToUpdate)).forEach((permalinkButton) => {
      const baseHref =
        permalinkButton.dataset.originalHref ||
        (() => {
          const href = permalinkButton.getAttribute('href');
          // eslint-disable-next-line no-param-reassign
          permalinkButton.dataset.originalHref = href;
          return href;
        })();
      permalinkButton.setAttribute('href', `${baseHref}${hashUrlString}`);
    });
  }
};

function BlobLinePermalinkUpdater(blobContentHolder, lineNumberSelector, elementsToUpdate) {
  if (!blobContentHolder) return;
  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;