Skip to content

Commit 11f20e6

Browse files
committed
feat: add browser notification when receiving a chat
1 parent 50e8356 commit 11f20e6

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

frontend/src/context/ChatProvider.tsx

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,13 @@ export function ChatProvider({ children }: { children: React.ReactNode }) {
1010
const [openChats, setOpenChats] = useState<OpenChat[]>([])
1111
const channelRef = useRef<ReturnType<typeof supabase.channel> | null>(null)
1212

13+
// Request notification permission when user is logged in
14+
useEffect(() => {
15+
if (myFriendId && 'Notification' in window && Notification.permission === 'default') {
16+
Notification.requestPermission()
17+
}
18+
}, [myFriendId])
19+
1320
// On mount (when account loads), fetch unread counts and open minimized chats
1421
useEffect(() => {
1522
if (!myFriendId) {
@@ -38,9 +45,19 @@ export function ChatProvider({ children }: { children: React.ReactNode }) {
3845
.on('broadcast', { event: 'message' }, ({ payload }) => {
3946
const senderFriendId: string = payload.sender_friend_id
4047
const senderUsername: string = payload.sender_username ?? senderFriendId
48+
const content: string = payload.content ?? 'New message'
4149

4250
setOpenChats((prev) => {
4351
const existing = prev.find((c) => c.friendId === senderFriendId)
52+
const chatIsMinimizedOrClosed = !existing || existing.minimized
53+
54+
if ('Notification' in window && Notification.permission === 'granted' && (document.hidden || chatIsMinimizedOrClosed)) {
55+
new Notification(`${senderUsername}`, {
56+
body: content,
57+
icon: '/pokemon-icon128.png',
58+
})
59+
}
60+
4461
if (!existing) {
4562
return [...prev, { friendId: senderFriendId, username: senderUsername, minimized: true, unreadCount: 1 }]
4663
}

0 commit comments

Comments
 (0)