wowchemy-utils.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*************************************************
  2. * Wowchemy
  3. * https://github.com/wowchemy/wowchemy-hugo-modules
  4. *
  5. * Wowchemy Utilities
  6. **************************************************/
  7. /**
  8. * Fix Mermaid.js clash with Highlight.js.
  9. * Refactor Mermaid code blocks as divs to prevent Highlight parsing them and enable Mermaid to parse them.
  10. */
  11. function fixMermaid() {
  12. let mermaids = [];
  13. // Note that `language-mermaid` class is applied to <code> block within <pre>, so we wish to replace parent node.
  14. [].push.apply(mermaids, document.getElementsByClassName('language-mermaid'));
  15. for (let i = 0; i < mermaids.length; i++) {
  16. // Convert <pre><code></code></pre> block to <div> and add `mermaid` class so that Mermaid will parse it.
  17. let mermaidCodeElement = mermaids[i];
  18. let newElement = document.createElement('div');
  19. newElement.innerHTML = mermaidCodeElement.innerHTML;
  20. newElement.classList.add('mermaid');
  21. mermaidCodeElement.parentNode.replaceWith(newElement);
  22. }
  23. }
  24. /**
  25. * @param {Element} parent
  26. * @param {Element} child
  27. */
  28. function scrollParentToChild(parent, child) {
  29. // Where is the parent on the page?
  30. const parentRect = parent.getBoundingClientRect();
  31. // What can the client see?
  32. const parentViewableArea = {
  33. height: parent.clientHeight,
  34. width: parent.clientWidth,
  35. };
  36. // Where is the child?
  37. const childRect = child.getBoundingClientRect();
  38. // Is the child in view?
  39. const isChildInView =
  40. childRect.top >= parentRect.top && childRect.bottom <= parentRect.top + parentViewableArea.height;
  41. // If the child isn't in view, attempt to scroll the parent to it.
  42. if (!isChildInView) {
  43. // Scroll by offset relative to parent.
  44. parent.scrollTop = childRect.top + parent.scrollTop - parentRect.top;
  45. }
  46. }
  47. export {fixMermaid, scrollParentToChild};