blob: 8d7ea67e0b721fe426852248c8c84cbc09a48bec (
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
|
import Overlay from './overlay.js';
import Shadow from './shadow.js';
export default class LightBox {
currentImage = null;
shadows = {};
/**
* ============
* Initializers
* ============
*/
constructor({ container }) {
this.container = container;
this.initOverlay();
this.initImages();
this.initControls();
}
initOverlay() {
this.overlay = new Overlay();
this.overlay.element.addEventListener('click', e => {
this.closeCurrent();
});
}
initImages() {
this.images = document.querySelectorAll(`${this.container} img[data-libo]`);
function 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;
// replace image with the linked one
parent.insertBefore(link, image);
link.appendChild(image);
} else {
link = parent;
}
return link;
}
this.images.forEach(image => {
// generate unique id for each image
image.id = crypto.randomUUID();
// make sure every image has a link
const link = wrapInLink(image);
// click link to open lightbox
link.addEventListener('click', e => {
e.preventDefault();
this.openLightBox(image);
});
});
}
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();
}
}
|