Skip to content

Commit

Permalink
Merge pull request #362 from dappforce/integration-unread
Browse files Browse the repository at this point in the history
Add unread count listener for integration
  • Loading branch information
olehmell authored Aug 31, 2023
2 parents 7e4af68 + 92c088b commit 7b6ddad
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
29 changes: 26 additions & 3 deletions integration/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,8 @@ const grill = {
waitingCallbacks: (() => void)[]
}
>,
currentUnreadCount: 0,
unreadCountListeners: [] as ((count: number) => void)[],

init(config: GrillConfig) {
const createInitError = (message: string) => new GrillError(message, 'init')
Expand Down Expand Up @@ -202,6 +204,14 @@ const grill = {

currentInstance.isReady = true
currentInstance.waitingCallbacks.forEach((callback) => callback())
} else if ((event.data + '').startsWith('grill:unread:')) {
const unreadCount = parseInt(event.data.split('grill:unread:')[1])
if (!isNaN(unreadCount) && this.currentUnreadCount !== unreadCount) {
this.currentUnreadCount = unreadCount
this.unreadCountListeners.forEach((listener) =>
listener(this.currentUnreadCount)
)
}
}
}

Expand Down Expand Up @@ -234,14 +244,27 @@ const grill = {
}
sendSetConfigMessage()
},

addUnreadCountListener(listener: (count: number) => void) {
listener(this.currentUnreadCount)
this.unreadCountListeners.push(listener)
},
removeUnreadCountListener(listener: (count: number) => void) {
this.unreadCountListeners = this.unreadCountListeners.filter(
(l) => l !== listener
)
},
}

export type Grill = typeof grill
export type Grill = Omit<
typeof grill,
'unreadCountListeners' | 'currentUnreadCount'
>
if (typeof window !== 'undefined') {
;(window as any).GRILL = grill
;(window as any).GRILL = grill as Grill
}

export default grill
export default grill as Grill

export class GrillError extends Error {
constructor(message = '', method = '') {
Expand Down
2 changes: 2 additions & 0 deletions src/components/chats/ChatList/ChatList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,8 @@ function ChatListContent({
lastReadIdIndex === -1
? 0
: filteredMessageIdsRef.current.length - lastReadIdIndex - 1
window.parent?.postMessage(`grill:unread:${newMessageCount}`, '*')

setInitialNewMessageCount(newMessageCount)
})
}
Expand Down

0 comments on commit 7b6ddad

Please sign in to comment.