aboutsummaryrefslogtreecommitdiff
path: root/beamer/viewer/screen/timer.js
blob: 9b069ac7e1eda646a4e75b4bf329a2f663ee3e64 (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
/*
 * Beamer Viewer, a web-based PDF presentation viewer
 * Copyright 2018-2024 Pacien TRAN-GIRARD
 * SPDX-License-Identifier: EUPL-1.2
 */

"use strict";

class Timer {
  constructor(window) {
    this.display = window.document.getElementById("timer-value");
    this.carryoverMs = 0; // saved on pause
    this.runningStartTs = null; // null if paused

    window.document.getElementById("timer-pause").addEventListener("click", event => {
      event.stopPropagation();
      this._startStop();
    });

    window.document.getElementById("timer-reset").addEventListener("click", event => {
      event.stopPropagation();
      this._reset();
    });

    setInterval(() => this._refreshTimer(), 1000);

    this._toggleDisplay(false);
    this._setDisplay(0);
    window.document.getElementById("timer").classList.remove("hidden");
  }

  start() {
    if (this.runningStartTs != null) return;
    this.runningStartTs = Date.now();
    this._toggleDisplay(true);
  }

  _stop() {
    if (this.runningStartTs == null) return;
    this.carryoverMs += Date.now() - this.runningStartTs;
    this.runningStartTs = null;
    this._toggleDisplay(false);
 }

  _startStop() {
    if (this.runningStartTs == null)
      this.start();
    else
      this._stop();

    this._refreshTimer();
  }

  _reset() {
    this.carryoverMs = 0;
    if (this.runningStartTs != null) this.runningStartTs = Date.now();
    this._setDisplay(0);
  }

  _refreshTimer() {
    if (this.runningStartTs == null) return;
    const timeDeltaMs = Date.now() - this.runningStartTs + this.carryoverMs;
    this._setDisplay(Math.floor(timeDeltaMs / 1000));
  }

  _setDisplay(seconds) {
    const dateObj = new Date(null);
    dateObj.setSeconds(seconds);
    this.display.textContent = dateObj.toISOString().slice(11, 11+8);
  }

  _toggleDisplay(active) {
    if (active)
      this.display.classList.remove("timer-paused");
    else
      this.display.classList.add("timer-paused");
  }
}