{"size": 1209, "ext": "js", "max_stars_repo_path": "src/utils/anchorHelper.js", "max_stars_repo_name": "GolosChain/golos.io", "max_stars_repo_stars_event_min_datetime": "2016-09-12T22:48:49.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-01T14:29:51.000Z", "max_issues_repo_path": "src/utils/anchorHelper.js", "max_issues_repo_name": "GolosChain/golos.io", "max_issues_repo_issues_event_min_datetime": "2016-09-15T14:23:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-09T01:09:15.000Z", "max_forks_repo_path": "src/utils/anchorHelper.js", "max_forks_repo_name": "GolosChain/golos.io", "max_forks_repo_forks_event_min_datetime": "2016-09-26T18:27:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-29T19:14:01.000Z"}
{"max_stars_count": 5, "max_issues_count": 363, "max_forks_count": 7, "avg_line_length": 21.2105263158, "max_line_length": 76, "alphanum_fraction": 0.6021505376}
import { getScrollElement } from 'helpers/window';

export function init() {
  window.addEventListener('hashchange', () => {
    tryMoveToAnchor();
  });

  window.addEventListener('click', e => {
    /*
     * Не проверяется на e.defaultPrevented потому что Link из react-router,
     * всегда превентит клики.
     */
    if (e.target.closest('a[href]')) {
      setTimeout(() => {
        hardTryMoveToAnchor();
      }, 10);
    }
  });

  hardTryMoveToAnchor();
}

function hardTryMoveToAnchor() {
  let testsCount = 0;
  const interval = setInterval(() => {
    tryMoveToAnchor();

    if (++testsCount === 10) {
      clearInterval(interval);
    }
  }, 100);
}

function tryMoveToAnchor() {
  const hash = location.hash.substr(1);

  if (hash) {
    const anchor = document.getElementById(hash);

    if (anchor) {
      if (anchor.scrollIntoViewIfNeeded) {
        anchor.scrollIntoViewIfNeeded();
      } else if (anchor.scrollIntoView) {
        anchor.scrollIntoView();
      }

      const bound = anchor.getBoundingClientRect();

      const delta = Math.round(120 + window.innerHeight / 6 - bound.top);

      if (delta > 0) {
        getScrollElement().scrollTop -= delta;
      }
    }
  }
}
