Files
fizzy/app/javascript/controllers/lightbox_controller.js
T
Mike Dalessio e9cb2956ee Lightbox uses Stimulus target callbacks instead of data-action
Remove data-action from the sanitizer allowlist to disallow injection
of potentially malicious Stimulus actions in user-provided
content. The lightbox controller now uses imageTarget callbacks to
handle clicks on image links.

Also add the file name as a caption in the light box, and fix the
caption color for dark mode visibility.
2025-12-13 17:06:03 -05:00

48 lines
1.1 KiB
JavaScript

import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = [ "caption", "image", "dialog", "zoomedImage" ]
imageTargetConnected(element) {
element.addEventListener("click", this.#handleImageClick)
}
imageTargetDisconnected(element) {
element.removeEventListener("click", this.#handleImageClick)
}
#handleImageClick = (event) => {
event.preventDefault()
this.#open(event.currentTarget)
}
#open(link) {
this.dialogTarget.showModal()
this.#set(link)
}
// Wait for the transition to finish before resetting the image
handleTransitionEnd(event) {
if (event.target === this.dialogTarget && !this.dialogTarget.open) {
this.reset()
}
}
reset() {
this.zoomedImageTarget.src = ""
this.captionTarget.innerText = ""
this.dispatch('closed')
}
#set(target) {
const imageSrc = target.href
const caption = target.dataset.lightboxCaptionValue
this.zoomedImageTarget.src = imageSrc
if (caption) {
this.captionTarget.innerText = caption
}
}
}