summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/lib/utils/notify.js
blob: aa7884846a3a218cade40a89a0ceef5f7c094e6b (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
/* eslint-disable consistent-return, no-return-assign */

function notificationGranted(message, opts, onclick) {
  const notification = new Notification(message, opts);
  setTimeout(
    () =>
      // Hide the notification after X amount of seconds
      notification.close(),
    8000,
  );

  return (notification.onclick = onclick || notification.close);
}

function notifyPermissions() {
  /* eslint-disable-next-line @gitlab/require-i18n-strings */
  if ('Notification' in window) {
    return Notification.requestPermission();
  }
}

function notifyMe(message, body, icon, onclick) {
  const opts = {
    body,
    icon,
  };
  // Let's check if the browser supports notifications
  /* eslint-disable-next-line @gitlab/require-i18n-strings */
  if (!('Notification' in window)) {
    // do nothing
  } else if (Notification.permission === 'granted') {
    // If it's okay let's create a notification
    return notificationGranted(message, opts, onclick);
  } else if (Notification.permission !== 'denied') {
    return Notification.requestPermission(permission => {
      // If the user accepts, let's create a notification
      if (permission === 'granted') {
        return notificationGranted(message, opts, onclick);
      }
    });
  }
}

const notify = {
  notificationGranted,
  notifyPermissions,
  notifyMe,
};

export default notify;