aboutsummaryrefslogtreecommitdiff
path: root/frontend/src/lightbox.ts
blob: cdc628ea9a1f8b9f513f4389cb94649fa04c5651 (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
77
78
79
80
81
82
import type { Note } from './main';

let currentMedia: Note['media'] = [];
let currentIndex = 0;

function updateLightbox() {
  const item = currentMedia![currentIndex];
  const img = document.getElementById('lightbox-img') as HTMLImageElement;
  const alt = document.getElementById('lightbox-alt')!;
  const prev = document.getElementById('lightbox-prev')!;
  const next = document.getElementById('lightbox-next')!;

  img.src = item.url;
  img.alt = item.alt || '';

  if (item.alt) {
    alt.textContent = item.alt;
    alt.style.display = 'block';
  } else {
    alt.style.display = 'none';
  }

  prev.style.display = currentIndex > 0 ? 'block' : 'none';
  next.style.display = currentIndex < currentMedia!.length - 1 ? 'block' : 'none';
}

function navigateLightbox(dir: number) {
  const next = currentIndex + dir;
  if (next < 0 || next >= currentMedia!.length) return;
  currentIndex = next;
  updateLightbox();
}

function lightboxKeyHandler(e: KeyboardEvent) {
  if (e.key === 'Escape') closeLightbox();
  if (e.key === 'ArrowLeft') navigateLightbox(-1);
  if (e.key === 'ArrowRight') navigateLightbox(1);
}

export function openLightbox(media: NonNullable<Note['media']>, index: number) {
  currentMedia = media;
  currentIndex = index;

  const overlay = document.createElement('div');
  overlay.id = 'lightbox';
  overlay.addEventListener('click', e => {
    if (e.target === overlay) closeLightbox();
  });

  const close = document.createElement('button');
  close.id = 'lightbox-close';
  close.textContent = '×';
  close.addEventListener('click', closeLightbox);
  overlay.appendChild(close);

  const img = document.createElement('img');
  img.id = 'lightbox-img';

  const alt = document.createElement('div');
  alt.id = 'lightbox-alt';

  const prev = document.createElement('button');
  prev.id = 'lightbox-prev';
  prev.textContent = '‹';
  prev.addEventListener('click', () => navigateLightbox(-1));

  const next = document.createElement('button');
  next.id = 'lightbox-next';
  next.textContent = '›';
  next.addEventListener('click', () => navigateLightbox(1));

  overlay.append(prev, img, alt, next);
  document.body.appendChild(overlay);
  updateLightbox();

  document.addEventListener('keydown', lightboxKeyHandler);
}

export function closeLightbox() {
  document.getElementById('lightbox')?.remove();
  document.removeEventListener('keydown', lightboxKeyHandler);
}