Website/docs/assets/js/akiNavigatorRouter.js

85 lines
2.3 KiB
JavaScript
Raw Normal View History

2023-03-02 21:09:33 -05:00
/**
* Contains edits to better suit the docs web app.
*/
'use strict';
class AkiNavigatorRouter {
constructor(routes, ...callbacks) {
this._header = undefined;
this._routerOutlet = undefined;
this._routes = routes;
this._onExec(callbacks);
}
_onExec(callbacks) {
this._getReferences();
window.addEventListener("hashchange", () => this.displayView(window.location.hash.substr(1)));
if (window.location.hash) {
this.displayView(window.location.hash.substr(1));
}
if (callbacks.length > 0) {
callbacks.forEach(callback => {
if (typeof callback == 'function') {
callback();
}
});
}
}
_getReferences() {
this._header = document.querySelector('header');
this._routerOutlet = document.querySelector('#router-outlet');
}
_removeChildren(element) {
let count = element.childNodes.length;
while (count--) {
element.removeChild(element.lastChild);
}
}
async _fetchView(view) {
const response = await fetch(`md/${view}`);
const text = await response.text();
this._removeChildren(this._routerOutlet);
// this._routerOutlet.innerHTML = text;
this._routerOutlet.innerHTML = marked(text);
Prism.highlightAll();
}
displayView(view) {
// Useless here. Only fetch is used.
// if (this._mode === 'fetch') {
// this._fetchView(view);
// } else {
// this._setView(view);
// }
this._fetchView(view);
const activeLinks = document.querySelectorAll('a[active]');
const newActiveLinks = document.querySelectorAll(`a[href='#${view}']`);
console.log('view:', view);
console.log('activeLinks:', activeLinks);
console.log('newActiveLinks:', newActiveLinks);
if (activeLinks.length > 0) {
activeLinks.forEach(link => link.removeAttribute('active'));
}
newActiveLinks.forEach(newLink => newLink.setAttribute('active', ''));
this._routerOutlet.scrollTop = 0;
// FIXME: history push is fucked rn.
// window.history.pushState(null, `${view}`, `#${view}`);
}
}