You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

32 lines
1.1 KiB

  1. import {svg} from '../svg.js';
  2. const headingSelector = '.markdown h1, .markdown h2, .markdown h3, .markdown h4, .markdown h5, .markdown h6';
  3. function scrollToAnchor() {
  4. if (document.querySelector(':target')) return;
  5. if (!window.location.hash || window.location.hash.length <= 1) return;
  6. const id = window.location.hash.substring(1);
  7. const el = document.getElementById(`user-content-${id}`);
  8. if (el) {
  9. el.scrollIntoView();
  10. } else if (id.startsWith('user-content-')) { // compat for links with old 'user-content-' prefixed hashes
  11. const el = document.getElementById(id);
  12. if (el) el.scrollIntoView();
  13. }
  14. }
  15. export default function initMarkdownAnchors() {
  16. if (!document.querySelector('.markdown')) return;
  17. for (const heading of document.querySelectorAll(headingSelector)) {
  18. const originalId = heading.id.replace(/^user-content-/, '');
  19. const a = document.createElement('a');
  20. a.classList.add('anchor');
  21. a.setAttribute('href', `#${encodeURIComponent(originalId)}`);
  22. a.innerHTML = svg('octicon-link');
  23. heading.prepend(a);
  24. }
  25. scrollToAnchor();
  26. window.addEventListener('hashchange', scrollToAnchor);
  27. }