summaryrefslogtreecommitdiff
path: root/src/lightbox.js
blob: 1a93a5390dfb5c3cd5ae8d8b392ee35980ebfe31 (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
import Overlay from './overlay.js';
import Shadow from './shadow.js';

export default class LightBox {
  shadows = {};

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

  constructor({ container }) {
    this.container = container;
    this.initOverlay();
    this.initImages();
  }

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

  initImages() {
    this.images = document.querySelectorAll(`${this.container} img[data-libo]`);
    this.images.forEach(image => {
      image.id = crypto.randomUUID(); // generate unique id for image
      const link = this.wrapInLink(image);
      // add event listener to open lightbox on click
      link.addEventListener('click', e => {
        e.preventDefault();
        this.openLightBox(image);
      });
    });
  }

  wrapInLink(image) {
    // wrap image with a link if it's not already wrapped
    const parent = image.parentElement;
    let link;
    if (!parent || parent.tagName !== 'A') {
      link = document.createElement('a');
      link.href = image.src;
      link.dataset.liboLink = true;

      parent.insertBefore(link, image);
      link.appendChild(image);
    } else {
      link = parent;
    }
    return link;
  }

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

  openLightBox(image) {
    image.style.visibility = 'hidden';
    const shadow = this.shadows[image.id] || new Shadow(image);
    if (!this.shadows[image.id]) {
      this.shadows[image.id] = shadow;
    }

    shadow.open();

    this.overlay.add(shadow);
    this.overlay.show();
  }

  closeLightBox(image) {
    image.style.visibility = 'visible';
    const shadow = this.shadows[image.id];
    if (!shadow) return;

    shadow.close();
    this.overlay.hide();
  }

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