summaryrefslogtreecommitdiff
path: root/templates/var/www/html/video-background.js
blob: 8f95a00b304a9c68419d3ad6034d06e38cdba20c (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
(async () => {
  const video = document.getElementById('background');
  const fadeOverlay = document.getElementById('fadeOverlay');
  const toggleBgBtn = document.getElementById('toggleBg');
  const FADE_DURATION = 1000;

  const resp = await fetch('/videos/videos.json');
  if (!resp.ok) {
    console.error('Failed to load videos.json');
    return;
  }
  const videos = await resp.json();

  let lastVideo = null;
  let bgEnabled = true;
  let loopCanceled = false;

  function pickRandomVideo() {
    if (videos.length === 1) return videos[0];
    let choice;
    do {
      choice = videos[Math.floor(Math.random() * videos.length)];
    } while (choice === lastVideo);
    lastVideo = choice;
    return choice;
  }

  async function playVideoLoop() {
    while (!loopCanceled) {
      const nextVideo = pickRandomVideo();
      video.src = `/videos/${nextVideo}`;
      video.style.opacity = '0';
      fadeOverlay.style.opacity = '1';

      await new Promise(r => setTimeout(r, FADE_DURATION));

      video.load();
      await new Promise(resolve => {
        video.onloadedmetadata = () => resolve();
      });

      if (loopCanceled) break;

      video.currentTime = 0;
      video.play().catch(console.error);

      video.style.opacity = '1';
      fadeOverlay.style.opacity = '0';

      await new Promise(r => setTimeout(r, (video.duration * 1000) - (2 * FADE_DURATION)));

      fadeOverlay.style.opacity = '1';
      video.style.opacity = '0';

      await new Promise(r => setTimeout(r, FADE_DURATION));
    }
  }

  toggleBgBtn.addEventListener('click', (e) => {
    e.preventDefault();
    bgEnabled = !bgEnabled;
    loopCanceled = !bgEnabled;

    if (!bgEnabled) {
      video.pause();
      video.style.display = 'none';
      fadeOverlay.style.display = 'none';
      toggleBgBtn.textContent = 'background (off)';
    } else {
      video.style.display = '';
      fadeOverlay.style.display = '';
      toggleBgBtn.textContent = 'background (on)';
      playVideoLoop();
    }
  });

  playVideoLoop();
})();