summaryrefslogtreecommitdiff
path: root/src/lightbox.js
blob: d21b7ab30542589ef01aa74500b580fadbf63784 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import Overlay from './overlay.js';
import Shadow from './shadow.js';

export default class LightBox {
  currentImage = null;
  shadows = {};

  /**
   * ============
   * Initializers
   * ============
   */

  constructor({ selector }) {
    this.selector = selector;
    this.initOverlay();
    this.initImages();
    this.initControls();
  }

  initOverlay() {
    this.overlay = new Overlay();
    this.overlay.element.addEventListener('click', () => {
      this.closeCurrent();
    });
  }

  initImages() {
    this.images = document.querySelectorAll(this.selector);
    this.images.forEach(image => {
      if (image.tagName !== 'IMG') return;
      image.id = crypto.randomUUID(); // generate unique id for each image
      image.addEventListener('click', () => this.openLightBox(image));  // click image to open lightbox
    });
  }

  initControls() {
    // keyboard shortcuts
    document.addEventListener('keydown', e => {
      if (e.key === 'Escape' || e.key === ' ') {
        this.closeCurrent();
      }
    });
    // scroll to dismiss
    document.body.addEventListener('wheel', e => {
      this.closeCurrent();
    });
  }

  /**
   * ============
   * Actions
   * ============
   */

  openLightBox(image) {
    // hide and store original image
    image.style.visibility = 'hidden';
    this.currentImage = image;

    // get shadow of this image
    const shadow = this.shadows[image.id] || new Shadow(image);
    if (!this.shadows[image.id]) {
      this.shadows[image.id] = shadow;
    }

    // place and open shadow
    if (!document.body.contains(shadow.element)) shadow.placeItself();
    shadow.open();

    this.overlay.show();
  }

  closeLightBox(image) {
    // show and unstore original image
    image.style.visibility = 'visible';
    this.currentImage = null;

    // close shadow
    const shadow = this.shadows[image.id];
    if (!shadow) return;
    shadow.close();

    this.overlay.hide();
  }

  closeCurrent() {
    if (!this.currentImage) return;
    this.closeLightBox(this.currentImage);
  }

  closeAll() {
    this.images.forEach(image => {
      this.closeLightBox(image);
    });
    this.overlay.hide();
  }
}