From cb1f2a87bd8694b8dfdbe8e0c14fb7ee0da841f3 Mon Sep 17 00:00:00 2001 From: Eltrac Date: Mon, 15 Sep 2025 11:28:38 +0800 Subject: refactor: lightbox ID generation and shadow management Replaces the async SHA-256 based unique ID generation with a synchronous hashCode method in Utility. Refactors LightBox to manage Shadow instances in a local cache instead of querying the DOM, and removes the static find method from Shadow. Also extracts image link wrapping logic into a helper method for clarity. --- src/lightbox.js | 48 ++++++++++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 22 deletions(-) (limited to 'src/lightbox.js') diff --git a/src/lightbox.js b/src/lightbox.js index 3b25585..579f14b 100644 --- a/src/lightbox.js +++ b/src/lightbox.js @@ -1,9 +1,10 @@ -import utility from './utility.js'; +import Utility from './utility.js'; import Overlay from './overlay.js'; import Shadow from './shadow.js'; export default class LightBox { overlay = new Overlay(); + shadows = {}; /** * ============ @@ -17,37 +18,36 @@ export default class LightBox { } init() { - const container = document.querySelectorAll(this.container); const images = document.querySelectorAll(`${this.container} img[data-libo]`); images.forEach(image => { - // generate unique id for image - const id = utility.generateUniqueId(image.src); - image.id = id; - - // get parent and 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; - } - + image.id = Utility.hashCode(image.src); // 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 @@ -55,7 +55,11 @@ export default class LightBox { */ openLightBox(image) { - const shadow = Shadow.find(image) || new Shadow(image); + 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); -- cgit v1.2.3