summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorEltrac <hi@guhub.cn>2025-09-15 14:44:38 +0800
committerEltrac <hi@guhub.cn>2025-09-15 14:44:38 +0800
commitd4d2cbf7c25f71fc8b8bb630552aecc02a6af6ad (patch)
tree09cb7e1ff9e3eb0bedb2c8bc3bd52c65c3b48c52 /src
parent60dd64756eb6d5befdb112fa4a66e7833cd8d58c (diff)
perf: use `closeCurrent` instead of `closeAll`
this reduce time complexity from O(n) to O(1)
Diffstat (limited to 'src')
-rw-r--r--src/lightbox.js24
1 files changed, 20 insertions, 4 deletions
diff --git a/src/lightbox.js b/src/lightbox.js
index 0582149..f3aeb6f 100644
--- a/src/lightbox.js
+++ b/src/lightbox.js
@@ -2,6 +2,7 @@ import Overlay from './overlay.js';
import Shadow from './shadow.js';
export default class LightBox {
+ currentImage = null;
shadows = {};
/**
@@ -20,7 +21,7 @@ export default class LightBox {
initOverlay() {
this.overlay = new Overlay();
this.overlay.element.addEventListener('click', e => {
- this.closeAll();
+ this.closeCurrent();
});
}
@@ -41,12 +42,12 @@ export default class LightBox {
// keyboard shortcuts
document.addEventListener('keydown', e => {
if (e.key === 'Escape' || e.key === ' ') {
- this.closeAll();
+ this.closeCurrent();
}
});
// scroll to dismiss
document.body.addEventListener('wheel', e => {
- this.closeAll();
+ this.closeCurrent();
});
}
@@ -74,26 +75,41 @@ export default class LightBox {
*/
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);