1 import * as DOM from '../services/dom.ts';
2 import {scrollAndHighlightElement} from '../services/util.ts';
3 import {Component} from './component';
5 function toggleAnchorHighlighting(elementId, shouldHighlight) {
6 DOM.forEach(`#page-navigation 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();
41 // Check the hash on load
42 if (window.location.hash) {
43 const text = window.location.hash.replace(/%20/g, ' ').substring(1);
47 // Sidebar page nav click event
48 const sidebarPageNav = document.querySelector('.sidebar-page-nav');
50 DOM.onChildEvent(sidebarPageNav, 'a', 'click', (event, child) => {
51 event.preventDefault();
52 window.$components.first('tri-layout').showContent();
53 const contentId = child.getAttribute('href').substr(1);
54 this.goToText(contentId);
55 window.history.pushState(null, null, `#${contentId}`);
64 const idElem = document.getElementById(text);
66 DOM.forEach('.page-content [data-highlighted]', elem => {
67 elem.removeAttribute('data-highlighted');
68 elem.style.backgroundColor = null;
71 if (idElem !== null) {
72 scrollAndHighlightElement(idElem);
74 const textElem = DOM.findText('.page-content > div > *', text);
76 scrollAndHighlightElement(textElem);
81 setupNavHighlighting() {
82 const pageNav = document.querySelector('.sidebar-page-nav');
84 // fetch all the headings.
85 const headings = document.querySelector('.page-content').querySelectorAll('h1, h2, h3, h4, h5, h6');
86 // if headings are present, add observers.
87 if (headings.length > 0 && pageNav !== null) {
88 addNavObserver(headings);