summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/streaming/handle_streamed_anchor_link.js
blob: 315dc9bb0a0a8974ad410f0458af1ab5ee8c0016 (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
import { throttle } from 'lodash';
import { scrollToElement } from '~/lib/utils/common_utils';
import LineHighlighter from '~/blob/line_highlighter';

const noop = () => {};

export function handleStreamedAnchorLink(rootElement) {
  // "#L100-200" → ['L100', 'L200']
  const [anchorStart, end] = window.location.hash.substring(1).split('-');
  const anchorEnd = end ? `L${end}` : anchorStart;
  if (!anchorStart || document.getElementById(anchorEnd)) return noop;

  const handler = throttle((mutationList, instance) => {
    if (!document.getElementById(anchorEnd)) return;
    scrollToElement(document.getElementById(anchorStart));
    // eslint-disable-next-line no-new
    new LineHighlighter();
    instance.disconnect();
  }, 300);

  const observer = new MutationObserver(handler);

  observer.observe(rootElement, { childList: true, subtree: true });

  return () => observer.disconnect();
}