summaryrefslogtreecommitdiffhomepage
path: root/packages/app/src/context/notification-index.ts
blob: 0b316e7ec103772b8a131f9bd7dc59cc09618353 (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
type NotificationIndexItem = {
  directory?: string
  session?: string
  viewed: boolean
  type: string
}

export function buildNotificationIndex<T extends NotificationIndexItem>(list: T[]) {
  const sessionAll = new Map<string, T[]>()
  const sessionUnseen = new Map<string, T[]>()
  const sessionUnseenCount = new Map<string, number>()
  const sessionUnseenHasError = new Map<string, boolean>()
  const projectAll = new Map<string, T[]>()
  const projectUnseen = new Map<string, T[]>()
  const projectUnseenCount = new Map<string, number>()
  const projectUnseenHasError = new Map<string, boolean>()

  for (const notification of list) {
    const session = notification.session
    if (session) {
      const all = sessionAll.get(session)
      if (all) all.push(notification)
      else sessionAll.set(session, [notification])

      if (!notification.viewed) {
        const unseen = sessionUnseen.get(session)
        if (unseen) unseen.push(notification)
        else sessionUnseen.set(session, [notification])

        sessionUnseenCount.set(session, (sessionUnseenCount.get(session) ?? 0) + 1)
        if (notification.type === "error") sessionUnseenHasError.set(session, true)
      }
    }

    const directory = notification.directory
    if (directory) {
      const all = projectAll.get(directory)
      if (all) all.push(notification)
      else projectAll.set(directory, [notification])

      if (!notification.viewed) {
        const unseen = projectUnseen.get(directory)
        if (unseen) unseen.push(notification)
        else projectUnseen.set(directory, [notification])

        projectUnseenCount.set(directory, (projectUnseenCount.get(directory) ?? 0) + 1)
        if (notification.type === "error") projectUnseenHasError.set(directory, true)
      }
    }
  }

  return {
    session: {
      all: sessionAll,
      unseen: sessionUnseen,
      unseenCount: sessionUnseenCount,
      unseenHasError: sessionUnseenHasError,
    },
    project: {
      all: projectAll,
      unseen: projectUnseen,
      unseenCount: projectUnseenCount,
      unseenHasError: projectUnseenHasError,
    },
  }
}