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.

anchors.js 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import {svg} from '../svg.js';
  2. const addPrefix = (str) => `user-content-${str}`;
  3. const removePrefix = (str) => str.replace(/^user-content-/, '');
  4. const hasPrefix = (str) => str.startsWith('user-content-');
  5. // scroll to anchor while respecting the `user-content` prefix that exists on the target
  6. function scrollToAnchor(encodedId) {
  7. if (!encodedId) return;
  8. const id = decodeURIComponent(encodedId);
  9. const prefixedId = addPrefix(id);
  10. let el = document.getElementById(prefixedId);
  11. // check for matching user-generated `a[name]`
  12. if (!el) {
  13. const nameAnchors = document.getElementsByName(prefixedId);
  14. if (nameAnchors.length) {
  15. el = nameAnchors[0];
  16. }
  17. }
  18. // compat for links with old 'user-content-' prefixed hashes
  19. if (!el && hasPrefix(id)) {
  20. return document.getElementById(id)?.scrollIntoView();
  21. }
  22. el?.scrollIntoView();
  23. }
  24. export function initMarkupAnchors() {
  25. const markupEls = document.querySelectorAll('.markup');
  26. if (!markupEls.length) return;
  27. for (const markupEl of markupEls) {
  28. // create link icons for markup headings, the resulting link href will remove `user-content-`
  29. for (const heading of markupEl.querySelectorAll('h1, h2, h3, h4, h5, h6')) {
  30. const a = document.createElement('a');
  31. a.classList.add('anchor');
  32. a.setAttribute('href', `#${encodeURIComponent(removePrefix(heading.id))}`);
  33. a.innerHTML = svg('octicon-link');
  34. heading.prepend(a);
  35. }
  36. // remove `user-content-` prefix from links so they don't show in url bar when clicked
  37. for (const a of markupEl.querySelectorAll('a[href^="#"]')) {
  38. const href = a.getAttribute('href');
  39. if (!href.startsWith('#user-content-')) continue;
  40. a.setAttribute('href', `#${removePrefix(href.substring(1))}`);
  41. }
  42. // add `user-content-` prefix to user-generated `a[name]` link targets
  43. // TODO: this prefix should be added in backend instead
  44. for (const a of markupEl.querySelectorAll('a[name]')) {
  45. const name = a.getAttribute('name');
  46. if (!name) continue;
  47. a.setAttribute('name', addPrefix(a.name));
  48. }
  49. for (const a of markupEl.querySelectorAll('a[href^="#"]')) {
  50. a.addEventListener('click', (e) => {
  51. scrollToAnchor(e.currentTarget.getAttribute('href')?.substring(1));
  52. });
  53. }
  54. }
  55. // scroll to anchor unless the browser has already scrolled somewhere during page load
  56. if (!document.querySelector(':target')) {
  57. scrollToAnchor(window.location.hash?.substring(1));
  58. }
  59. }