xref: /template/strap/resources/snippet/js/lightbox.js (revision 4cadd4f8c541149bdda95f080e38a6d4e3a640ca)
1window.addEventListener("DOMContentLoaded", function () {
2
3
4    document.querySelectorAll(".lightbox-combo").forEach((lightBoxAnchor) => {
5
6        let drag = false;
7
8        lightBoxAnchor.addEventListener('mousedown', () => drag = false);
9        lightBoxAnchor.addEventListener('mousemove', () => drag = true);
10
11        /**
12         * Click is an event that appears after mouseup
13         */
14        let startX;
15        let startY;
16        let delta = 6;
17        lightBoxAnchor.addEventListener("click", async function (event) {
18            // we open the lightbox on mouseup
19            event.preventDefault();
20        });
21        lightBoxAnchor.addEventListener("mousedown", async function (event) {
22            // capture the position to see if it's a drag or a click
23            startX = event.pageX;
24            startY = event.pageY;
25        });
26
27        lightBoxAnchor.addEventListener("mouseup", event => {
28            const diffX = Math.abs(event.pageX - startX);
29            const diffY = Math.abs(event.pageY - startY);
30            if (diffX < delta && diffY < delta) {
31                // A click
32                openLightbox();
33            }
34        });
35        let openLightbox = function () {
36            let lightBoxId = combo.toHtmlId(`combo-lightbox`);
37
38            let lightBoxModel = combo.getOrCreateModal(lightBoxId);
39            let src = lightBoxAnchor.getAttribute("href");
40            let img = lightBoxAnchor.querySelector("img");
41            let alt = "Image";
42            if (img !== null && img.hasAttribute("alt")) {
43                alt = img.getAttribute("alt");
44            }
45            let namespace = "-bs"
46            let bsVersion = parseInt(bootstrap.Modal.VERSION.substr(0, 1), 10);
47            if (bsVersion < 5) {
48                namespace = "";
49            }
50
51            let svgStyle = "max-height:95vh;max-width:95vw";
52            if (src.match(/svg/i) !== null) {
53                // a svg does not show without width
54                // because the intrinsic svg can be really small, we put a min with
55                svgStyle += ';width: 100%;min-width: 75vw'
56            }
57            let html = `
58<button type="button" class="lightbox-close-combo" data${namespace}-dismiss="modal" aria-label="Close">
59    <span aria-hidden="true">&times;</span>
60</button>
61<img src="${src}" alt="${alt}" style="${svgStyle}"/>
62`
63            lightBoxModel
64                .resetIfBuild()
65                .centered()
66                .addDialogStyle("max-width", "fit-content")
67                .addBody(html)
68                .addBodyStyle("padding", "0")
69                .noFooter()
70                .show();
71        }
72    });
73
74});
75