Completed
Push — master ( c8f34f...a578a1 )
by Jesús
12s
created

toast.ts ➔ showToast   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
import { currentTranslations } from '../../language';
2
3
const toastTimers = new Map<
4
  string,
5
  {
6
    show: NodeJS.Timeout | null;
7
    hide: NodeJS.Timeout | null;
8
    remove: NodeJS.Timeout | null;
9
  }
10
>();
11
12
let clickCount = 0;
13
let clickResetTimeout: NodeJS.Timeout | null = null;
14
15
export function showDisabledBoxToast(): void {
16
  clickCount++;
17
18
  if (clickResetTimeout) {
19
    clearTimeout(clickResetTimeout);
20
  }
21
  clickResetTimeout = setTimeout(() => {
22
    clickCount = 0;
23
  }, 2000);
24
25
  // Show toast only after 2+ clicks
26
  if (clickCount >= 2) {
27
    showToast('toast-notification', currentTranslations.disabledBoxMessage);
28
    clickCount = 0;
29
  }
30
}
31
32
export function showToast(id: string, message: string, duration: number = 3000, className: string = 'toast'): void {
33
  cleanupExistingToast(id);
34
  const toast = createToastElement(id, message, className);
35
  scheduleToastAnimations(id, toast, duration);
36
}
37
38
function cleanupExistingToast(id: string): void {
39
  const existingToast = document.getElementById(id);
40
  existingToast?.remove();
41
42
  clearToastTimers(id);
43
}
44
45
function clearToastTimers(id: string): void {
46
  const timers = toastTimers.get(id);
47
  if (timers) {
48
    if (timers.show) clearTimeout(timers.show);
49
    if (timers.hide) clearTimeout(timers.hide);
50
    if (timers.remove) clearTimeout(timers.remove);
51
  }
52
}
53
54
function createToastElement(id: string, message: string, className: string): HTMLElement {
55
  const toast = document.createElement('div');
56
  toast.id = id;
57
  toast.className = className;
58
  toast.textContent = message;
59
  toast.setAttribute('role', 'alert');
60
  toast.setAttribute('aria-live', 'polite');
61
  document.body.appendChild(toast);
62
63
  return toast;
64
}
65
66
function scheduleToastAnimations(id: string, toast: HTMLElement, duration: number): void {
67
  toastTimers.set(id, { show: null, hide: null, remove: null });
68
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
69
  const timers = toastTimers.get(id)!;
70
71
  timers.show = setTimeout(() => toast.classList.add('show'), 10);
72
73
  timers.hide = setTimeout(() => {
74
    toast.classList.remove('show');
75
    timers.remove = setTimeout(() => {
76
      toast.remove();
77
      toastTimers.delete(id);
78
    }, 300);
79
  }, duration);
80
}
81