summaryrefslogtreecommitdiffstats
path: root/assets/js/image-zoom.js
blob: 307c858774f84fe61193a4f33a623e8feb93217b (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
// Click (or Enter/Space) on an article image to see it full screen.
// One native <dialog> is shared by all images: Esc closes it natively,
// a click anywhere closes it too, and focus returns to the image.
(function () {
  var imgs = Array.prototype.filter.call(
    document.querySelectorAll('.prose img'),
    function (img) { return !img.closest('a'); }
  );
  if (!imgs.length) return;

  var dlg = document.createElement('dialog');
  dlg.setAttribute('aria-label', 'Enlarged image');
  dlg.style.cssText = 'padding:0;border:0;background:transparent;max-width:95vw;max-height:95vh;overflow:visible;cursor:zoom-out';
  var big = document.createElement('img');
  big.style.cssText = 'display:block;max-width:95vw;max-height:95vh;width:auto;height:auto;object-fit:contain;border-radius:0.5rem';
  dlg.appendChild(big);
  document.body.appendChild(dlg);

  var style = document.createElement('style');
  style.textContent = 'dialog[aria-label="Enlarged image"]::backdrop{background:rgba(0,0,0,0.85)}';
  document.head.appendChild(style);

  var opener = null;
  dlg.addEventListener('click', function () { dlg.close(); });
  dlg.addEventListener('close', function () { if (opener) opener.focus(); });

  function open(img) {
    opener = img;
    big.src = img.currentSrc || img.src;
    big.alt = img.alt;
    dlg.showModal();
  }

  imgs.forEach(function (img) {
    img.style.cursor = 'zoom-in';
    img.tabIndex = 0;
    img.setAttribute('role', 'button');
    img.addEventListener('click', function () { open(img); });
    img.addEventListener('keydown', function (e) {
      if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open(img); }
    });
  });
})();