summaryrefslogtreecommitdiff
path: root/ui/service-worker.js
blob: 56bfca97d13e986a552f661b8436274b6a6948d0 (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
/// <reference types="@sveltejs/kit" />
/// <reference no-default-lib="true"/>
/// <reference lib="esnext" />
/// <reference lib="webworker" />

self.addEventListener('install', (event) => {
  self.skipWaiting();
});

self.addEventListener('activate', (event) => {
  event.waitUntil(self.clients.claim());
});

// ###### Handle unread badge:
const conversationReadStatus = {
  // Format:
  // conversationId: { lastRead: Optional(Datetime), lastMessage: Datetime }
};

function countUnreadChannels() {
  return Object.values(conversationReadStatus)
    .map(({ lastRead, lastMessage }) => {
      return !lastRead || lastRead < lastMessage ? 1 : 0;
    })
    .reduce((total, current) => total + current, 0);
}

self.addEventListener('push', (event) => {
  // Let's show a notification right away so Safari doesn't tell Apple to be
  // mad at us:
  event.waitUntil(
    self.registration.showNotification('Test notification', {
      actions: [],
      body: event.data.text(),
    }),
  );
  // Now we can do slower things that might fail:
  conversationReadStatus[event.conversationId] ||= { lastRead: null, lastMessage: null };
  conversationReadStatus[event.conversationId].lastMessage = new Date();
  event.waitUntil(
    (async () => {
      if (navigator.setAppBadge) {
        navigator.setAppBadge(countUnreadChannels());
      }
    })(),
  );
});

// The client has to tell us when it has read a conversation:
self.addEventListener('message', (event) => {
  switch (event.data?.type) {
    case 'CONVERSATION_READ':
      conversationReadStatus[event.data.conversationId] ||= { lastRead: null, lastMessage: null };
      conversationReadStatus[event.data.conversationId].lastMessage = event.data.at || new Date();
      event.waitUntil(
        (async () => {
          if (navigator.setAppBadge) {
            navigator.setAppBadge(countUnreadChannels());
          }
        })(),
      );
      break;
    default:
      break;
  }
});