blob: 22cf0ff7c9aaa690c793634ed7b92e08f380418d (
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
|
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.style.cursor = 'zoom-in';
image.addEventListener('click', () => this.open(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
* ============
*/
// open lightbox = open shadow + show overlay
open(image) {
this.currentImage = image;
const shadow = this.shadows[image.id] || new Shadow(image);
if (!this.shadows[image.id]) {
this.shadows[image.id] = shadow;
}
shadow.open();
this.overlay.show();
}
// close lightbox = remove shadow + hide overlay
close(image) {
this.currentImage = null;
if (!this.shadows[image.id]) return;
this.shadows[image.id].close();
this.overlay.hide();
}
closeCurrent() {
if (!this.currentImage) return;
this.close(this.currentImage);
}
}
|