summaryrefslogtreecommitdiff
path: root/src/Plugins/Navigation.js
blob: bdd5e92723811e54910c5de4f39faf077cf0be5c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
 * @author Victor Häggqvist
 * @since 1/15/16
 */

export default class Navigation {

    register(lightbox) {
        this.lightbox = lightbox;
        lightbox.addOnStartListener(this.showNavigation.bind(this));
        lightbox.addOnEndListener(this.hideNavigation.bind(this));
        lightbox.addOnLoadEndListener(this.updateNavigation.bind(this));
    }


    showNavigation() {
        this.sink = document.createElement('div');
        this.sink.id = 'imagelightbox-nav-sink';
        this.nav = document.createElement('div');
        this.nav.id = 'imagelightbox-nav';
        this.sink.appendChild(this.nav);

        Array.prototype.forEach.call(this.lightbox.targets, _ => {
            this.nav.appendChild(document.createElement('a'));
        });

        document.body.appendChild(this.sink);

        let navItems = this.nav.querySelectorAll('a');
        Array.prototype.forEach.call(navItems, (item, i) => {
            ['click', 'touchend'].forEach(name => {
                item.addEventListener(name, this.navClick.bind(this, i));
            })
        });

        // make the nav actually centered, flex center dont make it
        let rect = this.nav.getBoundingClientRect();
        let diff = rect.width/2;
        this.nav.style.marginLeft = '-'+diff+'px';
    }

    updateNavigation() {
        Array.prototype.forEach.call(this.nav.childNodes, n => {
           n.classList.remove('active');
        });

        let current = Array.prototype.indexOf.call(this.lightbox.targets, this.lightbox.target);
        this.nav.childNodes[current].classList.add('active');
    }

    hideNavigation() {
        try {
            document.body.removeChild(this.sink);
        } catch (e) {}
    };

    navClick(index, e) {
        e.stopPropagation();
        e.cancelBubble = true;
        this.lightbox.switchToIndex(index);
    }

}