1 import * as DOM from '../services/dom';
2 import {scrollAndHighlightElement} from '../services/util';
3 import {Component} from './component';
5 function toggleAnchorHighlighting(elementId, shouldHighlight) {
6 DOM.forEach(`a[href="#${elementId}"]`, anchor => {
7 anchor.closest('li').classList.toggle('current-heading', shouldHighlight);
11 function headingVisibilityChange(entries) {
12 for (const entry of entries) {
13 const isVisible = (entry.intersectionRatio === 1);
14 toggleAnchorHighlighting(entry.target.id, isVisible);
18 function addNavObserver(headings) {
19 // Setup the intersection observer.
20 const intersectOpts = {
21 rootMargin: '0px 0px 0px 0px',
24 const pageNavObserver = new IntersectionObserver(headingVisibilityChange, intersectOpts);
26 // observe each heading
27 for (const heading of headings) {
28 pageNavObserver.observe(heading);
32 export class PageDisplay extends Component {
35 this.container = this.$el;
36 this.pageId = this.$opts.pageId;
38 window.importVersioned('code').then(Code => Code.highlight());
39 this.setupNavHighlighting();
40 this.setupDetailsCodeBlockRefresh();
42 // Check the hash on load
43 if (window.location.hash) {
44 const text = window.location.hash.replace(/%20/g, ' ').substring(1);
48 // Sidebar page nav click event
49 const sidebarPageNav = document.querySelector('.sidebar-page-nav');
51 DOM.onChildEvent(sidebarPageNav, 'a', 'click', (event, child) => {
52 event.preventDefault();
53 window.$components.first('tri-layout').showContent();
54 const contentId = child.getAttribute('href').substr(1);
55 this.goToText(contentId);
56 window.history.pushState(null, null, `#${contentId}`);
62 const idElem = document.getElementById(text);
64 DOM.forEach('.page-content [data-highlighted]', elem => {
65 elem.removeAttribute('data-highlighted');
66 elem.style.backgroundColor = null;
69 if (idElem !== null) {
70 scrollAndHighlightElement(idElem);
72 const textElem = DOM.findText('.page-content > div > *', text);
74 scrollAndHighlightElement(textElem);
79 setupNavHighlighting() {
80 const pageNav = document.querySelector('.sidebar-page-nav');
82 // fetch all the headings.
83 const headings = document.querySelector('.page-content').querySelectorAll('h1, h2, h3, h4, h5, h6');
84 // if headings are present, add observers.
85 if (headings.length > 0 && pageNav !== null) {
86 addNavObserver(headings);
90 setupDetailsCodeBlockRefresh() {
91 const onToggle = event => {
92 const codeMirrors = [...event.target.querySelectorAll('.CodeMirror')];
93 codeMirrors.forEach(cm => cm.CodeMirror && cm.CodeMirror.refresh());
96 const details = [...this.container.querySelectorAll('details')];
97 details.forEach(detail => detail.addEventListener('toggle', onToggle));