88 lines
2.5 KiB
JavaScript
88 lines
2.5 KiB
JavaScript
![]() |
'use strict';
|
||
|
|
||
|
class AkiNavigatorTemplate {
|
||
|
constructor(mode) {
|
||
|
this._header = undefined;
|
||
|
this._templates = undefined;
|
||
|
this._routerOutlet = undefined;
|
||
|
this._mode = mode;
|
||
|
|
||
|
this._onExec();
|
||
|
}
|
||
|
|
||
|
_onExec() {
|
||
|
console.log('Navigating using mode:', this._mode);
|
||
|
|
||
|
this._getReferences();
|
||
|
this._getTemplates();
|
||
|
|
||
|
window.addEventListener('hashchange', () => this.displayView(window.location.hash.substr(1)));
|
||
|
|
||
|
if (!window.location.hash) {
|
||
|
this._mode === 'fetch' ? this.displayView('home') : this.displayView('home');
|
||
|
} else {
|
||
|
this.displayView(window.location.hash.substr(1));
|
||
|
}
|
||
|
}
|
||
|
|
||
|
_getReferences() {
|
||
|
this._header = document.querySelector('header');
|
||
|
this._routerOutlet = document.querySelector('#router-outlet');
|
||
|
}
|
||
|
|
||
|
_getTemplates() {
|
||
|
this._templates = [].slice.call(document.getElementsByTagName('template'));
|
||
|
}
|
||
|
|
||
|
_viewModeAction() {
|
||
|
if (this._mode === 'fetch') {
|
||
|
this.fetchView(window.location.hash.substr(1))
|
||
|
} else {
|
||
|
this.setView(window.location.hash.substr(1));
|
||
|
}
|
||
|
}
|
||
|
|
||
|
_removeChildren(element) {
|
||
|
let count = element.childNodes.length;
|
||
|
|
||
|
while (count--) {
|
||
|
element.removeChild(element.lastChild);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
_setView(view) {
|
||
|
const template = this._templates.filter(template => template.id === `template-${view}`)[0];
|
||
|
this._removeChildren(this._routerOutlet);
|
||
|
this._routerOutlet.appendChild(template.content.cloneNode(true));
|
||
|
}
|
||
|
|
||
|
async _fetchView(view) {
|
||
|
const response = await fetch(`templates/${view}.html`);
|
||
|
const text = await response.text();
|
||
|
|
||
|
this._removeChildren(this._routerOutlet);
|
||
|
this._routerOutlet.innerHTML = text; // innerHTML gets the job done.
|
||
|
}
|
||
|
|
||
|
displayView(view) {
|
||
|
if (this._mode === 'fetch') {
|
||
|
this._fetchView(view);
|
||
|
} else {
|
||
|
this._setView(view);
|
||
|
}
|
||
|
|
||
|
const activeLinks = document.querySelectorAll('a[active]');
|
||
|
const newActiveLinks = document.querySelectorAll(`a[href='#${view}']`);
|
||
|
|
||
|
if (activeLinks.length > 0) {
|
||
|
activeLinks.forEach(link => {
|
||
|
link.removeAttribute('active')
|
||
|
});
|
||
|
}
|
||
|
|
||
|
newActiveLinks.forEach(newLink => newLink.setAttribute('active', ''));
|
||
|
|
||
|
// FIXME: history push is fucked rn.
|
||
|
// window.history.pushState(null, `${view}`, `#${view}`);
|
||
|
}
|
||
|
}
|