Skip to content

Commit

Permalink
[🐴] Decrement app badge when opening unread chat (#4040)
Browse files Browse the repository at this point in the history
* decrement badge count for chats

* handle decrement in `useMarkAsRead`

* remove async

* oops
  • Loading branch information
haileyok authored May 16, 2024
1 parent 4bceabc commit 5e8650a
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
5 changes: 3 additions & 2 deletions src/lib/hooks/useNotificationHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,10 +169,11 @@ export function useNotificationsHandler() {
payload.reason === 'chat-message' &&
payload.recipientDid === currentAccount?.did
) {
const isCurrentConvo = payload.convoId === currentConvoId
return {
shouldShowAlert: payload.convoId !== currentConvoId,
shouldShowAlert: !isCurrentConvo,
shouldPlaySound: false,
shouldSetBadge: false,
shouldSetBadge: !isCurrentConvo,
}
}

Expand Down
12 changes: 12 additions & 0 deletions src/lib/notifications/notifications.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react'
import * as Notifications from 'expo-notifications'
import {getBadgeCountAsync, setBadgeCountAsync} from 'expo-notifications'
import {BskyAgent} from '@atproto/api'

import {logger} from '#/logger'
Expand Down Expand Up @@ -109,3 +110,14 @@ export function useRequestNotificationsPermission() {
[gate],
)
}

export async function decrementBadgeCount(by = 1) {
if (!isNative) return

const currCount = await getBadgeCountAsync()
let newCount = currCount - by
if (newCount < 0) {
newCount = 0
}
await setBadgeCountAsync(newCount)
}
17 changes: 13 additions & 4 deletions src/state/queries/messages/list-converations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
import {useCurrentConvoId} from '#/state/messages/current-convo-id'
import {DM_SERVICE_HEADERS} from '#/state/queries/messages/const'
import {useAgent} from '#/state/session'
import {decrementBadgeCount} from 'lib/notifications/notifications'

export const RQKEY = ['convo-list']
type RQPageParam = string | undefined
Expand Down Expand Up @@ -116,10 +117,18 @@ export function useOnMarkAsRead() {
return useCallback(
(chatId: string) => {
queryClient.setQueryData(RQKEY, (old: ConvoListQueryData) => {
return optimisticUpdate(chatId, old, convo => ({
...convo,
unreadCount: 0,
}))
return optimisticUpdate(chatId, old, convo => {
// We only want to decrement the badge by one no matter the unread count, since we only increment once per
// sender regardless of message count
if (convo.unreadCount > 0) {
decrementBadgeCount(1)
}

return {
...convo,
unreadCount: 0,
}
})
})
},
[queryClient],
Expand Down

0 comments on commit 5e8650a

Please sign in to comment.