summaryrefslogtreecommitdiff
path: root/_includes/extensions/photo-swipe.html
blob: 9a5a51c3afc7f864618d5911d6285335d73e4b13 (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
<script src="//cdnjs.cloudflare.com/ajax/libs/photoswipe/5.3.7/umd/photoswipe-lightbox.umd.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/photoswipe/5.3.7/umd/photoswipe.umd.min.js"></script>
<link
  href="//cdnjs.cloudflare.com/ajax/libs/photoswipe/5.3.7/photoswipe.min.css"
  rel="stylesheet"
/>
<style>
  .pswp .pswp__container .pswp__img {
    background-color: white;
  }
</style>

<script>
  function initPhotoSwipe() {
    let customOptions = {};

    try {
      const data = `{{ site.photo_previewer }}`.replaceAll("=>", ":");
      customOptions = JSON.parse(data);
    } catch (e) {
      console.error("Invalid custom photo previewer options! " + e.message);
    }

    // Define object and gallery options
    const options = Object.assign(
      {
        gallery: "section.main",
        children: "a.photo-swipe",
        photo_scale: 2,
        // dynamic import is not supported in UMD version
        pswpModule: PhotoSwipe,
      },
      customOptions
    );

    const galleryEl = document.querySelector(options.gallery);
    if (!galleryEl) {
      return;
    }

    const imgEls = [];
    const els = galleryEl.querySelectorAll("img:not(.emoji)");
    els.forEach((el) => {
      if (!imgEls.includes(el)) {
        imgEls.push(el);
      }
    });

    if (imgEls.length === 0) {
      return;
    }

    imgEls.forEach((imgEl) => {
      imgEl.outerHTML = `
      <a class="photo-swipe"
        href="${imgEl.src}"
        data-pswp-width="${
          Math.max(imgEl.naturalWidth, imgEl.width) * options.photo_scale
        }"
        data-pswp-height="${
          Math.max(imgEl.naturalHeight, imgEl.height) * options.photo_scale
        }"
        data-pswp-caption="${imgEl.getAttribute("caption") || imgEl.alt}"
        target="_blank">
        ${imgEl.outerHTML}
      </a>`;
    });

    // Initialize PhotoSwipe 5
    var lightbox = new PhotoSwipeLightbox(options);

    lightbox.init();
  }

  window.addEventListener("load", initPhotoSwipe);
</script>