Websocket clock server web interface written in ReactJS/TypeScript
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AlarmNotif.js 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* Small set of function for Notification handling */
  2. /* Stores Notifications instance associated with alarm name */
  3. var _notifications = {};
  4. var _requested = false;
  5. /* Return True if the browser supports Notifications
  6. * Note : Return False in case user denied the permission to notify
  7. */
  8. function support() {
  9. return "Notification" in window && Notification.permission !== 'denied'
  10. }
  11. /* Return True if Notifications are supported and permission granted */
  12. function granted() {
  13. if(!support()) {
  14. return false;
  15. }
  16. return Notification.permission === 'granted'
  17. }
  18. /* Request permission for notifications */
  19. function requestPermission() {
  20. if(_requested) { return; }
  21. _requested = true
  22. Notification.requestPermission()
  23. }
  24. /* Given an alarm name and a ringtime, create a new notification
  25. * for the ringing alarm if none existing
  26. */
  27. function set_notif_alrm(name:string, time_str:string) {
  28. if(!support()) { return; }
  29. if(!granted()) {
  30. if(_requested) { return; } // allready requested
  31. _requested = true
  32. Notification.requestPermission().then(function (perm) {
  33. set_notif_alrm(name)
  34. })
  35. }
  36. if(name in _notifications) { return; }
  37. let notif = new Notification(time_str+" '"+name+"'",
  38. {body:time_str+' alarm "'+name+'" is ringing.'})
  39. notif.addEventListener('close', () => {
  40. if(!name in _notifications) {
  41. delete _notifications[name];
  42. }
  43. });
  44. notif.addEventListener('error', () => {
  45. if(!name in _notifications) {
  46. delete _notifications[name];
  47. }
  48. });
  49. _notifications[name] = notif;
  50. }
  51. /* Given an alarm name, delete & close associated Notification if one exists */
  52. function unset_notif_alrm(name:string) {
  53. if(!support()) { return; }
  54. if(name in _notifications) {
  55. _notifications[name].close()
  56. delete _notifications[name]
  57. }
  58. }
  59. const Notif = {
  60. set: set_notif_alrm,
  61. unset: unset_notif_alrm,
  62. requestPermission: requestPermission,
  63. };
  64. export default Notif;