vanillajs-deck/js/navigator.js

103 lines
2.9 KiB
JavaScript
Raw Normal View History

2019-11-23 00:37:45 +00:00
import { loadSlides } from "./slideLoader.js"
import { Router } from "./router.js"
2019-11-23 20:07:22 +00:00
import { Animator } from "./animator.js"
2019-11-22 19:28:19 +00:00
2019-11-23 00:37:45 +00:00
class Navigator extends HTMLElement {
constructor() {
super();
2019-11-23 20:07:22 +00:00
this._animator = new Animator();
2019-11-23 00:37:45 +00:00
this._router = new Router();
this._route = this._router.getRoute();
this.slidesChangedEvent = new CustomEvent("slideschanged", {
bubbles: true,
cancelable: false
});
this._router.eventSource.addEventListener("routechanged", () => {
if (this._route !== this._router.getRoute()) {
this._route = this._router.getRoute();
if (this._route) {
var slide = parseInt(this._route) - 1;
this.jumpTo(slide);
}
}
});
}
static get observedAttributes() {
return ["start"];
}
async attributeChangedCallback(attrName, oldVal, newVal) {
if (attrName === "start") {
if (oldVal !== newVal) {
this._slides = await loadSlides(newVal);
this._route = this._router.getRoute();
var slide = 0;
if (this._route) {
slide = parseInt(this._route) - 1;
}
this.jumpTo(slide);
}
}
2019-11-22 19:28:19 +00:00
}
get currentIndex() {
return this._currentIndex;
}
get currentSlide() {
2019-11-23 00:37:45 +00:00
return this._slides ? this._slides[this._currentIndex] : null;
2019-11-22 19:28:19 +00:00
}
get totalSlides() {
2019-11-23 00:37:45 +00:00
return this._slides ? this._slides.length : 0;
2019-11-22 19:28:19 +00:00
}
get hasPrevious() {
return this._currentIndex > 0;
}
get hasNext() {
return this._currentIndex < (this.totalSlides - 1);
}
jumpTo(slideIdx) {
2019-11-23 20:07:22 +00:00
if (this._animator.transitioning) {
return;
}
2019-11-22 19:28:19 +00:00
if (slideIdx >= 0 && slideIdx < this.totalSlides) {
this._currentIndex = slideIdx;
2019-11-23 00:37:45 +00:00
this.innerHTML = '';
this.appendChild(this.currentSlide.html);
this._router.setRoute(slideIdx+1);
this._route = this._router.getRoute();
this.dispatchEvent(this.slidesChangedEvent);
2019-11-23 20:07:22 +00:00
if (this._animator.animationReady) {
this._animator.endAnimation(this.querySelector("div"));
}
2019-11-22 19:28:19 +00:00
}
}
next() {
if (this.hasNext) {
2019-11-23 20:07:22 +00:00
if (this.currentSlide.transition !== null) {
this._animator.beginAnimation(
this.currentSlide.transition,
this.querySelector("div"),
() => this.jumpTo(this.currentIndex+1));
}
else {
this.jumpTo(this.currentIndex + 1);
}
2019-11-22 19:28:19 +00:00
}
}
previous() {
if (this.hasPrevious) {
this.jumpTo(this.currentIndex - 1);
}
}
2019-11-23 00:37:45 +00:00
}
export const registerDeck = () => customElements.define('slide-deck', Navigator);